text:
Q: Creating single application with multi dbs I don't think I described the problem properly through the title. However, I have a .NET Core Web Api application which all of my tenants will use. As well as the single API instance I have a single frontend Vuejs instance which all tenants can use as a 'portal'.
These tenants each have their own database. Currently the api's all require a header of tenant within a request to specify which tenant the request is being made for, this will then create a db connection according to the tenant from the request.
You can't pretend your a different tenant as all of the api's require authorization against a tenants db.
I guess the thing I'm stuck on is determining the tenant a user belongs to when logging in using the single frontend vuejs instance. It's not a problem when it comes to just using the api's as the tenant can be sent via the header of the request, but im not sure how to resolve the tenant in order to determine the correct db to use by a sign in which will be used across all tenants.
Apologies if I didn't explain the problem well, it's a tricky situation.

A: If all the DB's have the same structure I would use only one database and use the tenant id as index, that way you have only one connection in your project and the problem is solved. Otherwise you will have to check all databases every time a user tries to login.

A: where are your users live? You might have to extract users info into a separate identity database that contains info which user belongs to which tenant. That can be as simple as Key-Value store: email->TenantId. So for login you'll have to look up this tenantId, then authenticate against user info in the correct tenant database.
Or you can pull all your user information into a single database that contains all the info about the user, including password hash. You can also use some identity provider like Auth0 or IdentityServer - these have ability to add user properties like TenantId.
Whatever the scenario you choose, you'll have to have a single place where you map user to a tenant. Looking through multiple databases for user info is not ideal.
If your Vue.js app is using your backend API you can set TenantId in cookie or other way to persist this info between calls.

A: I would use a similar solution like this
https://docs.servicestack.net/multitenancy

ServiceStack provides a number of ways of changing the database connection used at runtime based on an incoming Request. You can use a Request Filter, use the [ConnectionInfo] Request Filter Attribute, use the [NamedConnection] attribute on Auto Query Services, access named connections in Custom Service implementations or override GetDbConnection(IRequest) in your AppHost.

Whether you use WebAPI or ServiceStack is upto you (I, personally, am a fan of the latter). Basically, what you have to do is create an interface IForTenant and have your service-models implement them.
public interface IForTenant
{
    string TenantId { get; }
}

You'll need a DB Connection Factory that takes tenant id as an argument to return an IDbConnection instance. Then you create a request filter, that checks if a request is of type IForTenant and get the correct IDbConnection instance from the aforementioned factory.


text:
Q: Set Mediaelement Source to Relative URI in WPF Code I have a project that is WPF4 and VB.net. I'm trying to set a mediaelement's source using a mediatimeline (inside a storyboard construct), so I can loop the mediaelement. However, I cannot figure out how to set the source to a relative URI in WPF. I know how to do it in VB.net, but by setting the source there, I can't have the media looping.
How do I set the source of a mediaelement in a mediatimeline to a relative URI?

A: See the MSDN reference to the MediaElement.Source property. Make sure the media file property "Copy To Output" is set to "Copy Always" or "Copy If Newer".
Example:
<MediaElement x:Name="xyzName" Width="Auto" Height="Auto" Source="MediaFolder/YourMediaFile.mov" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to run C++ program or any other program using spawn in node.js along with input file from which stdin is to be read I am trying to run a C++ program from within node.js using the spawn method. The normal way when I try to run just the .exe file by specifying: pchild = spawn(exefilename) works but I am looking for a way to run the exe so that the stdin is read from input file. In cmd, the command is : exefilename < inputfilename. I am looking for an equivalent in spawn.

A: I've tried something like this before . In Node.js v5.3.0 Documentation, I didn't see a straightforword answer  . The code below works for me , maybe not a elegant solution , you could take a look:
    var fs = require('fs');
    var cp = require('child_process');
    var cprocess = cp.spawn('exefilename');

    fs.readFile('inputfilename',function (err, data){
        if(err) throw err;

        //redirect standard input from inputfile
        cprocess.stdin.write(data);

        //end of standard input
        cprocess.stdin.end(function(){
            console.log('end of stdin');
        });

        //listen on your cprocess closing
        cprocess.on('close',function (code){
            console.log('ps process exited with code ' + code);
        });
   });


text:
Q: How to keep Authentication header with redirect using NGINX ingress annotations I have an nginx ingress controller for my kubernetes cluster. I have a need to add a permanent redirect to an ingress which I can successfully do with
nginx.ingress.kubernetes.io/permanent-redirect: "http://www.example.com"

This works great, except for the fact that path I'm redirecting is used for by users that send POST requests including an Authorization header.
My understanding is that by default (for security reasons) the header would get stripped out. However, I'm redirecting the post request from one server to another on the same domain.
Is there a way to add the necessary instructions to pass the Authorization header along with the redirect?
Thanks!

A: This is what I did to overcome the stripping of the Authorization header:
annotations:
  ... your other annotations
  nginx.ingress.kubernetes.io/configuration-snippet: |
    proxy_set_header Authorization $http_authorization;

This will force the setting of a new Authorization header that reads it's value from the actual authorization header.
I have not tried this with the external authorization though, only with basic auth.

A: You can use external authentication to point your original url as an auth-url
annotations:
    nginx.ingress.kubernetes.io/auth-url: https://original/user/passwd

Also take a look at this example
Hope this will help


text:
Q: "Measure" of induction for cut-elimination in sequent calculus I'm not very familiar with proof thoery, so I'm in trouble understanding different versions of the proof of the Cut-elimination Theorem for sequent calculus.
In Sara Negri & Jan von Plato, Structural Proof Theory (2001), page 35 :

the proof of admissibility of cut is by induction on the weight [amounting to the length of a formula] of the cut formula and a subinduction on the sum of heights of derivations [where the height of a derivation is the greatest number of successive applications of rules in it] of the two premisses.

In Gaisi Takeuti, Proof Theory (2nd ed - 1987), page 23, a preliminary Lemma is proved with Proof of Lemma 5.4. We prove the Lemma

by double induction on the grade $g$ [where the grade of a formula $A$ is the number of logical symbols contained in it] and rank $r$ [where the rank of a thread $\mathcal F$ containing a sequent $J$ is the number of consecutive sequents, counting upward from the upper sequent of $J$] of the proof $P$ (i.e., transfinite induction on $\omega.g + r$).

How to "unwind" Takeuti formula with Negri & von Plato "induction" ?

A: The proofs are the same and only the terminology changes.
The length of a formula (weight in [NvP2001]) corresponds to the number of connectives that it has (grade in [T1987]). This is because all connectives are binary (negation can be translated into implication to falsehood, $\neg A\equiv A\to\bot$).
So the outer induction is the same in both proofs. Then, for each $n$ of the outer induction, both proofs use an inner induction on the hight / rank of the derivation of the formula with length or weight $n$.
Hight of a derivation is the maximum number of successive rules, meaning the maximum path of the proof tree of the derivation. So, having a formula of length $n$ fixed from the outer induction, say $Q$ is the sequent that concludes that formula. Then, [NvP2001] does the inner induction on the greatest path of the derivations of the premises of $Q$, meaning the greatest path of the subtree that $Q$ defines.
Rank of a derivation is the maximum number of consecutive sequents starting to count from a sequent $J$. But if you put $J=Q$, then you see that the hight of the derivations of the premises of $Q$ is exactly the same as the rank of whole proof $P$ with respect to $Q$. I mean, in the proof of [T1987], after having fixed a formula of grade $n$, he does the inner induction on the rank of whole proof $P$, where $J$ is the sequent that concludes the formula that is fixed from the outer induction (which is $Q$). Then, the rank of $P$ with respect to $J$ is the maximum path of the subtree that $J$ defines. This is exactly the same as the hight of the derivations of the two premises of $J$, where $J=Q$.
When doing two inductions, you can define a double induction, meaning one induction on one variable that has parity two and on which you do the total induction. So, Takeuti says that the variable, $v$, of the total (inner and outer together) induction is $v(g,r)=\omega\cdot g+r$. Attention that $\omega\cdot g+r$ is a new variable defined on the previous two. What you stated to be $\omega\times\omega$ is the space from which $v$ takes values. Actually, the expression $\omega\cdot g+r$ defines a hierarchy on the two inductions. In this case, it means that induction on $r$ is a subinduction of the induction on $g$. This is because $v(g,r)=\omega g +r=g+r=\max\{g,r\}$ ($\omega g$ is the intersection of $\omega$ and $g$, which is of course $g$ and $g+r$ is the union of $g$ and $r$, which is their maximum). So, you have variable $v$ defined as:
$$v(g,r)=
\begin{cases}
g,~\text{ if } g\geq  r\\
r,~\text{ if } g< r
\end{cases}$$
But this is the same as doing an outer induction on $g$ and then doing an inner induction on $r$, for $r\leq g$. Because if the outer induction is on $g$, then this means that $v(g,r)=g\Rightarrow r\leq g$. So, then you do your inner induction on $r$.


text:
Q: What is "Microsoft.NETCore.App.Host.win-x64" used for? What is the NuGet package "Microsoft.NETCore.App.Host.win-x64" used for? I see that one of my projects downloads it from the feed, but I don't know why.
The package's description at nuget.org says:

Internal implementation package not meant for direct consumption. Please do not reference directly.

It must be a transitive dependency of one of the packages used in my project, but I have no idea which one.
Also, I noticed that the package is not copied to my Cache folder.
EDIT: Scratch that, I was wrong. It actually gets copied into the Cache as all the other NuGets do.

A: As name of package suggests, it hosts web application.


text:
Q: Simulating financial strategies with given value-at-risk (VaR) and mean I would like to generate thousands of distributions with respect to: VaR@5%=-7% and Median=0%.
A first idea:

*

*Choose a family, say the Gaussian one.

*Estimate its parameters. This is straightforward for the Gaussian but let's write the general algorithm (see mpiktas' answer on Estimating a distribution based on three percentiles):
library(nleqslv)
VaR_Threshold <- c(0.05,0.5)
VaR_Value <- c(-0.07,0)

ufn <- function(x,q) q-pnorm(VaR_Value, x[1],x[2])
usol <- nleqslv(c(0,1), ufn,q=VaR_Threshold)
usol$x

[1] -1.262016e-11  4.255698e-02 (estimated parameters)

