How do I write a Function type that strictly requires its parameters in Typescript

Question: I've run into an issue with combineReducers not being strict enough and I'm not sure how to get around it:
interface Action {
  type: any;
}

type Reducer<S> = (state: S, action: Action) => S;

const reducer: Reducer<string> = (state: string, action: Action) => state;

const reducerCreator = (n: number): Reducer<string> => reducer;

interface ReducersMapObject {
  [key: string]: Reducer<any>;
}

const reducerMap: ReducersMapObject = {
  test: reducer,
  test2: reducerCreator
}

I would expect reducerMap to throw an error because reducerCreator isn't a reducer (it's a function that takes a string and returns a reducer), but TypeScript is fine with this.
It seems that the source of the issue is that Reducer essentially boils down to any => any because functions with fewer parameters are assignable to functions that take more params..
This means that the ReducersMapObject type is basically just {[key: string]: function}
Is there a way to make the Reducer type stricter about requiring both parameters or another way to get more confidence that the ReducersMapObject actually contains reducer functions?
This code all compiles in the TypeScript playground if you're trying to replicate
Comment: @glenn replacing the  in reducersMapObject with a `T` would require that all of the reducers in the map return State of the same type.. These reducers are expected to manage different chunks of state and so need to be able to return whatever type they are individually responsible for
Comment: what you get if you replace all "any" with type T?
Comment: Good point. What about a new Type/class "ReducerState" with a field "state: any". Like a type wrapper for your state information.  Somthing like this  in your Code Reducer. Im not sure if this help? But this is like a EventArg oder Dto behavior.
Comment: @glenn not sure i follow.. could you maybe post a code example of what you're suggesting?
Answer: Nice question... there are two viable options toward the end of this rather long answer. You asked two questions, I answered each separately.
Question 1:

Is there a way to make the Reducer type stricter about requiring both parameters...

It will be difficult to achieve that, because of two obstacles in TypeScript functions.
Obstacle 1: Discarding Function Parameters
One obstacle, which you already noted, is documented here under the heading "Comparing Two Functions." It says that "we allow 'discarding' parameters." That is, functions with fewer parameters are assignable to functions with more parameters. The rationale is in the FAQ. In short, the following assignment is safe because the function with fewer parameters "can safely ignore extra parameters."
const add: (x: number, y: number) =
           (x: number) => { return x; }; // works and is safe

Obstacle 2: Function Parameter Bivariance
A second obstacle is that function parameters are bivariant. That
 means we cannot work around this problem with a user-defined type parameter. In some languages, we could define Pair along with a function that accepts a Pair.
class Pair {
    x: number;
    y: number;
}

let addPair: (p: Pair) => number;

In languages with covariant functions, the above would restrict arguments to subtypes of Pair.
In TypeScript, simple type assignment follows expected substitutability rules, but functions follow bivariant rules. In its simple type assignment, TypeScript allows us to assign type Pair to type Single but not to assign type Single to type Pair. This is an expected substitution.
class Single {
    x: number;
}

let s: Single = new Pair(); // works
let p: Pair = new Single(); // fails because of a missing property.

TypeScripts functions, though, are bivariant, and are not held to the same restrictions.
let addSingle: (s: Single) => number;
addSingle = (p: Pair) => p.x + p.y; // as expected, Pair is assignable to Single.

let addPair: (p: Pair) => number;
addPair = (s: Single) => s.x; // surprise, Single is assignable to Pair!

The result is that a function that expects a Pair will accept a Single.
Implications for Reducers
Neither of the following two techniques will enforce the number of parameters (or class properties) that Reducer implementations must accept.
class Action { }

// no restriction - TypeScript allows discarding function parameters
type Reducer01<S> = (state: S, action: Action) => S;
const reducer01: Reducer01<number> = (state: number) => 0; // works

// no restriction - TypeScript functions have parameter bivariance
class ReducerArgs<S> {
    state: S;
    action: Action;
}
type Reducer02<S> = (args: ReducerArgs<S>) => S;
const reducer02 = (args: { state: number }) => 0; // works

That probably will not be a problem practically, because letting ReducersMapObject accept a Reducer with fewer parameters is safe. The compiler will still ensure that:

each call to a Reducer includes all the Reducer arguments, and
each implementation of a Reducer only operates on its (possibly short) parameter list.

Question 2:

...or another way to get more confidence that the ReducersMapObject actually contains reducer functions?

One thing that we're trying to do is to make the reducerCreator function (and other functions of unusual shape) incompatible with the Reducer<S> function type. Here are two viable options.
Viable option 1: User-defined Parameter Type
The second technique from above, using a user-defined type called ReducerArgs<S>, will give us more confidence. It will not provide complete confidence, because we will still have bivariance, but it will ensure that the compiler rejects reducerCreator. Here is how it might look:
interface Action {
  type: any;
}

// define an interface as the parameter for a Reducer<S> function
interface ReducerArgs<S> {
    state: S;
    action: Action
}

type Reducer<S> = (args: ReducerArgs<S>) => S;

const reducer: Reducer<string> = (args: ReducerArgs<string>) => args.state;

const reducerCreator = (n: number): Reducer<string> => reducer;

interface ReducersMapObject {
  [key: string]: Reducer<any>;
}

const reducerMap: ReducersMapObject = {
  test: reducer,
  test2: reducerCreator // error!
}

Viable Option 2: Generics and Union Types
Another option is to use a generic ReducerMapObject<T> like this:
interface ReducersMapObject<T> {
  [key: string]: Reducer<T>;
}

And then to parameterize it with a union type that lists the types of all the reducers.
const reducer: Reducer<string> = (state: string, action: Action) => state;
const reducer1: Reducer<number> = (state: number, action: Action) => state;

const reducerMap: ReducersMapObject<string | number> = {
    test: reducer,
    test1: reducer1,
    test2: reducerCreator // error!
}

The result will be that any => any becomes T => T, where T is one of the types listed in the union. (As an aside, it would be great to have a type that says, "x can be any type, so long as it is that same type as y.")
While both of the above involve more code and are a bit clunky, they do serve your purpose. This was an interesting research project. Thank you for the question!


Why are two html elements with different attributes deepStrictEqual

Question: Create two html div elements give one an attribute of class="foo".
DeepStrictEqual asserts they are equal.
Why?
<code>const jsdom = require("jsdom");
const {JSDOM} = jsdom;
var assert = require('assert');
global.document = new JSDOM(`<!DOCTYPE html>`).window.document;

describe.only('add_attributes to elem', function () {

    it('test - same element different attributes', function () {
    let testhtml = document.createElement('div');
    testhtml.setAttribute('class', 'foo');
    let testhtml2 = document.createElement('div');
    //WHY ARE TWO DIFFERENT HTML ELEMENTS DEEP STRICT EQUAL.
    assert.deepStrictEqual(testhtml, testhtml2);

    });
    it('test2 - different elements', function () {
    let testhtml = document.createElement('div');
    let testhtml2 = document.createElement('span');
    //WHY ARE TWO DIFFERENT HTML ELEMENTS DEEP STRICT EQUAL.
    assert.deepStrictEqual(testhtml, testhtml2);

    });
});
</code>
Answer: document.createElement is "browser code" so it should not be part of my unit testing.
I'm not sure if assert.deepStrictEqual should return false when comparing non-identical objects created by document.createElement() but it's a bad unit test to try unless you're testing document.createElement itself (and not your logic).
see both answers here:
Javascript Unit Testing - DOM Manipulation
Answer: Here you have two different objects with each their own properties.
So deepStrictEqual returns false.
The doc at nodejs.org says:

"Deep" equality means that the enumerable "own" properties of child objects are recursively evaluated also by the following rules.

Have look at https://nodejs.org/api/all.html#assert_assert_deepstrictequal_actual_expected_message
Comment: Yes but  the first test returns true - which is not what I was expecting... (mocha.js with assert)


Who should analyze mouse input in MVC architecture

Question: I am pretty new to MVC, and I want to do things right from the beginning so :
I am building an MVC web app in jquery/html; I must know where the mouse is on the screen and do different stuff depending on that position.
Should the View take the mouse position and, depending on where it is, call different functions of the Controller, or should the View simply send the mouse position to the controller who then chooses what to do with it ?
Is there an example of MVC in web app that I could look throught ?
Thank you for your help.
Answer: View: Get the coordinates where the user interaction happened (mouse click). Send the coordinates + any additional information to Controller.
Controller: Get the details of the user interaction (mouse click) and decide what to do with it.


Is servlet the singleton?

