text:
Q: Adding minor tick marks to the x axis in ggplot2 (with no labels) Below is example code of a plot that does almost exactly what I want. The only thing I want to add is tick marks on the x axis (same size as the major ticks) according to the minor_breaks defined below.
df <- data.frame(x = c(1900,1950,2000), y = c(50,75,60))

p <- ggplot(df, aes(x=x, y=y))
p + geom_line() +
  scale_x_continuous(minor_breaks = seq(1900,2000,by=10),
                     breaks = seq(1900,2000,by=50),
                     limits = c(1900,2000),
                     expand = c(0,0)) +
  scale_y_continuous(breaks = c(20,40,60,80),
                     limits = c(0,100)) +
  theme(legend.position="none",
        panel.background = element_blank(),
        axis.line = element_line(color='black'),
        panel.grid.minor = element_blank())

A: Very nice functions above.
A solution I find somewhat simpler or easier to wrap my head around is to simply specify you major axis breaks in the increments you want for both major and minor breaks - so if you want major in increments of 10, and minor in increments of 5, you should nevertheless specify your major increments in steps of 5.
Then, in the theme, you are asked to give a color for the axis text. Rather than choosing one color, you can give it a list of colors - specifying whatever color you want the major axis number to be, and then NA for the minor axis color. This will give you the text on the major mark, but nothing on the 'minor' mark. Likewise, for the grid that goes inside the plot, you can specify a list for the line sizes, so that there is still a difference in thickness for major and minor gridlines within the plot, even though you are specifying the minor gridlines as major grid lines. As an example of what you could put in theme:
panel.grid.major.x = element_line(colour = c("white"), size = c(0.33, 0.2)),
panel.grid.major.y = element_line(colour = c("white"), size = c(0.33, 0.2)),
axis.text.y = element_text(colour = c("black", NA), family = "Gill Sans"),
axis.text.x = element_text(colour = c("black", NA), family = "Gill Sans"),

I suspect you can change the size of the outer tick mark in the exact same way, though I haven't tried it.

A: Although the response above is able to add breaks, thse are not actually the minor_breaks, To do so you could use annotation_ticks function, which works similarly to  annotation_logticks.
Code function is available here. You may need to load grid package
annotation_ticks <- function(sides = "b",
                             scale = "identity",
                             scaled = TRUE,
                             short = unit(0.1, "cm"),
                             mid = unit(0.2, "cm"),
                             long = unit(0.3, "cm"),
                             colour = "black",
                             size = 0.5,
                             linetype = 1,
                             alpha = 1,
                             color = NULL,
                             ticks_per_base = NULL,
                             ...) {
  if (!is.null(color)) {
    colour <- color
  }

  # check for invalid side
  if (grepl("[^btlr]", sides)) {
    stop(gsub("[btlr]", "", sides), " is not a valid side: b,t,l,r are valid")
  }

  # split sides to character vector
  sides <- strsplit(sides, "")[[1]]

  if (length(sides) != length(scale)) {
    if (length(scale) == 1) {
      scale <- rep(scale, length(sides))
    } else {
      stop("Number of scales does not match the number of sides")
    }
  }

  base <- sapply(scale, function(x) switch(x, "identity" = 10, "log10" = 10, "log" = exp(1)), USE.NAMES = FALSE)

  if (missing(ticks_per_base)) {
    ticks_per_base <- base - 1
  } else {
    if ((length(sides) != length(ticks_per_base))) {
      if (length(ticks_per_base) == 1) {
        ticks_per_base <- rep(ticks_per_base, length(sides))
      } else {
        stop("Number of ticks_per_base does not match the number of sides")
      }
    }
  }

  delog <- scale %in% "identity"

  layer(
    data = data.frame(x = NA),
    mapping = NULL,
    stat = StatIdentity,
    geom = GeomTicks,
    position = PositionIdentity,
    show.legend = FALSE,
    inherit.aes = FALSE,
    params = list(
      base = base,
      sides = sides,
      scaled = scaled,
      short = short,
      mid = mid,
      long = long,
      colour = colour,
      size = size,
      linetype = linetype,
      alpha = alpha,
      ticks_per_base = ticks_per_base,
      delog = delog,
      ...
    )
  )
}

#' Base ggproto classes for ggplot2
#'
#' If you are creating a new geom, stat, position, or scale in another package,
#' you'll need to extend from ggplot2::Geom, ggplot2::Stat, ggplot2::Position, or ggplot2::Scale.
#'
#' @seealso \code{\link[ggplot2]{ggplot2-ggproto}}
#' @usage NULL
#' @format NULL
#' @rdname ggplot2-ggproto
#' @export
GeomTicks <- ggproto(
  "GeomTicks", Geom,
  extra_params = "",
  handle_na = function(data, params) {
    data
  },

  draw_panel = function(data,
                        panel_scales,
                        coord,
                        base = c(10, 10),
                        sides = c("b", "l"),
                        scaled = TRUE,
                        short = unit(0.1, "cm"),
                        mid = unit(0.2, "cm"),
                        long = unit(0.3, "cm"),
                        ticks_per_base = base - 1,
                        delog = c(x = TRUE, y = TRUE)) {
    ticks <- list()

    # Convert these units to numbers so that they can be put in data frames
    short <- convertUnit(short, "cm", valueOnly = TRUE)
    mid <- convertUnit(mid, "cm", valueOnly = TRUE)
    long <- convertUnit(long, "cm", valueOnly = TRUE)

    for (s in 1:length(sides)) {
      if (grepl("[b|t]", sides[s])) {

        # Get positions of x tick marks
        xticks <- calc_ticks(
          base = base[s],
          minpow = floor(panel_scales$x.range[1]),
          maxpow = ceiling(panel_scales$x.range[2]),
          majorTicks = panel_scales$x.major_source,
          start = 0,
          shortend = short,
          midend = mid,
          longend = long,
          ticks_per_base = ticks_per_base[s],
          delog = delog[s]
        )

        if (scaled) {
          if (!delog[s]) {
            xticks$value <- log(xticks$value, base[s])
          }
        }

        names(xticks)[names(xticks) == "value"] <- "x" # Rename to 'x' for coordinates$transform

        xticks <- coord$transform(xticks, panel_scales)

        # Make the grobs
        if (grepl("b", sides[s])) {
          ticks$x_b <- with(
            data,
            segmentsGrob(
              x0 = unit(xticks$x, "native"),
              x1 = unit(xticks$x, "native"),
              y0 = unit(xticks$start, "cm"),
              y1 = unit(xticks$end, "cm"),
              gp = gpar(
                col = alpha(colour, alpha),
                lty = linetype,
                lwd = size * .pt
              )
            )
          )
        }
        if (grepl("t", sides[s])) {
          ticks$x_t <- with(
            data,
            segmentsGrob(
              x0 = unit(xticks$x, "native"),
              x1 = unit(xticks$x, "native"),
              y0 = unit(1, "npc") - unit(xticks$start, "cm"),
              y1 = unit(1, "npc") - unit(xticks$end, "cm"),
              gp = gpar(
                col = alpha(colour, alpha),
                lty = linetype,
                lwd = size * .pt
              )
            )
          )
        }
      }

      if (grepl("[l|r]", sides[s])) {
        yticks <- calc_ticks(
          base = base[s],
          minpow = floor(panel_scales$y.range[1]),
          maxpow = ceiling(panel_scales$y.range[2]),
          majorTicks = panel_scales$y.major_source,
          start = 0,
          shortend = short,
          midend = mid,
          longend = long,
          ticks_per_base = ticks_per_base[s],
          delog = delog[s]
        )

        if (scaled) {
          if (!delog[s]) {
            yticks$value <- log(yticks$value, base[s])
          }
        }

        names(yticks)[names(yticks) == "value"] <- "y" # Rename to 'y' for coordinates$transform
        yticks <- coord$transform(yticks, panel_scales)

        # Make the grobs
        if (grepl("l", sides[s])) {
          ticks$y_l <- with(
            data,
            segmentsGrob(
              y0 = unit(yticks$y, "native"),
              y1 = unit(yticks$y, "native"),
              x0 = unit(yticks$start, "cm"),
              x1 = unit(yticks$end, "cm"),
              gp = gpar(
                col = alpha(colour, alpha),
                lty = linetype, lwd = size * .pt
              )
            )
          )
        }
        if (grepl("r", sides[s])) {
          ticks$y_r <- with(
            data,
            segmentsGrob(
              y0 = unit(yticks$y, "native"),
              y1 = unit(yticks$y, "native"),
              x0 = unit(1, "npc") - unit(yticks$start, "cm"),
              x1 = unit(1, "npc") - unit(yticks$end, "cm"),
              gp = gpar(
                col = alpha(colour, alpha),
                lty = linetype,
                lwd = size * .pt
              )
            )
          )
        }
      }
    }
    gTree(children = do.call("gList", ticks))
  },
  default_aes = aes(colour = "black", size = 0.5, linetype = 1, alpha = 1)
)

# Calculate the position of log tick marks Returns data frame with: - value: the
# position of the log tick on the data axis, for example 1, 2, ..., 9, 10, 20, ...
# - start: on the other axis, start position of the line (usually 0) - end: on the
# other axis, end position of the line (for example, .1, .2, or .3)
calc_ticks <- function(base = 10,
                       ticks_per_base = base - 1,
                       minpow = 0,
                       maxpow = minpow + 1,
                       majorTicks = 0,
                       start = 0,
                       shortend = 0.1,
                       midend = 0.2,
                       longend = 0.3,
                       delog = FALSE) {

  # Number of blocks of tick marks
  reps <- maxpow - minpow

  # For base 10: 1, 2, 3, ..., 7, 8, 9, 1, 2, ...
  ticknums <- rep(seq(1, base - 1, length.out = ticks_per_base), reps)

  # For base 10: 1, 1, 1, ..., 1, 1, 1, 2, 2, ... (for example)
  powers <- rep(seq(minpow, maxpow - 1), each = ticks_per_base)

  ticks <- ticknums * base ^ powers

  ticks <- c(ticks, base ^ maxpow) # Add the last tick mark

  # Set all of the ticks short
  tickend <- rep(shortend, length(ticks))

  # Get the position within each cycle, 0, 1, 2, ..., 8, 0, 1, 2. ...
  cycleIdx <- ticknums - 1

  # Set the 'major' ticks long
  tickend[cycleIdx == 0] <- longend

  # Where to place the longer tick marks that are between each base For base 10, this
  # will be at each 5
  longtick_after_base <- floor(ticks_per_base / 2)
  tickend[cycleIdx == longtick_after_base] <- midend

  if (delog) {
    ticksCopy <- ticks

    regScale <- log(ticks, base)

    majorTicks <- sort(
      unique(
        c(
          minpow,
          regScale[which(regScale %in% majorTicks)],
          maxpow,
          majorTicks
        )
      )
    )

    expandScale <- c()

    if (length(majorTicks) > 1) {
      for (i in 1:(length(majorTicks) - 1)) {
        expandScale <- c(
          expandScale,
          seq(majorTicks[i], majorTicks[i + 1], length.out = (ticks_per_base + 1))
        )
      }

      ticks <- unique(expandScale)

      # Set all of the ticks short
      tickend <- rep(shortend, length(ticks))

      # Set the 'major' ticks long
      tickend[which(ticks %in% majorTicks)] <- longend
    }
  }

  tickdf <- data.frame(value = ticks, start = start, end = tickend)

  tickdf
}

