text:
Q: Unity Button Prefab Coming in as Null I have been having a problem all day now where my button prefab is coming in as null. The problem arose when I changed from using GameObject in my code to Button. I had to do this for my listener to apply properly. I am trying to create a list of save games from a file, and need to be able to differentiate between the buttons and chose to apply the listener to each one to return an integer. The specific error is  "The object you want to instantiate is null."
Here is my code
void Populate()
{
    Button newObj = Instantiate(NewSave, transform) as Button; // Create GameObject instance

    newObj.name = "NewSave";
    startList();
}
public void startList()
{
    Button newObj;
    int i = 0;

    clearList();
    foreach (PlayerType nextPlayer in GameManager.instance.saveStorage.returnSaves())
    {
        i++;
        // Create new instances of our prefab until we've created as many as is in list
        newObj = (Button)Instantiate(OldSaves, transform);

        //increment slot names
        Debug.Log(i);
        newObj.name = "Slot " + i.ToString();
        newObj.onClick.AddListener(() => ButtonClicked(i));
        saveList.Add(i);
    }

}

If you notice structure problems with the specific button creation please do not harp, I have torn this section of code apart quite a few times with the various suggestions online.
Essentially I have 2 button prefabs, one for a new save button and another for the individual save slots. It passes the listener to the save/load function and determines which slot to save it to before sending it to or from the file. The problem is on the first creation of the button, which was working fine until I implemented my listener setup and had to switch to using buttons instead.
I made sure that the buttons are connected via the inspector, and believe it is specifically something to do with my prefab itself as when I moved the prefab initialization to another line it followed. Here are some screenshots of my setup.
Inspector Objects
Button Prefab
Thanks for any help that can help me narrow the problem down, most of the threads I have been through were simple fixes like they forgot to connect it in the inspector, or someone had multiple scripts on the same object. I hope that its just another stupid mistake a new set of eyes will see quickly. I will post additional info or screenshots as needed when I get on tomorrow after work.
Update:
I solved the problem. I tried the suggestions and was typing up what went wrong when I found out that one of my inspector references was not set. I assumed that by changing the original populate saves it would set the references accordingly, however there were 2 locations I had to change it because I already had the script set on the object.
populatesave
I didn't catch it before because my save hierarchy has like 5 items each with multiple components, so when I attached it via the inspector I just went to the Master copy of my script. It was only jumping between my scripts and finding who calls what specifically that I happened to click on the one that actually hold my populateSave script. I am going to mark the second one as the answer because it was you asking me to find what was calling it that led me to figuring this out. Thanks a lot, it even explains why the saves were not looping right too, when I created it I set the number of saves to 23 for some reason lol.
I don't think I can mark the comment as the answer but still want to give you credit, can you post your comment as an answer or is that against the rules here?

A: Your problem is this line:
Button newObj = Instantiate(NewSave, transform) as Button;

Instantiate (usually) returns a GameObject. This is a different type to Button. When you use "as" it tries to cast it into the correct type. If it can't, it returns null.
What you want is:
Button newObj = (Instantiate(NewSave, transform) as GameObject).GetComponent<Button>();

I would also recommend changing the variable name of that button.
Keep in mind, a Button is a component, which is different to a gameobject.


text:
Q: android 3.0 honeycomb, finding and activating widgets Android 3.0 activates widgets differently from 2.x and maybe 4.x
I am trying to figure out how people accomodate this.
Basically on android 2.x the expected functionality is that a widget is downloaded and immediately available for use and the onUpdate method is ready to go to make the widget function as desired/
On Android 3.x it seems that several things don't happen the same way:

*

*After a widget is downloaded it isn't always seen in the list of widgets, until after a restart. (I have seen things detailing "why" this happens, but not why other widgets seem to not have this problem)

*In other cases, a widget is downloaded and is visible in the list of widgets, but added it to the launcher screen doesn't activate it. onUpdate seems not to be working, and touch events are not active, until after a restart.
I have seen posts talking about how a boot loader activates widgets when the launcher screen first loads, but I have seen widgets that don't have this problem.
Similarly, I have used that logic to force the launcher screen to reload by changing the phone's locale. But I would like widgets I create to be available without any troubleshooting, how would this be done?
Thanks

A: For HC+, you have to start any activity associated with the app at least one time after the app is installed, then it should show up in the list.  edit: also app on sdcard has issues see http://code.google.com/p/android/issues/detail?id=8555
Edit also yours is a duplicate of App Widget does not appear in the widget list on Honeycomb devices until Launcher is restarted

redpajama_set_name: RedPajamaStackExchange


text:
Q: Was Comic Book Guy correct about Green Lantern? In The Simpsons Movie, the following conversation occurs:

Grampa Simpson: [in video] Twisted tail! A thousand eyes! Trapped forever!!! EPA!!! EPA!!!
Marge: EPA? What could that be?
Comic Book Guy: I believe it's the sound the Green Lantern made when Sinestro threw him into a vat of acid. E-P-A!
Marge: Yeah. Thanks for coming over.

A later Green Lantern comic would reference this.

Did any comics released before The Simpsons Movie include Green Lantern being thrown into a vat of acid by Sinestro and making an "EPA" noise, or any scenario similar to that?

A:
Did any comics released before The Simpsons Movie include Green Lantern being thrown into a vat of acid by Sinestro and making an "EPA" noise, or any scenario similar to that?

The comic shown in your question appears to be Green Lantern Vol 4, #25. It hit stores in November 2007, with a cover date of 2008, according to Comic Vine.
The Simpsons Movie was released in July of 2007, at least 3 months prior.
According to this random guy, it may have been inspired by the film and not the other way around. Comic book resources also supports this.
I could find no other reference to acid vats, Sinestro or GL in any works published before then, so I think it is safe to say that the comic did it after it was heard in the film and it made it into the film because Comic Book Guy is just that kind of character. Also note that GL isn't making the sound but it seems like it is coming from the explosion or Sinestro's energy blast.


text:
Q: How to loop through an array and display user input with indexes? How do i loop through an array and display user input with indexes without the user input replicating?
Current output i'm getting:
Feedback 1
123456
Feedback 2
123456
The expected output for the case below should be:
Feedback 1
123
Feedback 2
456
<!DOCTYPE html>

Feedback Form

    <form>
        Enter Feedback : <textarea rows="3" cols="20" id="feedback"></textarea>

        <input type="button" value="Submit Feedback" id="create" onclick="addFeedback()">

        <input type="button" value="View Feedback" id="view" onclick="displayFeedback()">

    </form>

var myArray = [];

var myFeedback = document.getElementById("feedback");
var displayBox = document.getElementById("result");

function addFeedback(){

    //Store feedback into array
    myArray.push(myFeedback.value);

    //Clear textbox
    myFeedback.value = "";

    //Display message
    displayBox.innerHTML = "Successfully Added Feedback Details!";

    }

   function displayFeedback(){

    displayBox.innerHTML = "";

    for(var i = 0; i < myArray.length; i++){
    displayBox.innerHTML += "Feedback " + (i+1) + "
" + myArray.join();
    }

}

A: Use myArray[i] instead of join. Or more modern approach:
let innerHTML = "
";

myArray.forEach((value, index) => {
    innerHTML += `<li>Feedback ${index+1}: <br /> ${value}</li>`;
});

innerHTML += "
";

displayBox.innerHTML = innerHTML;


text:
Q: Would you let me know how to use the DPI and DPI-C? Hi when I use the systemverilog, there are some confused point.
first one is distinguish about DPI and DPI-C.
as following example used DPI not DPI-C . but As I know DPI-C is used to in C.
CODE:SV_file.sv
program main;
logic a;
import "DPI" function void show(logic a);
initial begin
a = 1'b0;
show(a);
a = 1'b1;
show(a);
a = 1'bX;
show(a);
a = 1'bZ;
show(a);
end
endprogram

CODE: C_file.v
#include <stdio.h>
#include <svdpi.h>

void show(svLogic a){
if(a == 0)
printf(" a is 0 \n");
else if(a == 1)
printf(" a is 1 \n");
else if(a == 2)
printf(" a is x \n");
else if(a == 3)
printf(" a is z \n");

}
RESULTS

a is 0
a is 1
a is z
a is x

Would you let me know how to use the DPI and DPI-C?

A: The difference has to do with which version of the standard your C code is based on: "DPI" is from the older Accellera standard, and "DPI-C" is the current IEEE standard.
Then key difference between two versions is how packed arrays of bit or logic are represented when they are passed through as arguments. The older "DPI" version did not standardize the representation of packed arrays - you had to know your tool's specific representation, or use macros provided by the tool vendor to access individual bits.
The current version standardizes the way you access bits of packed array, and that makes your C code binary compatible with any tool, meaning you don't have to recompile your DPI code for each tool vendor you work with. Annex H.13 of the IEEE 1800-2012 SystemVerilog LRM has more info on the differences.
My recommendation for "DPI-C" users is that unless you need access to 4-state values, keep your arguments C-compatible. That means using only ints, bytes(char) or unpacked array/structs of ints/bytes across the language boundary.


text:
Q: Computing the local ring of an affine variety Let $W=V(y^{2}-x^{3}) \subseteq \mathbb{A}^{2}$ and $k$ algebraically closed. Clearly the dimension of the tangent space at the origin is $2$. I want to compute this using the definition the fact that $\operatorname{dim} T_{(0,0)}W=\operatorname{dim}_{k} \mathfrak{m}/\mathfrak{m}^{2}$. Where $\mathfrak{m}$ is the maximal ideal of the local ring $\mathcal{O}_{(0,0),W}$.
OK according to Hartshorne the local ring is isomorphic to the localization of the corresponding coordinate ring localized at the ideal $(x,y)$ right?
So we need to compute the maximal ideal of $k[x,y]/(y^{2}-x^{3})$ localized at $(x,y)$. I know that in general given a ring $A$ then if $\mathfrak{p} \in \operatorname{Spec}(A)$ we have $\mathfrak{p}A_{p}=\{\frac{g}{h}: g,h \in P\}$ is the unique maximal ideal. However I don't see how to simplify things here. How to compute this?

A: If $M=(x,y)\subset k[X,Y]/(Y^2-X^3)=k[x,y]\stackrel{\text {def}}{=}A \;$, the maximal ideal you are interested in is $\mathfrak m=MA_M \subset A_M$ the maximal ideal of the local ring $A_M=\mathcal O_{(0,0),W}$.
The $k$-vector space $\mathfrak m/\mathfrak m^2$ is generated by $\bar x$ and $\bar y$ and all you have to check is that they are linearly independent.
A linear dependence relation $q\bar x+r \bar y=0$ ($q,r\in k$) means $qx+ry \in \mathfrak m^2=(x^2,xy,y^2)$.
Lifting to actual  polynomials this means $$qX+rY\in (X^2,XY,Y^2)+(Y^2-X^3)=(X^2,XY,Y^2)\subset k[X,Y]$$ and implies $q=r=0$.
So $\bar x$ and $\bar y$  are linearly independent in $\mathfrak m/\mathfrak m^2$ and $dim_k(\mathfrak m/\mathfrak m^2)=2$