Question: Reading some book that said the servlet is singleton from the container side. Is this true?
However even it is a singleton, we need to handle data synchronization etc
Comment: A servlet is not a singleton, but you should treat it as a singleton: synchronize or avoid instance level attributes. See [this](http://stackoverflow.com/questions/6888268/httpservlet-does-not-implement-runnable-or-extend-thread-why-is-it-thread-able/6888301#6888301) as well.
Answer: Looking at the definition of the Singleton Pattern as defined in the Cunningham & Cunningham, Inc. Wiki

Ensure a class has only one instance, and provide a global point of access to it.

I would say, no. From the perspective of the container one servlet object is accepted and managed including the creation of a ServletContext, but it does not prevent that there is not more than one instance of the servlet.
Regarding such issues I think it's best to look into the corresponding contract, which is in case of servlets defined in the Java Servlet Specification. They have addressed the number of instances of a servlet.

2.2 Number of Instances
The servlet declaration which is either via the annotation as
  described in Chapter 8, "Annotations and pluggability" or part of the
  deployment descriptor of the Web application containing the servlet,
  as described in Chapter 14, "Deployment Descriptor", controls how the
  servlet container provides instances of the servlet. For a servlet not
  hosted in a distributed environment (the default), the servlet
  container must use only one instance per servlet declaration. However,
  for a servlet implementing the SingleThreadModel interface, the
  servlet container may instantiate multiple instances to handle a heavy
  request load and serialize requests to a particular instance.
In the case where a servlet was deployed as part of an application
  marked in the deployment descriptor as distributable, a container may
  have only one instance per servlet declaration per Java Virtual
  Machine (JVM™). However, if the servlet in a distributable
  application implements the SingleThreadModel interface, the container
  may instantiate multiple instances of that servlet in each JVM of the
  container.

It only specifies that the container must only use one instance (in the former case) and as EJP has pointed out in the comment:

There is nothing in the Servlet Specification that prevents you from
  re-instantiating the same servlet class under a different name in the
  same web-app. Ergo, not a singleton.

Reference Java Servlet Specification 3.0 MR (p.6-7)
Comment: Well researched but not correct. There is nothing in the Servlet Specification that prevents you from re-instantiating the same servlet class under a different name in the same web-app. Ergo, not a singleton.
Comment: @EJP I agree with you. Taking a look at the singleton definition it is not ensured.
Answer: No. You can instantiate the same servlet class many times under different servlet names and URLs in the same web container and indeed in the same web-app.
Comment: If I have only one mapping rule for MyServlet in web.xml and not use @WebServlet annotation, can I be sure that there will always only one instance of MyServlet in container?
Comment: @JimJim2000 Not unless you also avoid the `SingleThreadModel`: see the other answer.
Answer: Servlet can be initialized as a single instance or a pool of instances.
Here is an extract from <<Java Platform, Enterprise Edition The Java EE Tutorial Release 7>>:
A web container will typically create a thread to handle each request. To ensure that a
servlet instance handles only one request at a time, a servlet can implement the
SingleThreadModel interface. If a servlet implements this interface, no two threads
will execute concurrently in the servlet's service method. A web container can
implement this guarantee by synchronizing access to a single instance of the
servlet or by maintaining a pool of web component instances and dispatching each
new request to a free instance.
Answer: No, Servlet is not a Singleton. It may create 2nd Object , depends on the incoming request and the Container behavior.
Comment: This doesn't add anything to the already-posted answers from almost 2 years ago.

Is servlet the singleton?


rails generator won't work inside my spree application.

Question: I am trying to integrate spree into a fresh install of a rails application.  I am following along with the getting started guide on spree's website.  I am at the step that tells me to call the generate command to create my Spree site.  when doing this i get an error:
    C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/ext/module.rb:36:in `c
onst_missing': uninitialized constant Devise::IndifferentHash (NameError)
        from C:/Ruby192/lib/ruby/gems/1.9.1/gems/spree_auth-0.40.0/lib/spree_aut
h.rb:17:in `activate'
        from C:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.1.1.rc2/lib/act
ive_support/callbacks.rb:413:in `_run_prepare_callbacks'
        from C:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.1.1.rc2/lib/act
ive_support/callbacks.rb:81:in `run_callbacks'
        from C:/Ruby192/lib/ruby/gems/1.9.1/gems/actionpack-3.1.1.rc2/lib/action
_dispatch/middleware/reloader.rb:46:in `prepare!'
        from C:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.1.1.rc2/lib/rails/ap
plication/finisher.rb:41:in `block in <module:Finisher>'
        from C:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.1.1.rc2/lib/rails/in
itializable.rb:29:in `instance_exec'
        from C:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.1.1.rc2/lib/rails/in
itializable.rb:29:in `run'
        from C:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.1.1.rc2/lib/rails/in
itializable.rb:54:in `block in run_initializers'
        from C:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.1.1.rc2/lib/rails/in
itializable.rb:53:in `each'
        from C:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.1.1.rc2/lib/rails/in
itializable.rb:53:in `run_initializers'
        from C:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.1.1.rc2/lib/rails/ap
plication.rb:96:in `initialize!'
        from C:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.1.1.rc2/lib/rails/ra
iltie/configurable.rb:30:in `method_missing'
        from C:/Users/Edu/workspace/my_store/config/environment.rb:5:in `<top (r
equired)>'
        from C:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.1.1.rc2/lib/rails/ap
plication.rb:83:in `require_environment!'
        from C:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.1.1.rc2/lib/rails/co
mmands.rb:22:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `'

I also get the same error if just simply run rails g or rails generate to see what generate tools i have available.
here is my gemfile for reference:
    source 'http://rubygems.org'

gem 'rails', '3.1.1.rc2'

# Bundle edge Rails instead:
# gem 'rails',     :git => 'git://github.com/rails/rails.git'

gem 'sqlite3'

gem 'spree'

gem 'rake', '0.9.2.2'

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 3.1.0'
  gem 'coffee-rails', '~> 3.1.0'
  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'

# Use unicorn as the web server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano'

# To use debugger
# gem 'ruby-debug19', :require => 'ruby-debug'

group :test do
  # Pretty printed test output
  gem 'turn', :require => false
end

Answer: Your spree version is (for some reason) set to 0.40.0. I would recommend upgrading this to  0.70.1, which you can do by putting this line in your Gemfile:
gem 'spree', '~> 0.70.1'

EDIT
You mentioned that you were using Rails 3.1.1.rc2, which is something I should have noticed in the stacktrace in the question.
Whoops.
Anyway, when you don't specify a version for Spree, Bundler will attempt to resolve all the dependencies as best it can. Partly because you were using Rails 3.1.1.rc2 and partly because Spree was silly enough to specify a >= dependency on Rails for 0.40.0 that this problem is encountered.
Spree 0.40.0 attempts to find the bestest Rails  version that's >= 3.0.3, and 3.1.1.rc2 satisfies that criteria nicely, so it carries on.
So then that begs the question of "Why isn't Spree using the latest version?". That's easily explainable if you understand dependency resolution, which many people make out as hard to understand but is actually quite easy. Think computers in the 1970s.
All versions of Spree >= 0.40.0 do not have Rails specified as >= [something], mainly because the Spree guys wisened up here and decided that it was a silly idea. By using >= you mean to get all versions of a gem that are >= to the specified version, which includes major versions. And we all know how different Rails 2 was from Rails 3, and so we should assume Rails 3 -> Rails 4 is going to be just as "fun".
So it's only  Spree 0.40.0 that has this dependency that matches your specific (3.1.1.rc2) Rails version. There's no non-beta / RC version of Spree above that that matches that particular dependency, and so Spree 0.40.0 is used instead.
In closing, it seems that this issue would only be prevalent for people who attempting to use a version of Rails that there isn't a corresponding version of Spree out for. One way to solve this problem would be to yank the 0.40.0 gem, but that leads to its own problems, as versions before that also have the same dependency. Therefore, you should always be checking that the current version of Rails that you're using is supported by at least one Spree version.
Comment: This did the trick. Thank you! I had to set my rails gem to 3.1.1 also, because of a dependency that spree 0.70.1 has on it.  I wonder why my Spree Version 0.40.0 and Rails Version 3.1.1.Rc2 were being installed. Any idea?
Answer: I had the same problem with rails 3.1 . The answer went put in my GEMFILE the following line.
===:git with the repository's url that works===
gem 'spree', :git => 'git://github.com/spree/spree.git'
Now it's work my generators and my spree.
greetings.


Find the projection of the vector onto subspace W.

Question: I cannot find the exact way to do this.... W is an orthogonal basis...
w ={{1,2,2,4},{4,-2,8,-4},{0,0,0,0}}
vector v = {7,2,2,1}
Anyone know how to project v onto w?
Comment: For some basic information about writing math at this site see e.g.
[here](//meta.math.stackexchange.com/q/5020),
[here](//meta.stackexchange.com/a/70559),
[here](//meta.math.stackexchange.com/q/1773) and
[here](/help/notation).
Comment: You cannot have the zero vector in a "basis" or in a linearly independent set.
Answer: So your subspace is $\operatorname{span}{W} = \operatorname{span}\{(1,2,2,4),(4,-2,8,-4),(0,0,0,0)\} = \operatorname{span}\{(1,2,2,4),(4,-2,8,-4)\}$.  Do you see why I can leave off the zero vector?
The projection of a vector onto a subspace will be a vector, denoted $\operatorname{proj}_{W}(\mathbf v)$ or $\mathbf v_{\|}$, of the same size as $\mathbf v$ which has the property $\mathbf v = \mathbf v_{\|} + \mathbf v_{\bot}$, where $\mathbf v_{\|} \in \operatorname{span}{W}$ and $\langle \mathbf v_{\bot}, \mathbf x\rangle = 0$ for every $\mathbf x \in \operatorname{span}W$.
Because your set is orthogonal, we could use the projection formula $\operatorname{proj}_{W}(\mathbf v) = \dfrac {\langle \mathbf v,\ (1,2,2,4)\rangle}{\|(1,2,2,4)\|^2}(1,2,2,4) + \dfrac {\langle \mathbf v,\ (4,-2,8,-4)\rangle}{\|(4,-2,8,-4)\|^2}(4,-2,8,-4)$.
Note that this formula only works if the basis is orthogonal.  So in general if it isn't, you'll need to use Gram-Schmidt orthogonalization to get an orthogonal basis set for your subspace.
Comment: so its v dot the first vector over the magnitude of the first vector times first vector, then v dot second vector over magnitude of second vector times 2nd vector ?? does this look right?
Comment: Sorry I just edited just to confirm, does my previous comment look correct?
Comment: Yes, that's correct.  If you're used to the notation $\mathbf v \cdot \mathbf w$, then that's the same as $\langle \mathbf v, \mathbf w\rangle$.
Comment: Sweet. Thanks! Check marked
Answer: If V is a subspace of Rn with orthonormal basis $\mathbf u_1$, $\mathbf u_2...\mathbf u_m$, then projection of $\mathbf x$ onto V is
$(\vec{\mathbf u_1}\cdot\mathbf x)\mathbf u_1$ + $(\vec{\mathbf u_2}\cdot\mathbf x)\mathbf u_2$ +···+$(\vec{\mathbf u_m}\cdot\mathbf x)\mathbf u_m$
Use this to calculate the projection of v onto w, where w is the orthonormal basis, m=3 and and the v you gave = x.
Source: http://isites.harvard.edu/fs/docs/icb.topic138287.files/Lesson13_-_Orthogonal_Bases_and_Projections_slides.pdf
Comment: so the project ends up being just a 4x1 vector?
Comment: @user1990406 The projection of $\mathbf v$ is the same type of object as $\mathbf v$.  Also you should notice that to use Gabriel's method, you'll need to first normalize your subspace vectors.
Comment: thanks man... appreciate it
Comment: The link to `isites.harvard.edu` is broken. I'm also unable to find any copy saved on the Wayback Machine.


Inductive Step For a Summation mathematical induction

Question: I have a bit of trouble with how I should go about showing the inductive step for my induction problem. I know the general idea is to show that it can work for all numbers based on the base case but I'm still stuck on how to show it.
$\sum_{i=2}^n \frac{1}{i} \leq \frac{n}{2}$ for n $\geq$ 2
I know we have to plug in k+1 instead of n and show that it is also equal to k by using algebra. I'm just stuck on how to show it. I guess the i is the part that confusing me.
Answer: Hint:
Compare
$$\sum_{i=2}^{k+1}\frac{1}{i} \leq \frac{k+1}{2}$$
to $$\sum_{i=2}^k\frac{1}{i} \leq \frac{k}{2}.$$
On the left-hand sides, the difference is $\dfrac1{k+1}$, and on the right-hand sides, it is $\dfrac12$.
Can you conclude ?


Why does row-fluid:before and row-fluid:after have a height?

Question: On my website (click), one of many on which I've used twitter-bootstrap v2.3.2, for some reason the row-fluid:before, row-fluid:after, clearfix:before and clearfix:after content all have a width of 9px and a height of 8px.
No other sites have this issue and the height ignores height: 0 !important and the only thing that can get rid of it is to remove the content entirely, which breaks the clearfix.
What is causing this? How can I get rid of it? I can't find anything on Google remotely related to this and it's been pissing me off all day!
I can't replicated this issue, I've tried copying a row and all it's content into jsfiddle, then link to every style sheet the website has included and it's fine, the :before content has no height and 1px width, the same as every other site I have.
After eliminating css files by commenting them out I've found out it's something to do with main.css.
Picture of the bug occurring in Chrome (replicable in Firefox too).
Comment: Well... I don't see it either... Is it a specific `row-fluid` div or every one?
Comment: Every single row-fluid and clearfix has this. I've just removed all css files bar the basic bootstrap and that got rid of the issue, so going to try and isolate which file is causing the issue.
Comment: On that site I see `.row-fluid:before, .row-fluid:after` has specifcally set `height: 0 !important;`
Comment: I've checked it in dev tools, they all have a height of 0... How do you see it has a 9px width and 8px height? Do you see by looking at it that there is some extra margin, or do you see it in your dev tools somehow?
Comment: Oh wait, I see what you mean now. It's because after and before are set to `display: table`
Comment: I've added a screen shot of what I get. @DavidG the `height: 0 !important` I added to try and get around this issue, it did nothing. The `display: table` is part of the default bootstrap code that works fine on every other site I have.
Comment: Aah now I see it as well, but not with EVERY div. Only the decendants of a div with class `no-line-height` (which have the rule `line-height: normal`) have this issue.
Comment: I tried removing `.no-line-height` from the css, no effect.
Comment: Got the specific line - `.home-content { border-spacing: 4px }` It's applying a border spacing to all tables inside `.home-content`.
Answer: The culprit is in main.css, you have some border-spacing applied, remove this and it goes away:
.home-content {
     border-spacing: 4px;
}

Comment: I've added `.home-content * {border-spacing: 0px;}`, I got it just about the same time you did. Thank you for your help :).


Can I use any coarse drywall screws when fixing nail pops in the ceiling?

Question: I have several nail pops in the ceiling sheet rock of my house and I've decided to finally address/fix them.  The house was built 40 years ago so I don't believe there is any underlying issue other than time.
I have a bucket of coarse thread screws left to me from a different project hanging green board in a bathroom and I'd like to use these rather than buy yet more.  However, I'm uncertain of the length (1-5/8") for ceiling drywall (which may only be 1/4"?) and the specific details of the screw (see pictures) such as the serrated head, etc.
Comment: Note those are not drywall screws they are for backer board and will tear the paper as I said in my answer. If you used them on "green board as in cement board you did the correct thing in the past, if you used them on green Sheetrock or water resistant Sheetrock you used the wrong product. The strength in Sheetrock is in the paper break that and you have no strength.
Answer: I would not use backer board screws they are designed to cut a bevel,
The cut will tear the paper and that is your strength in Sheetrock.
You do not want to break the paper, this is even more important on ceilings!
 use Sheetrock screws or bugle head Sheetrock screws these come in both fine and corse.
Answer: They will work but it would be an unnecessary expensive option and can create other problems.
They would create a larger countersink hole because you have drive them in a little farther to get them below the surface of the drywall paper. The serrations will cause unnecessary tearing of the paper which will be a problem when covering the heads with mud and weaken the holding power that that the screws are there for.
It would be better to just get the correct screws for the job, 1" 1/4 or 1" 5/8  will work and you can use a drywall screw driver tip that sets them at the correct depth.
Comment: Because of the tearing of the paper they would not be the proper screw.
Comment: @EdBeal thanks, i made it more clear.


Settings menu through UITableView

Question: I'm trying to build a nice looking config-screen using UITableView (much like the settings on the iPhone, in the clock etc).
I'm having some doubts as to how aproach this; I will need some UITableViewCells with switches in them (right now placed in the accessoryView), other that link to further pages and a detailLabel indicating the current setting (probably with CellStyleValue1).
How would I best design such a menu? Through IB? Through code? Generate all cells at init? Generate in cellForRow[...]?
Thanks!
Answer: Config screen usually contain limited number of cells, so there is no need to worry about cell reusability.
Design your cells in IB, bind with code like IBOutlet UITableViewCell* firstCell, secondCell... put them into array in proper order.
In tableView:cellForRowAtIndexPath: just return [array objectAtIndex:..]

Settings menu through UITableView


apache-maven-3.6.0.zip: Permission denied

Question: while running the below command i am facing this error
wget http://us.mirrors.quenda.co/apache/maven/maven-3/3.6.0/binaries/apache-maven-3.6.0-bin.zip -O apache-maven-3.6.0.zip
apache-maven-3.6.0.zip: Permission denied

Answer: This is because you are in a directory not writable to your current user.
Try this instead. You will find the application downloaded and saved to your desktop.
cd ~/Desktop/
wget http://us.mirrors.quenda.co/apache/maven/maven-3/3.6.0/binaries/apache-maven-3.6.0-bin.zip -O apache-maven-3.6.0.zip

Example:
In my home directory, download is successful:
subroot@subroot:~$ wget http://us.mirrors.quenda.co/apache/maven/maven-3/3.6.0/binaries/apache-maven-3.6.0-bin.zip -O apache-maven-3.6.0.zip
--2019-05-15 11:06:47--  http://us.mirrors.quenda.co/apache/maven/maven-3/3.6.0/binaries/apache-maven-3.6.0-bin.zip
Resolving us.mirrors.quenda.co (us.mirrors.quenda.co)... 18.104.22.168, 2001:19f0:a:5::28a6
Connecting to us.mirrors.quenda.co (us.mirrors.quenda.co)|184.108.40.206|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 9102386 (8.7M) [application/zip]
Saving to: 'apache-maven-3.6.0.zip'

apache-maven-3.6.0.zip                   100%[================================================================================>]   8.68M  1.59MB/s    in 13s

2019-05-15 11:07:01 (700 KB/s) - 'apache-maven-3.6.0.zip' saved [9102386/9102386]

subroot@subroot:~$

But if I change to the root folder / I can't download because I don't have permission to write to that folder.
subroot@subroot:~$ cd /
subroot@subroot:/$ wget http://us.mirrors.quenda.co/apache/maven/maven-3/3.6.0/binaries/apache-maven-3.6.0-bin.zip -O apache-maven-3.6.0.zip
apache-maven-3.6.0.zip: Permission denied
subroot@subroot:/$

Comment: Now it's working fine
Comment: @vidyadhar Cool. Kindly accept the answer to mark this question as resolved.


Getting the following error message in wine when I try to run Exact Audio Copy

Question: I just recently figured out how to install wine1.5. My primary purpose is to use Exact Audio Copy without having to reboot back to Windows.
I re-downloaded the installation executable, ran it, and installed it into my external hard drive. When I then tried to get wine to run it, it will give me the initial "Exact Audio Copy is starting up... Please Wait!" but then a second window opens. The second says the following message:
"Unhandled exception -
[X icon] at 0207ADF0 -> ACCESS VIOLATION"
Cancelling the window or hitting "ok" cancels wine entirely.
Any ideas?
Comment: Why don't you just use one of the native Linux audio extractors, like sound-juicer?
Comment: EAC is generally regarded as the best ripping program due to the quality of the rips. Is sound-juicer as good?
Comment: If you have a decent drive, then it doesn't matter what program you use, you will always get a correct rip.  For older/buggy drives, sound-juicer uses the original bad rip correcting program: `cdparanoia`.
Answer: I did the following to get it working:
cd ~/.wine/dosdevices/c\:/Program\ Files\ \(x86\)/Exact\ Audio\ Copy/

or wherever you installed EAC to.
regsvr32 sql*

Goto EAC options (F9) and Change the interface to "Installed external ASPI interface".


How to catch database exception and not display it to browser?

Question: I want to catch exception from query error or other database error in codeigniter 2.1.3 and display it or hide in another template, not in the browser actually.
I have done like this before :
<code>//Setting in config/database.php
$db['default']['db_debug'] = FALSE;

//then in the view
echo $this->db->_error_message();
echo $this->db->_error_number();
</code>
But nothing change, I have set my apllication in database error condition before, to test that I can catch the error or not.
Thanks.
Answer: I dont know if codeigniter has a special way of doing this but in regular php code you could just use a normal try catch block.
<code>try {
    // get data from database
    // use data
} catch (Exception $e) {
    // handle exception
}
</code>
http://php.net/manual/en/language.exceptions.php
Answer: You can throw an exception if there's any problem like this:
<code> try {
      //data from database

 } catch (\Exception $e) {
     throw new \Exception('Error: ' . $e->getMessage());
 }
</code>


How do I allow a user to override a schedule?

Question: I'm designing an app which will allow a user to both schedule playlists at different times of the day and override that schedule to play a playlist. How do I communicate to the user that playing a playlist will override their current schedule and how do I allow them to switch back to schedule mode?
Comment: I have already implemented a gcal like calendar for scheduling playlists. However on another screen I have a list of playlists with a play button next to each and I think that people don't understand that playing that playlist would override the currently scheduled playlist.
Comment: What happens at the end of a playlist? Does it revert to the schedule automatically?
Comment: Not currently but I was thinking of offering choices upon press of the play button. Something like 1 hour, 3 hours, or indefinitely.
Comment: And does the app give any visual indication when it's playing something that was scheduled versus playing something that was not scheduled? I.e. could I tell the difference by glancing at the interface?
Comment: @MattObee not currently
Answer: I guess a playlist is a fixed-length event in a calendar-like something, even if more precise than calendar events usually are.

done using the fullcalendar jQuery plugin
I don't see why you need modality here, it looks more like a list-detail issue to me.
Comment: Sorry my question had a typo in it. See my edit to my question.
Answer: I would give them a choice when they try to start a playlist that will interfere with their schedule.

download bmml source – Wireframes created with Balsamiq Mockups
I might be tempted to show which playlist(s) are affected, depending on how much information you want them to have.
As for "how do I allow them to switch back to schedule mode?", that's a little difficult to answer without seeing the rest of the interface. I do certainly think it's important that, whether the current playlist is scheduled or started manually, the user can tell the difference.


Unable to create channel - Attempted to include a member which is not in the consortium

Question: I am facing an issue on creation of channel:
Channel 1 consortium - Org 1, Org2, Org4, Org5
Channel 2 consortium - Org2, Org3, Org4, Org5
Orderer Genesis consortium - Org1, Org2, Org3, Org4, Org5.
From Cli peer ( Org2) - when i am trying to create channel 1 or 2, i am getting below issue:
> peer channel create -o orderer.clm.com:7050 -c $CHANNEL_ONE_NAME -f ./channel-artifacts/channelone.tx --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/clm.com/orderers/orderer.clm.com/msp/tlscacerts/tlsca.clm.com-cert.pem

2018-07-15 01:13:08.240 UTC [channelCmd] InitCmdFactory -> INFO 001 Endorser
and orderer connections initialized
Error: got unexpected status: BAD_REQUEST -- Attempted to include a member
which is not in the consortium

configtx.yaml File
Organizations:
- &OrdererOrg
    # DefaultOrg defines the organization which is used in the sampleconfig
    # of the fabric.git development environment
    Name: OrdererOrg

    # ID to load the MSP definition as
    ID: OrdererMSP

    # MSPDir is the filesystem path which contains the MSP configuration
    MSPDir: crypto-config/ordererOrganizations/clm.com/msp
    AdminPrincipal: Role.MEMBER

- &Org2
    Name: Bdc1MSP
    ID: Bdc1MSP
    MSPDir: crypto-config/peerOrganizations/bdc1.clm.com/msp
    AdminPrincipal: Role.MEMBER
    AnchorPeers:
        - Host: peer0.bdc1.clm.com
          Port: 7051

- &Org1
    # DefaultOrg defines the organization which is used in the sampleconfig
    # of the fabric.git development environment
    Name: Cp1MSP

    # ID to load the MSP definition as
    ID: Cp1MSP

    MSPDir: crypto-config/peerOrganizations/cp1.clm.com/msp
    AdminPrincipal: Role.MEMBER
    AnchorPeers:
        # AnchorPeers defines the location of peers which can be used
        # for cross org gossip communication.  Note, this value is only
        # encoded in the genesis block in the Application section context
        - Host: peer0.cp1.clm.com
          Port: 7051

- &Org3
    Name: Adp1MSP
    ID: Adp1MSP
    MSPDir: crypto-config/peerOrganizations/adp1.clm.com/msp
    AdminPrincipal: Role.MEMBER
    AnchorPeers:
        - Host: peer0.adp1.clm.com
          Port: 7051
- &Org4
    Name: Ottp1MSP
    ID: Ottp1MSP
    MSPDir: crypto-config/peerOrganizations/ottp1.clm.com/msp
    AdminPrincipal: Role.MEMBER
    AnchorPeers:
        - Host: peer0.ottp1.clm.com
          Port: 7051
- &Org5
        Name: RegMSP
        ID: RegMSP
        MSPDir: crypto-config/peerOrganizations/reg.clm.com/msp
        AdminPrincipal: Role.MEMBER
        AnchorPeers:
            - Host: peer0.reg.clm.com
              Port: 7051
Capabilities:
    Global: &ChannelCapabilities
        V1_1: true
    Orderer: &OrdererCapabilities
        V1_1: true
    Application: &ApplicationCapabilities
        V1_2: true

Application: &ApplicationDefaults

    Organizations:

Orderer: &OrdererDefaults

OrdererType: solo

Addresses:
    - orderer.clm.com:7050

# Batch Timeout: The amount of time to wait before creating a batch
BatchTimeout: 2s

# Batch Size: Controls the number of messages batched into a block
BatchSize:

    # Max Message Count: The maximum number of messages to permit in a batch
    MaxMessageCount: 10

    # Absolute Max Bytes: The absolute maximum number of bytes allowed for
    # the serialized messages in a batch.
    AbsoluteMaxBytes: 99 MB

    # Preferred Max Bytes: The preferred maximum number of bytes allowed for
    # the serialized messages in a batch. A message larger than the preferred
    # max bytes will result in a batch larger than preferred max bytes.
    PreferredMaxBytes: 512 KB

Kafka:
    # Brokers: A list of Kafka brokers to which the orderer connects
    # NOTE: Use IP:port notation
    Brokers:
        - 127.0.0.1:9092

Organizations:

Profiles:

    FiveOrgsOrdererGenesis:
        Capabilities:
            <<: *ChannelCapabilities
        Orderer:
            <<: *OrdererDefaults
            Organizations:
                - *OrdererOrg
            Capabilities:
                <<: *OrdererCapabilities
        Consortiums:
            SampleConsortium:
                Organizations:
                    - *Org2
                    - *Org1
                    - *Org3
                    - *Org4
                    - *Org5
    ChannelOne:
        Consortium: SampleConsortium
        Application:
            <<: *ApplicationDefaults
            Organizations:
                - *Org2
                - *Org1
                - *Org5
                - *Org4
            Capabilities:
                <<: *ApplicationCapabilities
    ChannelTwo:
        Consortium: SampleConsortium
        Application:
            <<: *ApplicationDefaults
            Organizations:
                - *Org2
                - *Org3
                - *Org5
                - *Org4
            Capabilities:
                <<: *ApplicationCapabilities

docker compose cli
cli:
container_name: cli
image: hyperledger/fabric-tools:$IMAGE_TAG
tty: true
stdin_open: true
environment:
  - GOPATH=/opt/gopath
  - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
  #- CORE_LOGGING_LEVEL=DEBUG
  - CORE_LOGGING_LEVEL=INFO
  - CORE_PEER_ID=cli
  - CORE_PEER_ADDRESS=peer0.bdc1.clm.com:7051
  - CORE_PEER_LOCALMSPID=Bdc1MSP
  - CORE_PEER_TLS_ENABLED=true
  - CORE_PEER_TLS_CERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/bdc1.clm.com/peers/peer0.bdc1.clm.com/tls/server.crt
  - CORE_PEER_TLS_KEY_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/bdc1.clm.com/peers/peer0.bdc1.clm.com/tls/server.key
  - CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/bdc1.clm.com/peers/peer0.bdc1.clm.com/tls/ca.crt
  - firstname.lastname@example.com/msp
working_dir: /opt/gopath/src/github.com/hyperledger/fabric/peer
command: /bin/bash
volumes:
    - /var/run/:/host/var/run/
    - ./../chaincode/:/opt/gopath/src/github.com/chaincode
    - ./crypto-config:/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/
    - ./scripts:/opt/gopath/src/github.com/hyperledger/fabric/peer/scripts/
    - ./channel-artifacts:/opt/gopath/src/github.com/hyperledger/fabric/peer/channel-artifacts
depends_on:
  - orderer.clm.com
  - peer0.bdc1.clm.com
networks:
  - byfn

Env variables from CLI container :
root@6a67b1de8f57:/opt/gopath/src/github.com/hyperledger/fabric/peer# env
HOSTNAME=6a67b1de8f57
TERM=xterm

CORE_PEER_TLS_ROOTCERT_FILE=
/opt/gopath/src/github.com/hyperledger/
fabric/peer/crypto/peerOrganizations/bdc1.clm.com/peers/
peer0.bdc1.clm.com/tls/ca.crt
CORE_PEER_TLS_KEY_FILE=
/opt/gopath/src/github.com/hyperledger/fabric/peer/
crypto/peerOrganizations/bdc1.clm.com/peers/
peer0.bdc1.clm.com/tls/server.key
LS_COLORS=REMOVED
CORE_PEER_LOCALMSPID=Bdc1MSP
CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
CORE_PEER_TLS_CERT_FILE=/opt/gopath/src/github.com/hyperledger/
fabric/peer/crypto/peerOrganizations/
bdc1.clm.com/peers/peer0.bdc1.clm.com/tls/server.crt
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
:/sbin:/bin:/opt/go/bin:/opt/gopath/bin
PWD=/opt/gopath/src/github.com/hyperledger/fabric/peer
CORE_PEER_TLS_ENABLED=true

CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/
fabric/peer/crypto/peerOrganizations/
firstname.lastname@example.com/msp
CORE_PEER_ID=cli
SHLVL=1
HOME=/root
GOROOT=/opt/go
CORE_LOGGING_LEVEL=INFO
FABRIC_CFG_PATH=/etc/hyperledger/fabric
CORE_PEER_ADDRESS=peer0.bdc1.clm.com:7051
LESSOPEN=| /usr/bin/lesspipe %s
GOPATH=/opt/gopath
CHANNEL_ONE_NAME=channelone
LESSCLOSE=/usr/bin/lesspipe %s %s

_=/usr/bin/env
Comment: sometimes this happen if channelName is wrong or not set correctly
Answer: In my case, I forgot to export CHANNEL_NAME:
root@e8daa001f461:/opt/gopath/src/github.com/hyperledger/fabric/peer# echo $CHANNEL_NAME

root@e8daa001f461:/opt/gopath/src/github.com/hyperledger/fabric/peer# peer channel create -o orderer.example.com:7050 -c $CHANNEL_NAME -f ./channel-artifacts/channel.tx --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
2018-12-07 18:07:18.375 UTC [channelCmd] InitCmdFactory -> INFO 001 Endorser and orderer connections initialized
2018-12-07 18:07:18.636 UTC [common/tools/configtxgen/localconfig] Load -> INFO 002 Loaded configuration: /etc/hyperledger/fabric/configtx.yaml
Error: got unexpected status: BAD_REQUEST -- Attempted to include a member which is not in the consortium

After exporting:
root@e8daa001f461:/opt/gopath/src/github.com/hyperledger/fabric/peer# export CHANNEL_NAME=mychannel

root@e8daa001f461:/opt/gopath/src/github.com/hyperledger/fabric/peer# peer channel create -o orderer.example.com:7050 -c $CHANNEL_NAME -f ./channel-artifacts/channel.tx --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
2018-12-07 18:03:29.985 UTC [channelCmd] InitCmdFactory -> INFO 001 Endorser and orderer connections initialized
2018-12-07 18:03:30.028 UTC [cli/common] readBlock -> INFO 002 Received block: 0

Answer: @arnabkaycee
Looks like shutting down docket containers with removal of volumes and orphans , resolved.
I recreated cryptos, channel artifacts again, which resolved it. Not sure, if any of my previous work had a conflict with it. Still clueless but resolved :)
Comment: That is implicit. You need to take care of these things.
Answer: I faced the same issue today. After a while i found why this happens. Turns out if the channelXXXXXX.tx and anchorXXXX.tx files are not in the same folder this will error out even if everything you have done is correct as its not able to link to the anchor peers.
In my case i had multiple channels defined with their individual folders. I was making the mistake of placing the channelXXXXXX.tx outside its folder and got the error.
Answer: This generally occurs when a member is not in the consortium is added to the channel.
Please post your configtx.yaml for more details.
You can refer to this answer for more details.
How can I add two orderers to the same channel?
EDIT
Check your environment in cli container :
$ env

Then check these variables are exported properly, if not, do them.
export CORE_PEER_LOCALMSPID="Org2MSP"
export CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt
export firstname.lastname@example.com/msp
export CORE_PEER_ADDRESS=peer0.org2.example.com:7051

Comment: Added config.tx yaml sample.
Comment: Looks good to me. What is the command you are using to create the channel?
Comment: mentioned it above..pasting here too
peer channel create -o orderer.clm.com:7050 -c $CHANNEL_ONE_NAME -f ./channel-artifacts/channelone.tx --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/clm.com/orderers/orderer.clm.com/msp/tlscacerts/tlsca.clm.com-cert.pem
Comment: also tried exporting above global vars , tried with Org2, Org5, Org4 which are part of both consortium :(
Comment: Please paste your global var exports.
Comment: added docker compose cli above..Noticed 1 thing, even if i keep same consortiums both orgs in channels and main consortium, it still gives me this error. Looks like issue is somewhere else, probably very small which i am missing.
Answer: I experienced this error in Node-SDK while creating a new channel.
Whenever we update the consortium we must generate the new transaction file for the channel.
In my case, I forgot to generate the respective one and hence got the error.
I generated a new transaction file mychannel.tx
And it resolved my issue.


No sound in headphones after moving to Ubuntu

Question: Today I just moved my PC (Asus ROG GRB II) to Ubuntu 18.04 from Win10. It doesn't have its own speakers, so I need to plug in headphones. Although I have 2 different ports (one for headphones, one for mic), in Win10 they always asked me what I wanted to connect (mic, loudspeakers, headphones, etc) in a small window, where I had to check the option "headphones" and click OK; then sound worked.
Ubuntu does not ask what I want to use for sound when I plug my headphones.I looked in pavucontrol output menu: on the first device - I suspect my headphones - I can see sound (orange label changing its length all the time).
Does someone know what's wrong and how to fix it?
Answer: So I opened pavucontrol and between two output devices (HDMI and stereo output) chose stereo output. Then I plugged headphones in the third port (on the other side of pc, don't know what it is for) and it worked
Answer: Try installing skype from snap instead of installing skypeforlinux
sudo apt-get remove skypeforlinux
sudo snap install --classic skype


Deserialize an Object from string without original object info in Java

Question: Say I have an object serialized string that looks something like this when displayed in terminal:
bd40efbfbdefbfbd00000000000a7371007e00000aefbfbdefbfbdefbfbd
2b020c49efbfbdefbfbdefbfbdefbfbd2b020c49efbfbd3fefbfbdefbfbd
efbfbd126eefbfbdefbfbd40efbfbdefbfbd000000000a7371007e00000a
efbfbdefbfbdefbfbdefbfbdefbfbd126eefbfbdefbfbdefbfbd53efbfbd
efbfbdefbfbd16efbfbd3fefbfbdefbfbdefbfbdefbfbd45efbfbd40efbf
bdefbfbd00000000000a7371007e00000aefbfbdefbfbdefbfbd3b645a1c
efbfbdefbfbdd0b4395810624e3fefbfbd020c49efbfbd5e3540efbfbdef
bfbd000000000a7371007e00000aefbfbdefbfbdefbfbdefbfbd126eefbf
bdefbfbdefbfbdefbfbd1aefbfbdefbfbd76c8b43fefbfbdefbfbd53efbf
bdefbfbdefbfbd1740efbfbdefbfbd00000000000a7371007e0000efbfbd
c49befbfbdefbfbd53efbfbdcfbf50624defbfbdefbfbdefbfbd3fefbfbd
efbfbd45efbfbdefbfbdefbfbd40efbfbdefbfbd000000000a7371007e00
00efbfbdc9ba5e353f7cefbfbdefbfbd1cefbfbd083126efbfbd3fefbfbd
2d0e560418efbfbd40efbfbdefbfbd00000000000a7371007e0000efbfbd
efbfbdefbfbd45efbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbf
bd126eefbfbd3fefbfbdefbfbd45efbfbdefbfbdefbfbd40efbfbdefbfbd
000000000a7371007e0000efbfbdefbfbd26efbfbd78efbfbdefbfbdefbf
bdefbfbd6eefbfbdefbfbd4fefbfbd3b3fefbfbd10624defbfbdefbfbd40
efbfbdefbfbd00000000000a7371007e00000aefbfbdefbfbd4fefbfbd3b
645aefbfbdefbfbd126eefbfbdefbfbd503fefbfbdefbfbdefbfbd22efbf
bdefbfbd6040efbfbdefbfbd000000000a7371007e0000efbfbdefbfbd49
efbfbd5e353f7defbfbdefbfbd10624defbfbdefbfbd3fefbfbd083126ef
bfbd78efbfbd40efbfbdefbfbd00000000000a7371007e00000aefbfbdef
bfbd26efbfbd78efbfbdefbfbdefbfbdefbfbdefbfbdefbfbd126eefbfbd
efbfbd3fefbfbdefbfbd16efbfbd2b020c40efbfbdef

This is the hex I see when typing:
xxd -p fileName in Terminal. I can also view it as Binary but I'm not sure how to decode the serialized object.
I know it is a set of Java serialized objects, but I don't know where the serialization starts/ends. I've tried to loop through with a start and end index but I keep getting:
java.io.StreamCorruptedException: invalid stream header: 30303061
I don't know what else to try, any help would be greatly appreciated.
Thank you!
Comment: Just to verify: Is what you want to show in your post actually mostly unprintable non-alpha-num noise? The problem is that what you see might be different from what I/we see, because of charactersets, unicode, ... I recommend to state that what you want to show is mostly unreadable. I realise that your question might be exactly about this, but a simple explanation/statement probably helps with the clarity. (downvote not by me, I only want to help)
Comment: See [java.io.StreamCorruptedException: invalid stream header: 75720002](https://stackoverflow.com/questions/6315247/java-io-streamcorruptedexception-invalid-stream-header-75720002). Also, please show us your code.
Comment: `0x303061` is two ASCII spaces followed by a lowercase `a`. `String` is not a container for binary data. *Why* don't you know where the Serialization starts and ends? How was this data produced?
Comment: OK, so scan the data for the object stream header sequence, which I believe is 0xCAFEBABE, but you will find it specified in the Protocol chapter of the Object Serialization Specification. You should have taken a hex dump, and posted it here, not the gibberish.
Comment: NB This file does not start with `0x30303061`. Can't see those three spaces and an `a` anywhere.
Comment: Sorry about the confusion, I meant that thats what I see when I type less "filename" in terminal. I can read it as hex/binary and ive tried all this but I am not sure how to approach the problem
Comment: I am doing research under a professor, the student before me produced a .jar file that sends this data over a socket. I was wondering if there was any way to decode this data without having the source code
Comment: Revised to hexdump as per suggestions, however I did not find either 0xCAFEBABE or 0x30303061 when scanning through the file, will try looking for those patterns in binary and get back to you
Comment: Justification as to thought process in previous comment: I do not know when the start and end of each object came in, therefore I feel it is possible that the binary wasn't aligned correctly with each hex value, maybe the binary is shifted over 1 or 2 bits which would make the hex output garbled
Comment: Shifted over 1 or 2 bits *how?* One thing is for sure, this is not serialized data. *Nor* is it the data that produced the `invalid stream header: 30303061` message. Try again. And post the code you are using to deserialize.
Answer: I figured out how to deserialize the object. After some research I went through the hex dump step by step to extract relevant information. The tricky part is that some of the data is sent in different packets over HTTP so the deserialization is kind of stitched together. Anyway here is what I was able to come up with. If anyone has any input on the unknown parts of the snippet below, please, do not hesitate to comment and I will attempt to edit my answer accordingly.
0005 – STREAM_VERSION
0a - UNKNOWN
73 – TC_OBJECT
72 – TC_CLASSDESC
0015 – length of the class name
616461732e746f6f6c6b69742e646174612e504144 - class name
efbfbd221844efbf – SerialVersionUID
bdefbfbdefbfbdefbfbd - UNKNOWN
02 - OBJECT SERIALIZABLE
0004 - NUMBER OF PROPERTIES (4)
44 - PROPERTY CODE (D : Double)

0001 - PROPERTY NAME LENGTH
61 - PROPERTY NAME (a)?

44 - PROPERTY CODE (D : Double)
0001 - PROPERTY NAME LENGTH
64 - PROPERTY NAME (d)

44 - PROPERTY CODE (D : Double)
0001 - PROPERTY NAME LENGTH
70 - PROPERTY NAME (p)

44 - PROPERTY CODE (D : Double)
0008 - PROPERTY NAME LENGTH
73657175656e6365 - PROPERTY NAME (sequence)
0a -UNKNOWN
78 - END BLOCK

70efbfbdefbfbdef - VALUE OF a: 1.00947731285363886197528984273E236
bfbd2b020c49efbf - VALUE OF d: -1.13937500000189637083813920526E-1
bdefbfbdefbfbd45 - VALUE OF p: -2.3100431973060554004134169949E-10
efbfbdefbfbdefbf - VALUE OF sequence: -1.9249974767166909849440370334E230

I hope this helps someone who is in the same situation as I was.
Thank you!
Helpful links:
Javaworld
Javapapers
Comment: Not accepting this answer since it only gives partial understanding.


Moisture in center and corner of windows when raining

Question: I have four double windows where moisture appears in the center or corners of the interior window sills when it rains. Even a light rain will show some moisture/softness on the interior window sill. I never see any water leaking though, just moisture appearing. It is not condensation — happens in all temperatures when it rains. Also, the windows seem to be draining properly - I don't see water collecting between the pane and the screen.
Windows are on three different sides of the building.

My downstairs neighbor has issues with one of the windows directly below mine. No one else in our building has reported any issues with their windows.
Our building has gotten a new roof (thought to be unrelated and seems to be), and we've had many attempts to fix the window leaking from the outside (resealing multiple times) and inside (recaulking around windows). Nothing seems to help.
The photos show 3 of the 4 windows (one has dark paint on the interior sill, so it's hard to photograph). Two of the windows have had interior repairs started, which is why you see plaster (?) instead of paint and discoloration of the plaster. The third window also has some issues with the bottom corner of the window frame, and the third window just leaks a bit different than the other two pictured.
We had a window/roofing company do a water test after the most recent exterior resealing and new roof, and they were hardly able to get the windows to leak at all. The only time a little moisture showed up was when water was directed on the top trim of the window, even though we never see any moisture at the top. They said the water test ruled out the siding, etc., though.
That company proposes the following solution: "Our solution for this is to remove the PVC trim surrounding the leaking windows, install tyvek siding tape on the wall area behind the removed PVC trim, install new PVC trim surrounding the leaking windows, and then seal with caulk."
Another company says that we need to replace all of the windows entirely, and the indicator of that is that there's moisture/wetness on the sill and not at the top of the windows.
We've had the outsides of the windows resealed with caulk so many times and seen zero improvement, so we're just not sure that fixing only the trim is the answer, but new windows are so expensive.
Has anyone else seen this happen? Any ideas?
Comment: Unless the window frames are rotted away or the windows are busted, replacement will only empty your pockets.  It might come down to the windows having to be removed and put back in right.
Comment: Bottom of window frames likely has clogged-up drainage channels. They can clog up just from accumulated dust, spider webs, fly "specks", etc. The mesh some window makers stuff inside the channels to exclude bugs makes the problem worse. The water backs up and leaks to the interior thru imperfect frame joints.
Answer: It is entirely plausible that rain is entering the area between the wall and the windows from the top.  gravity is pulling the moisture down and it is pooling at the bottom. That is manifesting itself as the  moisture spots that you are seeing.
The windows need to be sealed. The plan of removing the trim and sealing with window and door flashing tape, reinstalling the trim and caulking is a sound idea.
The previous caulking most likely was ineffective because it was directed at sealing the trim and not the window to the wall.
The idea of replacing the windows is an attempt to sell you windows.
Answer: Proposed option 1:

"remove the PVC trim surrounding the leaking windows, install tyvek
siding tape on the wall area behind the removed PVC trim, install new
PVC trim surrounding the leaking windows, and then seal with caulk."

This is the least intrusive intervention that might work, and would be my minimum first attempt. If the siding extends under the PVC trim, it will also need to be removed. I assume that inspection/investigation of possible sources of rain penetration farther up on the wall and on the roof above have already been looked into...


Are patches, updates, etc released at the same time worldwide?

Question: I intend to buy a PS4 here in the US and use it in Iceland over the holidays. The PS4 will not be released in Iceland until January 29th. It has been confirmed that the PS4 is auto-voltage, so I am not worried about the hardware, and the games are not region based, so I am not worried about that either. I am worried about the software.
Since Sony does not intend to release its console until the end of January, do they block software updates, patches, etc. from ISP providers in the countries where the console has not been released yet?
Comment: Seems unlikely that you would be unable to get the patches/updates. Assuming you are able to connect to PSN without an issue (can't see why not), it sounds counter-intuitive that Sony would spend time placing blocks on crucial software updates for regions where the console is not yet available.  Posting as a comment because I don't have any sources/concrete examples, but I really wouldn't worry.
Comment: Thanks Turbo. I also would consider it odd for Sony to make an effort to block it in that manner.
Answer: No one can answer this yet. As there have only been one patch to the system (available worldwide). There is not enough data available to say anything general.


How to create user agent?

Question: I'm trying out this function from the package edgarwebR
x <- paste0("https://www.sec.gov/Archives/edgar/data/",
            "933691/000119312517247698/0001193125-17-247698-index.htm")
try(filing_information(x))

But it returns me the following
No encoding supplied: defaulting to UTF-8.
Error in check_result(res) :
  EDGAR request blocked from Undeclared Automated Tool.
Please visit https://www.sec.gov/developer for best practices.
See https://mwaldstein.github.io/edgarWebR/index.html#ethical-use--fair-access for your responsibilities
Consider also setting the environment variable 'EDGARWEBR_USER_AGENT

So I went to SEC and the information tells me to declare my user agent in the request headers. I'm new to this. How do I create a user agent?
Answer: I use the edgar package so I'm not sure this is helpful. But this is how I would do it using edgar package
library("edgar")
useragent = "Your Name email@example.com"
info <- getFilingInfo('933691', 2021, quarter = c(1,2,3,4), form.type = 'ALL', useragent)

How to create user agent?


mvn build failure: Could not find artifact org.springframework.cloud:spring-cloud-sleuth:pom:1.2.2.BUILD-SNAPSHOT

Question: I'm trying to deploy a microservice from here.
The first step is mvn clean package but I meet the following errors:
[INFO] -----------------< fdse.microservice:ts-login-service >-----------------
[INFO] Building ts-login-service 1.0                                     [2/39]
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] ts-service-cluster 0.1.0 ........................... SUCCESS [  0.079 s]
[INFO] ts-login-service 1.0 ............................... FAILURE [  0.218 s]
...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.553 s
[INFO] Finished at: 2023-08-16T17:03:39+08:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal on project ts-login-service: Could not resolve dependencies for project fdse.microservice:ts-login-service:jar:1.0: Failed to collect dependencies at myproject.microservices:micro-service-monitoring-core:jar:1.2.2.BUILD-SNAPSHOT: Failed to read artifact descriptor for myproject.microservices:micro-service-monitoring-core:jar:1.2.2.BUILD-SNAPSHOT: Could not find artifact org.springframework.cloud:spring-cloud-sleuth:pom:1.2.2.BUILD-SNAPSHOT -> [Help 1]

I check the pom of myproject.microservices:micro-service-monitoring-core mentioned in the logs and find the following lines:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>myproject.microservices</groupId>
    <artifactId>micro-service-monitoring-core</artifactId>
    <packaging>jar</packaging>
    <name>micro-service-monitoring-core</name>
    <description>micro-service-monitoring-core</description>

    <parent>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-sleuth</artifactId>
        <version>1.2.2.BUILD-SNAPSHOT</version>
        <relativePath>..</relativePath>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <optional>true</optional>
        </dependency>
...

I guess the reason is the missing of spring-cloud-sleuth 1.2.2.BUILD-SNAPSHOT.
I tried to use spring-cloud-starter-sleuth and 1.22.RELEASE, and the building process became a success but when I run the whole system I meet the following errors:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'traceWebFilter' defined in class path resource
[org/springframework/cloud/sleuth/instrument/web/TraceWebAutoConfiguration.class]:
Unsatisfied dependency expressed through method 'traceWebFilter' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'traceFilter' defined in class path resource
[org/springframework/cloud/sleuth/instrument/web/TraceWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'traceFilter' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'sleuthTracer' defined in class path resource
[org/springframework/cloud/sleuth/autoconfig/TraceAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sleuthTracer' parameter 4; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'zipkinSpanListener' defined in class path resource
[org/springframework/cloud/sleuth/zipkin/ZipkinAutoConfiguration.class]: Unsatisfied dependency expressed through method 'zipkinSpanListener' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'reporter' defined in class path resource
[org/springframework/cloud/sleuth/zipkin/ZipkinAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate
[org.springframework.cloud.sleuth.zipkin.ZipkinSpanReporter]: Factory method 'reporter' threw exception; nested exception is java.lang.NoClassDefFoundError: zipkin/reporter/Sender

I'd like to know where to get the spring-cloud-sleuth 1.2.2.BUILD-SNAPSHOT or how can I solve the errors occur when starting the system.
Comment: Dont' use snapshots, use releases. Apparently you are missing dependencies in your project. Why is this even the parent of your project? It should be a dependency.
Comment: Thanks a lot! I modify it to `1.2.2.RELEASE` and it works now! I'm not sure why it is the parent instead of dependency since it's an open-source project on GitHub and I'm not very familiar with it for now.
Answer: Thanks to @M. Deinum.
I modify it to
    <parent>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-sleuth</artifactId>
        <version>1.2.2.RELEASE</version>
        <relativePath>..</relativePath>
    </parent>

and it works now.
Sometimes containers of ts-xxx-mongo exit with code 14, try docker system prune and then docker-compose up again.


Protractor test works on Firefox but fails on Chrome

Question: While i am using protractor with firefox (ubuntu) 46 all my test are green but when i use chrome some of them fails becouse command browser.executeScript('window.scrollTo(0,10000);'); doesn't work properly. I was trying to use :
var elm = element(by.sth)
browser.executeScript("arguments[0].scrollIntoView();", elm.getWebElement());
or
scrollIntoView : function(){ arguments[0].scrollIntoView(); }
but they didn't work aswell.
And my second question is, when i try to start the same test on Windows they all fail becouse of missing locators etc. is it becouse of archtecture differences of browseres or my tests aren't writen well.
Answer: I resolved problem.
Problem was with promises, We must treat browser.executeScript('window.scroll(0,600);') as a promise so if the test is too fast ,it fails.
Solution is using :
browser.executeScript('window.scroll(0,600);').then(function(){
    return this;
});

It also fix problem with missing locators, becouse the have time to load on windows.
Answer: Are you sure you need to use scrollIntoView ? I have scrollbars in the app I test, but Protractor scrolls automatically when needed.
Otherwise it would be helpful to have more details about the failure. What error message do you get? In what context is called your function? An extract of your code could help.
Comment: Never mind i handel my first problem with
```var sgpt = require('sg-protractor-tools');```
```sgpt.scroll.scrollTo(element);
```
but still got problem to start this test on windows :)


Why does Go's package flag use pointers?

Question: Consider the following code from gopl.io/ch2/echo4
package main

import (
    "flag"
    "fmt"
    "strings"
)

var n = flag.Bool("n", false, "omit trailing newline")
var sep = flag.String("s", " ", "separator")

func main() {
    flag.Parse()
    fmt.Print(strings.Join(flag.Args(), *sep))
    if !*n {
        fmt.Println()
    }
}

I'm interested why the variables n and sep are pointers to the flag variables, rather than normal variable type.
Comment: If it would not be a pointer than flag.Parse could not modify their value.
Answer: It is because they need to be assigned value after they are created. The order of actions is:

Create variable var n = flag.Bool("n", false, "omit trailing newline") The value is false now.
Assign value with flag.Parse(). Variable is now assigned value passed as command line argument.
Answer: If you check the code here, you'll see that there's an exported variable called CommandLine, which is a pointer to a FlagSet. This is where the magic happens. When you import that library, it's instantiated. When you invoke the exported functions, for example, flag.Bool(), that function, in turn, calls the method Bool(), which has a pointer receiver to...FlagSet. It will create a new bool to store your flag's value, invoke BoolVar() to store a pointer to the newly created bool variable within the FlagSet data structure (you'll need to trace BoolVar to see how this is accomplished), and returns the very same pointer to you so you can later get the current value (which could be the default value or an entirely new value as a result of the call toParse())
// CommandLine is the default set of command-line flags, parsed from os.Args.
// The top-level functions such as BoolVar, Arg, and so on are wrappers for the
// methods of CommandLine.
var CommandLine = NewFlagSet(os.Args[0], ExitOnError)

// NewFlagSet returns a new, empty flag set with the specified name and
// error handling property. If the name is not empty, it will be printed
// in the default usage message and in error messages.
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
    f := &FlagSet{
        name:          name,
        errorHandling: errorHandling,
    }
    f.Usage = f.defaultUsage
    return f
}

// A FlagSet represents a set of defined flags. The zero value of a FlagSet
// has no name and has ContinueOnError error handling.
//
// Flag names must be unique within a FlagSet. An attempt to define a flag whose
// name is already in use will cause a panic.
type FlagSet struct {
    // Usage is the function called when an error occurs while parsing flags.
    // The field is a function (not a method) that may be changed to point to
    // a custom error handler. What happens after Usage is called depends
    // on the ErrorHandling setting; for the command line, this defaults
    // to ExitOnError, which exits the program after calling Usage.
    Usage func()
    name          string
    parsed        bool
    actual        map[string]*Flag
    formal        map[string]*Flag
    args          []string // arguments after flags
    errorHandling ErrorHandling
    output        io.Writer // nil means stderr; use Output() accessor
}

// Bool defines a bool flag with specified name, default value, and usage string.
// The return value is the address of a bool variable that stores the value of the flag.
func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
    p := new(bool)
    f.BoolVar(p, name, value, usage)
    return p
}

// Bool defines a bool flag with specified name, default value, and usage string.
// The return value is the address of a bool variable that stores the value of the flag.
func Bool(name string, value bool, usage string) *bool {
    return CommandLine.Bool(name, value, usage)
}

Going back to your question:

why the variables n and sep are pointers to the flag variables, rather than normal variable type.

It's because Parse() can manipulate the original variables and your new variables n and sep would have only captured a copy of the original values. By using the pointer, you and the FlagSet are looking at exact the same variables.


How to convert int year into valid date format in my stored procedure

Question: My stored proc has the following select statement:
select Name,Holiday from tblNames where ID = @ID and DATENAME(YEAR, GETDATE()) = @Year

When executing the statement I have an error

"Error converting data type int to nvarchar."

How can I convert @Year parameter to a correct year?
Comment: As it turns out the title of this question should be changed to "How to get the year part of a date as an integer value?"
Answer: The return type of the datename function is nvarchar, you want the datepart function that returns an integer value, so change to DATEPART(YEAR, GETDATE()) instead.
datename is what you would use to get the name of a month or weekday.
Or you could use the year(getdate()) function instead as Gordon L mentioned in a comment.
Comment: Or better yet, just use `year()`.
Comment: @GordonLinoff Or that, indeed.
Answer: I'd recommend to switch back from fixing specific error message to the original question. You have a date in your table and need to filter it by range. So just provide to server the range bounds. This will also avoid any conversions of stored data. To avoid tail time issue you may append '23:59:59.997' to the upper bound of range or (my advice) provide next date and compare by < instead of <=
set @startdate = ...
set @enddate = dateadd(dd, 1, ...)

select *
from mytable
where t.date >= @startdate and t.date < @enddate

Complicated conversions can make it impossible to use appropriate index. If you can convert your arguments and provide prepared values to server - strive to do so.


Third-party apps are dark in desktop panel

Question: Third-party apps are dark in the notification area of the Ubuntu 22.04 desktop panel.

Normally the Discord logo should appear there, moreover not only Discord but all third-party application icons look like this.
I rebooted the system, changed themes, and disabled plugins, but nothing I tried worked.
Comment: I solved the problem using Ubuntu AppIndicators.
Answer: Enable the Ubuntu AppIndicators GNOME shell extension from the Extensions app (gnome-shell-extensions) as shown in the below screenshot.


How do I make udev rules work?

Question: I would like to learn udev rules. Here is what I do:
victor@X301A1:~$ ls /etc/udev/rules.d/
70-persistent-cd.rules  70-persistent-net.rules  README

Then:
victor@X301A1:~$ sudo gedit /etc/udev/rules.d/01-my-first-udev.rules

My rule:
ACTION=="add", RUN+="echo HELLO ! > /home/victor/udev_test_log.txt"

After saving the file:
 sudo udevadm control --reload-rules

I expected that connecting an USB device would write in the file but nothing happens.
Where am I wrong?
Answer: In RUN you must to put a path to a script. See man udev:

Add a program to the list of programs to be executed for a specific
             device. This can only be used for very short running tasks. Running
             an event process for a long period of time may block all further
             events for this or a dependent device. Long running tasks need to
             be immediately detached from the event process itself.

For examle, create a new script, let say hello.sh in /lib/udev with sudo -H gedit /lib/udev/hello.sh and put next lines inside:
#!/bin/bash

echo HELLO ! > /home/<username>/udev_test_log.txt

Change <username> with your user name. Save the file, close it and make it executable with:
chmod +x /lib/udev/hello.sh

Add a new rule in your /etc/udev/rules.d/01-my-first-udev.rules file like this:
ACTION=="add", RUN+="/lib/udev/hello.sh"

Comment: I tried with my mouse but nothing happens. How can I "debug" this ?
Comment: @VictorL I edited my answer. Is tested, so it should work.
Answer: Actually, I couldn't get a reference for this; But It's something got by Try  & Error.

udev requires the full path of script/program/file used either in PROGRAM, TEST, RUN or IMPORT.
udev doesn't support redirection operations.
udev can handle command with arguments.
udev has variable substitution.

So you can write multifunction script (not just blind/single task script :) ), Example that sure it works for me:
KERNEL=="2-1.2:1.[0-9]*", DRIVER!="usb-storage", RUN+="/bin/sh -c 'echo -n %k,%p > /home/sneetsher/Desktop/%n.txt'"

/bin/sh absolute path
> redirection is handled inside shell
-c '...' 2 command arguments
%k, %p, %n udev variables (device kernel name, device path, device number)

So for your case:
ACTION=="add", RUN+="/bin/sh -c 'echo HELLO ! > /home/victor/udev_test_log.txt'"

How do I make udev rules work?


What controller buttons does Firewatch require?

Question: I'm trying to decide what platform I should play Firewatch on: PC or PS4. I prefer PS4, but we only have one TV, so I'll end up playing most of the game via Remote Play on my PS Vita. This sucks if the game uses L3/R3, as the Vita implements them via touch-sensitive areas on the back. So, before I make my decision, I'd like to know what buttons on the PS4 controller does Firewatch require?
Answer: Here is a quick screencap of the DualShock 4 control scheme from the PC version of the game:

I can only assume the PS4 version uses the same control scheme.
Jogging is mapped to both L3 and Square, so you're not forced to use L3 if you'd rather avoid it, though it looks like the flashlight is only mapped to R3.


release or not release

Question: I'm developing an iPhone application.
I have the following property:
@property (nonatomic, retain) Point2D* endPoint;

And this is a method on the same class:
- (id)initWithX:(CGFloat)x Y:(CGFloat)y;
{
    if (self = [super init])
    {
        endPoint = [[Point2D alloc] initWithX:x Y:y];

    ...
}

And finally the dealloc method on the same class:
- (void)dealloc {
    [endPoint release];
    [super dealloc];
}

My question is it this code correct?
endPoint = [[Point2D alloc] initWithX:x Y:y];

Or maybe I have to do an autorelease here.
Answer: Go read the memory management guide as it'll explain all of this and a lot more.
In short, that code is correct.
If you did self.endPoint = [... alloc/init ...], then you'd need to autorelease or release in init to balance the extra retain.
Answer: Your assignment
endPoint = [[Point2D alloc] initWithX:x Y:y];
does not increase the retainCount, so if you want to keep endPoint to use later you don't use autorelease here.
Or you can use like this
self.endPoint = [[[Point2D alloc] initWithX:x Y:y] autorelease];
=> This assignment will increase the counter of endPoint.
Answer: change endPoint = [[Point2D alloc] initWithX:x Y:y]; to
Point2D *temp = [[Point2D alloc] initWithX:x Y:y];
self.endPoint = temp;
[temp release];

to take advantage of the properties retaining setter.
Comment: That'll leak without a balancing release in there somewhere.
Comment: I'd go with just setting the ivar directly;  avoids any setter override madness.
Answer: You shouldn't use endPoint directly but rather through self.endPoint.
@property (nonatomic, retain) Point2D* endPoint;

- (id)initWithX:(CGFloat)x Y:(CGFloat)y;
{
    if (self = [super init])
    {
        self.endPoint = [[[Point2D alloc] initWithX:x Y:y] autorelease]; //It'll retain it for us.

    ...
}

- (void)dealloc {
    self.endPoint = nil; //setting it to nil means it'll release the object it was previously pointing to.
    [super dealloc];
}

Comment: No, it really isn't.  If the setter/getter has been overridden in a subclass, you are hosed.  If there is a setter/getter that has custom behavior, it'll be fired during initialization/deallocation, exactly when the object is in an undefined state.  Note no down vote -- it isn't *that* big of a deal, in practice, but there are definitely some traps to be aware of.
Comment: Not really;  in init/dealloc there is a lot of reason to go directly to the ivar.
Comment: @bbum true but in this case it's best just to use the property.

release or not release


Angular Material: Validation error on non form input

Question: I would like to use Angular Material library in my project for showing the web page in Material design. I'm having input fields directly in a div, instead of having inside a form . How to properly do error validations now ?
Because the examples given on the documentation uses, form tag, which uses form name for showing ng-messages. How to achieve without form ?
Answer: You may use the ng-form angular directive (see docs here) to group anything, even outside a html form. Then, you can take advantage from angular FormController.

    <input name="myInput" type="text" class="form-control" ng-model="bindTo" ng-maxlength="5">
    Too long!

Example Plunker
Hope it helps


How to trigger an SVG animation with JavaScript? (No jQuery)

Question: I have an SVG line path animated with this sample I found:

svg {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0%;
  top: 0%;
  display: block;
  background: transparent;
}

.path {
  stroke: black;
  stroke-dasharray: 290;
  stroke-dashoffset: 130;
  animation: dash 6s 0s forwards infinite;
  stroke-width: 2px;
  stroke-linecap: round;
  stroke-linejoin: round;
}

@keyframes dash {
  from {
    stroke-dashoffset: 290;
  }
  to {
    stroke-dashoffset: 0;
  }
}
<svg viewbox="0 0 25 100" xmlns="http://www.w3.org/2000/svg">
<path class="path" d="M0 50 L 12 50, 12 0, 25 0" fill="transparent"></path>
</svg>

It works fine but it's triggered when the page loads. Is there a way (let's say with a button) to trigger this animation using JavaScript?
I can handle JS but I'm a noob with CSS and SVG animations.
Can anybody give me an example of how I can do it with my actual CSS?
Comment: [This](https://mb.sb/tech/animations/animations.html) is a small example I've written that shows how to animate an SVG with the browser's [web animation API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API). It includes a button and slider to animate the SVG.
Answer: You could also use SMIL animation syntax instead of CSS animation. This admittedly has the downside of not running in Microsoft browsers (both IE and Edge).

var animation = document.getElementById("dash");

function showSVG() {
  animation.beginElement();
}
svg {
  position: relative;
  width: 100%;
  height: 150px;
  left: 0%;
  top: 0%;
  display: block;
  background: transparent;
}

.path {
  stroke: black;
  stroke-dasharray: 290;
  stroke-dashoffset: 290;
  stroke-width: 2px;
  stroke-linecap: round;
  stroke-linejoin: round;
}
<button id="button" onclick="showSVG()">Click</button>
<svg id="svg" viewbox="0 0 25 100" xmlns="http://www.w3.org/2000/svg">
  <path class="path" d="M0 50 L 12 50, 12 0, 25 0" fill="transparent">
  <animate id="dash"
    attributeName="stroke-dashoffset"
    from="290" to="0"
    begin="indefinite"
    dur="6s"
    fill="freeze" />
  </path>
</svg>

This animation runs once every time you click. If you want it to repeat in fixed intervals, like CSS animation-repeat: infinite prescribes, use
<animate id="dash" attributeName="stroke-dashoffset"
    from="290" to="0"
    begin="indefinite" dur="6s" repeatCount="indefinite" />

Answer: svg {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0%;
    top: 0%;
    display: block;
    background: transparent;
}

.path {
    stroke: black;
    stroke-dasharray: 290;
    stroke-dashoffset: 130;
    stroke-width: 2px;
    stroke-linecap: round;
    stroke-linejoin: round;
    stroke-dashoffset: 290;
}

.animated {
    animation: dash 6s 0s forwards infinite;
    stroke-dashoffset: 0;
}

@keyframes dash {
    from {
        stroke-dashoffset: 290;
    }
    to {
        stroke-dashoffset: 0;
    }
}

Then you can add the class .animated to your path with js whenever you need it.
Answer: You should include your animation in a css class:
    .dash-animate {
        animation: dash 6s 0s forwards infinite;
    }

    @keyframes dash {
      from {
        stroke-dashoffset: 290;
      }
      to {
        stroke-dashoffset: 0;
      }
    }

And then simply apply that class when/where you want using js:
var button = getElementById('some-button');

button.addEventListner('click', function() {
  var elements = document.querySelectorAll('.path');
  Array.prototype.forEach.call(elements, function(el) {
    el.classList.add('dash-animate');
  });
});

Answer:

var svgPattern = document.getElementById("svg")
svgPattern.style.display = "none";
function showSVG(){
svgPattern.style.display = "block";
}
                svg{
                    position:absolute;
                    width:100%;
                    height:100%;
                    left:0%;
                    top:0%;
                    display:block;
                    background:transparent;
                }

                .path {
                    stroke:black;
                    stroke-dasharray: 290;
                    stroke-dashoffset: 130;
                    animation: dash 6s 0s forwards infinite;
                    stroke-width:2px;
                    stroke-linecap:round;
                    stroke-linejoin:round;
                }

                @keyframes dash {
                  from {
                    stroke-dashoffset: 290;
                  }
                  to {
                    stroke-dashoffset: 0;
                  }
                }
<button id ="button" onclick="showSVG()">Click</button>
               <svg id="svg" viewbox="0 0 25 100" xmlns="http://www.w3.org/2000/svg">
                    <path class="path" d="M0 50 L 12 50, 12 0, 25 0" fill="transparent"></path>
                </svg>


Tutorial ASP.NET Core app not seen by localhost

Question: Using MS Visual Studio 2022 on Windows 10 pro to build an ASP.NET Core MVC for the first time. When this tutorial (https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/start-mvc?view=aspnetcore-6.0&tabs=visual-studio) has me run it, Localhost comes up with some stuff relating to the app (its name, a welcome message).  The tutorial says to then add "/MvcMovie/" to the URL in the address field.  Then, localhost says "No webpage was found for the web address: https://localhost:44379/MvcMovie/".
I'm new at this.  Not sure from the tutorial when/if to actually add something to localhost.
Any help will be appreciated.
Comment: It would be best if you add your attempts with code snippets, that way one would be able to provide an accurate solution to your problem.
Answer: The MvcMovie mentioned in the document does not require you to enter in the URl, it is just the name of the created project:

If you need to use MvcMovie as the routing address in the Url, you can do this:
Controller:
 [ApiController]
    public class TestController : Controller
    {

        [HttpGet]
        [Route("MvcMovie")]
        public IActionResult MvcMovie()
        {
            return View();
        }
    }

View demo:

This is MvcMovie Controller!

Test url:https://localhost:7040/MvcMovie
Result:

I think you need to know the routing rules in mvc, you can read this document:
Routing to controller actions in ASP.NET Core
Answer: If you are refering to this:

In the Configure your new project dialog, enter MvcMovie for Project
name. It's important to name the project MvcMovie. Capitalization
needs to match each namespace when code is copied.

The tutorial is saying that your Project's name should be MvcMovie when you create it. Other than that, the tutorial doesn't ask you to go to localhost/mvcMovie. To figure out the routing in an MVC check the next few parts about Controllers-Views-Models. There will be explained about the routing part and how you can access different parts of the URL.


Rainwater Collection / Pond Water Storage (Tower) Support Question

Question: I am planning to build a *water tower for garden irrigation.  I live in NC and have a 45'x70' garden so this time of year I need a considerable amount of water.  Given how little rain we've been getting I believe I'll have to use my pond as a reservoir to help meet my irrigation needs.  All this said, I'm trying to determine how I want to support the tower.  My thought is to have (2) 330 gallon IBC totes elevated to about 10'-12' and possibly add (2) 275 gallon IBC totes below those, ~6'-8' off the ground.
Given the incredible load this would create I figure the easiest thing to use as a support structure would be pallet racks.  Does anyone have any thoughts on this?  I plan to side the sides and roof to keep the weather off of whatever structure I use.  The tower would be located on the back side of my house, where I could get approximately half of my roofs downspouts pouring into the system.  Given the proximity to my house I want to make sure the tower does not topple.  Would it be alright to set the pallet rack on a stone & sand bed or should I pour a re-bar reinforced cement pad?  Generally speaking this side of my house is very dry as there is a sump pump on the other side of the foundation wall.  The pump discharges a fair distance away, 4-5ft below the grade of where the tower would be located.
Comment: You're talking about 10,000 pounds of water. If you really want this sitting 10' off the ground, I wouldn't touch it without an engineer.  It would be easier, safer, and cheaper to put them on the ground and use a pump feed instead of a gravity feed.
Comment: I've considered that if I couldn't find a suitable support structure.. but I'm trying to avoid having to rely on anything other than gravity for water pressure.
Comment: Fancy cisterns on expensive properties where I live are on the ground not raised. To properly support that much weight at a height is just too costly, and too risky.
Answer: This is a stunningly bad idea, IMHO. As @Comintern notes, that's a rather significant load to plop beside your house.  Far simpler and safer to run your downspouts over to where your sump pump discharges, and put a basin & pump there that pumps water uphill, to your storage tanks, set somewhere uphill, so they will provide water pressure when you are without power, if that's your concern. You could even put a hand pump in the system alongside the electrical one if you like. Or you could construct a much less scary (far less weight) structure that carried a trough or pipe from your gutters to the storage tank. If you lack a suitable hill, you could build one at a safe distance from the house and convenient to the garden with a few dump-truck-loads of rock/gravel...
You would definitely need a reinforced slab to spread the load, and calling an engineer would be the right choice if you proceed down that path. What is your seismic hazard level? I'm in a "very low risk area" and I would still be quite concerned to have the structure you describe next to my house in the infrequent, rather minor and mostly far away quakes we have.
Comment: I live in the Piedmont area so the seismic risk is fairly low.  I could have the tower a fair distance from my house (double its height) and should still be able to collect rain water.  All this said I don't know that its worth trying to collect rain water from the house given most of the rain run off makes its way to the pond regardless.  I could put the tower right beside the garden and just only fill it from the pond, via a solar powered pump station.


How to make a custom element component with ionic2?

Question: I define a login-button component like this:
import { Component } from '@angular/core';

@Component({
  selector: 'login-button',
  template:
    `<ion-buttons end>
      <button ion-button round (click)="openLogin()">
        Login
        <ion-icon name="arrow-up"></ion-icon>
      </button>
    </ion-buttons>
    <ng-content></ng-content>
    `
})

export class LoginButton {

  constructor() {
    console.log('Hello LoginButton');
  }
}

Register it as provider in app.module.ts and then use it in a html file:
<ion-content padding>
</ion-content>
<ion-footer>
  <ion-navbar>
    <button ion-button icon-only menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>
      Fragen
    </ion-title>

    <login-button></login-button>
  </ion-navbar>
</ion-footer>

No error message. The constructor is called, but the template is not filled into the  element. Obviously one step is missing. Which one?
Answer: No need to register it as a provider, register it as under declarations and entryComponents.
Then the button can be displayed with the selector : <login-button></login-button> (no need to import explicitly)
Comment: Then on the console of the browser I get: "No provider for LoginButton"
Comment: hmm wait I just checked my code, I have the `LoginButton` declared in both `declarations` and `entryComponents` in the `NgModule`. No import statement on the page of use, just using the selector tag
Comment: Last thing was it. I imported it into the page of use. Put it away and it works. I also put LoginButton into the providers list again, that made the messaage "No provider for LoginButton" go away ;-)
Comment: Hmm weird I can't recall having to do that, working with a beta version of ionic2?
Comment: No. Version 2.1.12.
Comment: That's CLI or applib version I guess, framework rc2 or rc3 then, weird... Ah well, at least it works now xD


Why does _ray_ tracing work?

Question: Perspective projection (or at least non-orthogonal) is by far the most common in photo-realistic graphics. When we use perspective projection, the (equally thick) slices of volume visualized by each pixel get larger with the distance. But with ray tracing we normally cast cylinder-like rays instead of cones. It seems to me that this must make quite a difference to the results: consider the two fields of view of pixels: cone-like one at the LHS, and cylinder-like one at the RHS, the pixels are at the bottom:

The colored lines here represent walls of randomly-distributed light sources with the same density in each wall. If we assume that the intensities of the light sources are the same, so that one of the pixels would "see" white average color, the other must necessarily have a color tint, because the left one samples more red compared to blue than the right one.
Am I right in this? If so, why does then ray tracing work? Why don't we do "frustum tracing" or "cone tracing" to get the colors/illuminances right? And if I'm wrong, then what is my mistake?
Comment: Keep in mind that light intensity falls off with the square of distance, so neither of them would generate white, unless the intensities were set appropriately.
Comment: I wouldn't call the cylinder rays, more like infinitely thin rays that either fully hit or fully miss geometry.
Answer:
But with ray tracing we normally cast cylinder-like rays instead of cones.

Rays aren't really cylinders: they're infinitely thin. This infinitely thin ray can be an approximation to the cone just as much as it can be an approximation to the cylinder.

If we assume that the intensities of the light sources are the same, so that one of the pixels would "see" white average color, the other must necessarily have a color tint ... Am I right in this?

Sort of. Your left-hand diagram doesn't have a colour tint. Although it covers more of the red wall than the blue wall, both of them subtend the same solid angle from the camera's point of view. The same $\tfrac{1}{r^2}$ ratio between the amount of light included in the cone is exactly countered by the $\tfrac{1}{r^2}$ falloff of the light. If the world worked the way you describe, you could make anything brighter by moving it further away from your eye. The right-hand diagram would have a blue colour tint, because the blue light is closer, but this diagram is not how ray-tracing works.
There has been research in a few variants of beam tracing, where instead of tracing an infinitely thin ray, you trace a cylinder, or cone tracing, where you trace a cone or frustum as a simple approximation to the irregular solid that contributes to the pixel. The maths (and therefore the algorithm) are somewhat more complex (and therefore slower) than simple ray tracing, and then you have to deal with what happens when the cone partially intersects an object, and you have to use the same shape to approximate the continued path of the cone. These approaches never caught on.
Instead, supersampling with rays offers the same advantages as cone tracing but with the performance advantage of doing the same simple algorithm many times. You don't supersample by moving the origin of the rays, which would make a cylinder shape, but by varying the directions, which makes a cone shape. Instead of approximating that cone by a single ray along its axis, you're approximating it by (say) 32 rays spread throughout its volume.
Comment: @SimonF I'd rather do four simple rays with no edge cases than one complex cone with special handling for partial occlusion; more if I have a GPU to do them on.
Comment: *" but with the performance advantage of doing the same simple algorithm many times."* ... and the performance *disadvantage* of doing more rays ;-)
Comment: No worries :-) It was a tongue-in-cheek remark. FWIW 30 years(!) ago I was developing an Amantides-style cone ray tracer (https://dl.acm.org/citation.cfm?id=808589).  There are certainly pros and cons to it compared to simple rays.
Comment: @SimonF Oh yeah, that trade-off was a lot different before SIMD and then GPUs made it cheap to trace a zillion coherent supersampling rays.
Answer: It's useful to think of rays not as "tubes" or "cones" of vision, but as the units of bookkeeping of radiant power. This notion resembles that of photons: they also are emitted and detected as a whole, and, for a given frequency, light intensity is represented by density of these units, while the energy per unit doesn't change as the unit propagates.
Consider, for example, the well-known inverse-square law for intensity of light emitted by an isotropic source. Starting with $N$ rays emitted by a surface of area $A$, you'll see that these rays, propagating outwards, have more and more space between them – their density reduces, while number of them, $N$, remains the same (in empty space). Calculate average number of rays per unit surface at distance $r$, and you'll see that it's indeed proportional to $r^{-2}$.
Now, the above example was about forward ray tracing. Backward ray tracing is actually exactly the same, but the question of each ray is not "what object might absorb me?" – instead, it's "where could this unit of light come from?".

Why does _ray_ tracing work?