A: Minor axis ticks without labels can now easily be added with the {ggh4x} package. Only minor modifications to the original plot necessary (see comments in code).
library(ggh4x)
#> Loading required package: ggplot2
df <- data.frame(x = c(1900, 1950, 2000), y = c(50, 75, 60))

ggplot(df, aes(x, y)) +
  geom_line() +
  scale_x_continuous(
    minor_breaks = seq(1900, 2000, by = 10),
    breaks = seq(1900, 2000, by = 50), limits = c(1900, 2000),
    guide = "axis_minor" # this is added to the original code
  ) +
  theme(ggh4x.axis.ticks.length.minor = rel(1)) # add this to get the same length

Created on 2021-04-19 by the reprex package (v2.0.0)

A: This would do it in the precise instance:
scale_x_continuous(breaks= seq(1900,2000,by=10),
                  labels = c(1900, rep("",4), 1950, rep("",4), 2000),
                  limits = c(1900,2000), expand = c(0,0)) +

Here's a function that is not bullet-proof but works to insert blank labels when the beginning and ending major labels are aligned with the start and stopping values for the at argument:
insert_minor <- function(major_labs, n_minor) {labs <-
                              c( sapply( major_labs, function(x) c(x, rep("", 4) ) ) )
                              labs[1:(length(labs)-n_minor)]}

Test:
p <- ggplot(df, aes(x=x, y=y))
  p + geom_line() +
  scale_x_continuous(breaks= seq(1900,2000,by=10),
                     labels = insert_minor( seq(1900, 2000, by=50), 4 ),
                     limits = c(1900,2000), expand = c(0,0)) +
  scale_y_continuous(breaks = c(20,40,60,80), limits = c(0,100)) +
  theme(legend.position="none", panel.background = element_blank(),
        axis.line = element_line(color='black'), panel.grid.minor = element_blank())


text:
Q: How do I choose a particular DbSet from a DbContext using EFCore 3.1? My app works with 5 tables right now, maybe more in the future, and I would like to minimize code duplication. One example below is for Swd0004 and I also have the same code for Swd0013, and other duplicated functions for each table. The user chooses what table to work with from a drop down box. I'd like to take this drop down box selection and somehow pass that to the functions.
private void SWD_0004_Lookup()
{
    using (var ctx = new EFContext())
    {
        var query = ctx.Swd0004;
        var readList = query.ToList();
        Debug.WriteLine("QUERY COUNT: " + readList.Count);
        // create datatable from query results so I can populate datagridview
        var dt = LINQResultToDataTable(query);
        dgvQueryResults.DataSource = dt;
        GetColumnHeaders(dt);
        DataDT = dt; // copy local dt so we can use DataDT for getting record data
    }
}

This is a database first app. Swd0004 is a table in a database and therefore a DbSet in my EFContext class.
My Swd0004 class:
namespace SWDDB.Models
{
    public partial class Swd0004
    {
        public int Id { get; set; }
        public string PartNumber { get; set; }
...

Then do I need to add a generic to it to implement @abdusco answer? Maybe I'm not familiar enough with generics.
    public partial class Swd0004<TEntity> : ??? where TEntity : class

Here's another example:
private List<Swd0004> ConvertDT(DataTable dt)
{
    var importList = new List<Swd0004>();
    // convert DataRow object to SWD object, otherwise BulkInsert will fail
    foreach (DataRow row in dt.Rows)
    {
        var obj = CreateItemFromRow<Swd0004>(row);
        // BulkInsert needs a list
        importList.Add(obj);
    }
    return importList;
}

As you can see, I have to explicitly state Swd0004 three times. So I would have to duplicate this function for each table, 5 times.
UPDATE
I'm trying to implement what @bolkay suggested. I created this class:
using SWDDB.Models;
using System.Diagnostics;
using System.Linq;

namespace SWDDB
{
    public abstract class BaseLookup<TEntity> where TEntity : class
    {
        public virtual void PerformLookup()
        {
            using (var ctx = new EFContext())
            {
                var query = ctx.Set<TEntity>();
                Debug.WriteLine("QUERY COUNT: " + query.ToList().Count);
            }
        }
    }
    public class SWD0004Lookup : BaseLookup<Swd0004>
    {

    }
}

It feels like I'm close but I can't figure out how to call PerformLookup from my mainline code.

A: I don't fully understand the logic behind users selecting a table to work with.
You can do something like this as a starting point to remove duplication of methods.
Create a base class with the logic.
    public abstract class BaseLookUp<TEntity> where TEntity : class
    {
        public virtual void PerformLookup()
        {
            using (var ctx = new EFContext())
            {
                var query = ctx.Set<TEntity>();
                //etc...
            }
        }
    }
    public class SWD004Lookup : BaseLookUp<SWD004004>
    {

    }

Totally depending on your needs, you could just make it a static method etc.

A: You can get a DbSet using DbContext.Set<TEntity>() instead of using properties in your EfContext class:
private void SWD_Lookup<TEntity>() // <-- turn it into a generic method
{
    using (var ctx = new EFContext())
    {
        var query = ctx.Set<TEntity>(); // <-- get dbset by passing the type
        // ...
    }
}

then you can call it like this:
SWD_Lookup<Swd0004>();
SWD_Lookup<Swd0013>();

redpajama_set_name: RedPajamaStackExchange


text:
Q: string.Format does not append the given args I'm writing an extension for string.Format (which I've done before with no problems.)
My extension:
    public static string FormatWith(this string source, params object[] args) {
        source.ThrowIfNull("source");

        return string.Format(source, args);
    }

My test:
    [TestMethod]
    public void FormatWith_ShouldReturnCorrectResult_FromValidArgs() {
        var expected = "testing 123";
        var actual = "test".FormatWith("ing", " ", 123);

        Assert.AreEqual(expected, actual);
    }

In my test, after the call to FormatWith, actual should be "testing 123" but it is just "test".
My test's message:
    Assert.AreEqual failed. Expected:<testing123>. Actual:<test>.

I've tried passing types other than string into the extension but the result is unchanged. And I'm sure source.ThrowIfNull is not throwing an exception.
So what gives? Am I overlooking something? A nice answer would show me a working implementation of FormatWith along with an explanation of why my implementation is not working.
Edit: I'm an idiot and completely forgot about {0}, {1}... I use this on a daily basis too. Will accept first answer when timer is up. Thanks guys.

A: I'm not a .NET guy, but I can read API docs: http://www.dotnetperls.com/string-format
If I'm not mistaken, your source string needs to explicitly add your arguments to the string.
var actual = "test{0}{1}{2}".FormatWith("ing", " ", 123);

Feel free to correct me .NET folks.

A: You are looking for String.Concat. String.Format doesn't work like that.Only if you specify arguments like this:
string.Format("{0}, {1} ....",source,args);

Which you can not because you don't know the number of arguments.So you can use String.Concat or String.Join instead.

A: Rather than modify your usage of the function as some other others suggested, here's an implementation of FormatWith that will work as you intended it:
public static string FormatWith(this string source, params object[] args)
{
    var arguments = new List<object> {source};
    arguments.AddRange(args);

    return String.Concat(arguments);
}


text:
Q: jquery multiselect widget issue with jquery ui upgrading to 1.10.3 jQuery UI upgrade from 1.8 to 1.10.3 is causing an issue for multiselect widget plugin:

Error: cannot call methods on multiselect prior to initialization; attempted to call method 'widget'
throw new Error( msg );"

Does anybody have solution for this?

A: Try this out:- http://jsfiddle.net/adiioo7/akhyp/860/
Working fine with jQuery UI 10.0.3 version.

A: Code while error was coming
 $("select").multiselect("widget").find("input[value='CustShifts']:unchecked,input[value='attendance']:unchecked").each(function () {
                           this.click();
                       });

Working code without error
$("input[value='CustShifts']:unchecked,input[value='attendance']:unchecked").each(function () {
                           this.click();
                       });


text:
Q: why does it keep saying "TypeError: '<=' not supported between instances of 'int' and 'str'"? this is the full error of the code
i would really love the help

mainshop = [{"name":"Time_watch","price":1000,"description":"Resets certain cooldowns (limited uses)(WIP)"}, {"name":"Gun","price":10000,"description":"A better way to rob people with a shorter cooldown!"}, {"name":"Guhhh Placeholder!!","price":10000000,"description":"I sure love placeholders"}]
@client.command()
@commands.is_owner()
async def shop(ctx):#real#:troll:.name
    em = discord.Embed(title = "Shopping District")

    for item in mainshop:
      name = item["name"]
      price = item["price"]
      desc = item["description"] #i do believe its because you have like no DESCRIPTION in the item list thing
      #get fake
      em.add_field(name = name, value = f"${price} | {desc}")
#real
    await ctx.send(embed = em)

import discord
from discord.ext import commands
import asyncio
import os
import json

##### START LEVEL COMMAND #####

@client.command(name='bal')
async def balance(ctx, user:discord.Member=None):
    colour = randint(0, 0xffffff)
    await open_account(ctx.author)
    if user is None:
        user = ctx.author
    users = await get_bank_data()
    wallet_amt = users[str(user.id)]["wallet"]
    bank_amt = users[str(user.id)]["bank"]
    em = discord.Embed(title=f"{user}'s balance", color=colour)
    em.add_field(name="Wallet", value=wallet_amt)
    em.add_field(name="Bank", value=bank_amt)
    await ctx.send(embed=em)

async def buy_this(user,item_name,amount):
    item_name = item_name.lower()
    name_ = None
    for item in mainshop:
        name = item["name"].lower()
        if name == item_name:
            name_ = name
            price = item["price"]
            break

    if name_ == None:
        return [False,1]

    cost = price*amount

    users = await get_bank_data()

    bal = await update_bank(user)#r.i.p. KB's confindince

    if bal[0]<= cost:
        return [False,2]

    try:
        index = 0
        t = None
        for thing in users[str(user.id)]["bag"]:
            n = thing["item"]
            if n == item_name:
                old_amt = thing["amount"]
                new_amt = old_amt + amount
                users[str(user.id)]["bag"][index]["amount"] = new_amt
                t = 1
                break
            index+=1
        if t == None:
            obj = {"item":item_name , "amount" : amount}
            users[str(user.id)]["bag"].append(obj)
    except:
        obj = {"item":item_name , "amount" : amount}
        users[str(user.id)]["bag"] = [obj]

    with open("mainbank.json","w") as f:
        json.dump(users,f)

    await update_bank(user,cost*-1,"wallet")

    return [True,"Worked"]

@client.command()
async def buy(ctx,item,amount):#how come these arent definded no more? oh I prollydid smth by mistake guhhhhhhh
        res = await buy_this(ctx.author,item,amount)

        if not res[0]:
         if res[1]==1:
            await ctx.send("That is not an item in shop")
            return
         if res[1]==2:
            await ctx.send(f"You don't have enough money to buy the {amount}")
            return
            await ctx.send(f"Successfully bought {amount}: {item}")

@client.command()
@commands.is_owner()
async def bag(ctx):
    await open_account(ctx.author)
    user = ctx.author
    users = await get_bank_data()

    try:
        bag = users[str(user.id)]["bag"]
    except:
        bag = []

    em = discord.Embed(title = "Bag")
    for item in bag:
        name = item["item"]
        amount = item["amount"]

        em.add_field(name = name, value = amount)

    await ctx.send(embed = em)
 #Oh you mean this ? oh yeah Idk what I put that there

async def open_account(user):