text:
Q: How to replace "Male" into "Female"in the dataset? I have a dataset something like this:

How can I replace all the Male into Female using r?

A: First, welcome to Stackoverflow. As pointed in the comments, it's better to give a reproducible example. I'm happy to answer this time, but bear in mind that in the future, you are more likely to get answers if you give such an example.
I'm assuming you're working with a data frame. What you would need is:
> df <- data.frame("name"=c("A","B","C","D"), sex=c("Male","Male","Male","Female"))
> df
  name    sex
1    A   Male
2    B   Male
3    C   Male
4    D Female
> df$sex[df$sex == "Male"] <- "Female"
> df
  name    sex
1    A Female
2    B Female
3    C Female
4    D Female

The line df$sex[df$sex == "Male"] <- "Female" is what you are looking for. The first part, df$sex, selects the column named sex.
The second part, [df$sex == "Male"], selects all rows of the column which have sex equal to "Male".
The last part is assignment. <- "Female" assigns selected observations the value "Female".

A: We can use
library(data.table)
setDT(df)[sex=="Male", sex := "Female"]

Or using base R
df$sex <- with(df, replace(sex, sex=="Male", "Female"))


text:
Q: Implementing a full 3d scatter with bokeh in python I am currently working on a project where I would like to output a 3D interactive scatter plot using Bokeh. I would like to colour the dots based on 2 or 3 categories, and I would like to show the gene corresponding to the dot after hovering it. I am aware of the fact that Bokeh does not fully implement 3D plots, and I found the following script, which allows to produce such 3D plot with python (original code).
Although the original code produces a 3D surface, with some reading of the documentation I've managed to produce a 3D plot. I've also managed to color the dots based on categories. However, when I try to produce tooltips, whose information will be encoded in the 'extra' variable in python (or any other), I am unable to produce that information. I have no knowledge of JS, so I am just trying to tweak the variables to see what happens.
The code I produced is this one:
from __future__ import division
from bokeh.core.properties import Instance, String
from bokeh.models import ColumnDataSource, LayoutDOM
from bokeh.io import show
import numpy as np

JS_CODE = """
# This file contains the JavaScript (CoffeeScript) implementation
# for a Bokeh custom extension. The "surface3d.py" contains the
# python counterpart.
#
# This custom model wraps one part of the third-party vis.js library:
#
#     http://visjs.org/index.html
#
# Making it easy to hook up python data analytics tools (NumPy, SciPy,
# Pandas, etc.) to web presentations using the Bokeh server.

# These "require" lines are similar to python "import" statements
import * as p from "core/properties"
import {LayoutDOM, LayoutDOMView} from "models/layouts/layout_dom"

# This defines some default options for the Graph3d feature of vis.js
# See: http://visjs.org/graph3d_examples.html for more details.
OPTIONS =
  width:  '700px'
  height: '700px'
  style: 'dot-color'
  showPerspective: true
  showGrid: true
  keepAspectRatio: true
  verticalRatio: 1.0
  showLegend: false
  cameraPosition:
    horizontal: -0.35
    vertical: 0.22
    distance: 1.8

  dotSizeRatio: 0.01

  tooltip: true    #(point) -> return 'value: ' + point.z + '
' + point.data.extra

# To create custom model extensions that will render on to the HTML canvas
# or into the DOM, we must create a View subclass for the model. Currently
# Bokeh models and views are based on BackBone. More information about
# using Backbone can be found here:
#
#     http://backbonejs.org/
#
# In this case we will subclass from the existing BokehJS ``LayoutDOMView``,
# corresponding to our
export class Surface3dView extends LayoutDOMView

  initialize: (options) ->
    super(options)

    url = "https://cdnjs.cloudflare.com/ajax/libs/vis/4.16.1/vis.min.js"

    script = document.createElement('script')
    script.src = url
    script.async = false
    script.onreadystatechange = script.onload = () => @_init()
    document.querySelector("head").appendChild(script)

  _init: () ->
    # Create a new Graph3s using the vis.js API. This assumes the vis.js has
    # already been loaded (e.g. in a custom app template). In the future Bokeh
    # models will be able to specify and load external scripts automatically.
    #
    # Backbone Views create
 elements by default, accessible as @el. Many
    # Bokeh views ignore this default
, and instead do things like draw
    # to the HTML canvas. In this case though, we use the
 to attach a
    # Graph3d to the DOM.
    @_graph = new vis.Graph3d(@el, @get_data(), OPTIONS)

    # Set Backbone listener so that when the Bokeh data source has a change
    # event, we can process the new data
    @connect(@model.data_source.change, () =>
        @_graph.setData(@get_data())
    )

  # This is the callback executed when the Bokeh data has an change. Its basic
  # function is to adapt the Bokeh data source to the vis.js DataSet format.
  get_data: () ->
    data = new vis.DataSet()
    source = @model.data_source
    for i in [0...source.get_length()]
      data.add({
        x:     source.get_column(@model.x)[i]
        y:     source.get_column(@model.y)[i]
        z:     source.get_column(@model.z)[i]
        extra: source.get_column(@model.extra)[i]
        style: source.get_column(@model.color)[i]
      })
    return data

# We must also create a corresponding JavaScript Backbone model sublcass to
# correspond to the python Bokeh model subclass. In this case, since we want
# an element that can position itself in the DOM according to a Bokeh layout,
# we subclass from ``LayoutDOM``
export class Surface3d extends LayoutDOM

  # This is usually boilerplate. In some cases there may not be a view.
  default_view: Surface3dView

  # The ``type`` class attribute should generally match exactly the name
  # of the corresponding Python class.
  type: "Surface3d"

  # The @define block adds corresponding "properties" to the JS model. These
  # should basically line up 1-1 with the Python model class. Most property
  # types have counterparts, e.g. ``bokeh.core.properties.String`` will be
  # ``p.String`` in the JS implementatin. Where the JS type system is not yet
  # as rich, you can use ``p.Any`` as a "wildcard" property type.
  @define {
    x:           [ p.String           ]
    y:           [ p.String           ]
    z:           [ p.String           ]
    color:       [ p.String           ]
    extra:        [ p.String           ]
    data_source: [ p.Instance         ]
  }
"""

# This custom extension model will have a DOM view that should layout-able in
# Bokeh layouts, so use ``LayoutDOM`` as the base class. If you wanted to create
# a custom tool, you could inherit from ``Tool``, or from ``Glyph`` if you
# wanted to create a custom glyph, etc.
class Surface3d(LayoutDOM):

    # The special class attribute ``__implementation__`` should contain a string
    # of JavaScript (or CoffeeScript) code that implements the JavaScript side
    # of the custom extension model.
    __implementation__ = JS_CODE

    # Below are all the "properties" for this model. Bokeh properties are
    # class attributes that define the fields (and their types) that can be
    # communicated automatically between Python and the browser. Properties
    # also support type validation. More information about properties in
    # can be found here:
    #
    #    https://docs.bokeh.org/en/latest/docs/reference/core.html#bokeh-core-properties

    # This is a Bokeh ColumnDataSource that can be updated in the Bokeh
    # server by Python code
    data_source = Instance(ColumnDataSource)

    # The vis.js library that we are wrapping expects data for x, y, z, and
    # color. The data will actually be stored in the ColumnDataSource, but
    # these properties let us specify the *name* of the column that should
    # be used for each field.
    x = String
    y = String
    z = String
    extra = String
    color = String

X_data = np.random.normal(0,10,100)
Y_data = np.random.normal(0,5,100)
Z_data = np.random.normal(0,3,100)
color = np.asarray([0 for x in range(50)]+[1 for x in range(50)])
extra = np.asarray(['a' for x in range(50)]+['b' for x in range(50)])

source = ColumnDataSource(data=dict(x=X_data, y=Y_data, z=Z_data, color = color, extra=extra))

surface = Surface3d(x="x", y="y", z="z", extra="extra", color="color", data_source=source)

show(surface)

Given this, my idealized output from the project should be:

*

*Produce the correct tooltips, with the gene corresponding to the value.