plot(x<-seq(-1,1,by=0.01),dnorm(x,usol$x[1],usol$x[2]),type="l",col=2)
points(p<-VaR_Value,dnorm(p,usol$x[1],usol$x[2]))

pnorm(VaR_Value,usol$x[1],usol$x[2])

[1] 0.05 0.50 (check)

So this is for the Gaussian family: one unique solution.
My question: is there a parametric family flexible enough to generate thousands of distributions with a given VaR and median? I tried with the stable distributions (4 parameters : 2 manually fixed + 2 optimized), in vain, probably because I don't master it...

A: Almost any family with more than two parameters will do:
you just have to fix all the parameters but two.
Here is an example with stable distributions.
library(fBasics)
VaR_Threshold <- c( 0.05, 0.5)
VaR_Value     <- c(-0.07, 0)
alpha <- 1.2  # in (0,2]
beta  <- 0
# The third argument, gamma, should be positive.
f <- function(x) {
  r <- sum((
    VaR_Threshold -
    pstable(VaR_Value, alpha, beta, abs(x[1]), x[2], pm=2)
  )^2)
  cat(r, "\n")  # for debugging
  r
}
p <- optim(c(1,0),f)$par
pstable(VaR_Value, alpha, beta, abs(p[1]), p[2], pm=2)


text:
Q: Stop .animate() once the last item reached w/jQuery I have a div with overflow set to hidden. Two triggers allow to scroll items inside the layer with overflow.
I have an overflow div with items hidden. I can scroll the boxes inside the hidden area on click of UP/DOWN elements:
$("#up").click(function(){
    $("#container").find(".box").animate({"top": "+=20px"}, "slow");
});
$("#down").click(function(){
    $("#container").find(".box").animate({"top": "-=20px"}, "slow");
});

UP

item 1

qweqweqwe

qqqqqqqq

eeeeeee

rrrrrrrr

tttttt 11

DOWN

I need to disable .animate() once the scroll reaches first or last elements. The code above works, but it does not stop .animate(). I've added some code to check for position of the scrollable elements (see jsfiddle link) but it seems like I messed something up.
Here's my JSfiddle.

A: You should look into the 'ScrollTo' jquery plugin.. This will allow you to scroll to a specific item (with animation) rather than arbitrarily adding 20px to the scroll position.
Here is a quasi-working demo. Note that I updated the jQuery to 1.7 and included the scrollTo library http://jsfiddle.net/VP5Xb/12/
You could also accomplish this easily by obtaining the y coordinate of the items and changing the scrolltop value.


text:
Q: How can I set my connection up to my used as a proxy? As the title says, I want to be able to use my internet connection as a SOCKS (or some other type of proxy?) from another device and connection. What is the easiest way to go about this?
I'm on Windows 7 64-bit.


text:
Q: How do I play audio from an array of objects in React.js I'm trying to learn React and im working on a FreeCodeCamp.com project to build a drum machine. im trying to follow a demo video, what I have and the demo has looks the same except that the demo version works and mine does not. the code should render a set of buttons that are linked to an array of object's which contain links to audio clips. the code renders the buttons correctly but the sound wont play. I will also link the [Codepen][1] im building it on incase that helps. Any help would be greatly appreciated.
this is what I have so far.

  const bankOne = [
  {
    keyCode: 81,
    keyTrigger: 'Q',
    id: 'Heater-1',
    url: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3'
  },
  {
    keyCode: 87,
    keyTrigger: 'W',
    id: 'Heater-2',
    url: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3'
  },
  {
    keyCode: 69,
    keyTrigger: 'E',
    id: 'Heater-3',
    url: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-3.mp3'
  },
  {
    keyCode: 65,
    keyTrigger: 'A',
    id: 'Heater-4',
    url: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-4_1.mp3'
  },
  {
    keyCode: 83,
    keyTrigger: 'S',
    id: 'Clap',
    url: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3'
  },
  {
    keyCode: 68,
    keyTrigger: 'D',
    id: 'Open-HH',
    url: 'https://s3.amazonaws.com/freecodecamp/drums/Dsc_Oh.mp3'
  },
  {
    keyCode: 90,
    keyTrigger: 'Z',
    id: "Kick-n'-Hat",
    url: 'https://s3.amazonaws.com/freecodecamp/drums/Kick_n_Hat.mp3'
  },
  {
    keyCode: 88,
    keyTrigger: 'X',
    id: 'Kick',
    url: 'https://s3.amazonaws.com/freecodecamp/drums/RP4_KICK_1.mp3'
  },
  {
    keyCode: 67,
    keyTrigger: 'C',
    id: 'Closed-HH',
    url: 'https://s3.amazonaws.com/freecodecamp/drums/Cev_H2.mp3'
  }
];

const bankTwo = [
  {
    keyCode: 81,
    keyTrigger: 'Q',
    id: 'Chord-1',
    url: 'https://s3.amazonaws.com/freecodecamp/drums/Chord_1.mp3'
  },
  {
    keyCode: 87,
    keyTrigger: 'W',
    id: 'Chord-2',
    url: 'https://s3.amazonaws.com/freecodecamp/drums/Chord_2.mp3'
  },
  {
    keyCode: 69,
    keyTrigger: 'E',
    id: 'Chord-3',
    url: 'https://s3.amazonaws.com/freecodecamp/drums/Chord_3.mp3'
  },
  {
    keyCode: 65,
    keyTrigger: 'A',
    id: 'Shaker',
    url: 'https://s3.amazonaws.com/freecodecamp/drums/Give_us_a_light.mp3'
  },
  {
    keyCode: 83,
    keyTrigger: 'S',
    id: 'Open-HH',
    url: 'https://s3.amazonaws.com/freecodecamp/drums/Dry_Ohh.mp3'
  },
  {
    keyCode: 68,
    keyTrigger: 'D',
    id: 'Closed-HH',
    url: 'https://s3.amazonaws.com/freecodecamp/drums/Bld_H1.mp3'
  },
  {
    keyCode: 90,
    keyTrigger: 'Z',
    id: 'Punchy-Kick',
    url: 'https://s3.amazonaws.com/freecodecamp/drums/punchy_kick_1.mp3'
  },
  {
    keyCode: 88,
    keyTrigger: 'X',
    id: 'Side-Stick',
    url: 'https://s3.amazonaws.com/freecodecamp/drums/side_stick_1.mp3'
  },
  {
    keyCode: 67,
    keyTrigger: 'C',
    id: 'Snare',
    url: 'https://s3.amazonaws.com/freecodecamp/drums/Brk_Snr.mp3'
  }
];

const KeyboardKey = ({play, sound: {keyTrigger, url} }) => {
  return (
  <button className="drum-pad" onClick={()=> play(keyTrigger)} >
      <audio className="clip" id={keyTrigger} src={url} />
      {keyTrigger}
    </button>
  )
}
const Keyboard = ({play}) =>{
  return bankOne.map((sound) => <KeyboardKey play={play} sound={sound} />)
  }

const App = () => {

  const play = (keyTrigger) => {
      const audio = document.getElementById(keyTrigger)
      audio.currentTime = 0;
      audio.play()
    }
     return

      <Keyboard />

}