    users = await get_bank_data()

    if str(user.id) in users:
        return False
    else:
        users[str(user.id)] = {}
        users[str(user.id)]["wallet"] = 0
        users[str(user.id)]["bank"] = 0

    with open("mainbank.json", "w") as f:
        json.dump(users, f)

    return True

async def get_bank_data():
    with open("mainbank.json", "r") as f:
        users = json.load(f)

    return users

async def update_bank(user, change=0, mode="wallet"):
    users = await get_bank_data()

    users[str(user.id)][mode] += change

    with open("mainbank.json", "w") as f:
        json.dump(users, f)

    bal = [users[str(user.id)]["wallet"], users[str(user.id)]["bank"]]
    return bal

the code that should matter. I do not understand at all what is wrong with the code. I used this code before no errors. So if anyone could please explain that would be greatly appreciated. I have tried putting this in its own thing. it didnt work still. i have also tried putting if bal <= int(cost) this also didnt work.

A: on the line if bal[0]<= cost: if you cast to an integer int(bal[0]) it should be comparing two integers then, and vice-versa if cost is a string

A: Cost is already an int, looks like bal[0] is a string. Try int(bal[0]) <= cost instead (or float(bal[0]) if it has decimals)


text:
Q: How to calculate time of travel between 2 cities? I have following task: to calculate time of travel between 2 cities using any api or services. But I haven't made it before, and I have 2 ideas: calculate time using speed limit on roads or trafic flow. Are there means to help me with my task? May be Google Maps are able to help me? Thank you, anyway.
Additional: I don't have a speed of transport.

A: Google Maps API will do this. A simple google search returns many examples.
dead link removed.


text:
Q: Why does making this virtual destructor inline fix a linker issue? If I have a pure virtual class InterfaceA that consists solely of a pure virtual destructor, why do I have to define the destructor as inline? I I don't I get an error when I try to link it.
Below is an admittedly contrived example, however it illustrates the point. The point does not compile for me using cmake and g++. However, if I change the InterfaceA destructor definition as follows - inline InterfaceA::~InterfaceA(){}; then it compiles.
Why is this? What does the inline keyword do?
// InterfaceA.h, include guards ommitted for clarity
class InterfaceA
{
    public:
        virtual ~InterfaceA() = 0;
};

InterfaceA::~InterfaceA(){};

// A.h, include guards ommitted for clarity
#include "InterfaceA.h"
class A : public InterfaceA
{
    public:
        A(int val)
            : myVal(val){};
        ~A(){};

        int myVal;
};

// AUser.h, include guards ommitted for clarity
#include "InterfaceA.h"
class AUser
{
    public:
        AUser(InterfaceA& anA)
            : myA(anA){};
        ~AUser(){};

        int getVal() const;

    private:
        InterfaceA& myA;
};

// AUser.cpp
#include "AUser.h"
#include "A.h"

int AUser::getVal() const
{
    A& anA = static_cast<A&>(myA);
    return anA.myVal;
}

// main.cpp
#include "AUser.h"
#include "A.h"
#include <iostream>

int main(){
    A anA(1);
    AUser user(anA);
    std::cout << "value = " << user.getVal() << std::endl;
    return 0;
}

A: You have to use the inline keyword when defining functions in header files. If you do not, and the file is included in more than one translation unit, the function will be defined twice (or more times).
The linker error is probably something like "Symbol ... is multiply defined" right?
If you defined the member function in the body of the class, it would be implicitly inline and it would also work.
See this answer
To answer the question "What does the inline keyword do?":
In the old days it would be used to ask the compiler to inline functions i.e. insert the code whenever the function is used instead of adding a function call. Eventually it turned into a simple suggestion since compiler optimizers became more knowledgeable about which functions were inline candidates. These days it is used almost exclusively to define functions in header files that must have external linkage.

A: inline means that compiler is allowed to add code directly to where the function was called. It also removes function from external linkage, so both your compile units would have   local  version of.. pure destructor.
// InterfaceA.h, include guards ommitted for clarity
class InterfaceA
{
    public:
        virtual ~InterfaceA() = 0;
};

You declare  destructor virtual, so compiler almost never would make it inline. Why? because virtual functions are called through vtable - a internal working of virtual functions system, vtable  most likely implemented as an array of pointers to member functions. If function is inlined, it would have no address, no legal pointer. If attempt to get address of function is taken, then compiler silently disregards inline keyword.  The other effect will be still in place: inlined destructor stops to be visible to linker.
It may look like declaring pure virtual destructor looks like oxymoron , but it isn't.  The pure destructor is  kind of destructor that would be always called without causing UB. Its presence would make class abstract, but the implicit call in sequence of destructor calls would still happen. If you didn't declare destructor body, it would lead to an UB, e.g. purecall exception on Windows.
If you don't need an abstract base class, then inline definition will suffice:
class InterfaceA
{
public:
      virtual ~InterfaceA() {}
};

that is treated by compiler as inline as well, but mixing inline definition and  pure member declaration is not allowed.


text:
Q: How to replace component did update using react hooks in a functional component? I have developed a react native application. In there I am updating a state variable through redux-thunk action dispatch. Now what I want is I want to navigate to another component when It is updated. How I have written is like this.
  useEffect(() => {
    _navigateOnSuccessOtp(props.navigation);
  }, [props.success, props.navigation]);

This is navigated to next view even when navigation is changed because It also has been added as a dependency to this effect. This is my full code of the component.
import React, {useEffect} from 'react';
import {
  View,
  TouchableOpacity,
  KeyboardAvoidingView,
  Switch,
  TextInput,
  BackHandler,
} from 'react-native';
import I18n from 'react-native-i18n';
import {Formik} from 'formik';
import * as Yup from 'yup';
import {connect} from 'react-redux';
import {signinActions} from '_store/actions';
import SubmitButton from '_components/submitButton/';
import AppText from '_components/appText';
import {strings} from '_translations/i18n';
import styles from './loginstyle';
import Icon from 'react-native-vector-icons/FontAwesome';

const keepMe = (e) => {
  console.log(e);
};

const handleBackButton = () => {
  return true;
};

const _onPress = (values, sendOTP) => {
  console.log(values.mobileNo);
  sendOTP(values.mobileNo);
  // navigation.navigate('Otp');
};

const _navigateOnSuccessOtp = (navigation) => {
  navigation.navigate('Otp');
};

const changeLanguage = (navigate) => {
  navigate.navigate('Home');
};

const getCurrentLocale = () => {
  let locale;
  locale = I18n.locale;
  if (locale === 'en') {
    return <AppText styles={styles.bottomLinkText}>English</AppText>;
  } else if (locale === 'ta') {
    return <AppText styles={styles.bottomLinkText}>தமிழ்</AppText>;
  }
};

const Login = (props) => {
  useEffect(() => {
    BackHandler.addEventListener('hardwareBackPress', handleBackButton);

    return () => {
      BackHandler.removeEventListener('hardwareBackPress', handleBackButton);
    };
  }, []);

  useEffect(() => {
    _navigateOnSuccessOtp(props.navigation);
  }, [props.success, props.navigation]);

  return (
    <KeyboardAvoidingView style={{flex: 1}} enabled>
      <View style={styles.signinView}>
        <View style={styles.signinTitleView}>
          <AppText styles={styles.signinTitle}>
            {strings('login.title')}
          </AppText>
        </View>
        <View style={styles.colempty} />
        <View style={styles.signIn}>
          <View style={styles.signInContainer}>
            <AppText styles={styles.loginFormTitle}>
              {strings('login.title')}
            </AppText>
            <View style={styles.formContainer}>
              <Formik
                initialValues={{
                  mobileNo: '',
                  toggle: true,
                }}
                validationSchema={Yup.object({
                  mobileNo: Yup.string().required('Mobile number required'),
                })}
                onSubmit={(values, formikActions) => {
                  _onPress(values, props.sendOTP);
                  setTimeout(() => {
                    formikActions.setSubmitting(false);
                  }, 500);
                }}>
                {(formprops) => (
                  <View>
                    <View
                      style={
                        (!formprops.touched.mobileNo
                          ? styles.inputView
                          : null) ||
                        (formprops.values.mobileNo && !formprops.errors.mobileNo
                          ? styles.validInputView
                          : null) ||
                        (formprops.touched.mobileNo && formprops.errors.mobileNo
                          ? styles.inputViewError
                          : null)
                      }>
                      <TextInput
                        style={styles.textField}
                        placeholder={strings('login.mobile')}
                        placeholderTextColor="#bbbbbb"
                        value={formprops.values.mobileNo}
                        onChangeText={formprops.handleChange('mobileNo')}
                        onBlur={formprops.handleBlur('mobileNo')}
                        keyboardType="numeric"
                      />
                      {formprops.touched.mobileNo &&
                      formprops.errors.mobileNo ? (
                        <Icon name="times" size={20} style={styles.errorIcon} />
                      ) : null}
                      {formprops.touched.mobileNo &&
                      formprops.values.mobileNo ? (
                        <Icon name="check" size={20} style={styles.validIcon} />
                      ) : null}
                    </View>
                    {formprops.touched.mobileNo && formprops.errors.mobileNo ? (
                      <View style={styles.errorMessage}>
                        <AppText styles={styles.errorMessageText}>
                          {formprops.errors.mobileNo}
                        </AppText>
                      </View>
                    ) : null}
                    <View style={styles.togglebuttoncontainer}>
                      <View style={styles.toggleTextView}>
                        <AppText styles={styles.toggleText}>
                          {strings('login.keep-login')}
                        </AppText>
                      </View>
                      <View style={styles.toggleView}>
                        <Switch
                          trackColor={{false: '#dddddd', true: '#c1d6ee'}}
                          thumbColor={{false: '#ffffff', true: '#007aff'}}
                          ios_backgroundColor="#dddddd"
                          onValueChange={(value) =>
                            formprops.setFieldValue('toggle', value)
                          }
                          value={formprops.values.toggle}
                          style={styles.toggle}
                        />
                      </View>
                    </View>
                    <SubmitButton
                      onpress={formprops.handleSubmit}
                      btext={strings('login.button-text')}
                    />
                  </View>
                )}
              </Formik>
            </View>
          </View>
        </View>
        <View style={styles.hr} />
        <View style={styles.signInBottomContainer}>
          <View style={styles.signInBottomView}>
            <View style={styles.signInBottomContainerTextView}>
              <AppText styles={styles.signInBottomContainerText}>
                {strings('login.language-change')}?
              </AppText>
            </View>
            <View style={styles.signInBottomLinkView}>
              <TouchableOpacity
                onPress={() => changeLanguage(props.navigation)}>
                {getCurrentLocale()}
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </View>
    </KeyboardAvoidingView>
  );
};

const mapStateToProps = (state) => {
  console.log(state);
  return {
    success: state.signin.success,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    sendOTP: (number) => dispatch(signinActions.sendOtpActionCreator(number)),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Login);

I tried a lot to figure out how to do it correctly but I was unable to do so. So can someone help me with this problem? Thank you.

A: Since , _navigateOnSuccessOtp only uses navigation.navigate you can simply pass props.navigation.navigate as a dependency for useEffect and also as an argument to the function. Now navigate does not change and hence your useEffect won't be triggered unnecessarily.
const _navigateOnSuccessOtp = (navigate) => {
 navigate('Otp');
};

.....

useEffect(() => {
  _navigateOnSuccessOtp(props.navigation.navigate);
}, [props.success, props.navigation.navigate]);

You could also remove props.navigation from the dependency as you don't want useEffect to trigger on props.navigation change. Please check this post for more details: How to fix missing dependency warning when using useEffect React Hook?


text:
Q: Read INI file and check checkbox I have written an application that reads an INI file using
wAccessDeniedMsg.Text = ReadIni(File, Options, AccessDeniedMsg, "")

Now this fills a textbox with a message.
But I also want to have a checkbox checked when the value is 1.
So I wrote:
ReadIni(File, Options, AccessDeniedEnabled, "")
        If AccessDeniedEnabled = "1" Then
            wAccessDeniedEnabled.CheckState = CheckState.Checked
        End If

But this does not enable my checkbox.
I searched on several sites and forum but I could not get this to work.
Do you have any idea how I can get the checkbox set to Checked when the value is 1?


text:
Q: Rest api via spring I have to get all data from MySQL in a table using condition select query where fields is isdeleted=0, location=1. How could I implement this in repository and access manager.
public interface FoodCourtRepository  extends JpaRepository<FoodCourtEntity, Long> {
    List<FoodcaseEntity> findByIsdeleted(Boolean isDeleted);
}

In access manager
public List<FoodcaseDO> getAllFoodCourt() {
    List<FoodcaseEntity> foodCaseList = foodcourtRepository.findByIsdeleted(false);
}

A: You need to add another condition as well, for location, e.g.:
public List<FoodcaseEntity> findByIsdeletedAndLocation(boolean deleted, int location);

And call it with false and 1 as arguments, e.g.:
List<FoodcaseEntity> foodCaseList = foodcourtRepository.findByIsdeletedAndLocation(false, 1);

This should give you the required result.
Updte
If you want to fetch the data for multiple locations then you need to write a method that supports IN, e.g.:
public List<FoodcaseEntity> findByIsdeletedAndLocationIn(boolean deleted, List<Integer> location);

And then call it like this:
List<FoodcaseEntity> foodCaseList = foodcourtRepository.findByIsdeletedAndLocation(false, Arrays.asList(2,3,4,5));

A: JPA provides @Query to write custom query. You can define another interface called FoodCourtRepositoryCustom and write custom query as below:
public interface FoodCourtRepositoryCustom {
 @Query("SELECT fe FROM FoodcaseEntity fe WHERE fe.isdeleted=?1 AND fe.location=?2 ")
 List<FoodcaseEntity> findByIsdeletedAndLocation(Boolean isDeleted, Integer location);
}

Then extends this interface in your repository inteface as below:
public interface FoodCourtRepository  extends JpaRepository<FoodCourtEntity, Long>, FoodCourtRepositoryCustom{
List<FoodcaseEntity> findByIsdeleted(Boolean isDeleted);
}

Now method is available in your access manager.
public List<FoodcaseDO> getAllFoodCourt() {
List<FoodcaseEntity> foodCaseList = foodcourtRepository.findByIsdeleted(false);
List<FoodcaseEntity> foodCaseList = foodcourtRepository.findByIsdeletedAndLocation(false, 1);
}

A: In a repository class add,
List<FoodcaseEntity> foodCaseList = foodcourtRepository.findByIsdeletedAndLocation(boolean isSelected,int location);

then u can send selected and location values.it will return list of values based on condition.


text:
Q: Problem with move assignment in C++. Illegal instruction: 4 I'm writing a simple Matrix class, and I've defined, among others, an operator+ overloading and a move assignment.
It looks like something happens when the two of them interact, but I can't find where I am wrong.
Here's my code (I've deleted everything superfluous, and just left what is needed to show the bug).
The problematic line is at the end, in the main:
#include <iostream>
#define DEF -1

using namespace std;
//----- Matrix -----//
class Matrix{
private:
    float **matrixpp;
    int dim_r;
    int dim_c;

public:
    Matrix(int d_r = DEF, int d_c = 0);
    Matrix(const Matrix&);
    Matrix(Matrix&&);
    Matrix& operator=(Matrix&&);
    ~Matrix();