*Complementarily, add in the tooltip the category to which the dot belongs (if 1. can be done, I'd have no problem doing this one).

*Somehow, remove the colorbar (legend), which I won't need. It doesn't dissapear when putting the showLegend value to false.

Thank you in advance.

A: So there are two small tweaks to make to acheive what you want.
I think the most important is the version of visjs being used.
Change the url to url = "https://visjs.github.io/vis-graph3d/standalone/umd/vis-graph3d.min.js"
Secondly, the function declaration for tooltip should be changed to :
tooltip: (point) -> return 'value: ' + point.z + '
' + 'extra: ' + point.data.extra

Not a coffeescript user, but that seems to correct the syntax for using the custom tooltip html.
Here is the updated example, if needed. (Note, this is for bokeh version 0.12.9)
from __future__ import division
from bokeh.core.properties import Instance, String
from bokeh.models import ColumnDataSource, LayoutDOM
from bokeh.io import show
import numpy as np

JS_CODE = """
# This file contains the JavaScript (CoffeeScript) implementation
# for a Bokeh custom extension. The "surface3d.py" contains the
# python counterpart.
#
# This custom model wraps one part of the third-party vis.js library:
#
#     http://visjs.org/index.html
#
# Making it easy to hook up python data analytics tools (NumPy, SciPy,
# Pandas, etc.) to web presentations using the Bokeh server.

# These "require" lines are similar to python "import" statements
import * as p from "core/properties"
import {LayoutDOM, LayoutDOMView} from "models/layouts/layout_dom"

# This defines some default options for the Graph3d feature of vis.js
# See: http://visjs.org/graph3d_examples.html for more details.
OPTIONS =
  width:  '700px'
  height: '700px'
  style: 'dot-color'
  showPerspective: true
  showGrid: true
  keepAspectRatio: true
  verticalRatio: 1.0
  showLegend: false
  cameraPosition:
    horizontal: -0.35
    vertical: 0.22
    distance: 1.8
  dotSizeRatio: 0.01
  tooltip: (point) -> return 'value: ' + point.z + '
' + 'extra: ' + point.data.extra

# To create custom model extensions that will render on to the HTML canvas
# or into the DOM, we must create a View subclass for the model. Currently
# Bokeh models and views are based on BackBone. More information about
# using Backbone can be found here:
#
#     http://backbonejs.org/
#
# In this case we will subclass from the existing BokehJS ``LayoutDOMView``,
# corresponding to our
export class Surface3dView extends LayoutDOMView

  initialize: (options) ->
    super(options)

    url = "https://visjs.github.io/vis-graph3d/standalone/umd/vis-graph3d.min.js"

    script = document.createElement('script')
    script.src = url
    script.async = false
    script.onreadystatechange = script.onload = () => @_init()
    document.querySelector("head").appendChild(script)

  _init: () ->
    # Create a new Graph3s using the vis.js API. This assumes the vis.js has
    # already been loaded (e.g. in a custom app template). In the future Bokeh
    # models will be able to specify and load external scripts automatically.
    #
    # Backbone Views create
 elements by default, accessible as @el. Many
    # Bokeh views ignore this default
, and instead do things like draw
    # to the HTML canvas. In this case though, we use the
 to attach a
    # Graph3d to the DOM.
    @_graph = new vis.Graph3d(@el, @get_data(), OPTIONS)

    # Set Backbone listener so that when the Bokeh data source has a change
    # event, we can process the new data
    @connect(@model.data_source.change, () =>
        @_graph.setData(@get_data())
    )

  # This is the callback executed when the Bokeh data has an change. Its basic
  # function is to adapt the Bokeh data source to the vis.js DataSet format.
  get_data: () ->
    data = new vis.DataSet()
    source = @model.data_source
    for i in [0...source.get_length()]
      data.add({
        x:     source.get_column(@model.x)[i]
        y:     source.get_column(@model.y)[i]
        z:     source.get_column(@model.z)[i]
        extra: source.get_column(@model.extra)[i]
        style: source.get_column(@model.color)[i]
      })
    return data

# We must also create a corresponding JavaScript Backbone model sublcass to
# correspond to the python Bokeh model subclass. In this case, since we want
# an element that can position itself in the DOM according to a Bokeh layout,
# we subclass from ``LayoutDOM``
export class Surface3d extends LayoutDOM

  # This is usually boilerplate. In some cases there may not be a view.
  default_view: Surface3dView

  # The ``type`` class attribute should generally match exactly the name
  # of the corresponding Python class.
  type: "Surface3d"

  # The @define block adds corresponding "properties" to the JS model. These
  # should basically line up 1-1 with the Python model class. Most property
  # types have counterparts, e.g. ``bokeh.core.properties.String`` will be
  # ``p.String`` in the JS implementatin. Where the JS type system is not yet
  # as rich, you can use ``p.Any`` as a "wildcard" property type.
  @define {
    x:           [ p.String           ]
    y:           [ p.String           ]
    z:           [ p.String           ]
    color:       [ p.String           ]
    extra:       [ p.String           ]
    data_source: [ p.Instance         ]
  }
"""

# This custom extension model will have a DOM view that should layout-able in
# Bokeh layouts, so use ``LayoutDOM`` as the base class. If you wanted to create
# a custom tool, you could inherit from ``Tool``, or from ``Glyph`` if you
# wanted to create a custom glyph, etc.
class Surface3d(LayoutDOM):

    # The special class attribute ``__implementation__`` should contain a string
    # of JavaScript (or CoffeeScript) code that implements the JavaScript side
    # of the custom extension model.
    __implementation__ = JS_CODE

    # Below are all the "properties" for this model. Bokeh properties are
    # class attributes that define the fields (and their types) that can be
    # communicated automatically between Python and the browser. Properties
    # also support type validation. More information about properties in
    # can be found here:
    #
    #    https://docs.bokeh.org/en/latest/docs/reference/core.html#bokeh-core-properties

    # This is a Bokeh ColumnDataSource that can be updated in the Bokeh
    # server by Python code
    data_source = Instance(ColumnDataSource)

    # The vis.js library that we are wrapping expects data for x, y, z, and
    # color. The data will actually be stored in the ColumnDataSource, but
    # these properties let us specify the *name* of the column that should
    # be used for each field.
    x = String
    y = String
    z = String
    extra = String
    color = String

X_data = np.random.normal(0,10,100)
Y_data = np.random.normal(0,5,100)
Z_data = np.random.normal(0,3,100)
color = np.asarray([0 for x in range(50)]+[1 for x in range(50)])
extra = np.asarray(['a' for x in range(50)]+['b' for x in range(50)])

source = ColumnDataSource(data=dict(x=X_data, y=Y_data, z=Z_data, color = color, extra=extra))

surface = Surface3d(x="x", y="y", z="z", extra="extra", color="color", data_source=source)

show(surface)

A: Although not the best answer, a fully implemented Scatter in 3D can be now obtained using plotly.
import plotly.plotly as py
import plotly.graph_objs as go

import numpy as np

x, y, z = np.random.multivariate_normal(np.array([0,0,0]), np.eye(3), 200).transpose()
trace1 = go.Scatter3d(
    x=x,
    y=y,
    z=z,
    mode='markers',
    marker=dict(
        size=12,
        line=dict(
            color='rgba(217, 217, 217, 0.14)',
            width=0.5
        ),
        opacity=0.8
    )
)

x2, y2, z2 = np.random.multivariate_normal(np.array([0,0,0]), np.eye(3), 200).transpose()
trace2 = go.Scatter3d(
    x=x2,
    y=y2,
    z=z2,
    mode='markers',
    marker=dict(
        color='rgb(127, 127, 127)',
        size=12,
        symbol='circle',
        line=dict(
            color='rgb(204, 204, 204)',
            width=1
        ),
        opacity=0.9
    )
)
data = [trace1, trace2]
layout = go.Layout(
    margin=dict(
        l=0,
        r=0,
        b=0,
        t=0
    )
)
fig = go.Figure(data=data, layout=layout)
py.plot(fig, filename='simple-3d-scatter')

The code will produce an html file, and allows full personalization.


text:
Q: 300GB of phantom data on my Samsung 970 EVO M.2 and no option to format: Is there anything else I can do? The problem:
So something really weird is going on with my Samsung 970 EVO M.2 SSD. Opening the drive and ensuring hidden files are shown, it's empty:

but looking in the properties panel it's also not:

So time to try all tools available to figure this out, starting with the basics:
Debugging steps so far:
1. Disk Cleanup

Nothing to gain.
2. Optimize and Defragment

It was worth a shot but no dice.

3. Error Checking

Hmm, that's a lot of scanning for a drive you're so sure is empty Windows...

Nothing to see here.
4. Format Drive
If all else fails, let's just format the dang thing... Right?

Wrong.
5. Samsung Magician
Alright no luck yet, but it's a Samsung drive, so surely if anything can figure this out it'd be a Samsung drive management tool.

Alrighty then. Apparently Samsung doesn't fully support this product they sold me. EDIT: According to the rep, since M.2 was such a new product, the first version of the 970 EVO didn't support Diagnostic Scan, but the next gen of the same drive does support it.
6. Called Samsung
The tech noticed Disk Manager shows that the drive is listed as a pagefile. Now that I think about it, I do think I recall using some setting to let my other drives be used as page-files for memory because I was running a simulation program that needed massive memory space. But I dont recall what the setting was or where I found it
Is there anything else I can do?

A: Found the issue!
I had wandered into Windows advanced system settings and found how to set pagefile allocation on other drives. It was a long time ago and I never noticed until now.
Here's a guide to do (and undo) this:
https://www.windowscentral.com/how-move-virtual-memory-different-drive-windows-10
Settings > System > About > Related Settings / System Info > Advanced System Settings > Performance > Settings > Advanced


text:
Q: p4 submit files not in client view Is there a way to submit a file that is not part of the client view?
My client looks like:
//dir1/...
-//dir1/dir2/...

I am trying to create a new file that is a few megabytes at //dir1/dir2/file1 and submit it without syncing //dir1/dir2/ (which can be multi-gigabyte).
Is there any way to force-submit a file that doesn't exist in the client view if I can guarantee the base directory (//dir1/dir2) exists in the Perforce depot?
Edit: Yes, I understand that I can add this file to the client view, but my question, specifically, as above, is: "Is there any way to force-submit a file that doesn't exist in the client view"?

A: (Edit: Clarifying my answer, to try to more directly answer the (clarified) question)
No, there is no way to submit a file that doesn't exist in the client view. Without the information in the client view, the server doesn't know how to ask the client for the content of the file to be submitted, as the client view is what specifies which physical file on the client machine contains the content to be submitted.
As a workaround, you can refine your client view still further:
//dir1/...          //my-ws/location/dir1/...
-//dir1/dir2/...    //my-ws/location/dir1/dir2-files-I-don't-care-about/...
//dir1/dir2/file1   //my-ws/location/dir1/dir2/file1

You can read this as: "include everything in dir1, excluding everything in dir1/dir2, except for dir1/dir2/file1, which is specifically to be included."
After adjusting your view, you can use p4 add //dir1/dir2/file1 as you expect.
The order of the mapping lines is critical here, as described by this sentence from p4 help views:
If more than one mapping line refers to the same files, the later
mapping line overrides the earlier one.

If you wish, once you have submitted the file, you can remove that line from your view spec (and re-sync your client), to simplify your client back to its prior definition.


text:
Q: Can't resize Folder properties window I've opened the properties window of a folder to view it's security groups, but the security group names are too long to be fully readable in the security tab.
There is no way to resize the window.
Is there a logical purpose for this, or is it just designed to be a complete pain in the ass.
Happens on Win Server 2003, and Windows 7.

A: Try clicking the Advanced button then double click the dividing line between the Name and Permission fields in the column headers. You'll know your mouse pointer is in the correct position to do this when the cursor changes to a vertical bar with left and right arrows. This should expand the width of the column so that it's equal to the longest entry and provide a horizontal scrollbar.


text:
Q: UnimplementedError: Graph execution error: running nn on tensorflow I have been having this error, and I don't know why, especially since I am following someone's code exactly and the person had no error when running this
img_shape = (128,128,3)

# load pretrained model
base_model = tf.keras.applications.VGG19(input_shape=img_shape, include_top=False, weights='imagenet')

# freezing the model
base_model.trainable = False

#define the custom head for network
global_average_layer = tf.keras.layers.GlobalAveragePooling2D()(base_model.output)

# output / prediction layer
prediction_layer = tf.keras.layers.Dense(units=1, activation='sigmoid')(global_average_layer)

model = tf.keras.models.Model(inputs=base_model.input, outputs=prediction_layer)

# compile the model
opt = tf.keras.optimizers.RMSprop(learning_rate=0.0001)
model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])

# create data generators
# import library
from tensorflow.keras.preprocessing.image import ImageDataGenerator

# define objects
data_gen_train = ImageDataGenerator(rescale=1/255.0)
data_gen_test = ImageDataGenerator(rescale=1/255.0)

# define variables
train_generator = data_gen_train.flow_from_directory(directory=training_dir, target_size=(128,128), batch_size=128, class_mode='binary')
test_generator = data_gen_test.flow_from_directory(directory=test_dir, target_size=(128,128), batch_size=128, class_mode='binary')

