text:
Q: How to combine all solutions within one list in Mathematica? Using Solve function in Mathematica, we may get several solutions, e.g.
    In[1]:= Solve[x == 1 &&  2 >= y >= 1, {x, y}, Integers]
    Out[1]= {{x -> 1, y -> 1}, {x -> 1, y -> 2}}

In case there are tens of solutions, the lists above will be messy.
Now I want to list only all possible values of x and y with a list like this
    {x->1, y->1,2}

Is there any easy way to reformat the output of the solution?
Another question, how to use the value from a solution?
    In[1]:= Solve[x == 1,{x}]
    Out[1]= {x -> 1}
    In[2]:= x
    Out[2]= x
    In[3]:= Definition[x]
    Out[3]= Null
    In[4]:= ?x
            Global`x

A: The lists follow the pattern of Mathematica rules, and therefore list replacement is the easiest way to get values from such lists.
Let's call the solution list sol:
In[3]:= sol = Solve[x == 1 && 2 >= y >= 1, {x, y}, Integers]
Out[3]= {{x -> 1, y -> 1}, {x -> 1, y -> 2}}

Now take symbol x, and make the list of all replacements of x according to sol treated as a rule list:
In[4]:= x /. sol
Out[4]= {1, 1}

This immediately gives you an idea how to get all distinct values of x from all solutions:
In[5]:= Union[x /. sol]
Out[5]= {1}

Ditto for y, although all solutions are already distinct:
In[6]:= Union[y /. sol]
Out[6]= {1, 2}

Here's complete code from the above step-through for copying and pasting:
sol = Solve[x == 1 && 2 >= y >= 1, {x, y}, Integers]
x /. sol
Union[x /. sol]
Union[y /. sol]
Clear[sol]

A: For your first question you might use:
vars = {x, y};

sols = Solve[x == 1 && 2 >= y >= 1, vars, Integers];

Thread[ vars -> Union /@ (vars /. sols) ]

{x -> {1}, y -> {1, 2}}

For your second question please see this answer.
Most handily:
sols = Solve[x^2 + a x + 1 == 0, x]

MapIndexed[(gg[#2[[1]]][a_] := #) &, x /. sols];

This makes assignments to the symbol gg.
The function is then used with the syntax gg[1][17] to mean the first solution, and a == 17:
Plot[gg[1][a], {a, 1, 4}]

gg[2] /@ {1, 2, 3}

{1/2 (-1 + I Sqrt[3]), -1, 1/2 (-3 + Sqrt[5])}

A: You can transform the rules returned by Solve into lists by using ReplaceAll or its short form /. as follows
Solve[x == 1 && 2 >= y >= 1, {x, y}, Integers] /.  Rule[a_, b_] -> b

This produces a list of lists: {{1, 1}, {1, 2}}. To get the results in the format you desire you can pass this list through a function that takes a pair {a,b} and returns {x->a,y->b}. A function like
  {x -> #[[1]], y -> #[[2]]} &

does does exactly this tranformation. Combining the two steps
 solutionlist = (Solve[x == 1 && 2 >= y >= 1, {x, y}, Integers] /.
       Rule[a_, b_] -> b ) // {x -> #[[1]], y -> #[[2]]} &

produces
 {x -> {1, 1}, y -> {1, 2}}

for your example case.
To use the values from the solution, you can use
{xlist, ylist} = {x, y} /. solutionlist

Checking
 ?xlist

gives

EDIT: To delete duplicates change the function {x -> #[[1]], y -> #[[2]]} & to
 {x -> Union@#[[1]], y -> Union@#[[2]]} &


text:
Q: Using the value from a map as a key to another value in the map of a mustache template I'm using the jknack Java port of Handlebars. I need to create an A-Z list. The key to the map is a letter of the alphabet. At the moment, I have 26 of these in the mustache template:
{{#if A}}
A
{{else}}
A
{{/if}}

It would be nice of I could add an array of the letters to the model under the key "keys", for example, and loop through the results:
{{#keys}}
   {{#if .}}
{{.}}
{{else}}
{{.}}
{{/if}}
{{/keys}}

However, this doesn't check to see if the map has a key matching the value of the period.
Is there a way of using a value obtained from the map as the key to another object in the map?
Updated information
Looking at Mark's entry I can see that I was approaching the problem from the wrong direction. My model didn't have an entry in the Map if a letter had no results. However, if I update my model so that a key (letter) has an empty list rather than no key/entry at all then I can just use the keys on the Map rather than trying to use another entry to provide values that could represent all possible keys.

A: I'm not sure what your index data format looks like, so imagine the index was in JSON in this format:
{
   "items":[
      {
         "A":[]
      },
      {
         "B":[
            "dummy",
            "dummy",
            "dummy"
         ]
      },
      {
         "C":[]
      },
      {
         "D":[
            "dummy",
            "dummy",
            "dummy"
         ]
      },
      {
         "E":[]
      },
      {
         "F":[
            "dummy",
            "dummy",
            "dummy"
         ]
      }
   ]
}

Now to iterate through displaying used/unused indexes would require a template like:

{{#items}}
{{#each .}}
{{#if .}}

{{@key}}

{{else}}

{{@key}}

{{/if}}
{{/each}}
{{/items}}

which for the above example data would result in:

A

B

C

D

E

F

redpajama_set_name: RedPajamaStackExchange


text:
Q: TS interface - Object with any properties How to define interface in TypeScript for object with any properties?
interface Data {
  properties: Properties;
}

interface Properties {
  ...
}

A: An object with any properties is just like any. Why definining an additional interface?
One reason could be, that you want to allow specific value types. Then you can do something like this:
interface Properties {
  [key: string]: string|number|boolean;
}

A: You want the Record<> type:
interface Data {
  properties: Record<string, number|boolean|string>
}

A: Maybe you are looking for this
type Primitive = string | number | boolean
interface Data {
  [key: string]: Primitive
}

const data1: Data = {
  a: 1,
  b: true,
  c: 'asd'
}

// you basically dont need `Data` interface, instead you can use `Record` as below
const rec: Record<string, Primitive> = data1


text:
Q: Storybook nuxt build does not includes decorators TLDR:
Problem with nuxt + storybook + vuetify build
I've created a new project using Nuxt.js, Vuetify, and Storybook.
The Storybook dev server is working great, I only had to add a single decorator to the nuxt config:
// nuxt.config.js
storybook: {
    decorators: [
      // VApp decorator for Vuetify
      '<v-app>
<story/>
</v-app>',
    ],
  },

The only problem that is seems that when running the build it does not load the decorators so the Storybook does not represent the visual aspect properly.
// package.json
"storybook": "nuxt storybook",
"storybook:build": "nuxt storybook build"

Note:
I did use the official nuxt storybook
Example of Dev:

Example of Build:

A: OK so it took me a few trials and errors but I've made it work.
1) Add Vuetify as a plugin
The first thing that we would like to do is create a vuetify.js file in the plugin directory
.
├── plugins
│   └── vuetify.js

import Vue from 'vue';
import Vuetify from 'vuetify';
import colors from 'vuetify/es5/util/colors';
import { themes } from '~/config/themes';

import 'vuetify/dist/vuetify.min.css';

Vue.use(Vuetify);

export default (ctx) => {
  const vuetify = new Vuetify({
    customVariables: ['~/assets/variables.scss'],
    treeShake: true,
    options: {
      customProperties: true,
    },
    theme: {
      themes: {
        light: {
          ...themes.light,
        },
      },
    },
  });
  ctx.app.vuetify = vuetify;
  ctx.$vuetify = vuetify.framework;
};

2) Update nuxt config to load Vuetify
In your nuxt.config.js make sure you remove the Vuetify config and add vuetify as a plugin like so:
// nuxt.config.js
  plugins: ['@/plugins/vuetify.js'],

3) Add Storybook Decorator
Add a Vuetify decorator to support Vuetify in all of the Storybook stories.
In your nuxt.config.js add the following decorator
// nuxt.config.js

  storybook: {
    // Options
    decorators: [
      // VApp decorator for Vuetify
      `<v-app id='vuetify-storybook-decorator'><div><story/></div></v-app>`,
    ],
  },

4) Fix Storybook Visibility
To prevent eatch story taking too full screen height and allowing presenting more then a single story in a view, we would override the default vuetify min-height only in storybook;
In your nuxt.config.js file load a storybook.scss like so
// nuxt.config.js

 // Global CSS (https://go.nuxtjs.dev/config-css)
 css: ['@/assets/storybook.scss'],

And in your assets folder add the storybook.scss file:
.
├── assets
│   └── storybook.scss

/* storybook.scss */

#vuetify-storybook-decorator {
  // Remove the storybook full height of all components
  .v-application--wrap {
    min-height: unset;
  }
}

5) Build the project
Add the build comand to your package.json
// package.json
{
    "storybook": "nuxt storybook",
    "storybook:build": "nuxt storybook build"
}

Then run in the command line yarn storybook:build
The build will be placed in /storybook-static;
You can view the build by running any server on that folder, for example:
$ npx http-server ./storybook-static

That's it, I hope it would be helpfull:)


text:
Q: How to pass string from first html page to second html page in chromium framework (CEF)? I have two html page and I need to pass string value of first html page to second html page. I abed to get string value from first html page and now i want to pass to second html page.
I have tried this but does not work
const int64 frame_id =frame->GetIdentifier();  // getting frame id of second html page in OnContextCreated() method
      CefRefPtr<CefBrowser> contextRef1;
      string st = value;     //value from first html page
 CefRefPtr<CefFrame> frame = contextRef1->GetFrame(frame_id );
CefRefPtr<CefV8Context> context = frame->GetV8Context();
CefRefPtr<CefV8Context> contextRef2 = context->GetCurrentContext();
CefRefPtr<CefV8Value> object1 = contextRef2->GetGlobal();
str = CefV8Value::CreateString(value);
 object1->SetValue("myval", str, V8_PROPERTY_ATTRIBUTE_NONE);


text:
Q: gestures with new hammer.js is not working like before I just update hammer.js to newest version but after update I have error:
Uncaught TypeError: Cannot read property 'target' of undefined

because
var fieldId = event.gesture.target.id.split('_')[0];

Gestures are working but how can I handle my fieldId in new hammer.js ?
thanks for any help

A: See the API documentation.
The target is (now) a direct descendant of the event. So you're probably looking for simply event.target.


text:
Q: Mismatch output between custom loss function and in-built loss function I'm trying to implement the binary cross entropy loss instead of using keras function. Here is my code:
def softmax_fn(val):
  return tf.math.exp(val) / tf.math.reduce_sum(tf.math.exp(val))

def bce_fn(y_true, y_pred):
  y_pred_softmax = softmax_fn(y_pred)
  bce_loss = tf.cast(y_true, tf.float32) * tf.math.log(y_pred_softmax) + (1.0 - tf.cast(y_true, tf.float32)) * tf.math.log(1.0 - y_pred_softmax)
  return -tf.math.reduce_mean(bce_loss)

My problem is that i have an output mismatch between my loss and the keras one:
# keras loss
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)

y_true = [1.0, 1.0, 0.0, 0.0]
y_pred = [1.0, 0.0, 1.0, 0.0]

print(cross_entropy(y_true,y_pred))  # 0.75320446
print(bce_fn(y_true,y_pred))  # 0.903049

Could somenone explain me why is this happening?
Edit
I found the error: using from_logits=True in the in-built loss function means that we calculate probabilities like a sigmoid function and not like a softmax function. This discussion helped me
def bce_fn(y_true, y_pred):
  y_pred_sigmoid = tf.math.sigmoid(y_pred)  # sigmoid activation
  bce_loss = tf.math.reduce_mean(tf.cast(y_true, tf.float32) * -tf.math.log(y_pred_sigmoid) + (1 - tf.cast(y_true, tf.float32) ) * -tf.math.log(1 - y_pred_sigmoid))
  return bce_loss

Now the in-built function and my custom function have the same output.

A: Thank you Alexandru Ropotica for the update. For the benefit of community, posting solution in answer section.
# BinaryCrossentropy custom inbuilt function:
def bce_fn(y_true, y_pred):
  y_pred_sigmoid = tf.math.sigmoid(y_pred)
  bce_loss = tf.math.reduce_mean(tf.cast(y_true, tf.float32) * -tf.math.log(y_pred_sigmoid) + (1 - tf.cast(y_true, tf.float32) ) * -tf.math.log(1 - y_pred_sigmoid))
  return bce_loss

cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)

y_true = [1.0, 1.0, 0.0, 0.0]
y_pred = [1.0, 0.0, 1.0, 0.0]

print(cross_entropy(y_true,y_pred))
print(bce_fn(y_true,y_pred))

Output:
tf.Tensor(0.75320446, shape=(), dtype=float32)
tf.Tensor(0.75320446, shape=(), dtype=float32)


text:
Q: resize and save html2canvas generated image Here is the script I am using

HTML

Html2Canvas javaScript screenshot creator

<form class="well form-search"> Website URL:
    <input type=url id=url value="http://www.google.co.in" class="input-medium search-query"/><button class=btn id=getscreenshot>Get screenshot!</button>
</form>
Disable JavaScript (recommended, doesn't work well with the proxy)
<input id="disablejs" type="checkbox" checked="">

now it is generating screenshot of html body content
I need to resize the image and (store in/upload to) local server

A: What you need to do is send the source of the image to the server either by using ajax or by submiting a form. To get the source use something like:
var src = $("#your-image").attr('src');
$.post(url, {'source':src}, function(data){});

And in the php:
$img = $_POST['source'];
file_put_contents('image_file', base64_decode($img));

Haven't tested the code but should get you on the right track.

A: Instead of sending the image to the server,this seems a good approach. We can draw the image on another canvas using the drawImage method.
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);

sx ---- x coordinate where to start clipping
sy ---- y coordinate where to start clipping
swidth---- width of the clipped image
sheight---- height of the clipped image
x ---- x coordinate where to place the image on the canvas
y ---- y coordinate where to place the image on the canvas
width ---- width of the image to be used.
height ---- height of the image to be used.
After drawing on the canvas, we can get back the image source using "toDataURL".
 finalImgSrc = mycanvas.toDataURL();

With the help of this image source, we can get the image element.


text:
Q: A second hard drive, not working I have a second hard drive in my machine. It has worked correctly for.... ages. For some reason I can not work out, it has "stopped working".
When I use fdisk-l the second drive it simply is not seen. Disk Checker does not see it. I do not know what it used to be called other than "second drive".
I have opened my PC and physically remounted it but still I can not see it.
It used 100% for extra storage, not dual boot or anything complicated.
As an aside, since it "failed to work" boot up times seem to be longer but I do not know if this is perception or coincidence.
Any clues from anyone ?

A: Your second hard-drive is maybe just broken... Have you tried to use it in another machine ? You may also try to install it as master HDD and launch a bootable CD/USB key in order to check if it can be detected. I would also to put it in a USB enclosure, as you may get more debug information if plugged on a running system than at boot time.
The longer boot time suggests that either your OS is looking for the second HDD or has trouble accessing it. BTW, do you hear any noise (movement of heads on a classical HDD) ?

A: In short, it is just broken. Old fashioned broken.
I've tried a number of software solutions, from TestDisk, GParted and ..... and none of them were able to see the disk. I've also taken it out of the machine and put it in a USB enclosure. At this point I could hear a faint ticking as it was trying to mount, which, as mentioned above, would explain the longer boot times.
So, it is just broken.
P.


text:
Q: Adding a transition effect when hovering over a custom CSS checkbox I have a custom CSS checkbox as seen here: https://jsfiddle.net/apewjcg9/
Don't worry too much about the positioning and sizing of things. My main question is to deal with adding an ease-in transition when hovering over the checkbox. As you can see, when hovering, I have a border being applied to the box itself. However, I'd like a small ease-in transition effect for that border. No matter what I have tried, no transition appears to be applied.
HTML
<input type="checkbox" class="checkbox" id="myCheckbox" />
This is a checkbox label

CSS
.checkbox {
  opacity: 0;
  position: absolute;
}

.checkbox + .checkboxLabel::before {
  background-color: white;
  border: 1px solid black;
  border-radius: 2px;
  content: '';
  display: inline-block;
  height: 18px;
  width: 18px;
  font-size: 16.5px;
  text-align: center;
  vertical-align: top;
  margin-right: 5px;
}

.checkbox:checked + .checkboxLabel::before  {
  background-color: firebrick;
  border-radius: 2px;
  color: white;
  content: '\2713';
  font-size: 19px;
  line-height: 18px;
}

.checkboxLabel {
  cursor: pointer;
  display: inline-block;
  margin: 0;
}

.checkbox:hover + .checkboxLabel::before {
  border: 1.5px solid firebrick;
  box-sizing: border-box;
}

I've tried adding transition: border 1s to .checkbox + .checkboxLabel::before, to the label itself, to the input, nothing has worked as far as making that ease-in transition happen.

A: It looks like you got really close to the solution when trying to use transition: border 1s, just a small tweak to move it to the hover styling and it should work as you intended.
Something like the below will transition the colour. The box-sizing property that you've got on there currently will be changing the positioning of the box slightly which could be a little jarring - you could remove this if you wanted the box size/shape to stay the same.
.checkbox:hover + .checkboxLabel::before {
  border: 1.5px solid firebrick;
  box-sizing: border-box; <--- removing this will create a smoother transition
  transition: border 0.4s ease;
}

I've opted for ease in the transition, but here's a guide to help you decide which transition timing to go for.

A: You can use transition property to time the duration of the transition and then use transform: scale(x) to give it a zoom effect.

.checkbox {
  opacity: 0;
  position: absolute;
}

.checkbox+.checkboxLabel::before {
  background-color: white;
  border: 1px solid black;
  border-radius: 2px;
  content: '';
  display: inline-block;
  height: 18px;
  width: 18px;
  font-size: 16.5px;
  text-align: center;
  vertical-align: top;
  margin-right: 5px;
}

.checkbox:checked+.checkboxLabel::before {
  background-color: firebrick;
  border-radius: 2px;
  color: white;
  content: '\2713';
  font-size: 19px;
  line-height: 18px;
}

.checkboxLabel {
  cursor: pointer;
  display: inline-block;
  margin: 0;
}

.checkbox:hover+.checkboxLabel::before {
  border: 1.5px solid firebrick;
  transition: 0.5s;
  transform: scale(1.1);
}
<input type="checkbox" class="checkbox" id="myCheckbox" />
This is a checkbox label

A: You can try changing the  to make the transition effect visible clearly and then add {transition} property for the {border-width} and {border-color}  in color by making these changes to the code.
.checkbox:hover + .checkboxLabel::before {
      border: 4px solid firebrick;
      box-sizing:border-box;
      transition:
          border-width 0s ease-in 0.25s,
          border-color 0.25s ease-in 0.5s;

    }


text:
Q: Let $R$ be the set $\mathbb{R}$ of all real numbers with the co-finite topology. How can one show that $R$ is contractible? I have recently started learning Algebraic Topology, and more specifically, homotopy theory. That is where I encountered this question:

Let $R$ be the set $\mathbb{R}$ of real numbers, with the co-finite topology. Show that $R$ is contractible.

I already have some knowledge of point-set topology, the definition of homotopy, homotopy equivalence and the meaning of a contractible space.
The idea I used to approach the problem was to try and show that the identity map on $R$ was null homotopic. I considered the identity map $id:R\to R$ and $c:R\to R$, defined as $c(x)=x_0$ for all $x\in R$, where $x_0\in R$. I tried to check if the function $H:R\times\mathbb{I}\to R$ (where $\mathbb{I}=[0,1]$), given by $H(x,t)=(1-t)x+tx_0$, was continuous in the product topology by checking if the pre-images of closed sets are closed, but that is where I am stuck. I am finding it hard to do that.
Besides that, I found a result on the following webpage that might be helpful, albeit requiring a different approach. If it is possible to show that $R$ is path-connected, then that result suggests that it would be contractible. I am yet to perfectly understand the proof to it, but it could be applied too. Here's the link to it:
A strange contractible space.
Any help would be much appreciated.

A: In your linked blogpost there is the lemma

Let $X$ have the cofinite topology; then if $X$ is path-connected, then $X$ is contractible.

And $\Bbb R$ in the cofinite topology is path-connected: if $x \neq y$ in $\Bbb R$ then $p: [0,1] \to \Bbb R, p(t)=tx+(1-t)y$ is injective and thereby automatically continuous when the codomain has the cofinite topology (inverse images of closed sets are closed!), as $[0,1]$ is metric hence $T_1$.
So the proof in the blog applies and $\Bbb R$ in the cofinite topology is contractible.


text:
Q: Two columns are dependent on the values of a third column. How to I do link these values I have this dataframe as follows:
hello=pd.DataFrame(data={'citing':[11,13,11,15,17,18,18,17,20,15],'cited'[13,15,18,20,18,15,15,20,13,11],\
                       'firm':'A','D','A','C','D','C','C','D','F','C']})

The column citing has its corresponding firm value in the same row. All the elements in column-cited can be found in column-citing but in a different order. I'm trying to make another column that would list the firm values for "cited" based on the firm values that were obtained from citing.
For eg. the new column would have the values of ['B','C','E','F','E','C','C','F','B','A']. This is because 13 in 'citing' has a firm value of 'B'. Hence, 13 in 'cited' should also have 'B' in the new column. I Hope, I was able to explain this properly. Would highly appreciate if you could please help. Thanks!

A: You can use map.
hello['firm2'] = hello.cited.map(hello.drop_duplicates('citing').set_index('citing').firm)

    citing  cited   firm    firm2
0   11      13      A       B
1   13      15      B       C
2   11      18      A       E
3   15      20      C       F
4   17      18      D       E
5   18      15      E       C
6   18      15      E       C
7   17      20      D       F
8   20      13      F       B
9   15      11      C       A


text:
Q: Random NullReferenceException on Postback I have been stumped with this one. Users will randomly get a null reference exception when performing a postback. It seems to me the problem is coming from the model binder and possibly the order at which the properties a parsed. Just wanted to see if anyone has any input? Ive not been able to duplicate will debugging, only happens in production randomly on postback.
Fairly Simple ViewModel:
 public class ViewModel
{
    public Load Load { get; set; }

    public bool ReadOnly
    {
        get
        {
            return this.GetStatus(Load.Date);
        }
    }

    public Load PrevLoad { get; set; }

    private bool GetStatus(DateTime? date)
    {
        if (date != null)
        {
            if (date.Value.DayOfWeek == DayOfWeek.Monday)
                date = date.Value.AddDays(-2);

            return ((DateTime.Now.AbsoluteEnd() - date.Value.AbsoluteEnd()).TotalHours) <= -24 ? false : true;
        }
        else
            return true;
    }
}

StackTrace (Note I x'd out business sensitive namespaces):
System.Reflection.TargetInvocationException: Property accessor 'ReadOnly' on object

'XXX.XX.XXX.XXX.ViewModel' threw the following exception:'Object reference not set to an instance of an object.' ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at XXX.XX.XXX.ViewModels.ViewModel.get_ReadOnly()
   --- End of inner exception stack trace ---
   at System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component)
   at System.Web.Mvc.DataAnnotationsModelValidator.<Validate>d__15.MoveNext()
   at System.Web.Mvc.ModelValidator.CompositeModelValidator.<Validate>d__1.MoveNext()
   at System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
   at System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
   at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
   at System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass1e.<BeginInvokeAction>b__16(AsyncCallback asyncCallback, Object asyncState)

When I pass null to this.GetStatus I get a different exception; So I know that cant be it.
Do you think this is throwing an exception because there technically isnt an instance of the ViewModel when modelBinding occurs and when attempting to access this.GetSatus it fails?  That still wouldn't explain why this sometimes occurs.

A: According to the first line of the stack trace:

at XXX.XX.XXX.ViewModels.ViewModel.get_ReadOnly()

The exception is coming from here:
public bool ReadOnly
{
    get
    {
        return this.GetStatus(Load.Date);
    }
}

Assuming that this can never be null, that just leaves Load.  Looking at the rest of the view model, Load is never explicitly initialized.  The view model assumes that Load will be set when the view model is created.  If that's ever not the case, expect this exception.
Additionally in the stack trace, it looks like the framework is trying to read the properties on the view model in order to perform some validation.  This particular view model makes the assumption that Load will be initialized before it will ever be read, which isn't a very safe assumption to make.
One approach could be to initialize Load in the view model:
public ViewModel()
{
    this.Load = new Load();
}

As long as the same assumption doesn't exist elsewhere in the stack, this will at least ensure that Load doesn't give you a NullReferenceException.
In general it should be the internal responsibility of any given model to construct itself in a valid state.  Never assume that consuming code is going to set all of the properties.


text:
Q: How to print in decimal form rather than exponential form in perl I have written a program in perl.My requirement is to print the only the decimal numbers, not exponential numbers. Could you please let me know how to implement this ?
My program is calculating the expression 1/2 power(n) , where n can take up integer numbers from 1 to 200 only. And only 100 lines should be printed.
Example:
N=1, print 0.5
N=2, print 0.25
My program looks like:
   #!/usr/bin/perl
   use strict;
   use warnings;
   my $exp;
   my $num;
   my $count_lines = 0;
   while($exp = <>)
   {
        next if($exp =~ m/^$/);
        if($exp > 0 and $exp <=200 and $count_lines < 100)
        {
            $num = 1/(2 ** $exp);
            print $num,"\n";
            $count_lines++;
       }
  }

Input values:
If N = 100 , then out is getting printed in exponential form. But, the requirement is it should get printed in decimal form.

A: A simple print will pick the "best" format to display the value, so it chooses scientific format for very large or very small numberss to avoid printing a long string of zeroes.
But you can use printf (the format specifiers are documented here) to format a number however you want.
0.5200 is a very small number, so you need around 80 decimal places
use strict;
use warnings;

while (my $exp = <>) {

  next unless $exp =~ /\S/;
  my $count_lines = 0;

  if ($exp > 0 and $exp <= 200 and $count_lines < 100) {
    my $num = 1 / (2 ** $exp);
    printf "%.80f\n", $num;
    $count_lines++;
  }
}

output for 100
0.00000000000000000000000000000078886090522101181000000000000000000000000000000000

and for 200
0.00000000000000000000000000000000000000000000000000000000000062230152778611417000

If you would like to remove insignificant trailing zeroes then you can use sprintf to put the formatted number into a variable and then use s/// to delete trailing zeroes, like this
my $number = sprintf "%.80f", $num;
$number =~ s/0+$//;
print $number, "\n";

which gives
0.00000000000000000000000000000078886090522101181

and
0.00000000000000000000000000000000000000000000000000000000000062230152778611417

Note that the true value of the calculation has many more digits than this, and the accuracy of the result is limited by the size of the floating point values that your computer uses.

A: 0.5 ^ 200 is too small for a double floating point number, you need to use Math::BigFloat, that will overload basic math operations and output operators such as print for you, for example:
#!/usr/bin/perl

use strict;
use warnings;

use Math::BigFloat;

my $x = Math::BigFloat->new('0.5');
my $y = Math::BigFloat->new('200');

print $x ** $y, "\n";

Or use bignum:
#!/usr/bin/perl

use strict;
use warnings;

use bignum;

print 0.5 ** 200, "\n";

Output:
$ perl t.pl
0.00000000000000000000000000000000000000000000000000000000000062230152778611417071440640537801242405902521687211671331011166147896988340353834411839448231257136169569665895551224821247160434722900390625

A: You can use printf or sprintf to specify the format of what you want to print out.
#!/usr/bin/perl

use strict;
use warnings;

my $num = 0.000000123;

printf("%.50", $num)

If you need something like Perl 5 formats, take a look at Perl6::Form (note, this is a Perl 5 module, it just implements the proposed Perl 6 version of formats).


text:
Q: Matlab FFT and FFTW I'm trying to have the same FFT with FFTW and Matlab. I use MEX files to check if FFTW is good. I think I have everything correct but :

*

*I get absurd values from FFTW,

*I do not get the same results when running the FFTW code several times on the same input signal.

Can someone help me get FFTW right?
--
EDIT 1 : I finally figured out what was wrong, BUT...
FFTW is very unstable : I get the right spectrum 1 time out of 5 !
How come? Plus, when I get it right, it doesn't have symmetry (which is not a very serious problem but that's too bad).
--
Here is the Matlab code to compare both :
fs = 2000;                    % sampling rate
T = 1/fs;                      % sampling period
t = (0:T:0.1);                % time vector

f1 = 50;                       % frequency in Hertz
omega1 = 2*pi*f1;              % angular frequency in radians

phi = 2*pi*0.25;               % arbitrary phase offset = 3/4 cycle
x1 = cos(omega1*t + phi);      % sinusoidal signal, amplitude = 1

%%

mex -I/usr/local/include -L/usr/local/lib/ -lfftw3 mexfftw.cpp

N=256;
S1=mexfftw(x1,N);
S2=fft(x1,N);
plot(abs(S1)),hold,plot(abs(S2),'r'), legend('FFTW','Matlab')

Here is the MEX file :
/*********************************************************************
 * mex -I/usr/local/include -L/usr/local/lib/ -lfftw3 mexfftw.cpp
 * Use above to compile !
 *
 ********************************************************************/
#include <matrix.h>
#include <mex.h>

#include "fftw3.h"

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {

//declare variables
mxArray *sig_v, *fft_v;
int nfft;

const mwSize *dims;
double *s, *fr, *fi;
int dimx, dimy, numdims;

//associate inputs
sig_v = mxDuplicateArray(prhs[0]);
nfft = static_cast<int>(mxGetScalar(prhs[1]));

//figure out dimensions
dims = mxGetDimensions(prhs[0]);
numdims = mxGetNumberOfDimensions(prhs[0]);
dimy = (int)dims[0]; dimx = (int)dims[1];

//associate outputs
fft_v = plhs[0] = mxCreateDoubleMatrix(nfft, 1, mxCOMPLEX);

//associate pointers
s = mxGetPr(sig_v);
fr = mxGetPr(fft_v);
fi = mxGetPi(fft_v);

//do something
double *in;
fftw_complex *out;
fftw_plan p;

in = (double*) fftw_malloc(sizeof(double) * dimy);
out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * nfft);
p = fftw_plan_dft_r2c_1d(nfft, s, out, FFTW_ESTIMATE);

fftw_execute(p); /* repeat as needed */

for (int i=0; i<nfft; i++) {
    fr[i] = out[i][0];
    fi[i] = out[i][1];
}

fftw_destroy_plan(p);
fftw_free(in);
fftw_free(out);

return;
}

A: Matlab uses the fftw library to perform its ffts, on my platform (Mac OS) this leads to issues with the linker as mex replaces the desired library with Matlab's version of fftw. To avoid this static link to the library using mex "-I/usr/local/include /usr/local/lib/libfftw3.a mexfftw.cpp".
The input of fftw_plan_dft_r2c_1d is not destroyed so you don't need to duplicate the input (note: not true for fftw_plan_dft_c2r_1d). The output has size nfft/2+1 as the output of a real fft is Hermitian. So to get the full output use:
for (i=0; i<nfft/2+1; i++) {
    fr[i] = out[i][0];
    fi[i] = out[i][1];
}
for (i=1; i<nfft/2+1; i++) {
    fr[nfft-i] = out[i][0];
    fi[nfft-i] = out[i][1];
}

A: Should "p = fftw_plan_dft_r2c_1d(nfft, s, out, FFTW_ESTIMATE);"
be
"p = fftw_plan_dft_r2c_1d(nfft, in, out, FFTW_ESTIMATE);".
'in' is 16-byte aligned, but 's' may not.
I am not sure whether it will cause a problem.  I have a similar code about FFTW,
 it sometimes gives me correct result and other times NaN. Also, I tried to test
my code with python ctypes, and actually it has the same weired behavior.
Finally, I found this post Checking fftw3 with valgrind, and it helps me.
For me, the issue is the reservation of heap storage in FFTW which are not freed
even after the program terminates.

fftw_cleanup()

resolves my problem. Maybe it can help you too.


text:
Q: How to get index of the matching group I want to list all matching groups in the input. For example, I want to print all browsers I care about in a User-Agent HTTP header. One match is enough. Is there a way to get rid of the inner for loop in the code below. I looked in the boost/regex/sub_match.hpp and I have no ideas.
#include <string>
#include <iostream>
#include <boost/regex.hpp> // Boost 1.59, no C++14 for me

enum BrowserType
{
    FIREFOX = 0 ,
    CHROME,
    SAFARI,
    OPERA,
    IE,
    EDGE,
    OTHER,
};

const boost::regex BROWSERS_REGEX("(Firefox)|(Chrome)|(Safari)|(Opera)|(MSIE)|(Edge)|(Trident)");

int main()
{
        // I expect two matches here CHROME and SAFARI
        std::string input("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36 Chrome/62.0.3202.94");
        boost::sregex_iterator res(input.begin(), input.end(), BROWSERS_REGEX);
        boost::sregex_iterator end;
        for(; res != end; ++res)
        {
                // elude copy here ?
                boost::smatch what = *res;
                // Can I know the index of the matching group w/o 'for'?
                for (int type = 0;type < OTHER;type++)
                {
                        int groupIndex = type+1;
                        if (what[groupIndex].matched)
                                std::cout << (BrowserType)type << ",";
                }
                std::cout << "\n";

        }

        return 0;
}

Important update. The strstr() based code is the fastest approach for strings shorter than 1K bytes
    const char *input("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36 Chrome/62.0.3202.94");
    const char *browsers[OTHER+1] = {"Firefox", "Chrome", "Safari", "Opera", "MSIE", "Edge", "Trident"};
    int i = 0;
    for (const char **browser = &browsers[0];browser <= &browsers[OTHER];browser++, i++)
    {
            if (strstr(input, *browser))
            {
                    groupindex = i;
            }
    }

A: You can use named captures.
I just used it earlier today: While doing url encoding , The std::regex_replace doesn't work properly for character "+" . Can some body help me out?
In your case, though, I'd use qi::symbols:
struct browser_type_sym : boost::spirit::qi::symbols<char, BrowserType> {
    browser_type_sym() {
        this->add
            ("Firefox", FIREFOX)
            ("Chrome",  CHROME)
            ("Safari",  SAFARI)
            ("Opera",   OPERA)
            ("MSIE",    IE)
            ("Edge",    EDGE)
            ("Trident", OTHER);
    }
} static const browser_type;

You can simply use it with any container of BrowserType:
template <typename Types>
bool extract_browser_ids(std::string const& userAgent, Types& into) {
    using boost::spirit::repository::qi::seek;
    return parse(userAgent.begin(), userAgent.end(), *seek [ browser_type ], into);
}

Using vector<BrowserType>
As you will see, if you use vector<BrowserType it will retain order and duplicates:
Live On Coliru
int main() {
    for (std::string const input : {
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36 Chrome/62.0.3202.94",
            "Chrome; Opera; Chrome again!"
    }) {
        std::vector<BrowserType> types;
        extract_browser_ids(input, types);
        for(auto type : types)
            std::cout << type << ",";

        std::cout << "\n";
    }
}

Prints:
2,1,
1,3,1,

Using set<BrowserType>
When using set<> it will order and de-duplicate:
Live On Coliru
    std::set<BrowserType> types;

Prints:
1,2,
1,3,

Case Insensitivity
Just to show minor tweaks:
struct browser_type_sym : boost::spirit::qi::symbols<char, BrowserType> {
    browser_type_sym() {
        this->add
            ("firefox", FIREFOX)
            ("chrome",  CHROME)
            ("safari",  SAFARI)
            ("opera",   OPERA)
            ("msie",    IE)
            ("edge",    EDGE)
            ("trident", OTHER);
    }
} static const browser_type;

template <typename Types>
bool extract_browser_ids(std::string const& userAgent, Types& into) {
    using boost::spirit::repository::qi::seek;
    using boost::spirit::qi::no_case;
    return parse(userAgent.begin(), userAgent.end(), *seek [ no_case [ browser_type ] ], into);
}

Now case doesn't matter: Live On Coliru
Alternative: Boost Xpressive
Similarly you can use Boost Xpressive, which is slightly closer to the regex approach (though internally it still builds a trie of strings from the map).
The semantic actions require more manual labour, making it also less generic (it won't work with std::set without changes, unlike the Spirit Qi approach already shown).
Nevertheless, for completeness:
Live On Coliru
std::map<std::string, BrowserType> s_browser_type_map {
        {"Firefox", FIREFOX},
        {"Chrome",  CHROME},
        {"Safari",  SAFARI},
        {"Opera",   OPERA},
        {"MSIE",    IE},
        {"Edge",    EDGE},
        {"Trident", OTHER},
    };

#include <boost/xpressive/xpressive.hpp>
#include <boost/xpressive/regex_actions.hpp>

template <typename Types>
void extract_browser_ids(std::string const& userAgent, Types& into) {
    using namespace boost::xpressive;

    placeholder<Types> _result;
    sregex type = (a1 = s_browser_type_map) [ push_back(_result, a1) ];

    for (sregex_iterator it(userAgent.begin(), userAgent.end(), type, let(_result=into)),
            end; it != end; ++it)
    { } // all side-effects in the semantic action
}

Which prints the same output as the vector<> Spirit example:
2,1,
1,3,1,


text:
Q: http request by node-red with execution the stript I would like ask,
When I use node http request from Node-red for request to any page it returned me whole page like
msg.payload="<'html>
<'script>
function A;
function B;
window.onload = function() {...
etc...
<'/script>
<'body>
<'table>"

How can I execute the functions from the script? So how it could return executed page to node-red?
I mean, I need the results from the fucntions and I get just function in payload, so I don't know how could I execute function which are in payload.
Thank you
Pavol

A: The short answer is, you don't.
Running JavaScript embedded in a web page needs all the things a browser provides to the page, e.g. the DOM model these are just not there in the Node-RED runtime.
If you want to load and render a page then you need to look at something like node-red-contrib-nbrowser that will run the page in a virtual browser.


text:
Q: How to wrap DrawerLayout around PreferenceActivity in an Android app? I am writing an Android app to take advantage of Drawer Layout functionality. I want to have an ability to use Drawer Layout as a navigational tool available throughout the app. To use the Drawer Layout, I am using the following in my activity layout xml files:
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- The main content view -->
    <LinearLayout
        android:id="@+id/main_content_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- The navigation drawer -->
    <ListView android:id="@+id/navigational_drawer"
        android:layout_width="220dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#FFFFFF"/>
</android.support.v4.widget.DrawerLayout>

However, I am having a lot of difficulties wrapping DrawerLayout around the PreferenceActivity. PreferenceActivity is a special sort of activity that I'd like to preserve because it helps me to maintain the look and feel of the Android preferences in my app; that being said, it uses addPreferencesFromResource() calls to load preferences and does not use addContentView() calls to load XML files; the preference resources typically contain PreferenceScreen tags that don't like to be wrapped in DrawerLayouts.
Anybody had to deal with that issue and how did you solve it? If you have PreferenceActivity in your Android app and you have DrawerLayout available on the same activity, please share how did you do it. Any help would be much appreciated.
EDITED: If I change
<!-- The main content view -->
<LinearLayout
    android:id="@+id/main_content_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

to
<ListView
     android:id="@android:id/list"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent" />

then the app doesn't crash when PreferenceActivity is loaded (because the id "list" matches what the Preference Activity is expecting to find); however, the Drawer is not showing. It's almost as if everything below the ListView "list" is getting ignored.

A: This one took me a while, but I was able to make this work for my app. I don't know if it makes a difference, but I am using HoloEverywhere, so I only assume this will work on the standard PreferenceActivity as well.
In my PreferenceActivity when I overrode all versions of setContentView() to load my custom DrawerLayout which is like yours and has a ListView with the standard android id of list. In the last method I made sure to call onContentChanged() after I called super.setContentView():
@Override
public void setContentView(int layoutResID)
    {
    setContentView( getLayoutInflater().inflate( layoutResID ) );
    }

@Override
public void setContentView(View view)
    {
    setContentView( view, new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT ) );
    }

@Override
public void setContentView(View view, LayoutParams params)
    {

    // inflate the drawer layout

    super.setContentView( R.layout.navigation_drawer_base_layout );

    DrawerLayout dl = findViewById(R.id.drawer_layout);

    // do stuff here initialize the DrawerLayout like add a DrawerToggle, etc

    ...STUFF

    // Call onContentsChanged() to let the Activity know it needs to refresh itself.

    onContentChanged();

    }

In onBuildHeaders() I still call loadHeadersFromResource() to create all the Headers for my different PreferenceScreens.


text:
Q: How to fix Cannot find preset schema for namespace: http://www.sitemaps.org/schemas/sitemap/0.9 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">

==Schema Error: Cannot find preset schema for namespace: http://www.sitemaps.org/schemas/sitemap/0.9.


text:
Q: Advice for transformation in mixed models I use mixed models (random effect for person; repeated measurements) in lme4 to model a continuous outcome. Predictors are both categorical and continous.
My outcome variable (blood pressure; typically between 100 and 170) has a non-linear evolution over time, which is presented in the figure below.

code used:
model <- lmer(pressure ~ sex + treatment + onset_age + follow_up_time + (1|subject_ID), data=mixed6)

As you can see (figures) my model doesn't satisfy linearity. I have tried the following:
* centering the response variable
* not centering the time variable, i.e using the time variable as it is
* using the logarithm of the time variable.
* adding the square of the time variable (I(follow_up_time ^2)) to the model.
There are >700k observations in the study. 120k individuals.
I've heard that with that many observations, many of the assumptions of linearity become less important.
Any advice on transformations?
Should i convert to generalized mixed models or perhaps the non-linear (nlme?)?
I would really appreciate some opinions on this matter.


text:
Q: About Arrow Functions in JavaScript Confused about how arrow functions work...In this particular example:
class VillageState {
  constructor(place, parcels) {
    this.place = place;
    this.parcels = parcels;
  }

  move(destination) {
    if (!roadGraph[this.place].includes(destination)) {
      return this;
    } else {
      let parcels = this.parcels.map(p => {
        if (p.place != this.place) return p;
        return {place: destination, address: p.address};
      }).filter(p => p.place != p.address);
      return new VillageState(destination, parcels);
    }
  }
}

Particulary in,
let parcels = this.parcels.map(p => {
        if (p.place != this.place) return p;
        return {place: destination, address: p.address};})

What I can tell is that p is the argument of this arrow function but it is going to be replaced for what variable in this example? The only argument in the move method is destination but that's not going to replace p...I can't understand it.

A: Answer
Arrow functions don't have internal context (this) so they're super useful when you need to access the context from outside the function.
In this case you're using the arrow func inside a map and accessing the context from the class (because move is a method on VillageState it will also have access to this.place
Why is this cool? Well if you used a regular function and you tried accessing this.place you would get a ReferenceError because there is no place variable defined on the local this.
// dont do this at home
function mapFn(p) {
   /* This here is inside the mapFn and since this.place is not defined
      we get a ReferenceError */
   if (p.place != this.place) return p;
   return {place: destination, address: p.address};
}

let parcels = this.parcels.map(mapFn)
/* Hopefully the syntax above isn't confussing:
   * mapFn will be called by default with all the map() parameters
   * inside mapFn we only need p so that's the only name param used
*/

Resources
To learn more about arrow functions I'd check out Impatient JS, it's a really in depth explanation so it should answer most of your questions. The whole 'callable values' chapter is super useful. Also MDN.
https://exploringjs.com/impatient-js/ch_callables.html#arrow-functions
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

A:
What I can tell is that p is the argument of this arrow function but it is going to be replaced for what variable in this example?

It won't be replaced by any variable. The map function calls its callback once for each entry in the array. Each time it calls the callback (the arrow function), it passes in the entry's value. That's what the arrow function receives in its p parameter.
So for instance, suppose this.parcels looked like this:
this.parcels = [
    {
        place: "a",
        description: "parcel a"
    },
    {
        place: "b",
        description: "parcel b"
    },
    {
        place: "c",
        description: "parcel c"
    }
];

With those parcels, map would call the arrow function three times. p in the first call would refer to the { place: "a", description: "parcel a" } object. p in the second call would refer to the { place: "b", description: "parcel b" } object, and p in the third call would refer to the { place: "c", description: "parcel c" } object.
The only thing different about the arrow function vs. a traditional function in that example is that it closes over this (and arguments and super) — something that you want in that code, because it uses this to refer to the object holding parcels.
This code that you pointed to:
let parcels = this.parcels.map(p => {
    if (p.place != this.place) return p;
    return {place: destination, address: p.address};
})

...does the same thing this code using a traditional function does:
let _tmp = this; // *** Remember the value `this` has outside the function
let parcels = this.parcels.map(function(p) => {
    if (p.place != _tmp.place) return p;
//                 ^^^^−−−−−−−−−−−−−−−−−−−−−−−−−− use that value here
    return {place: destination, address: p.address};
})

A: It seems like you're trying to make sense of the higher-order functions in JS with fairly complex example.
First, what does the map method do? It iterates over an array and calls the provided callback function right?!

[1, 2, 3].map(n => n + 1); // [2, 3, 4]

// Which is equalent to this:
[1, 2, 3].map(function(n) { return n + 1 })

// or this...
function increment(n) { return n + 1 };
[1, 2, 3].map(n => increment(n));

Or for a better explanation, I would just suggest watching this video to get a clearer understanding of array methods and higher-order functions in JS: JavaScript Higher Order Functions & Arrays!
And after it would be much easier for you to reason about your concrete example :)


text:
Q: Android manage fragment circles I am using Fragments in a FragmentActivity with a FragmentManager.
I need to keep the last modifications in the fragment.
If I use FragmentTransaction.replace(); It will destroy the Fragment and reset it.
I decided to hide the previous Fragment and show the next one.
But the Fragment can be destroyed by an income call or a device rotation and they can't be shown anymore.
My question is how can I manage this?

*

*If I use show(), hide() I need to forbid the fragment's destruction

*If I use fragmentTransaction.replace() I need to save the last state.

The second solution looks better but I have no idea how to proceed.
Are there any other solutions?

A: Ok I fixed it.
THe trick is to use FragmentTransition.replace() and FragmentTransition.addTobackStack(null);
And overide onBackPressed of the activity like this:
@Override
public void onBackPressed()
{

}

Hope it will help!


text:
Q: how to store sql lite database in android studio to device memory? I am new to android . I would like to store and retrieve records in android studio . I am using embedded sql database in android studio . Data are inserted perfectly when my device is connected to studio. whenever, i run after disconnecting my device insertion is not performing . what is the problem ? please help me, what should i need to do?

A: Try this code
  private void exportDB(){
  File sd = Environment.getExternalStorageDirectory();
  File data = Environment.getDataDirectory();
   FileChannel source=null;
   FileChannel destination=null;
   String currentDBPath = "/data/"+ "com.example.yourpackname" +"/databases/"+SAMPLE_DB_NAME;
   String backupDBPath = SAMPLE_DB_NAME;
   File currentDB = new File(data, currentDBPath);
   File backupDB = new File(sd, backupDBPath);
   try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
        Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
    } catch(IOException e) {
        e.printStackTrace();
    }
}

Add permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


text:
Q: How can I make widgets adjust their size to look the same on every device? I was wondering how to make my interface's TextViews, ImageViews, Margins, etc... look the same on all devices no matter if I'm using it on a phone or a tablet. I was told that using fragments would help, but I don't seem to understand. Sorry for the babyish question...

A: You can use constraint layout and set the widget's height and width according to the screen's width and height. Or you can have different layout files for diffrent screen densities.


text:
Q: How to intergrate cas restful in Web application? I'm using CAS build SSO, I want to  implement login/logout by using CAS RESTful API in my own Web Application.
and the api like this http://sso.cvs.cn:9990/cas-server-webapp/v1/tickets
i test it by test case, and it succesful. here is the code:
public static void main(String... args) throws Exception {
    String username = "123";
    String password = "123";
    validateFromCAS(username, password);
}

public static boolean validateFromCAS(String username, String password) throws Exception {

    String url = "http://sso.cvs.cn:9990/cas-server-webapp/v1/tickets";
    try {
        HttpURLConnection hsu = (HttpURLConnection) openConn(url);
        String s = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
        s += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

        System.out.println(s);
        OutputStreamWriter out = new OutputStreamWriter(hsu.getOutputStream());
        BufferedWriter bwr = new BufferedWriter(out);
        bwr.write(s);
        bwr.flush();
        bwr.close();
        out.close();

        String tgt = hsu.getHeaderField("location");
        System.out.println(hsu.getResponseCode());
        if (tgt != null && hsu.getResponseCode() == 201) {
            System.out.println(tgt);

            System.out.println("Tgt is : " + tgt.substring(tgt.lastIndexOf("/") + 1));
            tgt = tgt.substring(tgt.lastIndexOf("/") + 1);
            bwr.close();
            closeConn(hsu);

            String serviceURL = "http://sso.cvs.cn:7070/cas-simple-site-alpha/";
            String encodedServiceURL = URLEncoder.encode("service", "utf-8") + "=" + URLEncoder.encode(serviceURL, "utf-8");
            System.out.println("Service url is : " + encodedServiceURL);

            String myURL = url + "/" + tgt;
            System.out.println(myURL);
            hsu = (HttpURLConnection) openConn(myURL);
            out = new OutputStreamWriter(hsu.getOutputStream());
            bwr = new BufferedWriter(out);
            bwr.write(encodedServiceURL);
            bwr.flush();
            bwr.close();
            out.close();
            System.out.println("Response code is:  " + hsu.getResponseCode());
            BufferedReader isr = new BufferedReader(new InputStreamReader(hsu.getInputStream()));
            String line;
            System.out.println(hsu.getResponseCode());
            while ((line = isr.readLine()) != null) {
                System.out.println(line);
            }
            isr.close();
            hsu.disconnect();
            return true;
        } else {
            return false;
        }
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
        throw mue;
    } catch (IOException ioe) {
        ioe.printStackTrace();
        throw ioe;
    }
}

but how i can use the api in my web application?

A: If i understand correctly your question is how the api would be usefull for you in general.
So if this is the case, with restful api enabled on cas, when a user gets authenticated by CAS server, he would be allowed to access other applications (cas enabled services) which are configured to have SSO with the same CAS server. Also you can do requests for tickets with POST as the documentation suggests.
Also another reason is that applications need to programmatically access CAS. Say one casified application can invoke other casified application's REST APIs on behalf of an authenticated user. For this purpose CAS Rest protocol will do the job


text:
Q: Window.print() to Link-OS Zebra Printer? Is it possible to print from Chrome Mobile (android) to a Link-OS Zebra Printer like this one using window.print()?
For example, when window.print() is called, a dialog box is opened asking the user to select the printer, orientation, etc.  If a Zebra Printer is connected via WiFi or BlueTooth, would the Zebra Printer show up as one of the options?
Also, would the file to be printed need to be a zpl file or would a pdf also work?

A: It is possible to use window.print() on Chrome for Android (Functionality for it was added in this commit). There are no requirements that I can find regarding the file format.
Regarding that specific printer, as long as it is recognized by Android, it should work correctly.


text:
Q: NHibenate assembly load problem I have problem on NHibenate assembly load problem.
error details :-
"Could not load file or assembly 'NHibernate, Version=3.0.0.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)"

A: Did you also reference

*

*Iesi.Collections

*Castle.DynamicProxy2

*Antlr3.Runtime


text:
Q: jquery displays html response on all div classes instead of only div i know similar questions have been previously asked, but none suits my need.
i have an XHR ajax return that i want to place on the respect div class in a php loop, the ajax call was successful, but when i used jquery to replace my div class html with the ajax return on the div, it replaces all the divs in the loop. please what am i doing wrong:
My php code for the loop is as follow;
public function getComments() {
     try{
         $user_data = @$_SESSION['user'];
         $userid = $user_data['userid'];
         $name = $user_data['name'];
         $con = new PDO("mysql:host=$this->serverhost;dbname=starstv;" , $this->serverusername, $this->serverpassword);
         $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
         $fetch_p_comment = $con -> prepare("SELECT parent_comments.name,parent_comments.likes,parent_comments.dislikes,parent_comments.comment,users.profile_pics,parent_comments.comment_time,parent_comments.code FROM parent_comments INNER JOIN users ON parent_comments.name = users.name ORDER BY comment_time DESC");
         $fetch_p_comment -> execute();
         $p = $fetch_p_comment -> fetchALL(PDO::FETCH_ASSOC);

         foreach($p as $item) {
            $item[] = $p;
            $date = new dateTime($item['comment_time']);
            $comment_time = date_format($date, 'M j, Y | H:i:s');
            $name = $item['name'];
            $comment = $item['comment'];
            $par_code = $item['code'];
            $user_image = $item['profile_pics'];
            $likes = $item['likes'];
            $dislikes = $item['dislikes'];
               echo '

';
            echo "
"
                .""
                ."".$name.""
                ."".$comment_time.""
                .'

'.$comment.'

'
                ." ".$likes." ".$dislikes."
"
                ."reply edit delete

";
            $fetch_c_reply = $con -> prepare("SELECT children_comments.name,children_comments.likes,children_comments.dislikes,children_comments.comment,users.profile_pics,children_comments.comment_time,children_comments.par_code FROM children_comments INNER JOIN users ON children_comments.name = users.name WHERE children_comments.par_code =? ORDER BY comment_time DESC");
            $fetch_c_reply -> bindParam(1,$par_code);
            if($fetch_c_reply -> execute()) {
            $c = $fetch_c_reply -> fetchALL(PDO::FETCH_ASSOC);
            $c_count = $fetch_c_reply->rowCount();

            if($c_count == 0) {
                // do nothing
            }else {
                echo "(".$c_count.")

"
                    ."
";
                    foreach($c as $com) {
                        $com[] = $c;
                        $c_date = new dateTime($com['comment_time']);
                        $c_comment_time = date_format($c_date, 'M j, Y | H:i:s');
                        $c_name = $com['name'];
                        $c_comment = $com['comment'];
                        $c_par = $com['par_code'];
                        $image = $com['profile_pics'];
                        $likes = $com['likes'];
                        $dislikes = $com['dislikes'];

                        echo '

';
                        echo "
"
                        .""
                        ."".$c_name.""
                        ."".$c_comment_time.""
                        ."

".$c_comment."

"
                        ." ".$likes." ".$dislikes."
"
                        ."

"
                        ."
";
                    }
                    echo  "
";
                }

            }
            echo "
";
         }

        }catch(PDOException $e) {
         throw new PDOException($e->getMessage());
     }
 }

that's the complete php code returning the loop;
the php loop code is below;
echo "
"
                .""
                ."".$name.""
                ."".$comment_time.""
                .'

'.$comment.'

'
                ." ".$likes." ".$dislikes."
"
                ."reply edit delete
";

my javascript code is below;
$(".likes-mama").one('click', function() {
                        var p_comment_likes = true;
                        var gCode = $(this).attr("name");

                        if(gCode != "" && p_comment_likes ==true) {

                            var hr = new XMLHttpRequest();
                            hr.open("POST","p_comment_likes_dislikes.php",true);
                            hr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                            hr.onreadystatechange = function () {
                                if((hr.readyState == 4) && (hr.status == 200 || hr.status == 304) ) {
                                    $(".likes-mama-updates").html(hr.response);
                                    alert(hr.response);
                                }
                            }
                            hr.send("code="+gCode+"&p_comment_likes="+p_comment_likes);
                        }
                  });

please your replies are appreciated

A: After a lot of work around, i was able to find the solution with parent-children relationship in jquery:
$(this).parent().children("my-class");

to locate the actual div i want.
thanks all for your quick response!!


text:
Q: How to make adduplex ads clickable in windows phone 8 ? I have implemented adduplex control exactly the same way as specified in adduplex website :
<adduplex:AdControl x:Name="adDuplexAd"
                AppId="YOUR_AppId_HERE"
                />

I used the nuget installation way and the following namespace :
xmlns:adduplex="clr-namespace:AdDuplex;assembly=AdDuplex.WindowsPhone"

The app displays ads perfectly however whenever the ads in the app are clicked , nothing happens , I tried searching on the adduplex blog , but didnt get anything .
I googled but still didn't get any substantial result . Is it some API error ?
Please help !

A: Your adControl might be covered by another element. Run the adControl in the Test mode and it will show any elements covering it in red on screen when debugging.
<adduplex:AdControl x:Name="adDuplexAd"
            AppId="YOUR_AppId_HERE"
            IsTest="True"
            />

or you can create the event handler for the AdCovered event and set a breakpoint and see if the ad is covered by another element.
<adduplex:AdControl x:Name="adDuplexAd"
                AppId="YOUR_AppId_HERE"
                AdCovered="adDuplexAd_AdCovered"
                />

private void adDuplexAd_AdCovered(object sender, AdDuplex.Models.AdCoveredEventArgs e)
{

}

Also you can add the event handler for the AdClick event and also set a break point and see if that is hit. ( same as the above code)


text:
Q: Find and Replace Multiple occurrences of a string within a large string I have a large string.
I want to find a specific tag from the large string and replace content within that tag. This tag could occur multiple times and has to be replaced each time.
Below is my code:
$FirstString = '<tag>'
$lastString  = '</tag>'

$contentVal = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. <tag> Aha Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes</tag>, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, <tag> Aha imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus.</tag> Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. <tag> Aha Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum.</tag>"

if ($contentVal.Contains('<tag>')) {
    $Pos1 = $contentVal.IndexOf($FirstString) + $FirstString.Length;
    $Pos2 = $contentVal.IndexOf($lastString);

    #Find text between <tag> and </tag>
    $FoundString = $contentVal.Substring($Pos1, $Pos2 - $Pos1);
    Write-Host $FoundString

    #Modify this FoundString by finding Aha and replacing with

    $FinalString = $FinalString.Replace("Aha","
")
    Write-Host $FinalString
}

Now I want to append this $finalString to $contentVal at the same position at which it was earlier.
Also, I have multiple occurences of <tag>.
How to manipulate each occurence and append to main string?


text:
Q: List of theorems equivalent to choice Can you please refer a source that you consider to contain the most complete list of statements and theorems equivalent to the axiom of choice (over the axioms of ZF)?  I am already aware of most of the equivalent statements listed on the wiki page here: https://en.m.wikipedia.org/wiki/Axiom_of_choice
I am most likely looking for a study or (maybe several) chapters of a book.


text:
Q: grepelli issue with autocomplete_search_fields class DemoProvider(models.Model):
    def __str__(self):
        if self.MidName == None:
            return u'%s, %s' % (self.LastName, self.FirstName)
        else:
            return u'%s, %s %s' % (self.LastName, self.FirstName, self.MidName)
    PracticeName = models.ForeignKey('DemoPractice', on_delete=models.CASCADE)
    FirstName = models.CharField(max_length=255, null=True, blank=True)
    MidName = models.CharField(max_length=255, null=True, blank=True)
    LastName = models.CharField(max_length=255, null=True, blank=True)

class Billing1500(models.Model):
    Practice = models.ForeignKey('DemoPractice', on_delete=models.CASCADE)
    Provider = models.ForeignKey('DemoProvider', on_delete=models.CASCADE)
    PatiName = models.CharField(max_length=255, null=True, blank=True, help_text='Last Name, First Name')
    PatiDOB = models.CharField(max_length=255, null=True, blank=True)
    PatiSex = models.CharField(max_length=255, null=True, blank=True)
    @staticmethod
    def autocomplete_search_fields():
        return ("Provider_icontains", )

@admin.register(Billing1500)
class Billing1500(admin.ModelAdmin):
    raw_id_fields = ('Provider',)
    autocomplete_lookup_fields = {
        'fk': ['Provider'],
    }
    pass

i'm trying to have autocomplete search fields in my grapellie admin models, however im getting errors when trying to bind my foreignkeys to my grappelli function. i'm having the following issue
ERRORS:
?: (grappelli.E001) Model Core.billing1500 returned bad entries for autocomplete_search_fields: Provider_icontains
        HINT: A QuerySet for {model} could not be constructed. Fix the autocomplete_search_fields on it to return valid lookups.

reading the docs it looks like what I have should be correct no?


text:
Q: How to increase the accuracy of my logistic regression model? I am dealing with a tricky, unbalanced data set and trying to run a logistic regression model. One class is present with a 10:1 ratio.
My objective here is to boost my predictive accuracy - minimize the incorrect predictions and maximize the correct ones.
I've tried undersampling (which doesn't work very well) and I have tried logistic regression,case-weighted logistic, and Firth logistic regression.
None of them are very successful.
While I can sometimes yield good true negative rates depending on the dataset, in the end the prediction is merely representative of its underlying class distribution. The case-weighted logistic does about as well as the Firth when I test it - which is to say, it does horribly.
So...

*

*Is there anything else I can do to meet my objective? From what I
can tell, exact logistic regression is an option but only for very
small datasets, which is not the case here.

*Do I need to go back and explore variable selection?

*Why is it that the penalized model (Firth) is not a substantial
improvement over the case-weighted logistic?

*Are there any options I am not considering?

*Should I change tactics and look to something like an anomaly
detection model instead?
--
Please excuse me if this question is lacking in details -this is my first time asking a question here. I would be happy to add in anything.

A: Just think about the fact that you have a 10:1 class ratio and yet your interest is in zero-one loss, that is, maximizing the proportion of cases correctly identified. The accuracy of a trivial model that just guesses the modal class for every case would be 10/(10 + 1) = 91%, which is pretty high. In order to substantially beat 91%, as with 95% accuracy, you need one or more highly predictive features. If you don't have any, as is often the case in real problems, the best you can hope for is quite small improvements on 91%. In a nutshell, this problem is too easy for statistics or machine learning to be able to get you much more predictive power.
Possibly I can give you more specific advice if you add details.

A: It might make sense for you to try different models. You might have some success with something like decision trees (which can also help you find highly predictive values as Kodiologist suggested), KNN, SVMs, or some other model that can handle non-linear relationships.

A: Generally, in case your model is biased you need to come up with a more complex model -- one way to achieve this is to add more (hopefully good) features as been pointed out previously. But this can be a no easy matter and probably depends on your domain expertise. What you, however, could try out of the box is features interaction. Essentially, you are not limited in choosing the order of interactions/number of interacting variables and then could compare different models produced in such a way. Hope this makes sence

A: As some others have suggested, moving to a more complex algorithm may provide an increase in accuracy. If you were to stick with logistic regression, perhaps oversampling your smaller cohort may help to enrich your predictive performance. This could be achieved using a weighted logistic regression weighted logistic regression. Thankfully social scientists have implemented many of these algorithms in R and SAS.
Another strategy could be to use either forward or backward feature selection.
Ultimately, my money would be to move to more complex models, and would give particular attention to random forests and boosting.


text:
Q: longtail player + anythingslider + event listeners I've implemented the AnythingSlider (http://css-tricks.com/anythingslider-jquery-plugin/) using image and video content (videos use the longtail flv player - licensed version 5).
Problem: When the user plays the video, the slideshow doesn't know this has happened, so the slideshow keeps cycling while the video runs. So you have the slideshow running - and user can hear the audio but the video has cycled off.

*

*UPDATE - here is a link to see what's going on:  http://silverberry.org/beta/slider-longtail/
I'm trying to figure out an event-listener that will look and see when the LONGTAIL player is in PLAYING state and signals to the AnythingSlider that it needs to STOP.
Here's what I've got so far ... the video player event listeners are working (right now I have alerts popping up so that I can be sure the events are being heard).  An alert pops up with the player is initialized .. and alert pops up when we press the PLAY button on the video ... and an alert pops up when the video STOPS playing.  But ... I've yet to work out the proper syntax for signaling to the anythingslider to STOP!
I thought it would be this:
$VUslider.startStop(false);

Below is the code I have so far ... beginning with the code that initializes the slider.
    function formatText(index, panel) {
  return index + "";
  }
$(function () {
 $('.VUslider').VUslider({
 autoPlay: true,
    delay: 7000,
    startStopped: false,
    animationTime: 200,
    hashTags: true,
    buildNavigation: false,
    pauseOnHover: true,
    navigationFormatter: formatText
    });
});

var player = null;
function playerReadyCallback(obj)  {
 player = document.getElementsByName(obj.id)[0];
    alert('the videoplayer '+obj['id']+' has been instantiated');
    player.addModelListener('STATE',     'stateMonitor');
}
function stateMonitor(obj) {
   currentState = obj['newstate'];
 if(currentState == 'PLAYING') {
   alert ('the videoplayer '+obj['id']+'  is playing now!');
   $VUslider.startStop(false);  // Trigger slideshow stop
    }
 if(obj.newstate == 'COMPLETED') {
   alert ('the videoplayer '+obj['id']+'  has stopped playing now!');
   $VUslider.startStop(true);  // Trigger slideshow start
    }
}

FOR REFERENCE ... HERE IS THE ANYTHING SLIDER CODE:
(function($){

    $.VUslider = function(el, options){
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;

        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el;

        // Set up a few defaults
        base.currentPage = 1;
        base.timer = null;
        base.playing = false;

        // Add a reverse reference to the DOM object
        base.$el.data("AnythingSlider", base);

        base.init = function(){
            base.options = $.extend({},$.VUslider.defaults, options);

            // Cache existing DOM elements for later
            base.$wrapper = base.$el.find('> div').css('overflow', 'hidden');
            base.$slider  = base.$wrapper.find('> ul');
            base.$items   = base.$slider.find('> li');
            base.$single  = base.$items.filter(':first');

            // Build the navigation if needed
            if(base.options.buildNavigation) base.buildNavigation();

            // Get the details
            base.singleWidth = base.$single.outerWidth();
            base.pages = base.$items.length;

            // Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
            // This supports the "infinite" scrolling
            base.$items.filter(':first').before(base.$items.filter(':last').clone().addClass('cloned'));
            base.$items.filter(':last' ).after(base.$items.filter(':first').clone().addClass('cloned'));

            // We just added two items, time to re-cache the list
            base.$items = base.$slider.find('> li'); // reselect

            // Setup our forward/backward navigation
            base.buildNextBackButtons();

            // If autoPlay functionality is included, then initialize the settings
            if(base.options.autoPlay) {
                base.playing = !base.options.startStopped; // Sets the playing variable to false if startStopped is true
                base.buildAutoPlay();
            };

            // If pauseOnHover then add hover effects
            if(base.options.pauseOnHover) {
                base.$el.hover(function(){
                    base.clearTimer();
                }, function(){
                    base.startStop(base.playing);
                });
            }

            // If a hash can not be used to trigger the plugin, then go to page 1
            if((base.options.hashTags == true && !base.gotoHash()) || base.options.hashTags == false){
                base.setCurrentPage(1);
            };
        };

        base.gotoPage = function(page, autoplay){
            // When autoplay isn't passed, we stop the timer
            if(autoplay !== true) autoplay = false;
            if(!autoplay) base.startStop(false);

            if(typeof(page) == "undefined" || page == null) {
                page = 1;
                base.setCurrentPage(1);
            };

            // Just check for bounds
            if(page > base.pages + 1) page = base.pages;
            if(page < 0 ) page = 1;

            var dir = page < base.currentPage ? -1 : 1,
                n = Math.abs(base.currentPage - page),
                left = base.singleWidth * dir * n;

            base.$wrapper.filter(':not(:animated)').animate({
                scrollLeft : '+=' + left
            }, base.options.animationTime, base.options.easing, function () {
                if (page == 0) {
                    base.$wrapper.scrollLeft(base.singleWidth * base.pages);
                    page = base.pages;
                } else if (page > base.pages) {
                    base.$wrapper.scrollLeft(base.singleWidth);
                    // reset back to start position
                    page = 1;
                };
                base.setCurrentPage(page);

            });
        };

        base.setCurrentPage = function(page, move){
            // Set visual
            if(base.options.buildNavigation){
                base.$nav.find('.cur').removeClass('cur');
                $(base.$navLinks[page - 1]).addClass('cur');
            };

            // Only change left if move does not equal false
            if(move !== false) base.$wrapper.scrollLeft(base.singleWidth * page);

            // Update local variable
            base.currentPage = page;
        };

        base.goForward = function(autoplay){
            if(autoplay !== true) autoplay = false;
            base.gotoPage(base.currentPage + 1, autoplay);
        };

        base.goBack = function(){
            base.gotoPage(base.currentPage - 1);
        };

        // This method tries to find a hash that matches panel-X
        // If found, it tries to find a matching item
        // If that is found as well, then that item starts visible
        base.gotoHash = function(){
            if(/^#?panel-\d+$/.test(window.location.hash)){
                var index = parseInt(window.location.hash.substr(7));
                var $item = base.$items.filter(':eq(' + index + ')');
                if($item.length != 0){
                    base.setCurrentPage(index);
                    return true;
                };
            };
            return false; // A item wasn't found;
        };

        // Creates the numbered navigation links
        base.buildNavigation = function(){
            base.$nav = $("

").appendTo(base.$el);
            base.$items.each(function(i,el){
                var index = i + 1;
                var $a = $("");

                // If a formatter function is present, use it
                if( typeof(base.options.navigationFormatter) == "function"){
                    $a.html(base.options.navigationFormatter(index, $(this)));
                } else {
                    $a.text(index);
                }
                $a.click(function(e){
                    base.gotoPage(index);

                    if (base.options.hashTags)
                        base.setHash('panel-' + index);

                    e.preventDefault();
                });
                base.$nav.append($a);
            });
            base.$navLinks = base.$nav.find('> a');
        };

        // Creates the Forward/Backward buttons
        base.buildNextBackButtons = function(){
            var $forward = $('>'),
                $back    = $('<');

            // Bind to the forward and back buttons
            $back.click(function(e){
                base.goBack();
                e.preventDefault();
            });

            $forward.click(function(e){
                base.goForward();
                e.preventDefault();
            });

            // Append elements to page
            base.$wrapper.after($back).after($forward);
        };

        // Creates the Start/Stop button
        base.buildAutoPlay = function(){

            base.$startStop = $("").html(base.playing ? base.options.stopText :  base.options.startText);
            base.$el.append(base.$startStop);
            base.$startStop.click(function(e){
                base.startStop(!base.playing);
                e.preventDefault();
            });

            // Use the same setting, but trigger the start;
            base.startStop(base.playing);
        };

        // Handles stopping and playing the slideshow
        // Pass startStop(false) to stop and startStop(true) to play
        base.startStop = function(playing){
            if(playing !== true) playing = false; // Default if not supplied is false

            // Update variable
            base.playing = playing;

            // Toggle playing and text
            if(base.options.autoPlay) base.$startStop.toggleClass("playing", playing).html( playing ? base.options.stopText : base.options.startText );

            if(playing){
                base.clearTimer(); // Just in case this was triggered twice in a row
                base.timer = window.setInterval(function(){
                    base.goForward(true);
                }, base.options.delay);
            } else {
                base.clearTimer();
            };
        };

        base.clearTimer = function(){
            // Clear the timer only if it is set
            if(base.timer) window.clearInterval(base.timer);
        };

        // Taken from AJAXY jquery.history Plugin
        base.setHash = function ( hash ) {
            // Write hash
            if ( typeof window.location.hash !== 'undefined' ) {
                if ( window.location.hash !== hash ) {
                    window.location.hash = hash;
                };
            } else if ( location.hash !== hash ) {
                location.hash = hash;
            };

            // Done
            return hash;
        };
        // <-- End AJAXY code

        // Trigger the initialization
        base.init();
    };

    $.VUslider.defaults = {
        easing: "swing",                // Anything other than "linear" or "swing" requires the easing plugin
        autoPlay: true,                 // This turns off the entire FUNCTIONALY, not just if it starts running or not
        startStopped: false,            // If autoPlay is on, this can force it to start stopped
        delay: 3000,                    // How long between slide transitions in AutoPlay mode
        animationTime: 600,             // How long the slide transition takes
        hashTags: true,                 // Should links change the hashtag in the URL?
        buildNavigation: true,          // If true, builds and list of anchor links to link to each slide
        pauseOnHover: true,             // If true, and autoPlay is enabled, the show will pause on hover
        startText: "Start",             // Start text
        stopText: "Stop",               // Stop text
        navigationFormatter: null       // Details at the top of the file on this use (advanced use)
    };

    $.fn.VUslider = function(options){
        if(typeof(options) == "object"){
            return this.each(function(i){
                (new $.VUslider(this, options));

                // This plugin supports multiple instances, but only one can support hash-tag support
                // This disables hash-tags on all items but the first one
                options.hashTags = false;
            });
        } else if (typeof(options) == "number") {

            return this.each(function(i){
                var anySlide = $(this).data('AnythingSlider');
                if(anySlide){
                    anySlide.gotoPage(options);
                }
            });
        }
    };

})(jQuery);

A: Are you setting $VUslider to equal $('.VUslider').VUslider({ . . }); ?
In your example code you are not.
You should be doing something like this:
$VUslider = $('.VUslider').VUslider({
    autoPlay: true,
    delay: 7000,
    startStopped: false,
    animationTime: 200,
    hashTags: true,
    buildNavigation: false,
    pauseOnHover: true,
    navigationFormatter: formatText
});

A: This is somewhat of a stab in the dark, so I'll try to explain my reasoning a bit.
After you've created the VUslider bits as you're already doing, try doing this to start/stop the slider:
$('.VUslider').VUslider.startStop(false);
// this will toggle between starting and stopping but doesn't give control
// to call start or stop specifically.
$('#start-stop').click();

When you call $('.VUslider').VUslider({...}), it doesn't return anything, so there's no handle to VUslider at that point ($.each(..) doesn't return anything).  This will hopefully get you a reference to the script and to the startStop function.
HTH


text:
Q: Java project is not running on tomcat server from tomcat manager after deploying war file to webapps? I have made a project on spring tool suit. This project is running fine in local embaded tomcat server. But when I deployed the war file to the external tomcat servers webapps folder I cannot run the project from the tomcat manager. When I click start it shows two errors: FAIL - Application at context path [/payemntmodule] could not be started
FAIL - Encountered exception [org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/paymentmodule]]]
Here are the details of my project:
java version
java --version
openjdk 11.0.11 2021-04-20
OpenJDK Runtime Environment (build 11.0.11+9-Ubuntu-0ubuntu2.20.04)
OpenJDK 64-Bit Server VM (build 11.0.11+9-Ubuntu-0ubuntu2.20.04, mixed mode, sharing)

tomcat.service
[Service]
Type=forking

Environment=JAVA_HOME= /usr/lib/jvm/java-1.11.0-openjdk-amd64
Environment=CATALINA_PID=/opt/tomcat/temp/tomcat.pid
Environment=CATALINA_HOME=/opt/tomcat
Environment=CATALINA_BASE=/opt/tomcat
Environment=CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC
Environment=JAVA_OPTS= -Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom

ExecStart=/opt/tomcat/bin/startup.sh
ExecStop=/opt/tomcat/bin/shutdown.sh

User=tomcat
Group=tomcat
UMask=0007
RestartSec=10
Restart=always

[Install]
WantedBy=multi-user.target

[![/opt/tomcat/webapps][1]][1]
[![Deployed war file to the tomcat manager][2]][2]
[![File permissions of webapps][3]][3]
Errors:
FAIL - Application at context path [/paymentmodule] could not be started
FAIL - Encountered exception [org.apache.catalina.LifecycleException: Failed to start
component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/paymentmodule]]]

[![Tomcat Manager with error][4]][4]
Logs:
[![tomcat.log][5]][5]
manager.log
[![manager.log][6]][6]
[![manager.log][7]][7]
[![manager.log][8]][8]

A: This is because your app does not knows that it is invoked by external tomcat.
Need to change scope to provided,add this in pom and check
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>


text:
Q: How do you read from stdin in python from a pipe which has no ending I've problem to read from Standard input or pipe in python when the pipe is from a "open" (do not know right name)
file.
I have as example
pipetest.py:
import sys
import time
k = 0
try:
   for line in sys.stdin:
      k = k + 1
      print line
except KeyboardInterrupt:
   sys.stdout.flush()
   pass
print k

I run a program that have continues output and Ctrl+c after a while
$ ping 127.0.0.1 | python pipetest.py
^C0

I get no output.
But if I go via an ordinary file it works.
$ ping 127.0.0.1 > testfile.txt

this is ended by Ctrl+c after a short while
$ cat testfile.txt |  python pipetest.py

PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.017 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.015 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.014 ms
64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.013 ms
64 bytes from 127.0.0.1: icmp_seq=5 ttl=64 time=0.012 ms

--- 127.0.0.1 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 3998ms
rtt min/avg/max/mdev = 0.012/0.014/0.017/0.003 ms
10

How do I do to get any output before the program ends, in this case ping has ended?

A: k = 0
try:
    while True:
        print sys.stdin.readline()
        k += 1
except KeyboardInterrupt:
    sys.stdout.flush()
    pass
print k

A: This is how I ended up doing this. I didn't really like any of the other solutions, they didn't seem very pythonic.
This will make a container for any open file input to iterate over all the lines. This will also take care of closing the file at the end of the context manager.
I feel like this is probably how the for line in sys.stdin: block should operate by default.
class FileInput(object):
    def __init__(self, file):
        self.file = file

    def __enter__(self):
        return self

    def __exit__(self, *args, **kwargs):
        self.file.close()

    def __iter__(self):
        return self

    def next(self):
        line = self.file.readline()

        if line == None or line == "":
            raise StopIteration

        return line

with FileInput(sys.stdin) as f:
    for line in f:
        print f

with FileInput(open('tmpfile') as f:
    for line in f:
        print f

From the command line both of the following should work:
tail -f /var/log/debug.log | python fileinput.py
cat /var/log/debug.log | python fileinput.py

A: while sys.stdin is a file-like object, meaning you can iterate over its lines, it will block until a EOF is inserted.
The behaviour can be described with the following pseudo-code:
while True:
    input = ""
    c = stdin.read(1)
    while c is not EOF:
        input += c
        c = stdin.read(1)
    for line in input.split('\n'):
        yield line

this means that, while you can iterate over sys.stdin's lines, you cannot use this approach for the task at hand and you must explicitly call read() or readline()

A: Try this:
import sys
import time
k = 0
try:
    buff = ''
    while True:
        buff += sys.stdin.read(1)
        if buff.endswith('\n'):
            print buff[:-1]
            buff = ''
            k = k + 1
except KeyboardInterrupt:
   sys.stdout.flush()
   pass
print k

A: For this to work without waiting until the stdin stream ends, you can iter on the readline. I think this is the simplest solution.
import sys
k = 0
try:
   for line in iter(sys.stdin.readline, b''):
      k = k + 1
      print line
except KeyboardInterrupt:
   sys.stdout.flush()
   pass
print k


text:
Q: Python library to plot regression residuals against each predictor and fitted values In R, when doing linear modeling I often use the residualPlots method from the cars library to plot my model residuals against my fitted values and against each numeric/applicable regressor.  This is done all at once with a single function call. For example,

Is there an equivalent library in Python that plots residuals against fitted values and against my predictors, all at once?
I'm aware I can plot small multiples in matplotlib using a loop, I'm looking for something that does it in one go.   I know statsmodels.graphics.plot_partregress does this for partial regression plots, but I haven't been able to find its equivalent just for straight residuals.  Integration with statsmodels, and ability to compute other residuals (externally studentized) as part of plotting a big bonus.


text:
Q: C++ Дружественная специализация шаблона Не получается сделать класс some дружественным.
Класс some является дружественным к классу A (some - класс создатель, только у него есть доступ к конструкторам класса A). В то же время класс A может создать ещё один экземпляр в функции foo. Но, как я понимаю, возникает ошибка именно из-за того, что я его объявляю дружественным и использую одновременно. Или нет?
template <class T, class Meta = void>
class some;

template <class T>
class some<T, std::enable_if<std::is_same<int, T>::value>::type>{
  // ...
};

Вариант N1
class A{
  friend class some<int>; // error C3856: "some": символ не является классом шаблон

  void foo(){
    some<int> a;
    //...
  }
};

Вариант N2
class A{
  template<class, class>
  friend class some;

  void foo(){
    some<int> a;  // error C2976: some: слишком мало аргументов шаблон
    //...
  }
};

Вариант N3
class A{
  template<class, class = void>
  friend class some;

  void foo(){
    some<int> a;  // error C2079: "a" использует не имеющую определения структуру struct "some<int,void>"
    //...
  }
};

A: В точке определения класса A, определение шаблона some не видно. Поэтому, при любой попытке воплощения получаете ошибку. Решение:
 // some.h
 template <class T, class Meta = void>
 class some;
 template <class T>
 class some<T, typename std::enable_if<std::is_same<int, T>::value>::type>{ // сдесь был забыт typename, хотя старые версии MSVC на него не ругаются.
    // ...
 };

Использование:
 #include "some.h"
 class A{
   template<class, class>
   friend class some;
   void foo(){
     some<int> a;
     //...
   }
 };

A: Предположение Chorkov было проверено и оказалось, что класс some действительно не виден в точке определения класса A. Всё бы ничего, но там заголовок был подключен и всё должно было работать. Скачал Clear MEF, почистил кэш, вправил студии мозги и всё заработало!


text:
Q: Detect overwrite mode in MS Edge I'm writing a script which leverages keypresses, and I have need of detecting whether or not the user is in insert mode or overwrite mode.
Fortunately overwrite mode is not a thing in Firefox, Chrome, or Safari, but it is in Edge.
I've done copious amounts of searching and the only applicable code I have found is:
document.queryCommandValue("OverWrite");

However this seems to have gone unsupported since IE11 from what I can gather. In Edge it returns an empty string regardless of whether or not you are in insert mode.
I've tried using document.queryCommandState('OverWrite'); instead, however likewise it always returns false.
Is anyone aware of the new way to test for this, assuming it is a thing that is possible to test for?

A: I try to test it with MS Edge and I am able to produce the issue. It can be possible that it is some kind of bug or the Edge team needs to add the support of the API. I will try to submit the feedback regarding this issue.
As a workaround, you could refer to this answer. You could use the jsfiddle demo in the answer to detect the overwrite mode in Edge. But the draw back of the function is when you add characters at the end of the inputs, the mode detect will not work.


text:
Q: import check_arrays from sklearn I'm trying to use a svm function from the scikit learn package for python but I get the error message:
from sklearn.utils.validation import check_arrays

ImportError: cannot import name 'check_arrays'

I'm using python 3.4. Can anyone give me an advice? Thanks in advance.

A: It seems like "check_arrays" doesn't exist (anymore).
I fixed it with:
sudo vi /usr/lib64/python2.7/site-packages/sklearn/metrics/cluster/bicluster/bicluster_metrics.py
change this:
from sklearn.utils.validation import check_arrays
to:
from sklearn.utils.validation import check_array as check_arrays
Kind of a hack, but it works for me.

A: For me...
This worked:
from sklearn.utils import check_array

Also this:
from sklearn.utils.validation import check_array

I am using version 0.16.0

>>> sklearn.__version__
'0.16.0'

Do this:
import sklearn

print sklearn.__version__

Tell us the results.

A: This method was removed in 0.16, replaced by a (very different) check_array function.
You are likely getting this error because you didn't upgrade from 0.15 to 0.16 properly. [Or because you relied on a not-really-public function in sklearn]. See http://scikit-learn.org/dev/install.html#canopy-and-anaconda-for-all-supported-platforms .
If you installed using anaconda / conda, you should use the conda mechanism to upgrade, not pip. Otherwise old .pyc files might remain in your folder.

A: You should change check_arrays to check_array.
Source: https://github.com/scikit-learn/scikit-learn/issues/4624


text:
Q: PHP isn't writing to file I'm making a registration form, but can't seem to write to text file. In this code, I'm putting a person's real name in their file in acc/pplid/[name].txt The file isn't writing at all - the echo doesn't output anything. I'm running off of Microsoft Webmatrix on my computer. Thanks in advance!
        $irlname = $_POST["irlname"];
        $name = $_POST["username"];
        $email = $_POST["email"];
        $password = $_POST["password"];
        $name = htmlentities($name);

        echo $name;
        file_put_contents("acc/pplid/".name.".txt", $irlname);
        echo file_get_contents("acc/pplid/".$name.".txt");

A: file_put_contents("acc/pplid/".name.".txt", $irlname);

Should be
file_put_contents("acc/pplid/".$name.".txt", $irlname);

unless name is defined else where, otherwise I'd say check the write permissions. Check the status of the folder with file_exists or is_dir prior to file_put_contents.
Example
if(is_dir("acc/pplid") && is_writable("acc/pplid")){
    file_put_contents("acc/pplid/".$name.".txt", $irlname);
} else echo "A problem with the folder occurred";


text:
Q: How to update OpenSSL version on AWS Lambda? How can I update the OpenSSL version, currently OpenSSL 1.0.1k-fips 8 Jan 2015 used in a Lambda function?
I need to build the Lambda environment with OpenSSL version 1.10 which supports the multiple -cert option.

A: You can include openssl version 1.10 with native libraries with your Lambda. This way you don't need to use the openssl given by the lambda container.
Alternatively you can also create your container with updated openssl and run with Fairgate.
Hope this helps.