    Matrix operator+(const Matrix&);

    void print();
    void fill();

};

//----- Matrix -----//
Matrix::Matrix(int d_r, int d_c){

    if(d_r == DEF){
        do{
            cout << "number of rows: ";
            cin >> dim_r;
            if(dim_r <= 0){
                cout << "ERROR" << endl;
            }
        }
        while(dim_r <= 0);

        do{
            cout << "Number of columns: ";
            cin >> dim_c;
            if(dim_c <= 0){
                cout << "ERROR" << endl;
            }
        }
        while(dim_c <= 0);

    }
    else{
        dim_r = d_r;
        dim_c = d_c;
    }

    matrixpp = new float*[dim_r];

    for(int i = 0; i < dim_r; i++){
        matrixpp[i] = new float[dim_c];
    }

    for(int r = 0; r < dim_r; r++){
        for(int c = 0; c < dim_c; c++){
            matrixpp[r][c] = 0;
        }
    }
}

Matrix::Matrix(const Matrix& tocopy)
:matrixpp(tocopy.matrixpp), dim_r(tocopy.dim_r), dim_c(tocopy.dim_c)
{

    matrixpp = new float*[dim_r];

    for(int i = 0; i < dim_r; i++){
        matrixpp[i] = new float[dim_c];
    }

    for(int r = 0; r < dim_r; r++){
        for(int c = 0; c < dim_c; c++){
            matrixpp[r][c] = tocopy.matrixpp[r][c];
        }
    }
}

Matrix::Matrix(Matrix&& tomove)
:matrixpp(tomove.matrixpp), dim_r(tomove.dim_r), dim_c(tomove.dim_c)
{
    tomove.matrixpp = nullptr;

}

Matrix& Matrix::operator=(Matrix&& tomove){

    cout << "--- MA ---" << endl;
    matrixpp = tomove.matrixpp;
    dim_r = tomove.dim_r;
    dim_c = tomove.dim_c;

    tomove.matrixpp = nullptr;
}

Matrix::~Matrix(){

    if(matrixpp != nullptr){
        for(int i = 0; i < dim_r; i++){
            delete[] matrixpp[i];
        }
        delete[] matrixpp;
    }
}

Matrix Matrix::operator+(const Matrix& m){

    if(this->dim_r == m.dim_r && this->dim_c == m.dim_c){
        Matrix new_m(m.dim_r, m.dim_c);

        for(int r = 0; r < new_m.dim_r; r++){
            for(int c = 0; c < new_m.dim_c; c++){
                new_m.matrixpp[r][c] = this->matrixpp[r][c] + m.matrixpp[r][c];
            }
        }

        return new_m;
    }
    else{
        cout << "ERROR" << endl;
    }
}

void Matrix::print(){
    int temp;

    for(int r = 0; r < dim_r; r++){
        for(int c = 0; c < dim_c; c++){
            cout << matrixpp[r][c] << " ";

        }
        cout << endl;
    }
    cout << endl;
}

void Matrix::fill(){
    float temp;

    for(int r = 0; r < dim_r; r++){
        for(int c = 0; c < dim_c; c++){
            cout << "new value: " << endl;
            this->print();
            cin >> temp;
            matrixpp[r][c] = temp;
            system("clear");
        }
    }
}

//-------- Main -------//
int main(){

    Matrix m0;
    m0.fill();
    Matrix m1(0);

    m1 = m0+m0; // problematic line

    //m1.print();

}

It gives me the error when the move assignment is called to move the result of m0+m0 in m1.
If I compile my code with g++ on a Mac, the error given is just "Illegal instruction: 4", nothing more, nothing less.
If I do it on a Linux, the error given is:

In member function 'Matrix Matrix::operator+(const Matrix&)':
  p.cpp:90:16: error: use of deleted function 'constexpr
  Matrix::Matrix(const Matrix&)'
           return new_m;
                  ^~~~~ p.cpp:9:7: note: 'constexpr Matrix::Matrix(const Matrix&)' is implicitly declared as deleted because 'Matrix' declares
  a move constructor or move assignment operator  class Matrix{
         ^~~~~~

Thank you in advance!

A: The problem is, when using pre-C++17 standard, there is no copy elision guarantee, so returning a value from a function follows copy initialization semantics, which requires move-or-copy constructor to be defined. Defining your own move assignment operator disables automatic constructor generation (Class copy CTOR generation rules). In fact the compiler provided constructor is defined, but deleted. To solve this problem, you have to define a move or copy constructor, or both of them according to the rule of five (Rule of three/five/zero).
Also, I suspect that the original problem (illegal instruction) is caused by a lot of undefined behaviours in your code (e.g. no return statement in your assignment operator, and no return in operator+ else branch).

A: the main problem is your operator = didnt have any return.
overload the operator + like this:
Matrix operator+(const Matrix &A ,const Matrix &m)
{
if(A->dim_r == m.dim_r && A->dim_c == m.dim_c){
    Matrix new_m(m.dim_r, m.dim_c);

    for(int r = 0; r < new_m.dim_r; r++){
        for(int c = 0; c < new_m.dim_c; c++){
            new_m.matrixpp[r][c] = A->matrixpp[r][c] + m.matrixpp[r][c];
        }
    }

    return new_m;
}
else{
    cout << "ERROR" << endl;
}

and make it friend of your class.
and in the end of operator =  add return statement like this :
Matrix& Matrix::operator=(Matrix&& tomove){
        if(this != &tomove) {
        cout << "--- MA ---" << endl;
        matrixpp = tomove.matrixpp;
        dim_r = tomove.dim_r;
        dim_c = tomove.dim_c;

        tomove.matrixpp = nullptr;
    }
    return *this;
}


text:
Q: Writing triple integrals in spherical coordinates over nonspherical/nonconical regions Defining upper and lower limits of integration for $\rho$, $\theta$, and $\phi$ is relatively easy when writing a triple integral in spherical coordinates if the region of integration is defined by spheres and/or cones centered at the origin. However, this becomes more involved when the region is bounded by any other type of surface, such as a cylinder or a paraboloid.
The following is an example I came across recently, and I can't figure out how to represent the upper and lower bounds for $\rho$:

Here's what I've come up with so far:
$\iiint\limits_E\mathrm{d}V=\int_{\arcsin(\frac{1}{\sqrt{6}})}^{\pi}\int_0^{2\pi}\int_0^\sqrt{6} \rho^2 \sin(\phi)\,\mathrm{d}\rho\,\mathrm{d}\theta\,\mathrm{d}\phi + \int_{\pi}^{\arcsin(\frac{1}{\sqrt{6}})}\int_0^{2\pi}\int_0^{\textbf{???}} \rho^2 \sin(\phi)\,\mathrm{d}\rho\,\mathrm{d}\theta\,\mathrm{d}\phi$
How does one going about finding the equation for $\rho$ on the segment of the region of integration where it meets the sides of the cylinder?

A: $$x^2+y^2=1\to x^2+y^2+z^2=1+z^2\to\rho^2=1+\rho^2\cos^2\phi\to\rho^2=\frac{1}{\sin^2\phi}$$

A: Hint: see the right triangle with angle $\phi$.

A: FIRST EDIT: Accidentally took twice the area desired. Now revised.
SECOND EDIT Fixed two errors: (i) forgot Jacobian for $V_{2}$ and (ii) had to integrals flipped (with differential forms in right order)
So, here's another approach!
First thing you should note is this is azimuthally independent and we can immediately reduce this to a two-dimensional problem (maybe this helps?)
You can now look at twice the size of the region (symmetric about $z=0$) and break it up into 3 regions, two of which are the same (where $r = \sqrt{x^2+y^2+z^2} = \sqrt{6}$ over which our bounds will be invariant; that is the maximal distance in the radial direction is constant. For this problem, let's call this $V_{1}$ and for the region where this maximal distance is changing, let's call this $V_{2}$.
We get that one region has $V_{1} = \oint_{V_{1}} r^2 \sin(\theta)\; dr\; d\theta\; d\phi = \int_{0}^{2\pi}\int_{0}^{\arcsin(1/\sqrt{6})}\int_{0}^{\sqrt{6}} r^2 \sin(\theta)\; dr\; d\theta\; d\phi$ and the other $V_{2} = \int_{0}^{2\pi}\int_{\arcsin(1/\sqrt{6})}^{\pi-\arcsin(1/\sqrt{6})}\int_{0}^{\sqrt{1+6\cos^2(\theta)}}r^2 \sin(\theta)\; dr\; d\theta\; d\phi$.
We conclude by stating that $V = \frac{1}{2}\cdot (2V_{1}+V_{2})$.


text:
Q: Handling ASP postbacks from Javascript Widget I am trying to make a small, data-driven widget that is populated with data from a database on the fly.  I can load it initially just fine, but when the index of an ASP DropDownMenu is changed, the widget returns a 404.
This could be a symptom of how I am using the Javascript, or how I am using the ASP.  I honestly don't know for sure.
Javascript: http://pastebin.com/f127d6b84
ASP: http://pastebin.com/f38c73708
VB.NET codebehind: http://pastebin.com/f7881a903

A: If the postback is returning 404, I'd look at the url that you're sending the postback to.
http://webwidgetstest.reeceandnichols.com/rDeskWidgetMLSt.aspx?agentname=jendene

A: Also your widget has some security issues going on, namely SQL Injection.

Dim SelectString As String = "select
  ListingNumber, ListingSearchHitCount,
  ListingDetailHitCount,
  VirtualTourHitCount from
  FNIS.dbo.ListingHitCountCurrent,
  RAN.dbo.Heartland_Residential where
  Heartland_Residential.LIST_AGENT_1_ID
  = '" & Request("agentname") & "' and Heartland_Residential.MLS_Number =
  FNIS.dbo.ListingHitCountCurrent.ListingNumber
  and Heartland_Residential.Status =
  'A'"

This inline SQL statement is not parameterizing the Request("agentname") field.


text:
Q: How does one implement a Hadoop Mapper in Scala 2.9.0? When I migrated to Scala 2.9.0 from 2.8.1, all of the code was functional except for the Hadoop mappers.  Because I had some wrapper objects in the way, I distilled down to the following example:

import org.apache.hadoop.mapreduce.{Mapper, Job}

object MyJob {
  def main(args:Array[String]) {
    val job = new Job(new Configuration())
    job.setMapperClass(classOf[MyMapper])

  }
}

class MyMapper extends Mapper[LongWritable,Text,Text,Text] {
  override def map(key: LongWritable, value: Text, context: Mapper[LongWritable,Text,Text,Text]#Context) {

  }
}

When I run this in 2.8.1, it runs quite well (and I have plenty of production code in 2.8.1.  In 2.9.0 I get the following compilation error:
error: type mismatch;
found   : java.lang.Class[MyMapper](classOf[MyMapper])
required: java.lang.Class[_ <: org.apache.hadoop.mapreduce.Mapper]
job.setMapperClass(classOf[MyMapper])

The failing call is when I call setMapperClass on the Job object.  Here's the definition of that method:
public void setMapperClass(java.lang.Class<? extends org.apache.hadoop.mapreduce.Mapper> cls) throws java.lang.IllegalStateException { /* compiled code */ }

The definition of the Mapper class itself is this:
public class Mapper<KEYIN, VALUEIN, KEYOUT, VALUEOUT>

Does anyone have a sense of what I'm doing wrong?  It looks to me like the type is fundamentally correct: MyMapper does extend Mapper, and the method wants something that extends Mapper.  And it works great in 2.8.1...

A: Silly as it seems, you can work around the problem by defining the Mapper before the Job.  The following compiles:
import org.apache.hadoop._
import org.apache.hadoop.io._
import org.apache.hadoop.conf._
import org.apache.hadoop.mapreduce._

class MyMapper extends Mapper[LongWritable,Text,Text,Text] {
  override def map(key: LongWritable, value: Text, context: Mapper[LongWritable,Text,Text,Text]#Context) {
  }
}

object MyJob {
  def main(args:Array[String]) {
    val job = new Job(new Configuration())
    job.setMapperClass(classOf[MyMapper])
  }
}


text:
Q: parent directive scope → child directive scope i have angularjs problem.
I want like ng-repeat at $index.

*

*this is ng-repeat code  https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js#L3
look at the function 'updateScope'
var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength){
    // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
    scope[valueIdentifier] = value;
    if (keyIdentifier) scope[keyIdentifier] = key;
    scope.$index = index;
    scope.$first = (index === 0);
    scope.$last = (index === (arrayLength - 1));
    scope.$middle = !(scope.$first || scope.$last);
    // jshint bitwise: false
    scope.$odd = !(scope.$even = (index&1) === 0);
    // jshint bitwise: true
};

this code action
'parent directive scope variables -> child directive scope variables'
and you can do this
ng-repeat(...)
    {{$index}}

I want this action!!
I try, but do not action
this is my code
-jade
m-progressbar(min="0", max="300", ng-model="value")
    label {{$ratio}}

-js
$scope.value=72;

-directive
define([
    'jquery', 'underscore', 'angular', 'jquery-ui'],
function ($, _, angular) {
    var progressbarApp = angular.module('directives.progress_bar', []);
    progressbarApp
    .directive('mProgressbar', [function mProgressbar () {
     return {
            templateUrl: '/directives/progress-bar.jade',
            restrict: 'EA',
            scope: {
                min: '=',
                max: '=',
                model: "=ngModel"
            },
            link: function (scope, iElement, iAttrs) {
                var progressbar = $( "#progressbar" );
                var value = scope.model;
                scope.$watch('model',function (newValue, oldValue, scope){
                    var ratio = ((newValue - scope.min) / (scope.max - scope.min)) * 100;
                    progressbar.progressbar({value:ratio});
                    scope.$ratio = ratio;
                });
            }
        };
    }])
});

my code point is

*

*scope.$ratio = ratio;

please tell me a answer
ㅠoㅠ

A: I think you just forgot to add $ before ratio if you want to use {{$ratio}} in your template.
I mean you should write like below.
scope.$ratio = ratio;


text:
Q: OAuth fails on one host This is my code:
$key = "xxx";
$secret = "xxx";
$url = "https://oauth.withings.com/account";

$config = array(
    "siteUrl" => $url,
    "consumerKey" => $key,
    "consumerSecret" => $secret,
    "requestMethod" => "GET"
);
$consumer = new Zend_Oauth_Consumer($config);

try {
    $token = $consumer->getRequestToken();
} catch (Zend_Oauth_Exception $e){
    print $e;
}

And when I run this on my Mac (OSX 10.8, PHP 5.3.13, Zend 1.11.12) it works as it should.
But when I run it on my Linux server (Debian 6.0.5, PHP 5.3.3, Zend 1.10.6) it fails. The Zend documentation is very thin, but did something happen between 1.10 och 1.11 that makes the same code fail? The error message is as follows:
"exception 'Zend_Oauth_Exception' with message 'Could not retrieve a valid Token response from Token URL: '"
The error seems to suggest that no URL was sent along. Now, the "siteUrl" config option seems to be the same for Zend 1.10 and 1.11 so that can't be it, right?
When constructing the URL manually and using CURL on my Linux host, I get the correct response, so it can't be a network or blocking problem.
When changing the URL to say "/accounts" (i.e. to make it an incorrect URL), it returns HTML 404 code for both the Mac and Linux using this code.
I'm at a loss here. Anyone know how to troubleshoot this problem?

A: 404 means not found, so the server can't serve a document for the URL, shouldn't have anything to do with auth... Auth failures should be 403. If you only get the 404 with auth on, the 404 could be on redirect... You should try Charles proxy or similar to debug the requests.
Edit I reread and see the 404 was intentional... I would still try to debug the requests

A: I found the exception in the code for Zend_Oauth_Http it seems as tho the response is failing a scheme check, you might want to explicitly set the scheme.
the code:
 /**
     * Manages the switch from OAuth request scheme to another lower preference
     * scheme during a request cycle.
     *
     * @param  Zend_Http_Response
     * @return void
     * @throws Zend_Oauth_Exception if unable to retrieve valid token response
     */
    protected function _assessRequestAttempt(Zend_Http_Response $response = null)
    {
        switch ($this->_preferredRequestScheme) {
            case Zend_Oauth::REQUEST_SCHEME_HEADER:
                $this->_preferredRequestScheme = Zend_Oauth::REQUEST_SCHEME_POSTBODY;
                break;
            case Zend_Oauth::REQUEST_SCHEME_POSTBODY:
                $this->_preferredRequestScheme = Zend_Oauth::REQUEST_SCHEME_QUERYSTRING;
                break;
            default:
                require_once 'Zend/Oauth/Exception.php';
                throw new Zend_Oauth_Exception(
                    'Could not retrieve a valid Token response from Token URL:'
                    . ($response !== null
                        ? PHP_EOL . $response->getBody()
                        : ' No body - check for headers')
                );
        }
    }

Hope it helps.


text:
Q: Check group membership for a Linux user using Java Hi I can't figure out how to verify if a user belong to one o more group under Linux os using  java 7 nio library.
Can anyone help me about this issue?

A: You can try to read the file /etc/group.
I have developed a class to easily query this file:
public class UserInfo {

    public UserInfo() throws FileNotFoundException, IOException {
        this.group2users = new HashMap<>();

        FileReader fileReader = new FileReader(groupsFilePath);
        BufferedReader groupsReader = new BufferedReader(fileReader);
        while(groupsReader.ready())
        {
            try
            {
                String line = groupsReader.readLine();
                String [] tokens = line.split(":");
                String groupName = tokens[0];
                Set<String> users = group2users.get(groupName);
                if(users == null)
                {
                    users = new HashSet<String>();
                    group2users.put(groupName, users);
                }
                if(tokens.length>3)
                {
                    for(String uStr: tokens[3].split(","))
                        users.add(uStr);
                }
            } catch (Exception e) { continue; }
        }
        groupsReader.close();
        fileReader.close();
    }

    public boolean belongs2group(String user, String group)
    {
        Set<String> groupRef = group2users.get(group);
        if(groupRef == null) return false;
        return groupRef.contains(user);
    }

    private String groupsFilePath = "/etc/group";
    private Map<String, Set<String>> group2users;

}

This code maps the /etc/group file and keep a map of groups-their users set.
I have developed just one query method (belongs2group) but it is fairly easy to add methods to list all groups and/or all users.
This code is written using the old-fashioned-mainstream java io-api but I think it can be easily adapted to nio. Let me know if you need me to complete that step.

A: I do not think that reading local /etc/passwd or /etc/group could be good idea, because nis/ldap/ipa/pam can introduce other sources of infromation about group membership.
So, it depends on you environment and some other details. E.g.:
Groups for logged in (current) user
  com.sun.security.auth.module.UnixSystem().getGroups()

Hadoop
  org.apache.hadoop.security.UserGroupInformation.getBestUGI(null,"root").getGroupNames()

If neither is you case
You can create jna wrapper for getgroups(2).
Or improve UnixSystem and Java_com_sun_security_auth_module_UnixSystem_getUnixInfo  from jdk to take user id/name parameter.
Or rewrite some implementation of org.apache.hadoop.security.GroupMappingServiceProvider interface to not depend on hadoop environment.


text:
Q: Smooch to Line Message Giving Forbidden in Smooch Logs I am trying to integrate with Line using Smooch. Everything is fine except I am not able to receive the message from Smooch to Line APP.
Giving Forbidden Error.
Below are the logs from Smooch Dashboard.

*

*Line to Smooch----OK

*Smooch to HTTP ---OK

*HTTP(API) to Smooch --OK

*Smooch to Line -- Error: Forbidden
403 Forbidden - Your credentials are valid but you don't have access to the requested resource.
I am not sure which resource is not accessible.
Any help is highly appreciated.
Thank you

A: The membership plan was not allowed for PUSH Messages.Now it is working after membership upgrade on LINE.


text:
Q: Two queries in one transaction with rollback i want to cancel the two queries if there is a failure in one of two, is my tests that execute the first query although the second aground
public function testCommit(){

        $host = "localhost";
        $db = "agm_gs";
        $user = "root";
        $password = "";
        $conn;
        $conn = new mysqli($host, $user, $password, $db);

        $sql1 = 'INSERT INTO livreur (id_livreur, code_livreur, nom_livreur, pre_livreur)  VALUES (NULL, \'L001\', \'nom1\', \'pre1\')';
        $sql2 = 'INSERT INTO otherTable XXXXXXXXXXincorrect queryXXXXXXXX';

        try
        {
            $conn->begin_transaction();
            $conn->autocommit(FALSE);

            $conn->query($sql1);
            $conn->query($sql2);

            $conn->commit();
            echo 'Sucess transaction';
        }
        catch(PDOException $e)
        {
            $conn->rollback();
            echo ' Error transaction <br />' . $e->getMessage();
        }
}

and this my result of insert

A: Try this :-
$sql1 = 'INSERT INTO livreur
id_livreur, code_livreur, nom_livreur, pre_livreur)
VALUES (NULL, \'L001\', \'nom1\', \'pre1\'),
(NULL, \'L002\', \'nom2\', \'pre2\')';

INSERT statements that use VALUES syntax can insert multiple rows. To
  do this, include multiple lists of column values, each enclosed within
  parentheses and separated by commas.


text:
Q: Parameter passing in Visual Studio and GCC Parameter passing in Visual Studio.  Note how __m128 types are passed. Does it mean that no more than 4 __m128 arguments should be passed by value.
void good_function(__m128, __m128, __m128, __m128, __m128&);
void bad_function(__m128, __m128, __m128, __m128, __m128);

Does the same rule apply to GCC?
Thank you!
EDIT: Is it possible that the fifth argument of bad_function can be misaligned? I read somewhere that only 3 arguments are passed in registers (I guess it is Win32, not x64).

A: The parameter passing description you linked to is actually a x86_64 Windows ABI (application binary interface) description demonstrating how values will be passed to a function at the assembly level (i.e., how the compiler will translate a C-function call to assembly).  That being said, the first four arguments will be passed as pointers to the __m128 types using registers on a x86_64 platform.  Since the x86_64 platform has more registers to work with compared to it's 32-bit couterpart, this type of parameter passing is done in order to speed up functions calls since accessing arguments stored in registers will be faster than accessing argument values stored in memory on the stack like you would normally see with cdecl-style function calls on a 32-bit x86 platform.  If you go beyond 4 arguments, then the rest of the pointers to the __m128 type are stored on the stack.  So there are no "good function" or "bad functions" simply based on the the number of arguments.  In your example, both of your functions are good, it's just with the second example the rest of the arguments must use stack-space, as the number of available registers that can be used to pass values have been used up.
That being said, the pointers to the __m128 types will most likely be pointing to addresses allocated on the stack if they are automatic variables.  So either way, you'll most likely be using stack space, either to store the variables being pointed to, or to pass extra arguments to functions when working with larger-than-64-bit values and other aggregate types like classes, unions, arrays, etc.
As for GCC, since what you've referenced is actually a platform-dependent ABI implementation (in this case x86_64 Windows), what you'll see on other platforms will differ somewhat, although again, for most x86_64 OS's, they will use a series of registers to pass the first couple arguments of a function call.  So GCC will actually use the same rules as Visual Studio on x86_64 Windows, but on other platforms it will create different assembly based on the x86_64 ABI's for those platforms.

A: Argument passing is defined by a calling convention from the system ABI (Application Binary Interface).  Which ABI is in use depends on what target (os + hardware platform) you're compiling for.  See for example the AMD64 ABI, which *nix uses (roughly, there are a few minor variants I believe).

The link you provided was to an article on the Microsoft x64 calling convention parameter passing.  It notes:

*

*__m128 are always passed by pointer, not by value

*the first four integers or pointers are always passed in RCX, RDX, R8, R9
So given any function with only __m128 arguments, up to four will pass as pointers in registers, and any others will pass as pointers on the stack.  As Jason notes in another answer, these pointers will be pointing to values that are also likely on the stack.
__m128 and __m128 & (and also __m128 *) are likely equivalent in cost in the Microsoft x64 calling convention -- they all pass by pointer.

Reading through the AMD64 ABI, it looks as if the first 8 XMM registers (%xmm0 through %xmm8) are 128 bits wide and will take an __m128 by value.  So on systems that use the AMD64 ABI (e.g. gcc on linux), the first eight __m128 args will end up in registers.
In this case, it might make sense to pass the 9th through 15th __m128 args as references/pointers -- they could make use of the integer registers.  This would avoid copying them to stack.

I'm not sure which convention gcc on windows (e.g. mingw) uses.  Presumably it must use Microsoft x64 convention if it is interacting with other libraries.

If you're curious, though, I'd highly recommend performing a few experiments and looking at the disassembly -- gcc's -S option is great for this!  If you're in Visual Studio you can use the disassembly window in the debugger.
It's always good to be peaking under the hood a bit, even if you're not fully understanding what's going on.  You'll start seeing patterns and can ask questions or research what you see.


text:
Q: Is it correct to say: "out of nostalgia for [someone]"? I'm a bit unsure because I didn't find that usage on Google.
Example sentence:

She came back to New Work out of nostalgia for Mark.

A: While that's absolutely fine grammatically and technically fine semantically, it's probably not the word you're looking for. Nostalgia, while it can absolutely be for a person, isn't usually felt for a person.
Perhaps you meant that she missed Mark? Without context we can't tell. If you're sure nostalgia is what you mean though, the sentence is fine.


text:
Q: Is it worth to sort array before looking for element? We have array with 1000000 elements inside and we will need to find 100 times some value.
There are two options: first - sort it with heapsort and then search by binary search, second - sequential search.
Without calculations I would say that first option is better but...
In second option in worst case we have num_of_elem * num_of_search = 100 * 1000000, in first we have (heapsort is O(nlogn)) so (1000000*log(1000000))*100*log(1000000) = 1000000*20*100*20. That mean that second option is better 400 times.
Am I correct here?

A: Remember that when the running time of an algorithm is specified using O-notation, it is
'asymptotic'. Overly simplified, a running time of O(log n) means that your program performs c*log n steps, where c is some constant that you don't actually know. It could be quite large. Therefore, using real numbers in the formulas for running time will not give you accurate results.
Here are two approaches to find an answer to your question:

*

*you could run a bunch of tests, for different inputs, to compare the two methods. Choose whichever performs the best way for your application.

*You can do a slightly more in-depth theoretical analysis:
Let's say there are n elements in the array you want to search in,
   and you want to find k elements. So in your example, n = 1000000
   and k = 100.
If you sort and use binary search for each element,
   you use O(n log n) time for sorting and O(k log n) time for
   searching, for a total of O(n log n + k log n). If you do linear
   search for each of the k elements, you use O(kn) time.
Now, if k = O(log n), then O(kn) becomes O(n log n), and using the two methods
   should be equally fast (asymptotically). However, if k = Omega(log n) (i.e, k is
   bounded from below by log n), then n log n = O(kn), and sorting before searching is faster (asymptotically).
What this means is that you can use some test of the type k < c log n for some constant c and use the linear search method if the test succeeds and the sort+search method otherwise. The exact value of c would have to be defined using tests and benchmarks, again due to the running times being asymptotic.
BONUS
There is another fun algorithm you can use if you know all the k values beforehand. Let A be the n numbers you want to search in, and B be the k numbers you want to search for.

*

*Sort B (O(k log k) time )

*Iterate over A, and for each element e, do a binary search in B for e ( O(n log k) time in total)

This way you will determine which numbers in B are also in A, and it will take O(n log k + k log k), which is asymptotically faster than (or as fast as) both the other methods if k = O(n) (for instance if k < n).


text:
Q: Spatstat, Interpolating data points in R I have covariate data which is rainfall. I also have a point pattern which represents settlements on a map within a specific area. I have the problem that part of my area of my region contains sea, however there are no settlements on the sea but the rain data does involve the sea area. I wish to set the rain values to those of a nearby point on land.
Any idea how to do this?
Maybe to find which rainfall x and y coordinates represent the sea i want to create a data frame that contains the centre points of all the square kilometres and then import the rain values for the locations which match and see which locations have no values. But im stuck. Here is my code:
> window<- data.frame(Lon=c(-1.560367, -1.078330 ), Lat=c( 50.576342, 51.243823))
> coordinates(window) <- ~Lon + Lat
>
>
> proj4string(window) = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")
>
> proj4string(winch2) <- latlong
>
> window <- spTransform(window, bng)
>
> (floor (coordinates (window) / 1000) + 0.5) * 1000
>
> W2<- owin(c(431500,464500), c( 75500, 149500))
>
> Region<-Settlements[W2]     ###Settlements is my data
>
> rain_im[W2]    ###rain is my covariate as a pixel image
>
> as.data.frame(rain_im[W2])  ###Converted this into a pixel image
>
> `summary(Region)`

Marked planar point pattern:  308 points
Average intensity 1.261261e-07 points per square unit

Coordinates are given to 2 decimal places
i.e. rounded to the nearest multiple of 0.01 units

marks are numeric, of type 'double'
Summary:
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max.
   2.375   19.000   47.500  103.029   88.364 5500.000

Window: rectangle = [431500, 464500] x [75500, 149500] units
Window area = 2.442e+09 square units

A: Please describe your data more clearly. You say you have "covariate data which is rainfall": what format is this data? Is it a pixel image (whose pixel values are rain amounts), or is it a data frame of rain gauge locations and recorded rain amounts? You have some values of the rain covariate at pixels which lie over the sea: what do you want to do with such values? What data do you have that tells you which locations are in the sea and which are on land?
If you had polygon data defining the coastline, you could convert this to an owin window object, say Land. Then if your rainfall data is a pixel image Rain you could just do ClipRain <- Rain[Land, drop=FALSE] to restrict the pixel image to the land area (assigning NA to any pixel over the sea).
If you have rainfall data at some locations, say a point pattern RainRecords with marks which are the rainfall values, then Smooth(RainRecords, sigma) is a pixel image containing a kernel smoothed interpolation of rainfall, and nnmark(RainRecords) is a pixel image in which each pixel value is the rainfall at the nearest recorded location. By clipping or sampling these images you can probably get what you need.


text:
Q: How to draw circle at a specific area? I wrote a simple C program to make a circle. It follow mid-point circle drawing algorithm.
This is my code right now:
#include <stdio.h>
#include <conio.h>
#include <graphics.h>

void main()
{
   int gd = DETECT, gm ;
   int r, x, y, xc, yc, P;

   initgraph(&gd, &gm ,"..//bgi");
   clrscr();

   printf("\n Enter the radius : ");
   scanf("%d", &r);
   printf("\n Enter the centre as X and Y : ");
   scanf("%d%d", &xc,&yc);

   x = 0;
   y = r;
   P = 1 - r;

   do
   {
     putpixel( x,  y, WHITE);
     putpixel( y,  x, WHITE);
     putpixel(-x, -y, WHITE);
     putpixel(-y, -x, WHITE);
     putpixel(-x,  y, WHITE);
     putpixel( y, -x, WHITE);
     putpixel( x, -y, WHITE);
     putpixel(-y,  x, WHITE);

     if(P < 0)
     {
       x = x + 1 ;
       P = P + (2 * x) + 1 ;
     }
     else
     {
       x = x + 1 ;
       y = y - 1 ;
       P = P + (2 * x) - (2 * y) + 1 ;
     }
  }while(x < y);

    getch();
    closegraph();

}

The problem is that the output seems to go in the top left corner and I can't see the whole output. Is there any way I can set the output to show up at specific area of my screen or something like that?
Screen shot of my current output:

EDIT: After the points suggested by LPs and koldewb, I re-wrote the whole code and now, I'm getting output in center, I mean, the output is much better. I added different color to see which quadrant was plotted... Here is the code :-
#include<stdio.h>
#include<conio.h>
#include<graphics.h>

void main()
{
   int gd = DETECT , gm ;
   int r , x , y , xc , yc  , P;

   initgraph(&gd , &gm ,"..//bgi") ;

   printf("\n Enter the radius : ") ;
   scanf("%d" , &r) ;
   printf("\n Enter the centre as X and Y : ") ;
   scanf("%d%d" , &xc,&yc) ;

   x = 0 ;
   y = r ;
   P = 1-r ;

   do
  {
     putpixel(xc+x,yc+y,WHITE) ;
     putpixel(yc+y,xc+x,WHITE) ;
     putpixel(xc-x,yc-y,WHITE) ;
     putpixel(yc-y,xc-x,WHITE) ;
     putpixel(xc-x,yc+y,WHITE) ;
     putpixel(yc+y,xc-x,WHITE) ;
     putpixel(xc+x,yc-y,WHITE) ;
     putpixel(yc-y,xc+x,WHITE) ;

     if(P<0)
     {
       x = x + 1 ;
       P = P + (2*x) + 1 ;
     }
     else
     {
       x = x + 1 ;
       y = y - 1 ;
       P = P + (2*x) - (2*y) + 1 ;
     }
     } while(x<y) ;

     getch() ;
     closegraph() ;
  }

I'm not sure if this would be of any help to anyone, But, well, I might as well post the updated code.
Screen shot of my Updated output:

A: User inserts coos of circle center into xc an yc variables, but your code always start with x=0 and y=r.
I cannot test the code, but probably you can add xc and yc offset each time you calculate a new x and y.


text:
Q: Fill empty rows in Pandas with value below from same column I can see countless posts asking on to fill empty rows with the above value or specific values, but none about filling rows with a value of the same column but below.
I would like to go from this table:

from a table with all lines above 3 filled with 3, and all lines above 2 and below 3 with 2, etc.
Thanks a lot!
EDIT: Found it!
df[col] = df[col].bfill() - as simple as that :)

A: Try this one:
import pandas as pd
import numpy as np

df = pd.DataFrame([[8, 2, "", 0],
                   [3, 4, "", 1],
                   [5, 3, "", 0],
                   [2, 3, 10, 4]],
                  columns=list("ABCD"))

df= df.replace(to_replace="", method='bfill').values
print(df)


text:
Q: Split string array using comma delimeter in java I have a string array -->
string[] arr={"CSE01A","ECE02B","MECH03C"};
Now I have to print course=CSE01, ECE02,MECH03
and grade= 'A','B','C'
I tried to use split() using the comma delimiter but that is not working for an array of strings..
Please let me know how to do this.

A: That's because there's no comma delimiter in what you're trying to split.
You need to loop through the array elements and grab the last character of each string.
for (String s : arr) {
    int l = s.length();
    String course = s.substring(0, l-1);
    String grade = s.substring(l-1);
}

For completeness:
List<String> courses = new ArrayList<String>();
List<String> grades = new ArrayList<String>();
for (String s : arr) {
    int l = s.length();
    courses.add(s.substring(0, l-1));
    grades.add(s.substring(l-1));
}
System.out.println(StringUtils.join(courses, ", "));
System.out.println(StringUtils.join(grades, ", "));

A: Java's split() takes a String and splits it into an array, e.g. ("abc,def,ghi").split(",") gives you a String[] with "abc", "def", "ghi". You need to take each String in your array and split the last letter (the grade) off. If you just want to print it out:
for(String s : arr) {
    String course = s.substring(0,s.length()-1);
    String grade = s.substring(s.length()-1);

    System.out.println("Course: "+course+" Grade: "+grade);
}

A: You don't need to split, you must combine the array elements to an string.
    String[] arr={"CSE01A","ECE02B","MECH03C"};

    StringBuilder coursesBuilder = new StringBuilder();
    StringBuilder gradeBuilder = new StringBuilder();
    String[] arr = new String[0];
    for (int i = 0; i < arr.length; i++) {

        String course = arr[i].substring(0, arr.length - 1);
        String grade = arr[i].substring(arr.length - 1);
        coursesBuilder.append(course);
        gradeBuilder.append("'" + grade + "'");

        boolean hasNext = (i + 1) < arr.length;
        if (hasNext) {
            coursesBuilder.append(", ");
            gradeBuilder.append(", ");
        }
    }

    String courses = coursesBuilder.toString();
    String grades = gradeBuilder.toString();

A: split() is Sting's method that accepts string and creates array. If you want to use it you should say str.split("\\s*,\\s*") - this is safe for spaces.
But you already have array, so you just want to print it. You can use Arrays.toString(arr).

A: the array is already split, it is not a string.  In order to print you would loop through the elements:
for ( String courseAndGrade : arr ) {
    // split the course and grade:

    System.out.println( ... );
}

A: Your course list isn't a string that contains commas so you can't simply "split" them. You can  iterate over an array with code that looks like this:
for(int i=0; i < arr.length; i++){
    String packedString = arr[i];
}

on each iteration of the loop, the variable packedString will contain your course number and grade (i.e. CSE01A on the first iteration of the array). So you just need to apply an method to unpack the data. If a grade is always just a single character, you can use substring to parse out the last character and everything before it, but if you have multi-character grades (A-, for instance) you'll need to do something a little more complex.
I hesitate to expand further as this sounds like homework.

A: The problem is, you don't have a delimiter for each course, the course and the grade are together in the same String.
Since you know that the grade is at the end, you could do something simple like this:
String[] arr = {"CSE01A","ECE02B","MECH03C"};
String[] courses = new String[arr.length];
char[] grades = new char[arr.length];

for (int i = 0; i < arr.length; i++) {
    courses[i] = arr[i].substring(0, arr[i].length() - 1);
    grades[i] = arr[i].charAt(arr[i].length()-1);
}

At the end, you'll have a String[] with the courses and a char[] with their respective grades.

A: This will iterate through your array and output your courses and grades:
StringBuilder courses = new StringBuilder();
StringBuilder grades = new StringBuilder();
String delimiter = "";

for (String s : arr) {
    courses.append(delimiter).append(s.subSequence(0, s.length() - 1));
    grades.append(delimiter).append("'").append(s.substring(s.length() - 1)).append("'");
    delimiter = ",";
}

System.out.println("Courses: " + courses.toString()); // prints CSE01,ECE02,MECH03
System.out.println("Grades: " + grades.toString()); // prints 'A','B','C'

A: You could use Guava to help simplify the effort to handle the string transformations and to stitch the results together:
package testCode;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

public class TestMain {

    static Joiner joinWithComma = Joiner.on(", ").skipNulls();

    private static String getCourses(Iterable<String> fromArray) {
        return joinWithComma.join(Iterables.transform(fromArray,
                new Function<String, String>() {
                    @Override
                    public String apply(String arg0) {
                        return arg0.substring(0, arg0.length() - 1);
                    }
                }));
    }

    private static String getGrades(Iterable<String> fromArray) {
        return joinWithComma.join(Iterables.transform(fromArray,
                new Function<String, String>() {
                    @Override
                    public String apply(String arg0) {
                        return arg0.substring(arg0.length() - 1, arg0.length());
                    }
                }));
    }

    public static void main(String[] args) {

        String[] arr = { "CSE01A", "ECE02B", "MECH03C" };

        System.out.println(getCourses(Lists.newArrayList(arr)));
        System.out.println(getGrades(Lists.newArrayList(arr)));

    }
}

Output:
CSE01, ECE02, MECH03
A, B, C
I have a feeling, though, that this is way over the top for what might be a simple homework assignment on iterating through arrays and string manipulation.


text:
Q: Are get parameter in https connection encrypted?
Possible Duplicate:
With HTTPS, are the URL and the request headers protected as the request body is?

When establishing a https connection, an ssl handshake takes place and secret key and the encryption algorithm are shared. Then the data sent is encrypted and cannot be subject ot man in the middle attack or eaves dropping.
My question is what type of data is encrypted. Are the url parameters sent in a get request also encrypted. I am asking this because, they are not included in the body. And are all the attributes that are set in the request headers encrypted?

A: Yes, they are. Absolutely everything is encrypted.


text:
Q: Best method of creating two classes that have the same variables, but with different access methods I know that by extending a class you can create a child class that has access to all of the variables and methods of its parent. However what I'm trying to achieve is one class with a number of required variables that are all editable from the editor window; and another that has all of those same variables, but with some that are not not editable and, instead have default values.
My specific example is a dialogue class that has a number of public variables:
public class Dialogue : MonoBehaviour
{
    // Public variables for determining whether the dialogue has automatic or manual triggering; and whether it's single use
    public bool isAutomatic, isSingleUse;

    // Public variables for determining whether an unlocked discovery is required in order to trigger the dialogue at all
    public bool requiresDiscovery;
    public string requiresDiscoveryType;
    public int requiresDiscoveryId;

    // Public lists for general conversations and default topic sentences
    public List<Conversation> generalConversations;
    public List<Sentence> defaultTopicSentences;

    // Public variable for holding the optional topics in our conversation (can be left empty if desired)
    public List<Topic> topics;

    /* Methods here... */

}

The above class is used in both Dialogue events and also Cutscene events (which can contain multiple dialogues with character movements and other more complicated stuff). It is perfect for the dialogue events, but I could do with creating a variant class where some of the variables (e.g. isAutomatic, isSingleUse, requiresDiscovery etc..) are set automatically to false with no option to alter them in the editor. This is because some of the variables are not relevant to Cutscene events and could potentially cause issues if set to true.
What I'm getting stuck with is whether I can use Dialogue as a parent and somehow override the public access of certain variables in the child class; or if there's another way this has to be done. If someone could give me a code example of how I can achieve the above that would be really helpful.
Thanks in advance.

A: Stick with inheritance, otherwise you will either end up with code duplication with the same properties in two classes, or trying to botch together a single class for two uses, which goes against SRP. Having them separate will make your life a lot easier.
By doing that, you will be able to have multiple Dialogue classes in a Cutscene, but still have the features of a Dialogue in a Cutscene itself.
Create a new class called Cutscene and set whatever Dialogue variables you need when creating a new instance of Cutscene.
public class Cutscene : Dialogue
{
     // Set whatever you need to false to prevent any issues
     public Cutscene() {
          this.isAutomatic = false;
          this.isSingleUse = false;
          this.requiresDiscovery = false
          // etc...
     }
}

If you want to learn more about inheritance, MSDN has a great page on it


text:
Q: Detect whether a templated function accepts a callback with a certain signature Currently I'm trying to create a statical check using sfinae which checks whether a callback taking function (consider [](auto&& callback) { callback(tag1{}); }) is accepting a callback with a certain signature:
#include <tuple>
#include <type_traits>

template <typename... Args> struct acceptor {
  void operator()(Args...) const {}
};

template <typename T, typename Args, typename = std::void_t<>>
struct testit : std::false_type {};

template <typename T, typename... Args>
struct testit<T, std::tuple<Args...>,
              std::void_t<decltype(std::declval<T>()(acceptor<Args...>{}))>>
//                                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Try to invoke the continuation with a callback of the given signature
    : std::true_type {};

struct tag1 {};
struct tag2 {};

int example() {
  auto continuation = [](auto&& callback) { callback(tag1{}); };

  std::true_type accept = testit<decltype(continuation), std::tuple<tag1>>{};

  std::false_type doesnt_accept = testit<decltype(continuation), std::tuple<tag2>>{};
  return 0;
}

Demo (GCC Explorer)
But it seems like that the evaluation of continuation(callback) doesn't make use of SFINAE since clang reports an error:
<source>:21:45: error: no matching function for call to object of type 'acceptor<tag2>'
auto continuation = [](auto&& callback) { callback(tag1{}); };

Is there any other possibility to make the check above work?
Note: Even when we make the return type of the continuation dependent on the callback ([](auto&& callback) { return callback(tag1{}); }) it doesn't work.


text:
Q: Linking MySQL Workbench to my Remote Server  I've just downloaded MySQL Workbench.
But I don't quite understand how to syn this with the databases on my remote server.
Work bench asks for "hostname" so I provided the hostname of my remote server. I designate port 3306.
I then provide a username. This is the username I use when I log into PhpAdmin -- should I be using a different one?
Then I provide a password, again the same one I use for PhpAdmin.
But this doesn't work.
Oddly, the error always tells me my user name is: username@current_network_im_using_to_access_the_internet
But this doesn't seem right -- on phpAdmin my user name says username@localhost.
I'm not quite sure what to do.
Can you help me?

A: MySQL treats logins as specific to the host they originate from. You can have a different password from your home machine than the one you use on the server itself, and you can have entirely different sets of permissions granted to the same username from different origin hosts.
On PHPMyadmin, the database is running on the same server as the web server, and therefore refers to itself as localhost, with IP 127.0.0.1.  Your machine on which Workbench is installed must access MySQL with different credentials than your username@localhost.  The server requires you to grant access to your username from any host you intend to connect from.
In PhpMyAdmin, you will need to grant access to your database from the remote host: (See also Pekka's answer for how to allow connections from any host)
GRANT ALL PRIVILEGES on dbname.* TO yourusername@your_remote_hostname IDENTIFIED BY 'yourpassword';

To see all the grants you currently have on localhost so that you can duplicate them for the remote host:
SHOW GRANTS FOR yourusername@localhost;

Additionally, the MySQL server needs to be setup to accept remote connections in the first place.  This isn't always the case, especially on web hosting platforms.  In the my.cnf file, the skip-networking line has to be removed or commented out. If there is no skip-networking line, you must comment out the line:
bind-address = 127.0.0.1

...then restart MySQL.

A: Your phpMyAdmin seems to run on the same server as the database itself.
Therefore, it can use username@localhost to connect to the server.
You would need to make mySQL accept connections from outside localhost by adding another user username@% (% meaning "any host").
Note however that this is not good practice - if you have a static IP, consider limiting access to that one address.

A: If you are planning to use MySQL workbench for managing MySQL databases and tables in a remote server, I am recommending connect over SSH. by following many articles and forums I tried many other ways by adding bind-address, adding a new user to MySql with uname@host with all privileges, etc. but in my case, all those steps were wasting of time,  those steps will be useful if your server is so strict.
Follow the steps below.

*

*Click on the + button beside the MySql connections Title to add a new connection.

*Enter Connection Name(Whatever you need).

*Select connection method Standard TCP/IP over SSH.

*Enter the SSH details like Host(IP/Domain), Username, and Password. (SSH using Password Authorisation should be enabled in server)

*MySQL host details like Hostname(By Default localhost or 127.0.0.1), port(3306), MySQL username and password.

*Then click on test connection.

A: To get connected to MySQL Workbench installed on Windows 10, I found the above post written by Shihab and edited by Dharman useful to get connected instantly.  But, here are the things that I did to connect via TCP/IP which was also useful for me to connect to MySQL via my code:
Step 1:Changing the bind address in MyMySQL
On the Ubuntu machine (where my MySQL Community Server is installed) using Putty, I changed the mysqld.cnf file with the command "sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf".  Using arrow keys, I scrolled down to the row with "bind-address" and I changed it from "127.0.0.1" to "0.0.0.0". I used ctrl+x to close and entered "Y" to save the file.
Step 2: Restart the MySQL Server
You have to restart the MySQL server. To do that, you can restart using the command "sudo service mysql restart".  If you are unable to restart, kill MySQL Process. First find the Process ID of MySQL  using "ps ax | grep mysql" then kill the process using "sudo kill [process_id]"
Step 3:Changing the Firewall Settings of Ubuntu
To allow outside connections, you should change the settings of the firewall.  I used UFW (Uncomplicated FireWall) to change the settings. Start the UFW if it is not yet enabled using the command "sudo ufw enable".  Check the status using "sudo ufw status". Now, enable connections to the MySql port 3306 (default) from a particular IP address using the command "sudo ufw allow from [ip_address] to any port 3306" or you can allow all connections to the port from any IP address is your IP address keeps changing using the command "sudo ufw allow mysql"
Step 4: Creating a user in MySQL
I created a user in MySQL to avoid logging in using the root using the command "CREATE USER 'user_name'@'your_IP_Address' IDENTIFIED BY 'password';
Step 5: Connect via the MySQL workbench

*

*Click Database

*Click Connect to Database

*In the Connection Method field, select "Standard TCP/IP"

*In the Hostname, enter your server IP address

*In the Server Port, leave as it is "3306" unless you have changed the port of MySql in your server

*In the Username, enter your server user name

*In the Password, enter your server password

*Click Ok

Step 6: If you are still not able to connect

*

*On your server, disable the firewall and check if you are able to connect

*If you are able to connect, reset the firewall with the command "sudo ufw reset" (Make sure you take a copy or screenshot of all the connections in the firewall.  You can get all the ports with the command "sudo ufw status").  If you are unable to connect go to step 9.

*Now allow each and every port that was earlier present with the command "sudo ufw allow 80", "sudo ufw allow mysql", etc.

*Disable and enable the firewall using the commands "sudo ufw disable" and "sudo ufw enable" respectively.

*Check if you are able to connect via the workbench

*If you are still not able to connect, just restart the server using the command "sudo reboot"

*Once the reboot is complete, you should be able to connect to the MySQL server.

*If you are still not able to connect, use something like nmap software to check for all the open ports and see if you can see 3306.  If you can't see the port, you have to debug what is stopping the firewall from blocking your MySQL connections.

*Check your MySQL privileges with the command "show grants for 'user_name'@'localhost';".  If you are able to see the grants, that means your IP address is not allowed.  Try to update the grants with your IP address with the following command "GRANT ALL PRIVILEGES ON database.* TO 'user'@'yourremotehost' IDENTIFIED BY 'newpassword';" or GRANT ALL PRIVILEGES ON database.* TO 'user'@'yourremotehost' IDENTIFIED BY 'newpassword'; (To allow connections from everywhere)

If the above steps don't work and still you want to connect via a quick hack
Premium Hack Step: Logging in using MySQL Workbench via SSH

*

*Click Database

*Click Connect to Database

*In the Connection Method field, select "Standard TCP/IP over SSH"

*In the SSH Hostname, enter your server IP address

*In the SSH Username, enter your server user name

*In the SSH Password, enter your server password

*In the SSH Key file, don't do anything

*In the MySQL Hostname, leave it as it is "127.0.0.1"

*In the Server Port, leave as it is "3306" unless you have changed the port of MySQL in your server

*In the Username, enter your MySQL username that you created in the previous step

*In the Password, enter your MySQL password that you created in the previous step

*Click Ok
Now, you should be able to enter your MySQL Workbench

Other useful commands:

*

*To check if MySQL is running: systemctl status mysql

*Entering MySQL: sudo mysql -u [username] -p  (Default username is root and password is nothing (just press enter key))

*To check the status of ufw: sudo ufw status

*To check the ufw status numbered for deleting a port access: sudo ufw status numbered

*To delete a ufw port access: sudo ufw delete [number_of_the_port_to_be_deleted_from_previous_command]

*To start MySQL service: sudo service mysql start

*To update all packages: sudo apt update

*To uninstall MySQL: sudo apt-get remove mysql*

*To install MySQL
Step 1: sudo apt update
Step 2: sudo apt install mysql-server
Step 3: sudo systemctl start mysql.service
Step 4 (if something is broken during installation): sudo apt --fix-broken install


text:
Q: Como centralizar o cabeçalho  de uma tabela HTML com css? Minha tabela:

    Ação

    Comedia

    Terror

    Drama

    Romance

A: Como já mencionado pelo @Andorinha, antes de mais nada vamos trocar os ids por class:
...
Ação
...
Comédia
... etc

Apesar de a maioria dos browsers por padrão centralizarem os th, isto não é garantido que sempre vá acontecer (até por uma possível definição anterior em outro css). Assim, o ideal é acrescentar uma entrada explícita no css que garanta isso:
.cabecalho {text-align: center}

A: Como o @bfavaretto disse no comentário, corrigindo o html:
Resposta em visualização aqui
E também é inválido usar o id cabecalho para todos os  mude para class:

        Ação

        Comedia

        Terror

        Drama

        Romance

Veja o porque não usar o mesmo ID para vários elementos, aqui Class e Ids


text:
Q: How to disable a link based on a variable value in HTML? I have piece of code in HTML.
I need to open a pop up based on a value in the variable?
if variable value is true then it should be clickable but, in case of false it should not perform any action. Below is the code i am using.
So "about" is a variable which is either true or false.
project.about = true/false
   <a title="Refresh Project"
   ng-click="refreshProjectPopUp(project)"

I am not able to think how to  add this condition here?
Thanks in advance.

A: You can try this
<a title="Refresh Project"
   <a *ngIf="project.about==true"
   ng-click="refreshProjectPopUp(project)"

A: You can use the ternary operator to bind the function. When the value is true the function will be called and if the value is false then nothing will happen.
Try to change the value of the project.about from true to false.
Working fiddle here

<!DOCTYPE html>

    link