ReactDOM.render(<App />, document.getElementById("drum-machine")); ```

  [1]: https://codepen.io/AlakT/pen/QWaRRwe

A: You forgot to pass play function as prop
    const App = () => {

      const play = (keyTrigger) => {
          const audio = document.getElementById(keyTrigger)
          audio.currentTime = 0;
          audio.play()
        }
         return

          <Keyboard play={play} /> // passing play function to <Keyboard />

    }


text:
Q: How to avoid coupling when using regions in Composite WPF I have an application designed using Microsoft's Composite Application Library. My shell has several regions defined so that I can inject content from separate modules. I'm looking for a design pattern that will reduce the coupling that these regions introduce.
In all examples I have seen, regions are defined and accessed using a string in a static class in the infrastructure project.:
<ItemsControl cal:RegionManager.RegionName="{x:Static inf:RegionNames.TabRegion}">

public static class RegionNames
{
    public const string TabRegion = "TabRegion";
}

This introduces an dependency on the shell from the infrastructure project, because part of the infrastructure project must now match the shell. The CAL RegionManager throws an exception if you attempt to access a region which is not defined, so I must ensure that the infrastructure and shell projects are kept in sync.
Is there a way to isolate the shell's regions so that they are defined only within the shell (no region names in the infrastructure project)?
Is there a way to make regions optional, so that shells can be swapped out even if they don't have all the same regions? (An example: One shell has menu and toolbar regions, another only has the menu... modules should be able to inject into the toolbar if it's available, without failing when it's not)

Update - More details on my architecture
In response to depictureboy's answer below, I wanted to describe the way my system is set up... perhaps there will be more good feedback on it.
I am treating the Infrastructure and Shell projects as generic libraries, and I have several applications which use them. The Infrastructure project provides "framework" code and resources (like MVVM stuff, reflection, icons), and my Shell is a generic host window, with the basic window layout (menus, toolbars, status bar, main content area). The applications all share a common look and behave similarly because they share the shell.
My applications get their individual functionality from the modules which get loaded, so I have a bootstrapper project per application which pulls everything together (infra, shell, modules).
I imagine if I ever need to develop a brand new application that is very different from the current ones, I will be able to re-use the infrastructure project, but not the shell. That is why I am curious about decoupling the infrastructure project and the shell.

A: I think you have your logic backwards. Your shell is the glue that binds everything together. In my mind you want the infrastructure and shell tightly coupled because they are the application. Your modules are the parts of the application that will be changing and switching around dynamically. You want your shell regions to be static so that, for example, another developer could write a module for your application knowing where his different views were going to be placed and how the application should behave with his module attached. The Infrastructure project is there to be the go between between your shell and its modules...thats just a fact of life at least in my book. One of the WPF gurus may come up with something that absolutely blows that out of the water tomorrow....


text:
Q: python complementing a complex regular expression Trying to learn regular expressions and despite some great posts on here and links to a regEx site, I have a case I was trying to hack out of sheer stubbornness that defied producing the match I was looking for.  To understand it, consider the following code which allows us to pass in a list of strings and a pattern and find out if the pattern either matches all items in the list or matches none of them:
import re
def matchNone(pattern, lst):
    return not any([re.search(pattern, i) for i in lst])

def matchAll(pattern, lst):
    return all([re.search(pattern, i) for i in lst])

To help w/ debugging, this simple code allows us to just add _test to a function call and see what is being passed to the any() or all() functions which ultimately return the result:
def matchAll_test(pattern, lst):
    return [re.search(pattern, i) for i in lst]

def matchNone_test(pattern, lst):
    return ([re.search(pattern, i) for i in lst])

This pattern and list produces True from matchAll():
wordPattern = "^[cfdrp]an$"
matchAll(wordPattern, ['can', 'fan', 'dan', 'ran', 'pan']) # True

This pattern on the surface appears to work with matchNone() in our effort to reverse the pattern:
wordPattern = "^[^cfdrp]an|[cfdrp](^an)$"
matchNone(wordPattern, ['can', 'fan', 'dan', 'ran', 'pan']) # True

It returns True as we hoped it would.  But a true reversal of this pattern would return False for a list of values where none of them are equivalent to our original list ['can', 'fan', 'dan', 'ran', 'pan'] regardless of what else we pass into it. (i.e. "match anything except these 5 words")
In testing to see what changes to the words in this list will get us a False, we quickly discover the pattern is not as successful as it first appears.  If it were, it would fail for matchNone() on anything not in the aforementioned list.
These permutations helped uncover the short-comings of my pattern tests:
["something unrelated", "p", "xan", "dax", "ccan", "dann", "ra"]
In my exploration of above, I tried other permutations as well taking the original list, using the _test version of the functions and changing one letter at a time on the original words, and or modifying one term or adding one term from permutations like what is above.
If anyone can find the true inverse of my original pattern, I would love to see it so I can learn from it.
To help with your investigation:
This pattern also works with matchAll() for all words, but I could not seem to create its inverse either: "^(can|fan|dan|ran|pan)$"
Thanks for any time you expend on this.  I'm hoping to find a regEx guru on here who spots the mistake and can propose the right solution.

A: I hope I understood your question. This is the solution that I found:
^(?:[^cfdrp].*|[cfdrp][^a].*|[cfdrp]a[^n].*|.{4,}|.{0,2})$

*

*[^cfdrp].*: if text starts not with c, f, d, r or p than match

*[cfdrp][^a].*: text starts with c, f, d, r or p: match if second character is not an a

*[cfdrp]a[^n].*: text starts with [cfdrp]a: match if third character is not a n.

*.{4,}: match anything with more than 3 characters

*.{0,2}: match anything with 0, 1, or 2 characters

It is equal to:
^(?:[^cfdrp].*|.[^a].*|..[^n].*|.{4,}|.{0,2})$

A: What you are looking to do is find the complement. To do this for any regular expression is a difficult problem. There is no built-in for complementing a regex.
There is an open challenge on PPCG to do this. One comment explains the difficulty:

It's possible, but crazy tedious. You need to parse the regexp into an NFA (eg Thompson's algorithm), convert the NFA to a DFA (powerset construction), complete the DFA, find the complement, then convert the DFA to a RE (eg Brzozowski's method). ie slightly harder than writing a complete RE engine!

There are Python libraries out there that will convert from a regular expression (the original specification refers to a "regular language", which only has literals, "or", and "star" -- much simpler than the type of regex you're thinking of [more info here]) to an NFA, to a DFA, complement it, and convert it back. It's pretty complicated.
Here's a related SO question: Finding the complement of a DFA?
In summary, it's far simpler to find the result of the original regular expression instead, then use Boolean negation.


text:
Q: Simple Flutter Getx code throwing error the improper use of a GetX has been detected import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:reactive_forms/reactive_forms.dart';

class FilePicker extends GetView {
  final FormControl? control;

  const FilePicker({
    this.control,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Obx(
      () => GestureDetector(onTap: () {}, child: const TextField()),
    );
  }
}

Error
trying to pick a file from gallery.
Using Getx for a simple code throwing error.
════════ Exception caught by widgets library ═══════════════════════════════════
The following message was thrown building Obx(has builder, dirty, state: _ObxState#d9976):
[Get] the improper use of a GetX has been detected.
You should only use GetX or Obx for the specific widget that will be updated.
If you are seeing this error, you probably did not insert any observable variables into GetX/Obx
or insert them outside the scope that GetX considers suitable for an update
(example: GetX => HeavyWidget => variableObservable).
If you need to update a parent widget and a child widget, wrap each one in an Obx/GetX.
The relevant error-causing widget was

A: The Obx needs an usage of observable item like
Obx(() => Text("${controller.name}"));

An observable example .obs
var name = 'Jonatas Borges'.obs;

If you use Obx without it, then becomes improper.


text:
Q: Community Server the new version do you recommend it? can you integrate new modules to it? I am planning to use community sever for one of our projects, i used it in the past but we had a lot of problems customizing it and understanding how things work, im affraid to get into that again, and i would like to add some things to it but i dont know how flexible it is.

A: Based on the fact we've been working with CS ever since version 1.0 (and even before as ASP.Net Forums) I can tell you this - CS 2007 and 2008 introduces a great out-of-the-box community solution along with a very extensive platform you can develop on top of and extend.
If you're aiming at Microsoft technologies this is the place to be.
IMPORTANT - Don't rush into their SDK and start changing the moving parts, focus on learning their theming engine (Chameleon) and using it's large variety of controls that get you farther than you could imagine. Use the SDK only when you need a better understanding of the inner working of things and when you've reached the point of extending CS.
IMPORTANT #2 - When extending, remember that Telligent releases two major versions every year, usually including features you'd want for your project, remember to review your changes and develop outside of the product core for easier upgrade to future versions.
Good luck!


text:
Q: How do you pass json data from one page to another to reference the same row of data? I am pulling address location information from a google spreadsheet and using it to create buttons.  When you click on a button it then should open and populate the data for that location in a new page or if need into a dialog box.
How do you pass the information to a new page and complete the if statement?  Everything works great if I manually add the entry.id.$t string in the last if statement.
$(document).ready(function () {
  $(function FISLocations() {
    $.getJSON("https://spreadsheets.google.com/feeds/list/GoogleSpreadsheetKey/od6/public/values? alt=json-in-script&callback=?",

      function (data) {
        $('.loc').append('

Alabama<input type="checkbox" id="mylist-node1" />

');
        $.each(data.feed.entry, function (i, entry) {
          var item = '' + entry.id.$t + '';
          item += ' ' + entry.gsx$cityst.$t;
          if (entry.gsx$state.$t == "AL") {
            $('.loclist').append('
' + item + '
');
          };
        });

        $('.poploc').append('

');
        $.each(data.feed.entry, function (i, entry) {
          var itemp = '' + entry.id.$t + '';
          itemp += '' + entry.gsx$address1.$t + '
';
          itemp += ' ' + entry.gsx$city.$t + ', ';
          itemp += ' ' + entry.gsx$state.$t;
          itemp += ' ' + entry.gsx$postal.$t + '
';
          itemp += ' ' + entry.gsx$phone.$t + '
';
          itemp += ' ' + entry.gsx$fax.$t + '
';
          itemp += '
 ' + entry.gsx$email.$t + '

';
          itemp += '

Map Us';
          itemp += ' Email Us ';
          itemp += ' Call us
';
          if (entry.id.$t == ? ? ? ? ? ? ) {
            $('.items').append('
' + itemp + '
');
          };
        });
      });
  });
});


text:
Q: Sensitivity of monitoring AltBeacon I'm developing mobile application for iBeacon.
Our product is for iOS and Android platforms. On iOS, monitoring of iBeacon is default feature, so they use their default methods. For implementing iBeacon on Android I use AltBeacon. But we detected 1 big difference between our platforms. Beacons that have to work for 1 meter radius (on iOS), my app can see on 3 meters from. It's a big problem for our product, because beacons have to work on the same distances on both platforms. So, on iOS they can't change anything in monitoring logic. Can I change sensitivity of monitoring?

A: It is very difficult to get different devices to detect beacons at the exact same distance.  The main problem is that different mobile devices can have quite different Bluetooth radios and antennas that have very different gains.  While detected signal levels these are fairly consistent across iOS devices (with the exception of iPod touch devices which have higher gain receivers and detect beacons further), Android devices are all over the map.
One way to try to make this more consistent is to combine monitoring with ranging.  Instead of triggering an action on a monitoring callback, start ranging as soon as you detect a beacon, then get a distance estimate, and only trigger the action if the distance estimate is close enough. I wrote a blog post that describes this process.
The aforementioned technique is still problematic, especially on Android, because accurate distance estimates require a formula matched for the bluetooth receiver on the particular Android device model.  The Android Beacon Library uses a Nexus 5 calculation by default, but that can significantly over or under-estimate the distance on other models.  For this reason, we have made the library support an expandable database of distance formulas on a per-device basis, and we have provided instructions for calculating the proper formula for other devices and getting them added to the database.  If you know you are targeting specific devices, this might be an option for you.
If, however, you want to have all Android devices detect the beacon at a very specific distance, you are unlikely to have success.  The large number of Android devices out there makes it unlikely that you will be able to get accurate distance estimates on all of them, so you must be willing to accept inaccurate estimates on some devices, or adjust your use case so this is not necessary.


text:
Q: Is it possible to view past versions of files after a renewed etckeeper init? So as the terminal was telling me that /etc wasn't a git repository after running git status and gitk resolv.conf & I made a mistake and ran sudo etckeeper init and sudo etckeeper commit "Initial version" which I already ran earlier before realizing that the terminal was printing out this misleading info(!) only when not using sudo.
Now I'd like to know whether (and if so how) I can view changes to files before I reran the init command. Are they still stored somewhere in a way that I could retrieve them? I'm using Debian 9.1 with KDE.

A: Yes.  etckeeper init is basically harmless, and it does not affect existing git history.


text:
Q: Javascript/ES2015 toggle array object value in React (or Redux) state If I have something like the following:
export default class Questions extends Component {

  state = {
    questions: [
      {value: 'value one, required: true},
      {value: 'value two, required: true},
      {value: 'value two, required: true}
    ]
  };
...

...and I want to change the middle object's required to false, what would be the best way? So I would end up with:
questions: [
  {value: 'value one, required: true},
  {value: 'value two, required: false},
  {value: 'value two, required: true}
]

I tried:
_toggleRequired = (index) => {
  this.setState({
    questions[index].required = !questions[index].required
  })
};

... but it's giving me a syntax error on the first [index]. Isn't it also probably best to return a new array instead of mutating the existing one?
TIA!

A: If you don't want to deal with immutable objects than this is what I recommend. If you create a new array of objects from the current state, make your changes to the object at the particular index, and then save that object as the state it should accomplish what you're trying to do.
_toggleRequired = (index) => {
  let q = this.state.questions;
  q[index].required = !q[index].required
  this.setState({questions : q });
};


text:
Q: HTTP Status 406 - org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation While sending request from postman it shows me
HTTP Status 406
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.
Also on console it print  org.springframework.web.HttpMediaTypeNotAcceptableException Exception
error--------->>
    13:30:24.143 [http-nio-8080-exec-4] DEBUG org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver - Resolving exception from handler [com.xptraining.controller.CartController@30ed94b8]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
    13:30:24.145 [http-nio-8080-exec-4] DEBUG org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver - Resolving exception from handler [com.xptraining.controller.CartController@30ed94b8]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
    13:30:24.145 [http-nio-8080-exec-4] DEBUG org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolving exception from handler [com.xptraining.controller.CartController@30ed94b8]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
    13:30:24.146 [http-nio-8080-exec-4] DEBUG org.springframework.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
14:39:11.951 [http-nio-8080-exec-10] DEBUG org.springframework.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling

Pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>xptraining</groupId>
    <artifactId>xptraining</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <!-- use the following artifactId if you don't need servlet 2.x compatibility -->
            <!-- artifactId>jersey-container-servlet</artifactId -->
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>
        <!-- uncomment this to get JSON support -->
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
        </dependency>

        <!-- Spring dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.8.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.7.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.7.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.7.4</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.7.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.0.0.RELEASE</version>
        </dependency>

        <!-- Hibernate dependencies -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.11.Final</version>
        </dependency>

        <!-- for JPA, use hibernate-entitymanager instead of hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.11.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>4.3.11.Final</version>
        </dependency>

        <!-- MySql-Connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-dbcp</artifactId>
            <version>7.0.55</version>
        </dependency>

    </dependencies>
    <properties>
        <jersey.version>2.24</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

controller -------->>>
package com.xptraining.controller;

import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xptraining.model.Cart;
import com.xptraining.model.Status;
import com.xptraining.services.CartService;

/**
 * The Cart Controller Class
 *
 * @author Harshad Kenjale
 *
 */

@Controller
@RequestMapping("/cart")
public class CartController {

    @Autowired
    CartService cartServices;

    /**
     * Get All records in Cart
     *
     * @return All Cart List
     */

  @RequestMapping(value = "/list", method = RequestMethod.GET)
    public @ResponseBody List<Cart> getCart() {

System.out.println("@@@@@@@@@@@@hello i m from list controller@@@@@@@@@@@");

          List<Cart> cartList = null;
        try {
            cartList = cartServices.getCartList();

        } catch (Exception e) {
            e.printStackTrace();
        }
        /*String joined = Joiner.on("\t").join(cartList);*/
        return cartList ;
    }

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>xptraining</display-name>

  <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/rest.xml</param-value>
    </context-param>

  <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

     <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/rest.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

rest.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/data/jpa
        http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
        ">
 <context:component-scan base-package="com.xptraining" />

<!-- Enable annotation driven transaction management -->

 <jpa:repositories base-package="com.xptraining.repository" />

         <context:annotation-config />

         <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/training" />
        <property name="username" value="root" />
        <property name="password" value="xpointers" />
    </bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
            p:packagesToScan="com.xptraining.model"
            p:dataSource-ref="dataSource"
            >
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="generateDdl" value="true" />
                <property name="showSql" value="false" />
            </bean>
        </property>
    </bean>

<tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

</beans>

A: You are not registering the annotation driven on your context. Add <mvc:annotation-driven/> to your rest.xml file.
Enabling the MVC Java Config or the MVC XML Namespace
Do not forget to add the mvc namespace at your xml header:
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="...
  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc.xsd">

By the way, you are using Spring 4.3 but your namespaces are pointing to 3.0.


text:
Q: laravel + vue router cannot get parameters from url I try to get parameters from url
let's say url contains:
localhost:8000/blog?q=hello

I want to grab hello to trigger function call
What I had declare in app.js in laravel webpack:
import VueRouter from 'vue-router';
Vue.use(VueRouter);

const router = new VueRouter({
    mode: 'history',
    routes: []
})

const app = new Vue({
    router
});

export default app;

In blog page, I try to extract the parameter from url
new Vue ({
       el: "#blog-content",
   },

   mounted: function() {
       q = this.$route.query.q
       console.log(q)
   }
)

I npm run dev to compile and run the blog page it show error:
TypeError: Cannot read property 'query' of undefined

what is wrong? I am sure that Vue Router is properly installed in the application.

A: I think that the blog page that you use is not correct.
You recreate another Vue instance and in that case that new instance doesn't have a router passed to it. So I think that's why this.$router is undefined.
Also you don't pass the view Component to your router so it doesn't know what to look for with the specific url.
Here's your app.js file corrected
import VueRouter from 'vue-router';
Vue.use(VueRouter);

import Blog from './views/Blog';

const router = new VueRouter({
    mode: 'history',
    routes: [
        {
            path: '/blog',
            name: 'blog',
            component: Blog
        },
    ]
});

The blog view page template : views/Blog.vue
<template>
    <div class="wrapper">
         My blog page
    </div>
</template>

<script>
    export default {
        data() {
            return {
                myvariable : ''
            }
        },
        mounted() {
            let q = this.$route.query.q;
            console.log(q);
        },
    };
</script>

Now it should works correctly :)
Edit : Also you don't need to export the app variable in your app.js
Remove the following line export default app; at the end of the file


text:
Q: How are PNG files defined as drawable objects resized based on the resolution of the Android phone? I have a PNG file that is 32x32 pixels.  I use 8 of these as drawables in a row for my app.  These drawables are not in the hdpi, mdpi, or ldpi folders.  I've found that when starting any of the 3 standard size emulators, the screen view with all 8 drawables looks pretty much the same.
I note that the ldpi emulator I'm using (QVGA) has a resolution of 240x320.  8 x 32 = 256, so since I can see all my drawables (and space in-between) I'm betting something is changing their size.
I've read the Supporting Multiple Screens document at the Android developers page, but I still don't understand what is actually happening.  Could you put your own words to explain what is happening to the size of my drawables and how the SDK knows to automatically modify them?

A: Of course - the system automatically resizes your images from the drawable directory to correspond to the DPI of the device if you don't define your own. So in fact the 'drawable' directory is pretty much the same as the 'drawable-mdpi' directory, and because you don't have the ldpi and hdpi versions defined the system automatically builds them out of your mdpi resources. See (1.) here: http://developer.android.com/guide/practices/screens_support.html#support - "Pre-scaling of resources (such as image assets)"
Of course your icons will look somehow ok on ldpi devices but ugly on hdpi devices. That's because the mdpi icons are scaled to match higher dimensions, effectively resulting in less information per pixel.


text:
Q: Javascript search replace string from array I am new in javascript. I want to replace string value from array if array key value match with string value
Here is my following code:
var arr= [];
arr[11] = 'XYZ';
arr[12] = 'ABC';

var string = "11-12";

My Output will be :
var str ="XYZ-ABC";

A: Use String#replace method with a callback.

var arr = [];
arr[11] = 'XYZ';
arr[12] = 'ABC';

var string = "11 - 12";

// match all digits in string and replace it with
// corresponding value in `arr`
var res = string.replace(/\d+/g, function(m) {
  return arr[m];
})

console.log(res);

A: You can use regx.test() to get the Boolean value to check if it is character or not .
var arr = [];
arr[11] = 'XYZ';
arr[12] = 'ABC';

if(/[a-zA-Z\s]+/.test(arr[11])&&/[a-zA-Z\s]+/.test(arr[12])){
var str=arr[11]+ " " +arr[12];
}

A: You just need array methods (split map and join), neither regex nor jquery:
var str = string.split("-").map(elem => arr[elem]).join("-");


text:
Q: setState not updating state even with callback and handleFunction - ReactJs I have a handle function which is called in another component. This passess a value called data, which I want to update into my state.
//basic code
initialState = {
  wordCount:"Some Value"
  text: "Some value"
}
class Home extends Component{
  state = initialState;
  handler(data){
    console.log('Arrived',data)
    this.setState({wordCount:data,text:GetText(data,this.state)});
    this.validation();
  }
  validation(){
    console.log(this.state.wordCount)
  }
  render(){
  return (

<Component handlerFunc={this.handler.bind(this)}

  )
  }

Printing out data in my handler function I do receive the right information as a string. The I use setState to replace wordCount's initial value with data. I do the same with text. GetText returns a string.
But when validation is run, my state is exactly the same. How could this be?

A: Note: setState in react is asynchronous.
This means there is no guarantee that state will have changed by the next statement. What you can do to avoid this is setState accepts callback which will be called when set state finishes.
this.setState(
   {
       wordCount:data,
       text:GetText(data,this.state)
   },
   () => {
    // Gets called when setState updates the state
    this.validation()
});


text:
Q: jQuery: append to bottom, after sibling Is there a more efficient way than as follows, to append to the bottom of the same level of an element, without selecting the parent item first. Here is an example of what I mean: http://jsfiddle.net/8cEjw/
If I have the following structure:
HTML:

jQuery:
$('#main')
    .parent()
        .append($('Test 1').on('click', function (e) {
            alert('Test 1')
        }))
        .append($('Test 2').on('click', function (e) {
            alert('Test 2')
        }));

Then I wondered whether there is a jQuery equivalent for 'appendToBottomAfterSibling'? If I do not have .parent(), and my .append()s become .after()s, then they display in reverse order; since presumably .after() will append the element immediately after itself.

A: Edit As per the JSPerf results, the below is 2 orders of magnitude slower than the OP.

You could use .siblings, as in .siblings().last(), and then .after.  (I'm not sure that is more efficient though).
$('#main').siblings().last().after(
    $("Test1") ...

(Fiddle)
(Note, if there's a chance that "#main" is the only sibling, then you can use .addBack to include it in the selector: $('#main').siblings().last().addBack() - Fiddle)


text:
Q: Do I still have to pass the ActivityContext to the AsyncTask in order to manipulate Views? This function runs on the UiThread, but it seems that doesnt mean it also has access to the activity context. Shall I implement to my AsyncTask a public Setter to pass the activity (as reference)?
protected void onPostExecute( Bitmap bitmap ) {
         //following is underlined red due to missing context
        (ImageView)findViewById(ResId)).setImageBitmap(bitmap);
      }

A: I can think about two options.

*

*If the AsyncTask is an inner class of you activity you can use getApplicationContext() to get the Context object, without passing the activity object.

*If you have to access the ImageView object from different methods or if the task handled by the AsyncTask class can run multiple times you might think about storing the ImageView object as a member of your activity class, so you can don't need a context to access it.


text:
Q: How to Update Related Models in Laravel Here in this documentation Laravel Inserting Related Model
there is no method to update the current related model.
Have a look:
   Relation Between two Models
private function UserToken($token,$expire,$user_id){

    if($JetUserPass=JetUserPass::find($user_id)->token){
        $JetT = new JetTokens(['id_token' =>$token,'expires_on'=>$expire]);
        $JetUserPass2=JetUserPass::find($user_id);
        $JetUserPass2->token()->save($JetT);//NOT WORKING

    }else{
        $JetT = new JetTokens(['id_token' =>$token,'expires_on'=>$expire]);
        $JetUserPass=JetUserPass::find($user_id);
        $JetUserPass->token()->save($JetT);
    }
}

Possible Error: Integrity Violation ...

Here in if block It is checking that the token is there for the user , if true then it will update the existing one,else it will create new. I want to update the JetTokens Model from JetUserPass Model i.e How to update Related Model?

A: Since you have not provided the error message, I won't be able to help you out properly. But there is another method called create on the same documentation page. It says:

In addition to the save and saveMany methods, you may also use the
  create method, which accepts an array of attributes, creates a model,
  and inserts it into the database. Again, the difference between save
  and create is that save accepts a full Eloquent model instance while
  create accepts a plain PHP array:

So, to answer your solution, you can do like this:
private function UserToken($token, $expire, $user_id)
{
    $jetUserPass = JetUserPass::find($user_id);

    $insertValues = [
        'id_token'   => $token,
        'expires_on' => $expire
    ];

    // Since you have same code, I have replaced it
    // in a single line following the principle of DRY.
    // Read the link below.
    $jetUserPass->token()->create($insertValues);
}

Just a side note:
Your code is violating the principles of DRY. This is because, your method's if and else block are having the same code except the JetUserPass and JetUserPass2 properties. That should be avoided under any circumstances.
Hope this helps you out. Happy Coding. Cheers.


text:
Q: Rails 3 form actions and methods I have made a resource.
resources :dashboards

I have a partial file which contains a form and I want to use this partial (as the form elements won't change) to update and create. So here is what I have:
Controller
class DashboardsController < ApplicationController
 def new
    @dashboard = Dashboard.new
  end
end

View
/dashboards/new.html.erb
<%= render :partial => "form", :locals => { :dashboard => @dashboard } %>

Partial Form
/dashboards/_form.html.erb
<%= form_for(@dashboard) do |form| %>
.....
<% end %>

Ruby Guide
The Ruby Guide states:
The Article model is directly available to users of the application, so — following the best practices for developing with Rails — you should declare it a resource. When dealing with RESTful resources, calls to form_for can get significantly easier if you rely on record identification. In short, you can just pass the model instance and have Rails figure out model name and the rest. For example:
## Creating a new article
# long-style:
form_for(@article, :url => articles_path)
# same thing, short-style (record identification gets used):
form_for(@article)

## Editing an existing article
# long-style:
form_for(@article, :url => article_path(@article), :html => { :method => "put" })
# short-style:
form_for(@article)

Result
I thought I have followed the Rails Guide correctly. Because I made @dashboard a resource. I could just pass it into the form and have it handle the action, method and the rest. Instead I'm getting this:
<form accept-charset="UTF-8" action="/dashboards" class="new_dashboard" id="new_dashboard_" method="post">

According to the docs. Shouldn't the action of my form now be "/dashboards/new" because we are on the new action? And should it be passing an extra field declaring the method to be put when I use the same code in the /edit action??
My result is always the same no matter what. The form never changes.
What am I doing wrong?
EDIT
Here is my router info from rake routes
GET    /dashboards(.:format)          dashboards#index
POST   /dashboards(.:format)          dashboards#create
GET    /dashboards/new(.:format)      dashboards#new
GET    /dashboards/:id/edit(.:format) dashboards#edit
GET    /dashboards/:id(.:format)      dashboards#show
PUT    /dashboards/:id(.:format)      dashboards#update
DELETE /dashboards/:id(.:format)      dashboards#destroy

A: You are correct that you should be able to "pass @dashboard into the form and have it handle the action, method and the rest." The issue here is what new is in the context of RESTful actions.
When you declare a set of resources with resources :dashboards, you are creating a set of routes which map requests to controller actions:
GET     /dashboards             index
GET     /dashboards/new         new
POST    /dashboards             create
GET     /dashboards/:id         show
GET     /dashboards/:id/edit    edit
PUT     /dashboards/:id         update
DELETE  /dashboards/:id         destroy

You can check this if you run rake routes.
The issue here is that the new action is defined as a GET request to the path /dashboards/new, i.e. this is the route for the form itself. The URL in the action attribute of the actual form is something else: this is where the form will post the data to with a POST request, which on the server (rails) side will map to the create controller action.
When you use the form helper with form_for(dashboard), a form is created with a route corresponding to what dashboard is: if it is a new record (i.e. it does not yet exist in the database), then the form action will be create (and point to /dashboards), whereas if it already exists it will point to the actual URL for the record (e.g. /dashboards/123). This is what makes the form helpers so useful.
So, to sum up, /dashboards is the correct URL, not for the new action but for the create action, which the form helper uses because dashboard is a new record. new is the route to the page where the form resides, i.e. /dashboards/new.
Hope that makes sense.
p.s. as a side note, you shouldn't be accessing @dashboard in the partial if you are passing it in as a local (:locals => { :dashboard => @dashboard }). Just use dashboard.


text:
Q: Next step when DBCC CHECKDB REPAIR_ALLOW_DATA_LOSS failes I'm in a situation where a few Tables of a Database (MSSQL2016 - 13.0.5081.1)
are corrupted (selecting data failes at some point)
There is no valid backup available (the error seems to be present in the DB for a long time) However, i finally end up by executing the DBCC CHECKDB command with the REPAIR_ALLOW_DATA_LOSS option.
But this fails too. The output returns messages like the following a couple of times:

Meldung 8909, Ebene 16, Status 1, Zeile 2
  Tabellenfehler: Objekt-ID 0, Index-ID -1, Partitions-ID 0, Zuordnungseinheits-ID -7451885722783318016 (Unknown-Typ), Seiten-ID (1:290902) enthält eine falsche Seiten-ID im Seitenheader. PageId-Wert im Seitenheader = (9978:208048830).
          Vor dem Beheben dieses Fehlers müssen zunächst andere Fehler behoben werden.

In english the message should be something like this...

Table error: Object ID 0, index id -1, partition ID 0, allocation unit
  ID -7451885722783318016 (unknown type), page id (1: 290902) contains
  an incorrect page ID in the page header. PageId value in page header =
  (9978: 208048830).
           Before resolving this error, other errors must be resolved first.

But  what does this mean:
 Before resolving this error, other errors must be resolved first.

Which oher errors? - This messages returns a few times for differnt pages but no hint to other errors. I am aware that this whole situation will end up in dataloss.. i have to live with that.
Does anybody know how to step further?
UPDATE:
As in the comments mentioned i tried to evaluate the pageinfo with the traceflag 3604 enabled:

PAGE: (9978:208048830)
BUFFER:
BUF @0x000001D69F08F000
bpage = 0x000001D440C64000          bhash = 0x0000000000000000
  bpageno = (1:290902) bdbid = 12                          breferences =
  0                     bcputicks = 0 bsampleCount = 0
  bUse1 = 16138                       bstat = 0x809 blog = 0x1215a
  bnext = 0x0000000000000000          bDirtyContext = 0x0000000000000000
  bstat2 = 0x0
PAGE HEADER:
Page @0x000001D440C64000
m_pageId = (9978:208048830)         m_headerVersion = 202
  m_type = 214 m_typeFlagBits = 0x86               m_level = 148
  m_flagBits = 0xe010 m_objId (AllocUnitId.idObj) = -1788167502
  m_indexId (AllocUnitId.idInd) = 39061 Metadata: AllocUnitId =
  -7451885722783318016                             Metadata: PartitionId = 0 Metadata: IndexId = -1              Metadata: ObjectId = 0              m_prevPage = (54490:-85112207) m_nextPage = (63487:2133407350)
  pminlen = 44485                     m_slotCnt = 15506 m_freeCnt =
  40634                   m_freeData = 52980
  m_reservedCnt = 43709 m_lsn = (-1571835192:-1449823006:20555)
  m_xactReserved = 12100 m_xdesId = (60082:-2118893827)
  m_ghostRecCnt = 18723               m_tornBits = -1316355089 DB Frag
  ID = 1
Allocation Status
GAM (1:2) = ALLOCATED               SGAM (1:3) = NOT ALLOCATED
  PFS (1:283080) = 0x40 ALLOCATED   0_PCT_FULL
  DIFF (1:6) = NOT CHANGED ML (1:7) = NOT MIN_LOGGED

The m_type returns a suspect value of 214 - which i'm unable to match to one the follow valid page types:
1 – data page
2 – index page
3 and 4 – text pages
8 – GAM page
9 – SGAM page
10 – IAM page
11 – PFS page
13 - Boot page
15 - File header page
16 - diff map apge
17 - ML map page
18 - deallocated page
19 - Temp page
20 - Pre-Allocated page für bulk operations


text:
Q: How do I configure two sets of hosts (3 for QA and 3 for Prod) for deploying a distributed system using Spinnaker? I am using Spinnaker to deploy a 3-tier system to QA and then to Production. Configuration files in each of these systems point to others. If I bake in the configuration for QA in the AMI, then how do I change it while promoting to Prod? Is it 1) by having two different sets of AMIs - one for QA and one for Prod, or, 2) by having the AMIs with no configuration and then configure it (somehow) after deployment to change the configuration files?
What is recommended?

A: I am struggling with similar problems myself in our company.
My solution was to create AMIs for specific purposes using a Packer script. This allows me to -
1. Configure the server as much as I can and then store those configurations in an AMI.
2. Easily change these configurations if the need arises.
Then, launching the AMI using an Ansible script, and make all the rest of the configurations on the specific instance.
In my case I chose creating different images for staging and production, but mostly because they differ greatly. If they were more alike I might have chosen using a single AMI for both.
The advantage Ansible gives you here is factoring your configurations, and including written once to both production and staging servers.

A: You can define custom AWS user data for cluster at deploy time ( under advanced settings of the cluster configuration ). You can then retrieve this user data in your application. This will allow you to change these type of configurations.
At Netflix, we have a series of init scripts that are baked into the base image and provide a mechanism for extending custom startup ( init.d ) scripts via nebula / gradle. This usually sets values like NETFLIX_ENVIRONMENT that are well known and programmed against.
We also use a feature flipping mechanism via https://github.com/Netflix/archaius . This allows us to add properties that are external to the clusters but can be targeted towards them.
When it comes to secured credentials, the approach is outlined in this presentation, but essentially the images reach out to an external service that issues these type of creds. https://speakerdeck.com/bdpayne/key-management-in-aws-how-netflix-secures-sensitive-data-without-its-own-data-center


text:
Q: How to place chords over lyrics in Java and keep them above the right syllabe? sorry for my dumb question, but i need some help.
I'm making an app that shows the lyrics and chords of songs. I need to place the chord letter above the correct syllable of the word. Example:
"[G]These are the lyrics o[Am]f the song"
so the expected outcome for the above example is:
G                    Am
These are the lyrics of the song

See that the chord letters should stay above the correct word. I don't know how to achieve this.
I found a similar question but it was for javascript: Format lyrics with inline notes to readable song with chords on top
It is possible to achieve this?
Sorry about my English.
I really don't know how to achieve this.


text:
Q: how to override a function (in an abstract base class) with a covariant parameter I have several classes D with public sections of the form:
class D
{
    public:
        D& foo();
        void bar(D&);
}

I'd like to create a single abstract class from which they all derive.
My (naive) attempt was:
// in .h file
class B
{
    public:
        virtual B& foo() = 0;
        virtual void bar(B&) = 0;
}

class D : public B
{
    public:
        D& foo() override;
        void bar(D&) override;
}

// in .cpp file
D& D::bar() {return *(new D());}
void D::foo(D& d) {}

This failed to compile for (what I eventually realized was) a fairly sensible reason: Any function overriding the function
void bar(B&)=0;

must be defined for any parameter which is a reference to type B. The supplied candidate
virtual void bar(D&) override;

is only defined for (the smaller collection) of parameters which are references to type D.
Note that this is not a problem with the function foo. Indeed, if you comment out the three lines with bar, everything compiles fine.
I think that the technical explanation for this phenomenon is that C++ does not support covariance in parameters (but it does support contravariance in parameters).
The answer to the post C++ covariance in parameters suggests that I can't define an interface (i.e. an abstract class) for my classes D.
Is there some simple or conventional way to create a single "interface" for all my classes D? Alternatively, perhaps there is a different design pattern for hiding the different implementations of these classes.
Thanks in advance for your comments and suggestions.
dan

A: You can't, and for good reason.  A derived class can't add preconditions that are more restrictive than the interface it derives from without breaking every principle of OOP that exists.  By requiring the parameter to be more specific in your implementation of the interface this is exactly what you are doing.
An argument could be made that something like this could be useful:
struct IfaceA {};
struct IfaceB : IfaceA {};

struct Base { void f(IfaceB &); };
struct Derived : Base { void f(IfaceA &); };

This lessens preconditions rather than increase them, so it's OK.  It's simply not done in C++, or any other language I'm aware of for that matter, so you just can't do it.
In both cases you can make an overload with the alternative parameter type and call the overridden version.
It's the opposite case with return types.  Return values are post-conditions.  You can make post conditions more specific, but can't make them more broad.  So you can return your derived type but can't broaden it by returning a more abstract type.  C++ implements covariant returns though at least one, very commonly used compiler does it very badly so that there are numerous bugs.

A: Based on the code that you have provided you have tried to override two diferent function signatures.
The best option you have is use the same signature, and then cast the result.
A simple example,
// in .h file
class B
{
    public:
        virtual B* foo() = 0;
        virtual void bar(B*) = 0;
};

class D : public B
{
    public:
        B* foo() override;
        void bar(B*) override;
};

// in .cpp file
B* D::foo()
{
    D* p=new D();
    return p;
}
void D::bar(B* d)
{
    D* casted=dynamic_cast<D*>(d);
}

int main(void)
{
    D son;
    B* father=dynamic_cast<B*>(son.foo());
}

I hope that this can solve your problem, or at least give you a clue.

A: Could you use a templated base class?
template <typename Deriving>
struct Base {
    virtual Deriving& foo() = 0;
    virtual void bar(Deriving&) = 0;
};

struct Deriving : public Base<Deriving> {
    ...
};

You don't have a single interface class, but there is a single interface template, which is sometimes versatile enough.


text:
Q: jQuery/JavaScript for-Loop and .append I started yesterday with jQuery and JavaScript and run into an error.
All I want is to place Ads randomly after an H1-Tag (so let's say there are 10 H1 on a page dived by 2 = 5 AdPosition) now add 5 AdBlocks after a randomly choosen H1.
Sounds pretty easy but I cant achieve this...: / because jQuery or myCode only paste one AdBlock.
JsFiddle: http://jsfiddle.net/byt3w4rri0r/eCBCK/ - working!

MyHTML:

Headline

Headline

Headline

Headline

Headline

Headline

Headline

Headline

Headline

Headline

MyJQUERY/JavaScript:
//count H1
var countH1 = parseFloat($("#content-inner h1").length)-1; //-1 because 0 is also a number!

//how often the ads should be displayed
var ad_count = Math.round(countH1 / 2);

//random helper
var min = 0;
var max = countH1;

//random position
for (counter = 0; counter < ad_count; counter++){
    var random_position = Math.round((Math.random() * (max - min)) + min);

    console.log("Random_Position:", random_position);

    // paste google-code

    if ($(".headline").hasClass('advertised') == true) {
        random_position++;

        console.log('already advertised!')

        if (random_position > countH1) {
            random_position--;
            }
    } else {
        $('h1:eq('+random_position+')').append('

');
        $('h1.headline').addClass('advertised');
        }
}

console.log("CountH1 -1, because 0=1, 1=2,....", countH1);
console.log(werbung_anzahl);
console.log(zufall_position);
console.log(counter);

A: With this line
if ($(".headline").hasClass('advertised') == true)

you are checking if any(!) of the .headline elements has already been advertised. And after the first step there is always one .headline that has been advertised, so this comparison will be true.
What you wanted to do: Check if the .headline with the current index has been advertised
if ($(".headline").eq(random_position).hasClass('advertised') == true)

On top of this, you are adding the class "advertised" to all(!) your h1.headline elements. This is what you wanted to do instead
$('h1.headline').eq(random_position).addClass('advertised');

EDIT: This is the full changed for loop from the latest fiddle at http://jsfiddle.net/eCBCK/19
for (counter = 0; counter < ad_count; counter++){
    var random_position = Math.round((Math.random() * (max - min)) + min);

    console.log("Random_Position:", random_position);

    // paste google-code

    if ($(".headline").eq(random_position).hasClass('advertised') == true) {
        counter--;

        console.log('already advertised!')

    } else {
        $('h1:eq('+random_position+')').append('

');
        $('h1.headline').eq(random_position).addClass('advertised');
        }
}

A: Someone correct me if i'm wrong, but you are adding the class "advertised" to all of your h1 elements, this means that on the second loop you are testing if advertised has already been added to the h1, which will now always be true and no more adds are appened

A: Use jQuery's chaining feature:
$('h1:eq('+random_position+')').append('

').addClass('advertised');

This will only add the advertised class to the H1 that you just appended to.


text:
Q: Index was outside the bounds of the array Friends
I have got an error which tells "Index was outside the bounds of the array"  I dont know y it was happening since after completeting the for loop  and entering the loop fresh again it was showing the variable value when exited from the loop before.
        int[,] arrScr = new int[lstTest.Count, cnt2 + 3];
        string[,] arrName = new string[lstTest.Count, cnt2 + 3];
        int p;

        for (i = 0; i < lstTest.Count; i++)
        {
            using (DataTableReader dtr3 = ds.Tables["scord_mark_table" + (i + 1).ToString()].CreateDataReader())
            {
                p = 0;
                while (dtr3.Read())
                {
                    arrName[i, 2 + p] = dtr3[15].ToString();
                    for (int k = 2; k < 12; k++)
                    {
                        arrScr[i, 2 + p] += Convert.ToInt32(dtr3[k].ToString());
                    }
                    p++;
                }
            }

A: Change k <= 12 to  k < 12.
If this is not the cause of your problem you should rewrite k <= 12 to  k < 13 as that is the convention most coders are used to read and write.

A: What is in dtr3[12]?  does it return null?
What is the value of cnt2?

A: This means that your array does not contain as many elements as you are trying to access.

A: It's going to exit from the loop as k = 13 because the last valid value of k is 12, then it went through the loop, executed k++ (making it 13). At which point it fails the condition because 13 > 12 and that's when it actually exits.


text:
Q: Outlook: how to fill the auto complete cache? We use Outlook 2010 and 2013 connected to Microsoft Office365 (corporate accounts).
We imported a big address book. Every account has access to it, no problem there.
I search a way to use auto-complete from this address book when people type an email address.
The usual trick is: create a new email, add every contact to the "A" field, then close the email.
It works as long as Outlook remains open. Once Outlook is restarted, only the old auto-complete remains.
Is there a way to "import" contacts into the auto-complete cache ?
edit:
We tried what appear to be the usual trick: manually remove the Stream_Autocomplete.dat file then restart Outlook. Then Outlook recreate the file. But in our case the file is not recreated and the problem remain the same.
We also tried to clear the autocomplete cache (from Options/Mail/...), uncheck the use of autocomplete, restart Outlook, recheck autocomplete. This hasn't solved the problem.

A: The Software "NK2Edit" edits nk2 and stream_autocomplete.dat files.
It allows you to import a complete adressbook into the file, edit and delete certain rows etc.
http://www.nirsoft.net/utils/outlook_nk2_edit.html (Download is at the bottom of the page)

A: You can follow Microsoft's guide from here which tells how to copy an autocomplete file from one PC to another.
In summary:
Copy the file with an nk2 extension from the old PC.  This will be in the %APPDATA%\Microsoft\Outlook folder.
Copy the file onto the new computer in the %APPDATA%\Microsoft\Outlook folder for the profile of the person you wish to have the list.
Rename the file to match the profile name
Invoke Outlook using the command outlook /importnk2


text:
Q: Why does it require 20X more time for these calculations when the values get tiny I am a circuit designer, not a software engineer, so I have no idea how to track down this problem.
I am working with some IIR filter code and I am have problems with extremely slow execution times when I process extremely small values through the filter. To find the problem, I wrote this test code.
Normally, the loop will run in about 200 ms or so. (I didn't measure it.) But when TestCheckBox->Checked, it requires about 7 seconds to run. The problem lies with the reduction in size of A, B, C and D within the loop, which is exactly what happens to the values in an IIR filter after it's input goes to zero.
I believe the problem lies with the fact that the variable's expononent value becomes less than -308. A simple fix is to declare the variables as long doubles, but that isn't an easy fix in the actual code, and it doesn't seem like I should have to do this.
Any ideas why this happens and what a simple fix might be?
In case its matters, I am using C++ Builder XE3.
int j;
double A, B, C, D, E, F, G, H;
//long double A, B, C, D, E, F, G, H; // a fix
A = (double)random(100000000)/10000000.0 - 5.0;
B = (double)random(100000000)/10000000.0 - 5.0;
C = (double)random(100000000)/10000000.0 - 5.0;
D = (double)random(100000000)/10000000.0 - 5.0;
if(TestCheckBox->Checked)
 {
  A *= 1.0E-300;
  B *= 1.0E-300;
  C *= 1.0E-300;
  D *= 1.0E-300;
 }
for(j=0; j<=1000000; j++)
{
 A *= 0.9999;
 B *= 0.9999;
 C *= 0.9999;
 D *= 0.9999;
 E = A * B + C - D; // some exercise code
 F = A - C * B + D;
 G = A + B + C + D;
 H = A * C - B + G;
 E = A * B + C - D;
 F = A - C * B + D;
 G = A + B + C + D;
 H = A * C - B + G;
 E = A * B + C - D;
 F = A - C * B + D;
 G = A + B + C + D;
 H = A * C - B + G;
}

EDIT:
As the answers said, the cause of this problem is denormal math, something I had never heard of. Wikipedia has a pretty nice description of it as does the MSDN article given by Sneftel.
http://en.wikipedia.org/wiki/Denormal_number
Having said this, I still can't get my code to flush denormals. The MSDN article says to do this:
_controlfp(_DN_FLUSH, _MCW_DN)

These definitions are not in the XE3 math libraries however, so I used
controlfp(0x01000000, 0x03000000)

per the article, but this is having no affect in XE3. Nor is the code suggested in the Wikipedia article.
Any suggestions?

A: You've entered the realm of floating-point underflow, resulting in denormalized numbers - depending on the hardware you're likely trapping into software, which will be much much slower than hardware operations.

A: You're running into denormal numbers (ones less than DBL_MIN, in which the most significant digit is treated as a zero). Denormals extend the range of the representable floating-point numbers, and are important to maintain certain useful error bounds in FP arithmetic, but operating on them is far slower than operating on normal FP numbers. They also have lower precision. So you should try to keep all your numbers (both intermediate and final quantities) greater than DBL_MIN.
In order to increase performance, you can force denormals to be flushed to zero by calling _controlfp(_DN_FLUSH, _MCW_DN) (or, depending on OS and compiler, a similar function). http://msdn.microsoft.com/en-us/library/e9b52ceh.aspx


text:
Q: QuoteString & DoubleQuoteString Replacement With CsvHelper 20.0.0, WriterConfiguration.QuoteString and WriterConfiguration.DoubleQuoteString have been removed.
I was relying on those fields to implement UseExcelLeadingZerosFormatForNumerics as seen here.
Is there another way I can access QuoteString and DoubleQuoteString?

A: You can replace QuoteString with configuration.Quote.ToString() and DoubleQuoteString with new String(configuration.Quote, 2).


text:
Q: Factor Theorem and Long Division For instance
Given $f(x) = 2x^3-7x^2+2x+3$, and $(x-3)$ is one of the factors, how do I obtain $2x^2-x-1$ as the quotient without using the long division. Is there any other method apart from long division?
Many thanks.

A: Although there's already an answer linking to the method known as Ruffini's Rule, I detail its computation below, because it was very popular when I was in high school. It enables us to find easily the division of a polynomial by a linear term of the form $ x-x_0 $, even when the remainder $r(x)$ is not equal to $0 $. In your case $ x_0=3 $ and $r(x)=0$.
You want to find the unique second degree polynomial $ g (x) $ satisfying
$$\frac{f(x)}{x-x_0}=\frac{2x^3-7x^2+2x+3}{x-{\color{blue}3}}=g (x).$$
Its coefficients can be found by Ruffini's Rule. Applied to this division it consists of the following algorithm:
\begin{array}{c|rrrl}
&  x^{3} & x^{2} & x^{1} & \phantom{-} x^{0}   \\
& 2 & -7 & 2 & \; \; \phantom{-}3 &\to \text{  coefficients of } f (x) \\
   x_0={ \color{blue}3} & \downarrow & 6 & -3 & \;\;-3 \\
              &    & {\color{gray}{=}}{\; \color{blue}3}{\color{gray}{\cdot 2}} &  {\color{gray}{=}}{\; \color{blue}3}{\color{gray}{ (-1)}} &  {\color{gray}{=}}{\; \color{blue}3}{\color{gray}{ (-1)}} \\
    \hline  & 2 & -1 & -1 & |\phantom {-}{\color{green}0}&\to \text{  coefficients of } g (x) \text{ and }{\color{green}{\text{remainder}}} \\
   & & { \color {gray} {=-7+6 } } &  { \color {gray}{=2-3} }  & | {   \color {gray}{=3-3 }} \\
 &  x^{2} & x^{1} & x^{0} & |\color{green}{\text{remainder}}
    \end{array}
which confirms that
\begin{equation*}
g(x)=2x^{2}-x-1.
\end{equation*}
ADDED. In this answer I've posted another example of the application of Ruffini's rule.

A: You can simplify the process of long division by a linear factor using an algorithm known as synthetic division, also called Ruffini's Rule. You are working only with coefficients here plus you are dealing with addition rather than subtraction, which tends to be easier.
You can read more here:
http://www.purplemath.com/modules/synthdiv.htm
https://en.m.wikipedia.org/wiki/Ruffini%27s_rule

A: You can set-up and solve simultaneous questions.
You know that $2x^3-7x^2+2x+3$ will factorise as follows:
$$2x^3-7x^2+2x+3 \equiv (x-3)(ax^2+bx+c)$$
where $a$, $b$ and $c$ are constants you need to find. If you expand the right-hand side you get
$$2x^3-7x^2+2x+3 \equiv ax^3+(b-3a)x^2+(c-3b)x-3c$$
Comparing coefficients gives: $a=2$, $b-3a=-7$, $c-3b=2$ and $-3c=3$. You need to solve these simultaneously. It's clear that $a=2$ and $c=-1$ so we get $b=-1$ and hence
$$2x^3-7x^2+2x+3 \equiv (x-3)(2x^2-x-1)$$
I would recommend that you try to master long division. It is much easier when, for example, you are dividing a quartic by a quadratic and there is a remainder. For easy questions, the method above is fine, but for more complicated ones, division is the way to go.

A: To divide a polynomial $P(x)$ by another $D(x)$, you need to find a third polynomial $Q(x)$ such that
$$P(x)=D(x)\times Q(x),$$ where the $\times$ denotes the product of polynomials. From this relation, we see that the degree of $P$ equals the sum of the degrees of $D$ and $Q$.
It turns out that in general this factorization is impossible, as is the case with integers. Anyway, the situation can be also rescued by considering a remainder polynomial $R(x)$ such that
$$P(x)=D(x)\times Q(x)+R(x),$$ and the degree of $R$ is smaller than that of $D$.
In the special case that $D(x)=x+a$, a binomial of the first degree, we have that the degree of $Q$ must be one less than that of $P$ and the degree of $R$ is $0$ ($R$ is a constant.)

The most efficient and easy way to obtain $Q$ is by long division.

A: Put
$$g(x) = \frac{2x^3 -7 x^2 + 2 x + 3 }{x-3}$$
To write $g(x)$ explicitly as a quadratic polynomial (where you remove the removable singularity at $x = 3$) can then be done in many different ways, long division, or equating it to an undetermined quadratic and solving for the coefficients as in Fly by Night's solution, or series expansion around x = infinity is equivalent to synthetic division mentioned by Deepak.
Another method is to use use Lagrange interpolation to find the quadratic polynomial. You then evaluate $y_i = g(x_i)$ at 3 different points $x_i$. You can then write:
$$g(x) = \sum_{i} y_{i}\prod_{j\neq i}\frac{x-x_j}{x_i-x_j}$$


text:
Q: Support Function What does |supp(p)| less than equal to |supp(q)| mean? Can someone please give an example. Here supp represents the support function
supp(p)= {z: p(z) > 0}
And it it true that|supp (p)| less that equal to |supp(q)| iff supp{alpha p+ (1- Alpha) r} less than equal to supp {alpha q + (1-alpha) q }?
Here p,q and r belong to [0,1]

A: The expression $|\operatorname{supp} p|\le|\operatorname{supp}  q|$ means that the size (that is, cardinality) of the set $\operatorname{supp} p$ is not bigger than the size of the set  $\operatorname{supp} q$, that is there exists an injective map from $\operatorname{supp} p$ to $\operatorname{supp} q$.
For instance, let $X=\{0,1,2\} $, $p$ and $q$ be functions from $X$ to $\Bbb Z $ such that $p(0)=p(1)=0$, $p(2)=1$, $q(0)=0$, $q(1)=q(2)=1$ then $\operatorname{supp} p=\{1\}$, $\operatorname{supp} q=\{1,2\}$, so $|\operatorname{supp} p|=1\le 2=|\operatorname{supp}  q|$.
An other example. Let $X=\Bbb Z$ and $p$ and $q$ be functions from $X$ to $\Bbb Z $ such that for each $x\in X$ we have $p(x)=1$, if $x$ is even and  $p(x)=0$, otherwise; $q(x)=1$, if $x$ is divisible by three and  $q(x)=0$, otherwise.
Then  $\operatorname{supp} p=2\Bbb Z$, $\operatorname{supp} q=3\Bbb Z$, so $|\operatorname{supp} p|=\aleph_0=|\operatorname{supp} q|$, that is both $|\operatorname{supp} p|\le|\operatorname{supp}  q|$ and $|\operatorname{supp} q|\le|\operatorname{supp}  p|$.


text:
Q: Reverse track forced records relationships based on user-defined tagging I have this table where the tagging [Tag_To] is updated by an algorithm based on Year and Period of coverage.  My current task (in question) is to update the Status given the Year.
ID   Year    Method    Period_From   Period_To    SeqNo   Tag_To       Status
-----------------------------------------------------------------------------------
10   2019      A       2019-01-01    2019-12-31     1
11   2019      B       2019-01-01    2019-06-30     2       1
12   2019      B       2019-07-01    2019-12-31     3       1
13   2019      C       2019-01-01    2019-06-30     4       2

14   2020      A       2020-01-01    2020-12-31     1
15   2020      B       2020-01-01    2020-06-30     2       1
16   2020      B       2020-07-01    2020-12-31     3       1
17   2020      C       2020-01-01    2020-12-31     4       2,3

18   2021      A       2021-01-01    2021-12-31     1
19   2021      B       2021-01-01    2021-12-31     2       1
20   2021      C       2021-07-01    2021-12-31     3       2

The SeqNo is applied per Year and the Tag_To is done based on period of coverage.

*

*11 and 12 are tagged to 10 since B follows A and their period falls within 10 period coverage.

*13 is tagged to 11 since C follows B and the period...

*15 and 16 to 14

*Also note that 17 is tagged to 15 and 16 (2,3) because 17's coverage spans across the 2 periods of 15 and 16 combined

*and so on...

The objective is to update the Status by Year such that each path is considered Closed if the path already has Methods A, B and C (there are actually more methods, but to simplify).  Status should be Open for paths that haven't completed the methods.
From the example above, there are 5 paths:

*

*10(A)-->11(B)-->13(C) = Closed

*10(A)-->12(B)-->??? = Open

*14(A)-->15(B)-->17(C) = Closed

*14(A)-->16(B)-->17(C) = Closed

*18(A)-->19(B)-->20(C) = Closed

Therefore the status update should be:
ID   Year    Method    Period_From   Period_To    SeqNo   Tag_To       Status
-----------------------------------------------------------------------------------
10   2019      A       2019-01-01    2019-12-31     1                  Open
11   2019      B       2019-01-01    2019-06-30     2       1          Closed
12   2019      B       2019-07-01    2019-12-31     3       1          Open
13   2019      C       2019-01-01    2019-06-30     4       2          Closed

14   2020      A       2020-01-01    2020-12-31     1                  Closed
15   2020      B       2020-01-01    2020-06-30     2       1          Closed
16   2020      B       2020-07-01    2020-12-31     3       1          Closed
17   2020      C       2020-01-01    2020-12-31     4       2,3        Closed

18   2021      A       2021-01-01    2021-12-31     1                  Closed
19   2021      B       2021-01-01    2021-12-31     2       1          Closed
20   2021      C       2021-07-01    2021-12-31     3       2          Closed

I hope I have explained everything clearly.  Would really appreciate if anyone could help.

A: Just to update viewers that I have managed to solve this on my own although the solution is super non-dynamic and quite inefficient, it pretty much did the job for me.  Here's what I did.
UPDATE Table SET
    Status =
    CASE WHEN Method = 'B'
            AND NOT EXISTS ( SELECT * FROM Table P INNER JOIN
                (
                SELECT VALUE AS Tag_To
                FROM Table AV
                CROSS APPLY STRING_SPLIT(AV.Tag_To, ',')
                WHERE AV.Method = 'C'
                ) C ON P.Sequence_No = C.Tag_To
            WHERE P.ID = AValue.ID
        )
            THEN 'Open'
        WHEN Method = 'A'
            AND NOT EXISTS ( SELECT * FROM Table P INNER JOIN
                (
                SELECT VALUE AS Tag_To
                FROM Table AV
                CROSS APPLY STRING_SPLIT(AV.Tag_To, ',')
                WHERE AV.Method = 'B'
                ) C ON P.Sequence_No = C.Tag_To
            WHERE P.ID = AValue.ID
        )
            THEN 'Open'
        ELSE 'Closed'
    END
FROM Table AValue
WHERE Year = @Year

;WITH CTE AS
(
    SELECT
        ROW_NUMBER() OVER(PARTITION BY A.Method ORDER BY A.Sequence_No ASC) SN,
        A.ID,
        A.Method,
        A.Sequence_No,
        A.Tag_To,
        A.Period_From,
        A.Period_To,
        A.Status
    FROM Table A
    LEFT JOIN
        (
        SELECT VALUE AS Tag_To
        FROM Table AV
        CROSS APPLY STRING_SPLIT(AV.Tag_To, ',')
        WHERE Year = @Year
        ) B ON A.Sequence_No = B.Tag_To
    WHERE Year = @Year
),
CTE2 AS
(
 SELECT DISTINCT SN FROM CTE
 WHERE Status = 'Open'
)
UPDATE Table SET
    Status = 'Open'
FROM Table
INNER JOIN CTE ON Table.ID = CTE.ID
INNER JOIN CTE2 ON CTE.SN = CTE2.SN

Yeah, it's ugly but, hey, it did the job!  :)


text:
Q: Sorting a table by date in Slick 3.1.x I have the following Slick class that includes a date:
import java.sql.Date
import java.time.LocalDate

class ReportDateDB(tag: Tag) extends Table[ReportDateVO](tag, "report_dates") {

  def reportDate = column[LocalDate]("report_date")(localDateColumnType)

  def * = (reportDate) <> (ReportDateVO.apply, ReportDateVO.unapply)

  implicit val localDateColumnType = MappedColumnType.base[LocalDate, Date](
    d => Date.valueOf(d),
    d => d.toLocalDate
  )

}

When I attempt to sort the table by date:
    val query = TableQuery[ReportDateDB]
    val action = query.sortBy(_.reportDate).result

I get the following compilation error

*

*not enough arguments for method sortBy: (implicit evidence$2: slick.lifted.Rep[java.time.LocalDate] ⇒
  slick.lifted.Ordered)slick.lifted.Query[fdic.ReportDateDB,fdic.ReportDateDB#TableElementType,Seq].
  Unspecified value parameter evidence$2.

*No implicit view available from slick.lifted.Rep[java.time.LocalDate] ⇒ slick.lifted.Ordered.

How to specify the implicit default order?

A: You need to make your implicit val localDateColumnType available where you run the query. For example, this will work:
implicit val localDateColumnType = MappedColumnType.base[LocalDate, Date](
  d => Date.valueOf(d),
  d => d.toLocalDate)

val query = TableQuery[ReportDateDB]
val action = query.sortBy(_.reportDate).result

I'm not sure where the best place to put this is, but I usually put all these conversions in a package object.

A: It should work like described here:
implicit def localDateOrdering: Ordering[LocalDate] = Ordering.fromLessThan(_ isBefore _)

A: Try add this line to your import list:
import slick.driver.MySQLDriver.api._


text:
Q: How to create a dictionary in LINQ when populating a class? Description:
At the moment I have a class which looks like so:
 public class SupplierSummaryReport {
            public string SupplierName { get; set; }
            public Dictionary<string, decimal> DateValues { get; set; }
        }

Using LINQ, I am trying to create an IQueryable list of the SupplierSummaryReport class. However, when trying to create the dictionary in C#, the application fails. I'm not sure how to create the dictionary, can anyone help?
LINQ/C#:
 public IQueryable<APData.Audit.Models.ReportModels.SupplierSummaryReport> GetSupplierSummaryReportData() {
            var data = (from i in _ctx.Invoices
                        where i.Turnover == true
                        select new {
                            Year = i.InvoiceDate.Year.ToString(),
                            AccountName = i.AccountName,
                            Value = i.NetAmount_Home ?? 0
                        });

            return data.GroupBy(r => new { r.Year, r.AccountName })
                .Select(g => new APData.Audit.Models.ReportModels.SupplierSummaryReport {
                    SupplierName = g.Key.AccountName,
                    //I believe it fails when creating the dictionary
                    DateValues = new Dictionary<string, decimal> {
                        {g.Key.Year, g.Sum(r=> r.Value)}
                    }
                }).OrderBy(r => r.SupplierName);
        }

Expected Outcome:
Supplier Name = "Test", DateValues = {2010, 500}
Supplier Name = "Test2", DateValues = {2011, 900}

Actual Outcome:
Receive this error:

Only list initializer items with a single element are supported in
  LINQ to Entities.

A: Once you start the .Select(g => there's no point creating a dictionary as you have only one g.Key. You would only be creating a dictionary with one element in it if you tried. I think you have your logic wrong.
I think this is what your return statement should look like:
return
    data
        .GroupBy(r => r.AccountName)
        .Select(g => new APData.Audit.Models.ReportModels.SupplierSummaryReport
        {
            SupplierName = g.Key.AccountName,
            //I believe it fails when creating the dictionary
            DateValues = g
                .GroupBy(x => x.Year, x => x.Value)
                .ToDictionary(x => x.Key, x => x.Sum())
        })
        .OrderBy(r => r.SupplierName);

Now you may need to put a .ToArray() after data to bring the records in to memory to make this query work.


text:
Q: android - How to update a specific textview of a CardView My first cardView shows an alert dialog, i want that the item selected on the dialog set into the description of my first cardView.
How can i reference to a specific cardView?
i have this
holder.mTextDescription.setText(string);

it sets the text, but it does on the last cardView.
i actually solve it, but not sure if this is the bes way to do it;
private void onUpdate(int position, String string) {
    String titulo = mDataset.get(position).titulo;
    String type = mDataset.get(position).type;
    mDataset.remove(position);
    mDataset.add(position, new Archivos(titulo, string, type));
    notifyItemChanged(position);
}

A: For your particular case having a method that receives the updated string and the position at which your object is, works. It could be somehow improved like this
Archivos archivos = mDataSet.get(position);
archivos.setXXXXX(stringVariable)
notifyItemChanged(position);

Gets the object once, update your property and notify that something changed at that position.