model.fit_generator(generator=train_generator, epochs=5, validation_data=test_generator)

This is the error I am getting
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:1: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.
  """Entry point for launching an IPython kernel.
Epoch 1/5
---------------------------------------------------------------------------
UnimplementedError                        Traceback (most recent call last)
<ipython-input-46-18b18ca5977c> in <module>()
----> 1 model.fit_generator(generator=train_generator, epochs=5, validation_data=test_generator)

2 frames
/usr/local/lib/python3.7/dist-packages/keras/engine/training.py in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, validation_freq, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
   2221         use_multiprocessing=use_multiprocessing,
   2222         shuffle=shuffle,
-> 2223         initial_epoch=initial_epoch)
   2224
   2225   @doc_controls.do_not_generate_docs

/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
     65     except Exception as e:  # pylint: disable=broad-except
     66       filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67       raise e.with_traceback(filtered_tb) from None
     68     finally:
     69       del filtered_tb
/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     53     ctx.ensure_initialized()
     54     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 55                                         inputs, attrs, num_outputs)
     56   except core._NotOkStatusException as e:
     57     if name is not None:

UnimplementedError: Graph execution error:

Detected at node 'model/block1_conv1/Conv2D' defined at (most recent call last):
    File "/usr/lib/python3.7/runpy.py", line 193, in _run_module_as_main
      "__main__", mod_spec)

I could not put in the complete error at the end, but
Please, can someone tell me what's wrong

A: it is easy the train_generator is old you can use this.
It is about the memory you create the matrixes initial operations that will reduce the working loads and perform well on data sizes.
[ Sample ]:
import os
from os.path import exists

import tensorflow as tf

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Variables
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
img_shape = (128,128,3)
BATCH_SIZE = 1
IMG_SIZE = (128, 128)

database_buffer = "F:\\models\\buffer\\" + os.path.basename(__file__).split('.')[0] + "\\TF_DataSets_01.h5"
database_buffer_dir = os.path.dirname(database_buffer)

if not exists(database_buffer_dir) :
    os.mkdir(database_buffer_dir)
    print("Create directory: " + database_buffer_dir)

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: DataSets
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
PATH = 'F:\\datasets\\downloads\\cats_name'
train_dir = os.path.join(PATH, 'train')
validation_dir = os.path.join(PATH, 'validation')

train_dataset = tf.keras.utils.image_dataset_from_directory(train_dir,
                                                                        shuffle=True,
                                                                        batch_size=BATCH_SIZE,
                                                                        image_size=IMG_SIZE)

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Model Initialize
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
# load pretrained model
base_model = tf.keras.applications.VGG19(input_shape=img_shape, include_top=False, weights='imagenet')

# freezing the model
base_model.trainable = False

#define the custom head for network
global_average_layer = tf.keras.layers.GlobalAveragePooling2D()(base_model.output)

# output / prediction layer
prediction_layer = tf.keras.layers.Dense(units=1, activation='sigmoid')(global_average_layer)

model = tf.keras.models.Model(inputs=base_model.input, outputs=prediction_layer)
model.summary()

# compile the model
opt = tf.keras.optimizers.RMSprop(learning_rate=0.0001)
model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Training
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
history = model.fit( train_dataset, batch_size=100, epochs=50 )

[ Output ]:


text:
Q: How can I get a string result from a stored procedure called by Database.ExecuteSqlCommand I have a stored procedure in SQL Server 2016 that I want to call from a method in an ASP.Net Core project using Entity Framework Core v1.1.1.
Here is my method...
    private string GetNextSerialNumber(string a_mailerId, string a_serviceTypeCode)
    {
        try
        {
            var mailerId = new SqlParameter
            {
                ParameterName = "@mailerId",
                SqlDbType = SqlDbType.NVarChar,
                Direction = ParameterDirection.Input,
                Size = 9,
                Value = a_mailerId
            };

            var serviceTypeCode = new SqlParameter
            {
                ParameterName = "@serviceTypeCode",
                SqlDbType = SqlDbType.NVarChar,
                Direction = ParameterDirection.Input,
                Size = 4,
                Value = a_serviceTypeCode
            };

            var serialNumber = new SqlParameter
            {
                ParameterName = "@serialNumber",
                SqlDbType = SqlDbType.NVarChar,
                Size = 14,
                Direction = ParameterDirection.Output
            };

            var result = m_mailpieceRoContext.Database.ExecuteSqlCommand(
                "exec GetNextSerialNumber @mailerId, @serviceTypeCode, @serialNumber OUT", mailerId, serviceTypeCode, serialNumber);

            return result;

        }
        catch (Exception ex)
        {

            throw;
        }

    }

and here is my stored procedure...
ALTER PROCEDURE [dbo].[GetNextSerialNumber]
    @mailerId               NVARCHAR(9),
    @serviceTypeCode        NVARCHAR(4),
    @serialNumber           NVARCHAR(14)    OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @counter        BIGINT
    DECLARE @start_counter  BIGINT
    DECLARE @end_counter    BIGINT
    DECLARE @length         INT
    DECLARE @tempCounters   TABLE
    (
        current_counter     BIGINT,
        start_counter       BIGINT,
        end_counter         BIGINT,
        [length]            INT
    )

    INSERT INTO
        @TempCounters
    SELECT
        current_counter,
        start_counter,
        end_counter,
        [length]
    FROM
        MailerIdCounters
    WHERE
        mailer_id = @mailerId
        AND service_type_code = @serviceTypeCode
        AND active = 1

    IF EXISTS (SELECT * FROM @tempCounters)
    BEGIN
        SELECT @counter = current_counter FROM @tempCounters
        SELECT @start_counter = start_counter FROM @tempCounters
        SELECT @end_counter = end_counter FROM @tempCounters
        SELECT @length = [length] FROM @tempCounters
    END

    IF (@counter + 1) > @end_counter
        SET @counter = @start_counter
    ELSE
        SET @counter = @Counter  + 1

    UPDATE MailerIDCounters
    SET current_counter = @counter
    WHERE mailer_id = @mailerId
    AND service_type_code = @serviceTypeCode

    SELECT RIGHT('00000000000000'+CAST(@counter AS VARCHAR(14)), @length)
    SET @serialNumber = @counter
END

When I run my stored procedure from SSMS 2016, I get the desired string result (i.e. 00000123460) but the value of result in the GetNextSerialNumber method listed above is -1.
Any ideas?
Thanks in advance for any help you can provide.

A: context.Database.ExecuteSqlCommand(
   "exec GetNextSerialNumber @serialNumber OUT", serialNumber);

ExecuteSqlCommand returns execution result only (it's -1). To get serial number, just check the output parameter value after the command has been executed:
var val = serialNumber.Value;


text:
Q: C# Broad Exception Handling Background
I am developing software running in a larger executive program, to which I can communicate using only its API. After extensive testing, I've determined there is an architecture problem in the executive concerning how it handles exceptions.
The executive program has its own exception handling in the form of a pop-up dialog providing the user with information about the exception. Based on the program's behavior, I suspect it resembles this:
// Executive Program
try {
    // A simple state machine controlling execution mode within the Executive Program
    // Not actually certain a switch is used, but this is representative of behavior
    switch(executiveStateMachine){
        case setUp:
            // [....]
            break;
        case starting:
            // [....]
            break;
        case run:
            while(true){
                // [...]
                // My software running inside executive program
                // [...]
                // Eventual break after successful completion
                break;
            }
            break;
        case finish:
            // [....]
            break;
    }
}
    catch(Exception except){
        // On any, show a proprietary exception dialog
        if(ExceptionDialog.ShowDialog(Exception) == DialogResult.OK) break;
    }

When handling exceptions, it appears the Executive Program occasionally creates fatal errors within its state machine transitions causing the entire program to crash.
While I've filed a bug request with the Executive's Developer, I don't think it will be fixed any time soon and would really like to handle both my own software's exceptions and the Executive Program's exceptions myself.
Question; (TLDR)
Is it possible in C# to catch an exception using some method before a larger, encapsulating (and unseen) try-catch block can?


text:
Q: How do I force implementations of a method to be inside a try-catch block in Java? This may be a Java question, or it may be an Eclipse question, I'm not positive.
I'm creating custom View in Android: HelpTextView extends View
I would like to override View.setVisibility(), forcing calls to HelpTextView.setVisibility() to be written inside try-catch (NullPointerException nex) blocks.
I added both a throws declaration to the method  (which is what I thought would do the trick) as well as a throw command but no luck.  Is this not working because it's simply never going to work (perhaps overriding just doesn't work that way) or am I doing something wrong?

A: NullPointerException is a subclass of RuntimeException. A RuntimeException is an unchecked exception, meaning that you do not need to catch it.
No matter how you declare your method, you cannot force a NullPointerException to be caught.
You can, however, create your own Exception and force that to be caught.

A: You can not override a method and add an exception which is not already declared in super method except RuntimeExceptions.

A: You cannot do this because NullPointerException is a RuntimeException, which does not need to be caught by the caller.
Your best approach is to implement your own Exception.
public class HelpTextView extends View {

    public setThisVisibility(boolean isVisible) throws MyNullPointerException {
        ...
    }

}
and your MyNullPointerException cannot be RuntimeException


text:
Q: making and using an android library app I'd like to know if there is a good way of packaging a library as an Android app that can be used by other Android apps, so that there is only one copy of the library on the phone, and it is used by many separate apps. Some obvious candidates are a numerical library with the Fourier transforms and standard numerical calculus and linear algebra routines, a physics engine, and embedded scripting with your favourite interpreted language. I'm pretty sure those examples are not part of the Android SDK. Even if they are, it is easy to imagine some other kind of library that almost definitely is not, like a library for computing the evolution of cellular automata, or for doing quantum mechanics simulations. I can't seem to find any library apps like this in Google Play, though. Is it because it can't be done? Why not?
Now, I know there are going to be some people asking me why I would want to do this. I'll pre-emptively reply, never mind my reasons for now. Can it be done? Although the advantages of such an approach, as compared to putting a copy of the library in every app that needs it, should be obvious, it is not the subject of this question.

A: There are a few ways of doing a 'library app'.

*

*One way is making the project ,and releasing it as a library
project. eg. is this. In this method, the library is imported
as a project by the app developer.

*Another way of making a library is writing the library, and
compiling it into a .jar file.Here is another example.

*And finally, you can make a proper app(.apk file) and release it
into the market.In the app, you can create provisions for receiving
Intents, processing, and sending back Intents. It will besomething like
communicating between apps.

The last method, however will be slow, as both apps will have to be started, and it will all be a hassle.


text:
Q: Use float to align div elements I am trying to align some div tag containing some images for a small gallery. I used float:right and seems working but for some reason in some row instead of having a div the space is simply empty and the div is in the next row jumping to it. You can see it here : example

".$row['titel']."

".$row['size']."

";

.gridImage{

width:40%;
float:right;
padding:10px;
display:inline;
text-align:center;
}

A: try this?
.gridImage {
    width: 40%;
    display: inline-block;
    text-align: center;
}


text:
Q: Command executed via pexpect not taking effect I am trying to cherry-pick gerrit reviews using a python script. I already have the string required to cherry-pick a review. I have used pexpect to automate the password input step.
Here is an example. For each review I have to execute the following 2 commands:

*

*git fetch "ssh://myusername@my-gerrit.server.net:34343/project" refs/changes/45/255645/38

*git cherry-pick FETCH_HEAD

Only the first command asks for a password. Here is the code i have written:
child = pexpect.spawn('git fetch "ssh://myusername@my-gerrit.server.net:34343/project" refs/changes/45/255645/38')
child.logfile_read = sys.stdout
child.expect(r'Enter passphrase for key(.*?):', timeout=10)
child.sendline('mypwd')
child.expect([pexpect.TIMEOUT, 'host$', pexpect.EOF])

child.sendline('git cherry-pick FETCH_HEAD')
child.expect([pexpect.TIMEOUT, 'host$', pexpect.EOF])

When i run the script i dont see any error. However the second command (git cherry-pick FETCH_HEAD) doesnt seem to be executed. I say this because when i run these commands manually the second command throws a git merge conflict. When i run the script i dont see cherry-pick in progress (git status shows all clean). I tried some variants but cannot get it to work. Please help.
Thanks in advance

A: In order to add logs without modifying your script, use GIT_TRACE2 environment variables for tracing events.
export GIT_TRACE2=1
export GIT_TRACE2_EVENT=1

(or set, if you are on Windows)
Make also sure to launch your script with the same account you used to do manual testing.

If the second command does not seem to be executed, check if, as in this thread, the prompt is the issue:

It seems the problem was with the prompt I expected back.
If I change the expect to "child.expect('$ .*', timeout=15)", it works.


text:
Q: IT-/Networking-specific dictionary I am tasked with preparations of technical negotiations with a foreign company where the technicans' native language is Russian. I would like to have a technical dictionary for terms specific to the IT industry, more specifically the networking and management segments to be able to translate things like

*

*software package

*network switch

*ip address

*settings dialog

*property

into widely-understood and unambiguous Russian counterparts. Where would I ask/look for one?
My trouble with general-purpose dictionaries is that their translation proposals, if applicable at all, often are extremely cumbersome and poorly understood. Anybody who has seen a badly localized application should instantly know, what I mean. And for those who haven't:

Is this your idea of a broken pipe?

A: I finally managed to find an online dictionary which has provided me with the basic vocabulary at http://translate.academic.ru
Best of all, it has passed the "broken pipe" test:

Using gettext catalogs in locales in Linux installations as suggested by @JamesSneeringer is also an excellent starting point when dealing with Linux-related projects.


text:
Q: problem with Bluetooth 5.3 dongle on Ubuntu 22.04LTS Using Ubuntu 22.04.1 LTS and it is up to date.
I opened Settings, clicked Bluetooth, on the panel to the right it said: No Bluetooth Found, plug in a dongle to use Bluetooth. So I bought a Bluetooth 5.3 compatible dongle and plugged it into a USB port. The wee light on the dongle flashed several times then stayed on and the Settings->Bluetooth panel changed to: Bluetooth Turned Off, Turn on to connect devices and receive file transfers.
At that point the toggle switch at the top of the screen was on the left side so I clicked on the right side. The switch moved to the right side and the message said: Bluetooth Turned Off, Turn on to connect devices and receive file transfers. Huh? I had just toggled the switch and it's still off?  Very strange!!!!!!!!!!!!!
So I toggled the switch again and moved it to the left side. The message changed to: Airplane Mode is on, Bluetooth is disabled when airplane mode is on. And a button titled Turn Off Airplane Mode appeared.
So I clicked the Turn Off Airplane Mode button and got the Bluetooth Turned Off, Turn on to connect devices and receive file transfers.
At no point did I see anything like "Scanning for Bluetooth devices, this may take a few minutes....". No whirlygigs spinning to indicate something happening.
My system hardware specs
My system hardware specs is the output from "sudo lshw" when my USB 5.3 dongle is plugged in. It's ~580 lines and probably more than requested but ya never know. In that file I see

            *-usb

                  description: Bluetooth wireless interface
                  product: general adapter
                  vendor: Actions
                  physical id: 1
                  bus info: usb@1:1.1
                  version: 88.91
                  serial: ACTIONS1234
                  capabilities: bluetooth usb-2.00
                  configuration: driver=btusb maxpower=100mA speed=12Mbit/s

which is my BT5.3 dongle. With the dongle unplugged sudo lshw | grep -i "ACTIONS" returns a blank.  With the dongle inserted the same command finds lines for the dongle which proves only that the system sees it when it's there and doesn't see it when it's gone.
My system hardware specs also shows a Logitech unifying receiver dongle and the Logitech K580 wireless keyboard and M720 Triathlon mouse it serves. Those 2 are the only USB dongles in the system and I suspect they may be at odds with each other. I reported trouble with the mouse in a thread I started ~1 month ago. The problems mostly went away when I updated from Ubuntu 20.xx to 22.04 but not completely, mainly that the wheel doesn't scroll the screen properly. Looking further into that today...
~$ sudo dmesg | grep -i "error"
[    0.645649] RAS: Correctable Errors collector initialized.
[    9.074185] EXT4-fs (sda5): re-mounted. Opts: errors=remount-ro. Quota mode: none.
[58528.772485] logitech-hidpp-device 0003:046D:405E.0004: Couldn't get wheel multiplier (error -110)
[222518.808683] logitech-hidpp-device 0003:046D:405E.0004: Couldn't get wheel multiplier (error -110)
[273770.417745] logitech-hidpp-device 0003:046D:405E.0004: Couldn't get wheel multiplier (error -110)
[280809.085517] logitech-hidpp-device 0003:046D:405E.0004: Couldn't get wheel multiplier (error -110)
[297332.046910] logitech-hidpp-device 0003:046D:405E.0004: Couldn't get wheel multiplier (error -110)
[305550.133903] logitech-hidpp-device 0003:046D:405E.0004: Couldn't get wheel multiplier (error -110)

~$ sudo dmesg | grep -i bluetooth
[296996.432303] Bluetooth: Core ver 2.22
[296996.432342] NET: Registered PF_BLUETOOTH protocol family
[296996.432344] Bluetooth: HCI device and connection manager initialized
[296996.432351] Bluetooth: HCI socket layer initialized
[296996.432355] Bluetooth: L2CAP socket layer initialized
[296996.432360] Bluetooth: SCO socket layer initialized
[312427.210137] Bluetooth: BNEP (Ethernet Emulation) ver 1.3
[312427.210143] Bluetooth: BNEP filters: protocol multicast
[312427.210149] Bluetooth: BNEP socket layer initialized

Uh-oh. I pasted the wrong output under the 2 "dmesg" commands in the box above. Fixed now.

A: I upgraded my ubuntu version from 20.04 to 22.04 few months ago. I had problems connecting my bluetooth headset after the upgrade. In my case, the devices were showing but not connecting, so I started searching the internet and found an app called blueman in the software center. It solved my problems. This is not a solution but it solved my problem. Maybe it will work for you too. Good luck :)


text:
Q: android длительное нажатие кнопки Как сделать кнопку, которая должна запустить выполнение метода только после удержания данной кнопки три секунды, и показать сообщение, что метод запущен, а если не прошло трёх секунд, то ничего не делать?

A: Можно как-то так: назначаем слушатель прикосновений, при начале прикосновения замеряем время начала прикосновения, в момент отпускания считаем сколько прошло времени с начала прикосновения.
button.setOnTouchListener(new View.OnTouchListener(){

    long startTime;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: // нажатие
              startTime = System.currentTimeInMills();
              break;
            case MotionEvent.ACTION_MOVE: // движение
              break;
            case MotionEvent.ACTION_UP: // отпускание
            case MotionEvent.ACTION_CANCEL:
              long totalTime = System.currentTimeInMills() - startTime;
              long totalSecunds = totalTime / 1000;
              if( totalSecunds >= 3 )
              {
                  //ВОТ тут прошло 3 или больше секунды с начала нажатия
                  //можно что-то запустить
                  System.out.println("Три секунды прошло с нажатия!");
              }
              break;
          }
          return true;
    }
});

A: Вы можете попробовать использовать Touch Listener:
    Handler handel = new Handler();
    b.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            switch (arg1.getAction()) {
            case MotionEvent.ACTION_DOWN:
                handel.postDelayed(run, 3000);
                break;

            default:
                handel.removeCallbacks(run);
                break;

            }
            return true;
        }
    });

b -  это view, в вашем варианте должна быть кнопка нажатие которой вы хотите отслеживать.
run:
Runnable run = new Runnable() {

    @Override
    public void run() {
        // Your code to run on long click

    }
};

A: Button button = new Button();
long then = 0;
button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            then = (Long) System.currentTimeMillis();
        } else if(event.getAction() == MotionEvent.ACTION_UP){
            if(((Long) System.currentTimeMillis() - then) >= 3000){
                return true;
            }
        }
    }
})


text:
Q: How do I insert a bit of XML into an XDocument using Visual Basic? I'm trying to create a sitemap in an ASP.NET MVC project.
This code in my Node controller...
Function Sitemap() As ContentResult
    Dim db As New EfrDotOrgEntities
    Dim Nodes = db.Node.ToList
    Dim RequestUrl As Uri = Url.RequestContext.HttpContext.Request.Url
    Dim AbsoluteRoot As String = String.Format("{0}://{1}", RequestUrl.Scheme, RequestUrl.Authority)

    Dim map As XDocument = <?xml version="1.0" encoding="UTF-8"?>
                           <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
                           </urlset>
    For Each n As Node In Nodes
        map.Add(<url>
                    <loc><%= AbsoluteRoot + Url.RouteUrl("IdOnly", New With {.id = n.Id}) %></loc>
                </url>)
    Next
    Return Content(map.ToString, "text/xml", Encoding.UTF8)
End Function

(here's an image because Stack Overflow doesn't color VB code well)

...produces this error:

This operation would create an
  incorrectly structured document.

It wouldn't know where to add that content.
How do I tell it to insert that bit of XML into the <urlset>?

A: You need to add it to the top level element in the document (the root):
map.Root.Add(...)

A: Why not fill it out completely with another xml literal hole?
Dim map As XDocument = <?xml version="1.0" encoding="UTF-8"?>
                       <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
                           <%= From n In Nodes.Cast(Of Node)() _
                               Select <url>
                                          <loc><%= AbsoluteRoot + Url.RouteUrl("IdOnly", New With {.id = n.Id}) %></loc>
                                      </url> %>
                       </urlset>


text:
Q: Laravel authorization 404 Been using laravel (current stable version) for 2 days now, and after reading the documentation... played a bit with the templating systems and some other stuff.
Now after installing Authority bundle along with Laravel-Administrator the problem I have is that when I try opening http://local.laravel/admin which redirects me to http://local.laravel/user/login and it's when the 404 magic happens.
My logs point good and I really don't know where else or what else to do, to try and debug this... any ideas?

A: I am the creator of the Authority bundle,
All I can tell you is that it doesn't do any redirects, so you will have to look at the administrative bundle.
Good luck!

A: Hey I wrote the Administrator bundle. Check out this section of the docs:
https://github.com/FrozenNode/Laravel-Administrator#installation--documentation
Notice in the config there are several options: auth_check, login_path, and login_redirect_key. What appears to be happening here is that your auth_check is being run, it fails, and then redirects you to the default login_path, which you probably don't have on your system. I'm guessing you haven't set these configuration options up, but they are pretty much required! I set it up this way because I wanted to let devs use their own auth system for the admin panel.
Update: Check out the configuration docs section on the permission, login_path, and login_redirect_key.

A: For anyone beginning with Laravel and stept into this problem, I had to set up the login form in order form, which it's not mentioned in the mentioned Bundle's install tutorials.

*

*I changed user/login to login in config/administrator.php -> login_path

*Added the router to handle the login and logout

More detail in this article http://codehappy.daylerees.com/authentication


text:
Q: Нет разрешения доступа к данным по api JS Здравствуйте, возникла проблема с получением данных по api.
Делаю запрос (убрал все лишнее для удобства):
try {
    fetch(API_SERVER)
      .then(response => {
        if (response.ok) {
          return response.json()
            .then(products => {
              console.log(products)
            })
        } else {
          console.log(new Error(response.status));
        }
      });
  } catch (err) {
    alert(err);
  }

И получаю ошибку:

Failed to load https://apiName: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
  localhost/:1 Uncaught (in promise) TypeError: Failed to fetch

Если делаю fetch(API_SERVER, {mode: 'no-cors'}), то вообще не понимаю, что происходит.
console.log(new Error(response.status)); в консоль выводит Error: 0
Сначала думал, что дело в localhost, но при загрузке на хостинг ошибка та же. Скачал расширение для Chrome Allow-control-allow-origin *, при включенном расширении при mode: 'cors' ошибки никакой нет.
Подскажите, пожалуйста, в чем проблема может быть и как ее решить?

A: Ошибка заключается в том что API которая Вам должна ответить, не добавляет в заголовок: Access-Control-Allow-Origin, следственно безопасность браузера не позволит Вам принять данный запрос.
API которая должна Вам ответить должна иметь настроенный CORS.


text:
Q: Spring Boot PropertySources in test environment I have an application.properties the values in which I am trying to autoWire in a bean
@Component
public class ConfigurationValues {
    @Value("${my.host}") private String myHost
}

This works well when I run the application. However When I run a JUnit test, I get an error
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'my.host' in string value "${my.host}"

And this is my test code
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
public class AnotherDummyTest {

    @Autowired
    private ConfigurationValues configurationValues;

    @Test
    public void testValue() {
        Assert.assertEquals("localhost", configurationValues.getMyHost());
    }
}

This test case fails with the IllegalArgumentException that I mentioned.

A: Try this:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class,
    initializers = ConfigFileApplicationContextInitializer.class)
public class AnotherDummyTest {


text:
Q: "He go to school directly". Why this sentence is wrong?
"He go to school directly"

I heard this sentence from someone and he told me that it's wrong. But I don't know why it is wrong. I need full explanation with examples which get me to understand this sentence.

A: Should be probably like this.

He goes to school directly.

Alternatively like this.

He will go to school directly.

A: If you are using directly in the sense "without taking any detours" the usual way would be this:

He goes directly to school.


text:
Q: Python Multiple Inheritance - Call a method of a class, but which one? class MyClass(Class1, Class2):
    pass

Both parents have a getImage method.
thing = MyClass()
thing.getImage() #I want to call Class1's
thing.getImage() #I want to call Class2's

Which getImage gets called? How do I specify which one to call?

A: In this case, thing.getImage will call Class1.getImage provided that it exists.  If you want to call the other, you can use the longer form:
Class2.getImage(thing)

These things can be inspected via the class's method resolution order (__mro__):
>>> class foo(object): pass
...
>>> class bar(object): pass
...
>>> class baz(foo,bar): pass
...
>>> print baz.__mro__
(<class '__main__.baz'>, <class '__main__.foo'>, <class '__main__.bar'>, <type 'object'>)

This shows that baz is searched for the method first, then foo, then bar and finally object.
Further reading about multiple inheritance
Further reading about mro


text:
Q: When (NOT how) should I test UI components on Android? I found lots of material on how to conduct UI tests using the Espresso framework and others. However, I am struggling to find any information that tells me to what extent should I test the UI: should I write tests that test every possible GridItem in every gridView? Just the items that are clickable? How should I go about determining what, and in how in depth I should test any given Android UI?
For this question, you should assume that you are the developer, the owner, and the designer.
It would be nice to get something that gets at what to prioritize in the general case.

A: Any answer to this question will be opinion based and it also depends on many factors. Let me give you some factors I would consider myself.
Unit testing:
The first question to ask is whether UI tests will be the only automated tests.
If you already unit test your code and have a reliable test suit, then I wouldn't invest too much time in UI tests. Write some tests that check the basic integration between UI elements and the rest of the application, but don't try to test the internal logic with UI tests - this is unit tests purpose.
If you don't have unit tests and the only automated testing will be done through UI, then you want to go deeper. Map all the flows that your application should perform, sort them according to testing complexity, and start writing UI tests for each flow starting with simplest. You would also want to measure the coverage of your UI tests so that you could have some visibility into the parts of the application that are not being tested.
Manual testing (QA):
The next factor is the amount of manual testing that you can afford.
Since you mentioned that this is a one-man show, you probably can't allocate days for manual testing before each release. In this case, it makes sense to have a broader suit of UI tests. Especially for flows that involve data validation - you really don't want to ensure (each release) that register flow doesn't accept malformed emails/usernames/passwords.
If, on the other hand, you have dedicated testers, then you can drastically reduce the investment into UI testing. I would say that, in some cases, you can remove UI testing completely if you have dedicated testers and a good suite of unit tests.
Requirements change rate:
UI testing is a huge PITA if requirements change often. Especially if these changes affect UI/UX.
If you have a stable product with existing user base then you can add more UI tests because the rate of change will probably be relatively low, and you want to guarantee that the existing functionality will not break.
If, on the other hand, you are just bootstrapping the app or exploring ideas and UI/UX is very unstable, then maintenance of UI tests will require much effort.
Cost of errors:
Think about what will be the cost of errors and adjust your testing strategy appropriately.
If the cost of a bug is just bad user experience and minor inconvenience, then you don't need to invest much into UI testing. If the cost of a bug is personal data being compromised, I would invest some more into testing. If your app can cause people to get injured, please make sure to test thoroughly and have a separate team that will carry this out.
General remarks:
For quality assurance, IMHO, three techniques are the most effective on Android: code reviews, unit testing and exploratory manual testing.
UI tests are less effective than the above three. Therefore, if you have not mastered one of the above yet, then you'd better invest the time into them instead of UI testing.


text:
Q: Issue with Spring Cacheable - Not injecting service I'm using the latest version of spring and using the caching concept. My (rest) service class seems to not be injected with the caching annotation. If I remove them it works perfectly however I don't use cache which is not what I want.
Application:
@SpringBootApplication
@EnableCaching
public class MyApplication{

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("MyCache")));
        return cacheManager;
    }

The service:
@CacheConfig(cacheNames = "MyCache")
@Service
public class MyServiceImpl implements MyService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final String errormessage = "Error getting books";
    @Autowired
    private UserRepositoryCrud userRepository;

    public MyServiceImpl () {

    }

    @Override
    @Cacheable(value = "MyCache", key = "#description", unless = "#result?.size() > 0")
    public final List<Books> getBooks(String description) {
        logger.debug("Starting getBooksService");
        //service implementation ...

(I also have a Restcontroler that only call this service)
When calling this method getBooks, I got a nullpointer on the logger, but when debugging I realize that everything is null, even the errormessage string...
If I remove the @Cacheable annotation, it then works but I do not have the cache working which is not what I want.
Do you know what can be wrong ?
Thanks a lot,

A: Guys I found the issue... because the method was final!!! I spent a lot of time to find this!


text:
Q: How to add submenu? html

asd

asd

asdf

asd

asd

asd

how to add submenu to the menu "ASDF" ??? I tryed but it looks ugly.
I tryed but destroys my whole website.
My system is only design not some cms
here's css code which can help you

.main_nav {
  margin-right: -3px;
  height: 100%;
  flex-basis: 200%;
  text-align: right;
}

.nav_items {
  height: 100%;
}

.nav_items li {
  display: inline-block;
  margin-left: 35px;
  height: 100%;
}

.nav_items li a {
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  color: #0b1033;
  letter-spacing: 3.5px;
  height: 100%;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-left: 14px;
  padding-right: 10px;
}

.nav_items li.active {
  background: #ff4200;
}

.nav_items li.active a {
  color: #FFFFFF;
}

.nav_items li:hover {
  background: #ff4200;
}

.nav_items li:hover a {
  color: #FFFFFF;
}

asd

asd

asdf

asd

asd

asd

This is my code i want to add submenu normal lookin.
If someone can help me with that i will be thankful.

A: This should work fine for you, you need to add styles as per your requirement. this is a CSS based on hover dropdown. you need to implement js/Jquery for onclick dropdown

.main_nav {
  margin-right: -3px;
  height: 100%;
  flex-basis: 200%;
  text-align: right;
}

.nav_items {
  height: 100%;
}

.nav_items li {
  display: inline-block;
  margin-left: 35px;
  height: 100%;
}

.nav_items li a {
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  color: #0b1033;
  letter-spacing: 3.5px;
  height: 100%;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-left: 14px;
  padding-right: 10px;
}

.nav_items li.active {
  background: #ff4200;
}

.nav_items li.active a {
  color: #FFFFFF;
}

.nav_items li:hover {
  background: #ff4200;
}

.nav_items li:hover a {
  color: #FFFFFF;
}

.has_drop {
  position: relative
}

.drop_down {
  position: absolute;
  width: 100%;
  top: 100%;
  height: auto;
  padding:0px;
  margin:0;
  left:0;
  display:none;
}

.drop_down li {
  width: 100%;
  display: block;
  padding: 6px 12px;
  margin:0
}

.has_drop:hover .drop_down {
  display:block;
 }
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

asd

asd

        asdf

List Item

List Item

List Item

List Item

asd

asd

asd

A:

<!DOCTYPE html>

  <button class="dropbtn">Dropdown</button>

    Link 1
    Link 2
    Link 3

A:

body{ font-family: Gotham, "Helvetica Neue", Helvetica, Arial, "sans-serif";}
 .main_nav {
  margin-right: -3px;
  height: 100%;
  flex-basis: 200%;
 /* text-align: right;*/
  background: #ff4200;
  display: table;

}

.nav_items {
  height: 100%;
}

.nav_items li {
  display: inline-block;
  margin-left: 35px;
  height: 100%;
}

.nav_items li a {
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  color: #0b1033;
  letter-spacing: 3.5px;
  height: 100%;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-left: 14px;
  padding-right: 10px;
 text-decoration: none;

}

.nav_items li.active {
  background: #ff4200;
}

.nav_items li.active a {
  color: #FFFFFF;
}

.nav_items li:hover {
  background: #ff4200;
}

.nav_items li:hover a {
  color: #FFFFFF;
}

.has_drop {
  position: relative
}

.drop_down {
  position: absolute;
  width: 150px;
  top: 100%;
  height: auto;
  padding:10px;
  left:0;
  display:none;
background: #cccccc;
 font-size: 12px;
}

.drop_down li {
  width: 100%;
  display: block;
  padding: 8px 0px;
  margin:0;
 border-bottom: 1px solid #ddd;
}
/*.drop_down li:hover { background: #f3f3f3;}*/

.has_drop:hover .drop_down {
  display:block;
 }

asd

asd

        asdf

List Item

List Item

List Item

List Item

asd

asd

asd


text:
Q: Only able to select first node when there is a default namespace in xpath I've been having problems querying an xml file that contains default namespaces and it's been a nightmare.
I've been able to select the first node after declaring a namespace but anything that follows gets ignored.
$str = '<?xml version="1.0"?>
<GetLowestOfferListingsForASINResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
    <GetLowestOfferListingsForASINResult>
      <Product>
        <LowestOfferListings>
          <LowestOfferListing>
            <Qualifiers>
              <ItemCondition>Used</ItemCondition>
              <ItemSubcondition>Good</ItemSubcondition>
              <FulfillmentChannel>Merchant</FulfillmentChannel>
              <ShipsDomestically>Unknown</ShipsDomestically>
              <ShippingTime>
                <Max>0-2 days</Max>
              </ShippingTime>
              <SellerPositiveFeedbackRating>95-97%</SellerPositiveFeedbackRating>
            </Qualifiers>
            <NumberOfOfferListingsConsidered>1</NumberOfOfferListingsConsidered>
            <SellerFeedbackCount>83352</SellerFeedbackCount>
            <Price>
              <LandedPrice>
                <CurrencyCode>GBP</CurrencyCode>
                <Amount>7.40</Amount>
              </LandedPrice>
              <ListingPrice>
                <CurrencyCode>GBP</CurrencyCode>
                <Amount>4.60</Amount>
              </ListingPrice>
              <Shipping>
                <CurrencyCode>GBP</CurrencyCode>
                <Amount>2.80</Amount>
              </Shipping>
            </Price>
            <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
          </LowestOfferListing>
        </LowestOfferListings>
      </Product>
    </GetLowestOfferListingsForASINResult>
</GetLowestOfferListingsForASINResponse>';

$xml = new SimpleXMLElement($str);
$xml->registerXPathNamespace('c', 'http://mws.amazonservices.com/schema/Products/2011-10-01');
print_r($xml->xpath("c:GetLowestOfferListingsForASINResult"));          //works
print_r($xml->xpath("c:GetLowestOfferListingsForASINResult/Product"));  //not working
print_r($xml->xpath("c:GetLowestOfferListingsForASINResult//Product")); //not working

A: Xpath has no automatic default namespace (it's always the null-namespace), so you need to explicitly use the "c:" prefix with all element names:
c:GetLowestOfferListingsForASINResult/c:Product
                                      ^^

c:GetLowestOfferListingsForASINResult//c:Product
                                       ^^

if you're interested in the details why this is the case, there is the following existing Q&A on this website:

*

*XPath in SimpleXML for default namespaces without needing prefixes


text:
Q: What is the DB_URL has to be in docker and spring boot configuration? I try to deploy spring boot jar on docker container. But Connection is failed.
The DB_URL in application.properties is like below,
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost/test?characterEncoding=utf8&serverTimezone=Asia/Seoul
spring.datasource.username = root
spring.datasource.password = password

I build mysql docker container with mysql image from docker hub which port number is 3306. When I execute the application jar file on localhost with the following command,
java -Dfile.encoding=UTF8 -jar Spring-Blog-Jpa-0.0.1-SNAPSHOT.jar

it works well without errors. The application can communicate the mysql docker container having port number 3306 on localhost. Next I make docker container of application with below Dockerfile,
FROM openjdk:11-jdk
ADD target/Spring-Blog-Jpa-0.0.1-SNAPSHOT.jar blog-app.jar
EXPOSE 8080
ENTRYPOINT ["java","-Dfile.encoding=UTF8","-jar","blog-app.jar"]

The application docker image is built successfully. But the container can not connect to MySQL Docker container at all. The exception is connection refused.
In localhost, the application Spring-Blog-Jpa-0.0.1-SNAPSHOT.jar can connect to MySQL docker container, But In application docker container connection to MySQL docker container failed. What does DB_URL have to be to connect the mysql container?


text:
Q: EntityFramework Core load automatically all dependencies by Id for classes that evolve quickly in terms of dependencies with plenty of ForeignKeys in new classes that are being created iteration after iteration during the development process, is there a way to tell EntityFramework to load all the dependencies you find for a given object by Id assuming that there are other objects in new tables with that reference as a ForeignKey?
Basically what I want to avoid is changing the way of loading the object adding the relevant Include every time I have a new dependency.


text:
Q: Can I retrieve a list of AD OUs using a variable? I am trying make a form to allow me to enter site name in a textbox and get all of the OUs for that specific site. I can get the powershell command to work if I enter the site name directly without the variable but I have 80+ sites and would rather not have to configure for that many sites.
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);'

[Console.Window]::ShowWindow([Console.Window]::GetConsoleWindow(), 0)
<#
.NAME
    Template
#>

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

$Form                            = New-Object system.Windows.Forms.Form
$Form.ClientSize                 = New-Object System.Drawing.Point(400,400)
$Form.text                       = "Form"
$Form.TopMost                    = $false

$Site_Location = $TextBox_Site.text

$Site_Name                          = New-Object system.Windows.Forms.Label
$Site_Name.text                     = "Enter Site Name"
$Site_Name.AutoSize                 = $true
$Site_Name.width                    = 25
$Site_Name.height                   = 10
$Site_Name.location                 = New-Object System.Drawing.Point(18,10)
$Site_Name.Font                     = New-Object System.Drawing.Font('Microsoft Sans Serif',10)

$TextBox_Site                       = New-Object system.Windows.Forms.TextBox
$TextBox_Site.multiline             = $false
$TextBox_Site.Text                  = ""
$TextBox_Site.width                 = 100
$TextBox_Site.height                = 30
$TextBox_Site.location              = New-Object System.Drawing.Point(18,46)
$TextBox_Site.Font                  = New-Object System.Drawing.Font('Microsoft Sans Serif',10)

$Button_Get                         = New-Object system.Windows.Forms.Button
$Button_Get.text                    = "Get Site OUs"
$Button_Get.width                   = 100
$Button_Get.height                  = 30
$Button_Get.location                = New-Object System.Drawing.Point(18,138)
$Button_Get.Font                    = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
#Controls
$Form.controls.AddRange(@($Site_Name,$Button_Get,$TextBox_Site))
#End Controls
#Actions
$Button_Get.Add_Click({ GetSiteOUs })
#End Actions

#Functions
$Site_Location = $TextBox_Site.text
function GetSiteOUs  {Get-ADOrganizationalUnit -Filter 'Name -Like "$Site_Location"' | Select-Object -Property Name, distinguishedname | Out-GridView -PassThru -Title "Select the OU" }

#End Functions

[void]$Form.ShowDialog()

A: I believe your .Click event could be simplified to this, which, should work properly:
$Button_Get.Add_Click({
    Get-ADOrganizationalUnit -Filter "Name -Like '*$($TextBox_Site.Text.Trim())*'" |
        Select-Object Name, Distinguishedname |
        Out-GridView -PassThru -Title "Select the OU"
})

The issue with your code is that, first the Filter is incorrect, it will not allow the variable expansion:
'Name -Like "$Site_Location"'

Should be:
"Name -Like '$Site_Location'"

And the second issue is that $Site_Location is being assigned outside the event instead of inside, this assignment happens only once when the form is loaded instead of each time there is a clicking of the button.


text:
Q: How to get presigned URL for CloudFront Media content I want to get presigned URL for my CloudFront media content files.
I have code in c# for S3 Presigned URL but that doesnt work for ColudFront
Please help me in this regards.
I have C# code for the cloudFront, but not able to figure out how to implement it.
Below is the code:
    private const string AccessKeyId = "";- what to put here

    private const string SecretAccessKey = "";- what to put here

    private const string KeyPairId = "";- what to put here

    private const string PrivateKey = "";- what to put here , is it a filename or the path

    private static void Main()
    {
        const string FileName = "My.File.Zip";
        const string S3Bucket = "mybucket";
        const string CloudFrontBaseUrl = @"http://blahblah.cloudfront.net/";
        const int MinutesValid = 15;

        var expiry = DateTime.Now.AddMinutes(MinutesValid);

        var s3SecureUrl = S3.GetSecureUrl(S3Bucket, FileName, expiry, AccessKeyId, SecretAccessKey);
        var cloudFrontSecureUrl = CloudFront.GetSecureUrl(CloudFrontBaseUrl + FileName, expiry, PrivateKey, KeyPairId);

}

A: Got the solutions!!!!!!
please refer below blog
http://improve.dk/how-to-set-up-and-serve-private-content-using-s3/


text:
Q: Unity VideoPlayer audio broken after an Agora.io video call Our application has a scene that does video calling built on agora.io and another scene which plays videos using the Unity VideoPlayer. The problem is that when opening the video player scene after leaving an agora.io call the video playback does not have any audio. This only seems to be a problem on iOS. Android playback is fine.
In xcode when trying play the video we see a lot of the below error repeating while the video plays:

AudioSampleProvider buffer overflow. 4096 sample frames discarded.

A: Is it possible that you can provide a stripped-down sample project that reproduces this issue?
Otherwise, my recommendation is try a few things:

*

*Do not destroy the Agora engine or disable audio when leaving the Agora scene.

*Check if the volume of playback is set to zero (with/without #1 above)

*Call the following private API before joining the agora channel:
    // Stops the Agora SDK from ending the audio session
mRtcEngine.SetParameters("{\"che.audio.keep.audiosession\": true}");


text:
Q: what to pass in filecontent in core _files upload Moodle webservice I am trying to use the core_files_upload function and the file goes in the $filecontent parameter in base64, however, in the test I passed the base64 of a .jpg image the function returns me a "File not specified" error message.
Error:
{
   "Exception": "moodle_exception",
   "Errorcode": "nofile",
   "Message": "File not specified."
}


text:
Q: Problems with getPosition() in SFML I'm new to c++ so I'm a bit confused on this one. I'm trying to have the player spawn, then when the user presses "C", the player switches with a car. What's happening currently is the player is initially spawning in the correct location, then the car is spawning where the player initially spawned, not where it currently is. However, since I'm using the function getPosition(), I would assume it would spawn in the current position of the player.
Player.h:
#pragma once
#include <SFML\Graphics.hpp>
#include <string>
class player {

public:
    sf::Texture normalTexture;
    sf::Sprite normalSprite;
    sf::Texture carTexture;
    sf::Sprite carSprite;
    sf::Texture springTexture;
    sf::Sprite springSprite;
    sf::Texture rocketTexture;
    sf::Sprite rocketSprite;
    sf::IntRect normalRect[1];
    sf::IntRect carRect[1];
    sf::IntRect springRect[1];
    sf::IntRect rocketRect[1];

bool rocket=false;
bool car=false;
bool spring=false;
bool normal=false;

player();
player(sf::Vector2f position, std::string normalFileLoc, std::string carFileLoc, std::string springFileLoc, std::string rocketFileLoc);

void update();
};

Player.cpp:
#include "Player.h"

player::player() : player::player(sf::Vector2f(100, 0), "player.jpg", "car.png", "spring.png", "rocket.png") {
}

player::player(sf::Vector2f position, std::string normalFileLoc, std::string
carFileLoc, std::string springFileLoc, std::string rocketFileLoc)
{
normalTexture.loadFromFile(normalFileLoc);
normalRect[0] = sf::IntRect(0, 0, 64, 128);
normalSprite.setTexture(normalTexture);
normalSprite.setTextureRect(normalRect[0]);
normalSprite.setOrigin(0,0);
normalSprite.setScale(1, 1);
normalSprite.setPosition(position.x, position.y);

carTexture.loadFromFile(carFileLoc);
carRect[0] = sf::IntRect(0, 0, 64, 64);
carSprite.setTexture(carTexture);
carSprite.setTextureRect(carRect[0]);
carSprite.setOrigin(0, -64);
carSprite.setScale(1, 1);
carSprite.setPosition(normalSprite.getPosition().x, normalSprite.getPosition().y);

}

Main.cpp I know it looks gross, I plan on making it look nicer later:
#include <SFML/Graphics.hpp>
#include <SFML\Graphics\Rect.hpp>
#include "player.h"
int main()
{
sf::RenderWindow window(sf::VideoMode(750, 750), "SFML Works!");

player thePlayer;

const float gravity = .001;
int groundheight = 500;
sf::Vector2f velocity(sf::Vector2f(0, 0));

thePlayer.normal = true;

while (window.isOpen())
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            window.close();

        if (event.type == sf::Event::KeyPressed)
        {
            if (thePlayer.car && event.key.code == sf::Keyboard::C)
            {
                thePlayer.car = false;
                thePlayer.spring = false;
                thePlayer.rocket = false;
                thePlayer.normal = true;
                break;
            }
            if (thePlayer.spring && event.key.code == sf::Keyboard::S)
            {
                thePlayer.car = false;
                thePlayer.spring = false;
                thePlayer.rocket = false;
                thePlayer.normal = true;
                break;
            }
            if (thePlayer.rocket && event.key.code == sf::Keyboard::R)
            {
                thePlayer.car = false;
                thePlayer.spring = false;
                thePlayer.rocket = false;
                thePlayer.normal = true;
                break;
            }
            if (event.key.code == sf::Keyboard::C)
            {
                thePlayer.car = true;
                thePlayer.spring = false;
                thePlayer.rocket = false;
                thePlayer.normal = false;
                break;
            }
            if (event.key.code == sf::Keyboard::R)
            {
                thePlayer.car = false;
                thePlayer.spring = false;
                thePlayer.rocket = true;
                thePlayer.normal = false;
                break;
            }
            if (event.key.code == sf::Keyboard::S)
            {
                thePlayer.car = false;
                thePlayer.spring = true;
                thePlayer.rocket = false;
                thePlayer.normal = false;
                break;
            }

        }

    }

    if (thePlayer.normal)
    {
        velocity.x = 0;
        thePlayer.normalSprite.move(velocity.x, velocity.y);
        if (thePlayer.normalSprite.getPosition().y < groundheight)
        {
            velocity.y += gravity;
        }
        else
        {
            thePlayer.normalSprite.setPosition(thePlayer.normalSprite.getPosition().x, groundheight);
            velocity.y = 0;
        }

    }

    if (thePlayer.car)
    {
        thePlayer.carSprite.move(velocity.x, velocity.y);
        if (thePlayer.carSprite.getPosition().y < groundheight)
        {
            velocity.y += gravity;
        }
        else
        {
            thePlayer.carSprite.setPosition(thePlayer.carSprite.getPosition().x, groundheight);
            velocity.y = 0;
        }

    }

    window.clear();
    if (thePlayer.normal)
    {
        window.draw(thePlayer.normalSprite);
    }
    if (thePlayer.car)
    {
        window.draw(thePlayer.carSprite);
    }

    window.display();
}
}

Thanks so much!

A: Before drawing the car you should adjust its position to your player position :
if (thePlayer.car)
{
    thePlayer.carSprite.setPosition(thePlayer.normalSprite.getPosition());
    window.draw(thePlayer.carSprite);
}

But as ractiv said, you should organize your code differently. I suggest you to learn more about c++ "good pratices" before trying to do this kind of games.

A: We miss the main function to know exactly what happens when the car spawns but I think that you initialize the car in the Player constructor and does not move it when the player presses 'C'.
You should have something like that :
if(event.key.code == sf::Keyboard::C) {
    player.spawnCar();
}

and in your spawnCar() function :
carSprite.setPosition(normalSprite.getPosition());

EDIT
As I said in my comment, you should use getters and setters to access to your attributes. According to your current main.cpp, you should have this :
if (event.key.code == sf::Keyboard::C)
{
    thePlayer.car = true;
    thePlayer.spring = false;
    thePlayer.rocket = false;
    thePlayer.normal = false;
    carSprite.setPosition(normalSprite.getPosition());
    break;
}


text:
Q: Just store any data from an object to a table, regardless of what structure it has? I'm downloading data from an API, it's badly documented, and I want to store what ever comes out of it into a database, just adding new columns whenever  newly labeled data comes up.
If an object looks like this:
{ location:
          position: {
              latitude: 59.34534777,
              longitude: 18.27299453 },
          },
       listPrice: 6700000,
       livingArea: 129,
},

I would like it to create a table that looks somthing like this:
location.position.longitude | location.position.latitude | listPrice | livingArea
59.34534777                 | 18.27299453                | 6700000   | 129

Does this have a name? And is there some ORM/library/database that would make this simple for me? Currently i'm using sqlite but that is not a requirement.

A: A document db would work very well for this. MongoDb is a safe choice.


text:
Q: I need to show logged user's name I am using this webpage password protector
It's working fine but i want to make the logged user's name appears in the protected page after logging in successfully.
May you please help me ?

A: Modify this part of your code:
  else {
    // set cookie if password was validated
    setcookie("verify", md5($login.'%'.$pass), $timeout, '/');

    // Some programs (like Form1 Bilder) check $_POST array to see if parameters passed
    // So need to clear password protector variables
    unset($_POST['access_login']);
    unset($_POST['access_password']);
    unset($_POST['Submit']);
  }

to read as:
  else {
    // set cookie if password was validated
    setcookie("verify", md5($login.'%'.$pass), $timeout, '/');

    echo "Username: " . $login;

    // Some programs (like Form1 Bilder) check $_POST array to see if parameters passed
    // So need to clear password protector variables
    unset($_POST['access_login']);
    unset($_POST['access_password']);
    unset($_POST['Submit']);
  }


text:
Q: marginal distribution of response in multiple linear regression I know that in linear regression, the marginal distribution of $y$ is usually not of interest. But, just out of curiosity, what is the marginal distribution of the response variable, in the case of the multiple linear regression model? I can think of two cases:

The predictors are not random variables
In this case (by far the most common), we know that
$$ p(y|\mathbf{x}) = \mathcal{N}(\beta_0+\boldsymbol{\beta}^T\cdot\mathbf{x},\sigma^2)$$
Since $\mathbf{x}$ is not a random vectors, it doesn't make sense to think of the joint distribution of $y$ and $\mathbf{x}$. I think in this case $y$ must be considered a stochastic process, i.e., a function from $\mathbb{R}^d\times\Omega\to\mathbb{R}$ ($d$ is the number of predictors, of course). For each given $\mathbf{x}$, $y|\mathbf{x}$ is a random variable and it makes sense to ask about its distribution (which is just a normal distribution as shown above). However, it doesn't make sense to think of "marginalizing" this distribution with respect to $\mathbf{x}$, since $\mathbf{x}$ is not random.

The predictors are random variables
As before,
$$ p(y|\mathbf{x}) = \mathcal{N}(\beta_0+\boldsymbol{\beta}^T\cdot\mathbf{x},\sigma^2)$$
but now this is a "real" conditional distribution, so we can marginalize. In practice
$$ p(y) =\int p(y,\mathbf{x})\text{d}\mathbf{x}=\int p(y|\mathbf{x})p(\mathbf{x})\text{d}\mathbf{x}$$
Now it all depends on the joint distribution of the $d$ predictors. Depending on $p(\mathbf{x})$, the marginal distribution of $y$ could be basically anything.

What do you think? Is my reasoning correct, or am I missing something?


text:
Q: Using Rails console to insert an array of data If I want to insert a record into my model I usually do something like this within the Rails console:
m = ModelName.create(name: 'This is my name')
m.save

But if I have an array
['Name 1', 'Name 2', 'Name 3' ]

How can I create a record for each of the items in the array using the Rails console?

A: You can do as below :
records_to_create = ['Name 1', 'Name 2', 'Name 3' ].map { |val| {:name => val } }
ModelName.create records_to_create

#create documentation is clear on this :-

Creates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.

Doco has some examples too :-
#..
# Create an Array of new objects
User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])