text:
Q: Devise routing: is there a way to remove a route from Rails.application.routes? devise_for creates routes including a DELETE route, which we want to remove, and devise_for doesn't support an :except or :only option.
How can I remove a route from Rails.application.routes?  Either in the draw block, or afterward?

Here are details of a bug, which was the reason we needed to remove the route.

*

*we were issuing a DELETE request to a custom UJS controller action

*in the controller action we were removing what we wanted to, then doing a 302 redirect.  This was a bad idea, and we have since corrected it by returning some JSON instead.

*some clients, upon receiving the 302 would issue a new DELETE request to the redirect, which routes to a Devise delete route!  Thereby inadvertantly deleting the person! Yikes. We were assuming this would be a GET.   Bad assumption.

This bug has been fixed, but i would like to remove the route nonetheless.

Here is what I did in the end, which was suggested by the bounty-winner in his quote from Jose´ Valim:
In config/routes.rb, I added this above the devise_for call, which sets up the rest of my 'people' routes:
delete '/person', :to => 'people#destroy'

Then in my existing people_controller.rb, I added a no-op method:
def destroy
  render :nothing => true
end

I'm still a little irked that there isn't a simple way to just remove the route from the RouteSet.  Also, the delete route still exists for the devise controller, but it won't get called because rails looks for the first match in config/routes.rb and returns it.

A: Actually devise_for does support :skip and :only, for example (docs):
devise_for :user, :skip => :registration

This will skip all the registration controller's routes, rather than one specifically. You could then implement the routes you need. This seems cleaner than removing the route after the fact.
UPDATE:
Another possible solution is to use Rails' advanced constraints feature to block the unwanted route completely:
# config/routes.rb
constraints lambda {|req| req.url =~ /users/ && req.delete? ? false : true} do
  devise_for :users
end

Here is a post on using lambdas for route constraints. The request object is explained here. This might be the simplest solution.

A: I found a simple solution with Devise 4.2.0 and Rails 5.0.1. I think this will work with Rails 4, and I'm uncertain about older versions of Devise.
Create an initializer overriding the devise_* route helpers. Examples methods are devise_session, devise_password, devise_confirmation, devise_unlock, and devise_registration. Check out the source.
Ensure the initializer is loaded after the Devise initializer by giving the filename a larger alphanumeric value.
For example, Devise creates a :confirmation route with the :new, :create, and :show actions. I only want the :create action.
# config/initializers/devise_harden.rb
module ActionDispatch::Routing
  class Mapper

    # Override devise's confirmation route setup, as we want to limit it to :create
    def devise_confirmation(mapping, controllers)
      resource :confirmation, only: [:create],
               path: mapping.path_names[:confirmation], controller: controllers[:confirmations]
    end
  end
end

Now POST /auth/confirmation is the only route setup for confirmation.

A: Here is what Jose Valim (the author of devise) has to say on the subject:

There is no way to remove routes individually. Or you use :skip to
  remove all and draw the ones you need manually or you overwrite this
  routes by defining a route to the same path first in your config/
  routes.rb

So the short answer to your question is no, you can't delete that one route. You can of course try doing things like patching the devise_for method, but that would be a somewhat involved undertaking (a day or several worth of effort). I'd just use the :skip option, then implement the routes you do want for that controller and leave off the one that you don't.

A: Yes, kinda. You can completely overwrite devise controllers used and write your own (inheriting Devise's if needed). This wiki page can serve as guideline.
Edit
Why I have said kinda :)
Overriding sessions using:
devise_for :users, :controllers => { :sessions => 'custom_devise/sessions'}, :skip => [:sessions] do
  get 'sign_in' => 'custom_devise/sessions#new', :as => :new_user_session
  post 'sign_in' => 'custom_devise/sessions#create', :as => :user_session
end

will give you only two routes [:get, :post], but not :destroy
new_user_session GET  /sign_in(.:format) {:controller=>"custom_devise/sessions", :action=>"new"}
user_session POST /sign_in(.:format) {:controller=>"custom_devise/sessions", :action=>"create"}

So, effectively, you skip destroy/delete route. Now in controller you can go:
class SessionsController < Devise::SessionsController

  def new
    super
  end

  def create
    super
  end

end

You can now repeat the process for registrations, passwords and unlocks.
Second Edit
Ah, yes there is another, simpler way. You can manually create routes (documentation) using devise_scope also known as "as" without overriding:
as :user do
  get  "sign_in", :to => "devise/sessions#new"
  post "sign_in", :to => "devise/sessions#create"
  ...
end

Gives:
sign_in GET  /sign_in(.:format) {:controller=>"devise/sessions", :action=>"new"}
        POST /sign_in(.:format) {:controller=>"devise/sessions", :action=>"create"}

Third Edit
Also, you could overwrite part of Devise in charge of creating these routes, (only to be used in applications that will have no devise "destroy" route whatsoever), by creating an initializer:
module ActionDispatch::Routing
  extend ActionDispatch::Routing
  class Mapper

    protected
      def devise_session(mapping, controllers) #:nodoc:
        resource :session, :only => [], :controller => controllers[:sessions], :path => "" do
          get   :new,     :path => mapping.path_names[:sign_in],  :as => "new"
          post  :create,  :path => mapping.path_names[:sign_in]
        end
      end

      def devise_registration(mapping, controllers) #:nodoc:
        path_names = {
          :new => mapping.path_names[:sign_up],
          :cancel => mapping.path_names[:cancel]
        }

        resource :registration, :only => [:new, :create, :edit, :update], :path => mapping.path_names[:registration],
                 :path_names => path_names, :controller => controllers[:registrations] do
          get :cancel
        end
      end
  end
end

Note that this fix removes all destroy routes used in Devise (there are only two in "sessions" and "registrations") and is a fix only for this specific case.
In addition
You could also add :except option to routes. In order to do it, you must add devise_for method (copy it from original and modify to suit your wishes) to Mapper class so it sends [:except] member of options to above-mentioned (in code) private methods.. Then you should modify those to add routes based on conditions.
Fastest, dirty way, would be to add @scope[:except] = options[:except] and then to modify private methods so that except hash (if you decide to have fine grained route control like: :except => {:sessions => [:destroy]}, thus making :skip obsolete) or array (if you want to remove this specific action from all routes, like: :except => [:destroy]) is checked before adding route.
Anyway, there are plenty ways to achieve what you need. It's up to you to pick the one you think is best suited.


text:
Q: Match among values of List I want to write some clean pattern-matching code.
I have a List of Regex:
val myList = List(
    ".+\\.a".r,
    ".+\\.b".r,
    ".+\\.c".r.+
)

I would like to do something approaching the following:
myInputString match {
    case matchAnyRegexFromMyList(s) => //do something
}

As an alternative to:
myInputString match {
    case regex1(a)|regex2(b)... => //do something
}

Is it at least possible to be more concise?

A: It's not possible to generate case clauses at runtime. You could write a macro to create them at compile time.
You can use a custom extractor though:
case class MultiPattern(patterns: List[Regex]) {
  def unapply(s: String): Option[String] =
    patterns.flatMap(_.findFirstIn(s)).headOption
}

val myMultiPattern = MultiPattern(myList)

val myInputString = "x.b"
myInputString match {
  case myMultiPattern(s) => println(s) // output: x.b
}

A: If your patterns were not pre-compiled you could combine them when they are compiled.
val myList = List( ".+\\.a"
                 , ".+\\.b"
                 , ".+\\.c" )

val myListRE = myList.mkString("|").r

"blah.b" match {
  case myListRE() => println("hit")
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: What information should I include / not include in my posts? Is there any information other than a password that would be considered a security threat?
I am primarily interested in knowing what could compromise the security of a server, rather than the security of intellectual property.
For example, it seems to me that it would be a security threat to include both my username and domain name.
If I post a large amount of output, it is not possible for me to know what nefarious uses it could be put to, especially if data were combined from across multiple posts.
EDIT:
Based on suggestions in comments below, I have moved this question to Server Fault.
EDIT2:
Moderators at ServerFault migrated it to meta.serverfault ... but is that any better than here?

A: You should include enough relevant information in the post to enable people to answer your question.  You should exclude all irrelevant information.  The hard part is knowing what's relevant and what's not.  You can typically disguise user names and passwords (posting 'password' as the password is fine - assuming that isn't actually the password you really use); you can use example.com as the domain name (it is reserved by the IETF for that purpose).  You should hide names of organizations and people hidden in paths and URLs if there's the slightest sensitivity about them.
As to the meta-meta-question of where this question belongs - I really don't see why it doesn't belong on meta.stackoverflow.com.  The principles are much the same regardless; it is a perfectly good question.
It is getting far too hard to find 'the right site™' to post questions.


text:
Q: file_get_contents($remote_url) not working I am working on a project where I need to fetch a .htm file from another server.
But file_get_contents() doesn't seem to work as it always returns this:

file_get_contents(https://hvgg.de/): failed to open stream: Connection timed out

This is my code
$url = "https://hvgg.de/vplan/f" . $day . "/subst_001.htm";

$opts = array("http" =>
    array("header" => "Connection: close")
);

$context = stream_context_create($opts);
$f = file_get_contents($url, false, $context);

If I run the very same code but on my localhost, everything works perfectly well and is quick.
This is an extract of my php.ini:
allow_url_fopen                 On
allow_url_include               Off
always_populate_raw_post_data   Off

Note: The server that I am trying to access uses ssl and a ssl certificate which is (as far as I know) not authorised by an authority.
I also tried cURL which didn't really work either, this is the output that curl_getinfo() returned:
Array
(
    [url] => https://hvgg.de/
    [content_type] =>
    [http_code] => 0
    [header_size] => 0
    [request_size] => 0
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 63.11468
    [namelookup_time] => 0.005179
    [connect_time] => 0
    [pretransfer_time] => 0
    [size_upload] => 0
    [size_download] => 0
    [speed_download] => 0
    [speed_upload] => 0
    [download_content_length] => -1
    [upload_content_length] => -1
    [starttransfer_time] => 0
    [redirect_time] => 0
    [certinfo] => Array
        (
        )

    [primary_ip] => 89.19.241.160
    [primary_port] => 443
    [local_ip] =>
    [local_port] => 0
    [redirect_url] =>
)

Any idea on what I could do?
I also read that maybe this is an error due to IPv6 or my /etc/resolv.conf. Could that be the case?


text:
Q: How to convert a PNG file in to a matrix of pixels? I want to convert a PNG file into matrix of pixels. I tried
I = imread('d:\image.png');

In matlab and I am getting 3 separate matrices ( R matrix, G matrix, B matrix).
I want a single RBG matrix representing the image pixel data.

A: As no-one seems to have been able to do what you want in Matlab, I will show you how to do it with ImageMagick so you can at least get on with what you are trying to do.
First, create a PNG image that is 8x4 pixels with the RGB components of each pixel set to R=00hex, G=44hex, B=55hex so that we have something to play with.
convert -size 8x4 xc:"#004455" image.png

Check it looks right, with identify
identify image.png
image.png PNG 8x4 8x4+0+0 8-bit sRGB 2c 276B 0.000u 0:00.000

Now, separate the channels of the image into RGB, and swap channels 1 and 2, i.e. swap the Green and Blue channels leaving the Red (channel 0) as is, then recombine the separated channels and write as a raw binary file
convert image.png -separate -swap 1,2 -combine RGB:out.raw

Now look at the file contents, with xxd grouping into threes:
xxd -g3 -c12 out.raw
0000000: 005544 005544 005544 005544  .UD.UD.UD.UD
000000c: 005544 005544 005544 005544  .UD.UD.UD.UD
0000018: 005544 005544 005544 005544  .UD.UD.UD.UD
0000024: 005544 005544 005544 005544  .UD.UD.UD.UD
0000030: 005544 005544 005544 005544  .UD.UD.UD.UD
000003c: 005544 005544 005544 005544  .UD.UD.UD.UD
0000048: 005544 005544 005544 005544  .UD.UD.UD.UD
0000054: 005544 005544 005544 005544  .UD.UD.UD.UD

You can hopefully see the file contains 4 rows of 8 pixels, each with RBG #005544
Or, if you prefer it as text:
convert image.png -separate -swap 1,2 -combine out.txt

# ImageMagick pixel enumeration: 8,4,255,srgb
0,0: (0,85,68)  #005544  srgb(0,85,68)
1,0: (0,85,68)  #005544  srgb(0,85,68)
2,0: (0,85,68)  #005544  srgb(0,85,68)
3,0: (0,85,68)  #005544  srgb(0,85,68)
4,0: (0,85,68)  #005544  srgb(0,85,68)
5,0: (0,85,68)  #005544  srgb(0,85,68)
6,0: (0,85,68)  #005544  srgb(0,85,68)
7,0: (0,85,68)  #005544  srgb(0,85,68)
0,1: (0,85,68)  #005544  srgb(0,85,68)
1,1: (0,85,68)  #005544  srgb(0,85,68)
2,1: (0,85,68)  #005544  srgb(0,85,68)
3,1: (0,85,68)  #005544  srgb(0,85,68)
4,1: (0,85,68)  #005544  srgb(0,85,68)
5,1: (0,85,68)  #005544  srgb(0,85,68)
6,1: (0,85,68)  #005544  srgb(0,85,68)
7,1: (0,85,68)  #005544  srgb(0,85,68)
0,2: (0,85,68)  #005544  srgb(0,85,68)
1,2: (0,85,68)  #005544  srgb(0,85,68)
2,2: (0,85,68)  #005544  srgb(0,85,68)
3,2: (0,85,68)  #005544  srgb(0,85,68)
4,2: (0,85,68)  #005544  srgb(0,85,68)
5,2: (0,85,68)  #005544  srgb(0,85,68)
6,2: (0,85,68)  #005544  srgb(0,85,68)
7,2: (0,85,68)  #005544  srgb(0,85,68)
0,3: (0,85,68)  #005544  srgb(0,85,68)
1,3: (0,85,68)  #005544  srgb(0,85,68)
2,3: (0,85,68)  #005544  srgb(0,85,68)
3,3: (0,85,68)  #005544  srgb(0,85,68)
4,3: (0,85,68)  #005544  srgb(0,85,68)
5,3: (0,85,68)  #005544  srgb(0,85,68)
6,3: (0,85,68)  #005544  srgb(0,85,68)
7,3: (0,85,68)  #005544  srgb(0,85,68)

A: There are many different ways to represent an image. Go directly to option3 for a quick answer, but I will also explain in option1 and 2 how the image is represented:
To give an example on a very small sample I will use a very simple image. A blue-ish bullet point:
The actual image used is a downsized version (5x5px) of the bullet point shown above. You can find it here: http://i.imgur.com/QvuBpmI.png
option1
If you read that with your command:
>> I = imread('icon-bullet_5x5.png')
I(:,:,1) =
    0    0    0    0    0
    0   15   53   26    0
    0   41   89   59    1
    0   16   36   23    1
    0    0    2    0    0
I(:,:,2) =
    0    0    0    0    0
    0   31  103   54    0
    0   96  187  130    4
    0   46  110   69    2
    0    0    4    0    0
I(:,:,3) =
    0    0    0    0    0
    0   56  163   91    0
    0  167  255  216   13
    0   91  212  133    4
    0    0   12    0    0

You obtain a 3D matrix of uint8 (8 bit unsigned integers). Each "slice" of the matrix is the proportion of Red, Blue and Green (on a scale [0 255]). You can vaguely recognize that the value are positioned in the matrix as on the image (some colours in the centre and nothing on the periphery.
This can be viewed as a "single RGB" matrix as you were asking (as discussed with Ander in the comments of his answer, Matlab handle that very well and it is quite convenient).

option2
Another way proposed here was to convert that to indices to a colormap. If you do:
>> [X,map] = rgb2ind(I,8)
X =
    0    0    0    0    0
    0    2    6    7    0
    0    6    5    3    0
    0    7    4    1    0
    0    0    0    0    0
map =
                         0                         0       0.00392156862745098
        0.0901960784313725         0.270588235294118          0.52156862745098
        0.0588235294117647          0.12156862745098         0.219607843137255
         0.231372549019608         0.509803921568627         0.847058823529412
         0.141176470588235         0.431372549019608         0.831372549019608
         0.349019607843137         0.733333333333333                         1
         0.184313725490196         0.388235294117647         0.647058823529412
        0.0823529411764706         0.196078431372549         0.356862745098039

This represent the same image. The map variable contains a list of 8 RGB triplets defining 8 different colors (I chose only 8 colors to not overload the example, but the map could define a lot more colors of course)
The values in X are positioned as in the image, and represent the "line number" in the map. The line number in this case starts at 0.
For example the pixel at position X(2,2) (x=2,y=2 from left, from top) has the value 2, so the colour for this pixel is defined by the 3rd line in the map => R/G/B = 0.0588235294117647, 0.12156862745098, 0.219607843137255.
Careful, here the scale for each colour goes from 0 to 1 (instead of [0 255]), but the interpretation is the same.

option3
However, for your application were you have to communicate with a chip, you will not benefit of Matlab matrix handling and you have to "serialize" it. In memory, there is no concept of 2D, 3D or even higher order. The memory is only 1D, a long succession of addresses. It is only the use of pointers and handlers which gives us the impression of more dimension for a more convenient way to handle these data.
To send that to your chip, you do not need a "single matrix" of RGB values but a single vector (a single column or line). A serial succession of pixel information, and a convention defining the relationship between their order in the vector and their position in the matrix (for example as Matlab will lay them out, from top to bottom, from left to right)
A common way (but definitely not the only way) to represent pixel colours in a serial way is to express them as series of 24 bits values. Each 24 bit value is actually composed of 3 concatenated bytes (8 bits unsigned integer) representing R / G / B. Since 24 bits integers are not so human readable to represent colours, this is often represented in hexadecimal format (which is also very handy when you deal directly with microchips).
Matlab offer tools to help you convert easily.
RGBhex = [ dec2hex(I(:,:,1)) dec2hex(I(:,:,2)) dec2hex(I(:,:,3)) ]  ;
>> RGBhex
RGBhex =
000000
000000
000000
000000
000000
000000
0F1F38
2960A7
102E5B
000000
000000
3567A3
... // and so on

In this representation, the 7th pixel with value 0F1F38 has Red=0F=15, Green=1F=31, Blue=0F=56.
If you count the pixels starting from the top left and column wise, his position in the image is the same than the pixel we took as example above x=2,y=2 (from left, from top)
note: some format also includes the "transparency" of each pixel in an Alpha channel. In this case it is usually concatenated with the RGB triplets and each pixel becomes a 32 bits (4 bytes) value Alpha / R / G / B. I did not include that here to keep things simple.

Just as a verification, you can notice that the value are the same than in example 1 (which showed 15/31/56 for the pixel at this position).
A quick conversion also shows that this is the same RGB value than in example 2:
>> uint8([[0.0588235294117647, 0.12156862745098, 0.219607843137255]]*256)
ans =
   15   31   56

If you do not want to handle hexadecimal value and prefer arrays of byte, you can also simply reshape the original matrix:
>> RGBuint = reshape( I , [] , 3 )
RGBuint =
    0    0    0
    0    0    0
    0    0    0
    0    0    0
    0    0    0
    0    0    0
   15   31   56
   41   96  167
   16   46   91
    0    0    0
    ... // and so on

This gives you an array of integers (uint8). The position of each pixel is given with the same rule than in the hexadecimal example above. Depending if your chip handle 8/16 or 32 bits communication you can send the bytes one by one or concatenate them to send them in packets.

A: How is that you are getting 3 separate matrices?
You should have 1 matrix, of size MxNx3. If you want that 3 to become 1, you are going to loose information most likely. You have several options, depending what you want.
One of them is to convert your RGB image into grayscale, easy to do with Ig=rgb2gray(I).
Another, as @Dan suggested, is to create an indexed image. An indexed image has integers instead of colors, integers that are supposed to be indexes of a dictionary where the real colors are stored. you can do [Iind,dict]=rgb2ind(I). Indexed images allows you, for example, to store a big image with few colors in less memory.
I will leave this here, and If this is not what you are looking for, let me know to update the answer with more info.


text:
Q: How to find fastest and shortest distance for round trip using Google Map API V3 I have Two destinations
A.  185 Railroad St, Williamstown, VT 05679, USA
B.  244 Granger Rd, Berlin, VT 05602, United States
For Single trip, I have fastest path VT-63 W, which has 13 miles and 19 mins,so for round trip, distance should be 26 miles and 38 mins. but Why google displays 20 miles and 40 mins for round trip?
Please refer RoundTrip_Mileage.png

How can I find fastest path for roundtrip?
Is there any why that  google map API can understand this is round trip?
Or Is there any logic that I can found this is round trip and than double distance and mileage for round trip?

A: I don't think this belongs in stack overflow. It should have been asked in https://superuser.com/.
Regardless, for the single trip you selected to take VT-63 W. https://maps.google.com/maps?saddr=85+Railroad+St,+Williamstown,+VT+05679&daddr=44.1654204,-72.5409985+to:244+Granger+Rd,+Berlin,+VT+05602&hl=en&sll=44.172688,-72.531622&sspn=0.178282,0.393791&geocode=FY1JoQIdGDqt-ynb7ORanQS1TDFY0UFoLeuI5g%3BFSzpoQIduhyt-yk1hH2lJAS1TDFwLz9qWHdFTA%3BFeaaogId0sGs-ynpTSwANAa1TDF_Or0L4jEMTg&gl=us&mra=ls&t=m&z=12&via=1
For the round trip, you don't get recommended various paths and a different path is chosen for you.https://maps.google.com/maps?saddr=85+Railroad+St,+Williamstown,+VT+05679&daddr=244+Granger+Rd,+Berlin,+VT+05602+to:85+Railroad+St,+Williamstown,+VT+05679&hl=en&sll=44.172688,-72.531622&sspn=0.178282,0.393791&geocode=FY1JoQIdGDqt-ynb7ORanQS1TDFY0UFoLeuI5g%3BFeaaogId0sGs-ynpTSwANAa1TDF_Or0L4jEMTg%3BFY1JoQIdGDqt-ynb7ORanQS1TDFY0UFoLeuI5g&gl=us&mra=ls&t=m&z=12
Because each set of directions takes a different path, they have different total distance traveled and total travel time.
Edit: Setting provideRouteAlternatives to True in the API would give you alternate routes. https://developers.google.com/maps/documentation/javascript/reference


text:
Q: Second isomorphism theorem for semigroups Let $S$ be a semigroup. If $S$ has a zero element, define $S^0 = S$. Otherwise define $S^0$ as $S$ with a zero element adjoined. A subset $I$ of $S$ is an ideal if it is closed under left and right multiplication by every $s \in S$. The Rees quotient $S/I$ is the quotient semigroup $S/\sim_I$ where $a \sim_I b \iff a = b \lor (a \in I \land b \in I)$.
Here is an exercise in my book:

Let $I$ be an ideal and $H$ be a subsemigroup of a semigroup $S$. Then $H \cup I$ is a subsemigroup of $S$, $I$ is an ideal of $H \cup I$, $I \cap H$ is an ideal of $H$, and $H \cup I / I = H / H \cap I$

I think this is incorrect. If $I$ is nonempty and $H \cap I = \varnothing$, $H \cup I / I$ is not $H / H \cap I$ but with a zero element adjoined. So the correct statement should be $H \cup I / I = (H / H \cap I)^0$. Is this right?
Edit: This holds only if $I$ is nonempty. If $I$ is empty this also doesn't hold. Then what would be the general correct statement?

A: First observe that $I$ is the zero element of $S/I$ is $I\ne \emptyset$.
Also, if $S$ has a zero and $I\ne\emptyset$, then necessarily $0\in I$.

Let $I$ be an ideal and $H$ be a subsemigroup of a semigroup $S$. Then

*

*$H\cup I$ is a subsemigroup of $S$,

*$I$ is an ideal of $H\cup I$,

*$I\cap H$ is an ideal of $H$, and

*$\bigl((H\cup I)/I\bigr)^0$ is canonically isomorphic to $\bigl(H/(H\cap I)\bigr)^0$

The first three items are trivial. For the last item consider the map
$f\colon H\cup I\to \bigl(H/(H\cap I)\bigr)^0$ given by
$$f(x)=\begin{cases}0&x\in I\\ [x]_{H\cap I}&x\in H\setminus I\end{cases} $$
This is quite clearly a homomorphism and factors over the $\sim_I$ equivalence relation. Hence it defines a homomorphism $H(H\cup I)/I\to  \bigl(H/(H\cap I)\bigr)^0$, which extends in a unique way to a homomoprhism $\tilde f\colon \bigl((H\cup I)/I\bigr)^0\to \bigl(H/(H\cap I)\bigr)^0$.
Similarly, we can start with $g\colon H\to \bigl((H\cup I)/I\bigr)^0$, given by
$$ g(x)=\begin{cases}0&x\in H\cap I\\ [x]_I&x\in H\setminus I\end{cases}$$
to find $\tilde g\colon  \bigl(H/(H\cap I)\bigr)^0\to \bigl((H\cup I)/I\bigr)^0$. One quickly verifies that $\tilde f\circ \tilde g$ and $\tilde g\circ \tilde f$ are the respective identity homomoprhisms. $\square$.
As you noted, in general we cannot simply drop the $(-)^0$ operator.

A: The exercise should be slightly modified as follows, avoiding at the same time introducing $S^0$:

Let $I$ be an ideal and $H$ be a subsemigroup of a semigroup $S$. Then $H \cup I$ is a subsemigroup of $S$, $I$ is an ideal of $H \cup I$, $I \cap H$ is an ideal of $H$, and if $I \cap H$ is nonempty, then $(H \cup I) / I = H / (H \cap I)$.

The proof is immediate, since both semigroups have support
$$
\bigl((H \cup I) - I\bigr)\cup \{0\} = (H - I) \cup \{0\} = \bigl(H - (H \cap I)\bigr)\cup \{0\}
$$
with product $*$ defined, for all $x,y \in (H - I) \cup \{0\}$ by
$$
x * y = \begin{cases}
xy&\text{if $x, y, xy \in H - I$}\\
0&\text{otherwise}
\end{cases}
$$


text:
Q: Custom module uninstall I've created my uninstall class/script.
After installing my sample module using composer I can see the module working.
Then, I try to uninstall the module using:
bin/magento module:uninstall Barbanet_SampleModule

And I see this message:
You are about to remove code and/or database tables. Are you sure?[y/N]y

Enabling maintenance mode

You are about to remove a module(s) that might have database data. Do you want to remove the data from database?[y/N]y

You are removing data without a database backup.
Removing data of Barbanet_SampleModule
Removing Barbanet_SampleModule from module registry in database
Removing Barbanet_SampleModule from module list in deployment configuration
Removing code from Magento codebase:

Then I press enter a few times I got this message:
Command "remove" failed: Loading composer repositories with package information
    Authentication required (repo.magento.com):
      Username:       Password:

  [Composer\Downloader\TransportException]
  Invalid credentials for 'https://repo.magento.com/packages.json', aborting.

remove [--dev] [--no-progress] [--no-update] [--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [packages1] ... [packagesN]

Please disable maintenance mode after you resolved above issues.

My module was removed from composer.json, also was deleted from the steup_module table and also the custom table was deleted from the database.
My composer keys are stored at my personal auth.json file too.
Someone knows why I'm getting this message and why the uninstall process isn't finishing correctly.

A: Alan Storm point me to this link on GitHub: Issue #2523
It seems that Magento reads the composer credentials from var/composer_home.
One solution is to create a symbolic link inside var/composer_home with:
ln -s ~/.composer/auth.json .

A: Below are the steps to Uninstall Module Manually for Magento 2

*

*Delete the Module folder from {folder path}\app\code

*Remove module entry from database table setup_module

*Run command

go to mangeto root in command prompt like http://prntscr.com/flx68n (go as per your folder drive)
  then run command like : php bin/magento setup:upgrade
  then clear cache like : php -f bin/magento cache:flush

A: Composer stoped in load data from repo.magento.com
My auth.json was not correct.
This decision helped me
config http-basic.repo.magento.com <public_key> <private_key>

How to use the new repo.magento.com


text:
Q: C# enum as generic Cheers!
I had a two enums, describing my entityes: Players and guns types:
public enum PlayersType {
    Scout,
    Tank
}

public enum GunsType {
    Machinegun,
    Tesla
}

I had a generic a struct generic class, and 2 realizations of it:
public class EntityType<T> where T: struct, IConvertible {
    public GameObjectType ObjectType;
}

public class PlayerEntity: EntityType<PlayersType> { }

public class TowerEntity: EntityType<GunsType> { }

And i want to create class, who has EntityType field and inherite ScriptableObject class.
I did this:
public class ObjectTypeConfig: ScriptableObject
{
    public EntityType<Enum> EntityType;
}

But its return error:

The type 'System.Enum' must be a non-nullable value type in order to use it as type parameter `T' in the generic type or method.

Does anyone know how can i create necessary field?
As a result i'm want to create Class, who will be has a Array of ObjectTypeConfigs, containing Players and Towers Entitiyes.

A: You declared the property as EntityType<Enum> but EntityType has the generic constraint of EntityType<T> where T : struct.
The struct constraint means:

The type argument must be a value type. Any value type except Nullable can be specified

If You check Enum you see it is a class - and therefore can be assigned null and fails the generic constraints specified.
I suspect you want one of two:

*

*Change property to be EntityType<GunsType> or EntityType<PlayersType>

*Make the ObjectTypeConfig class generic too with the same constraints and then EntityType<T> EntityType

A: public class ObjectTypeConfig<T>: ScriptableObject where T: struct, IConvertible
{
    public EntityType<T> EntityType;
}


text:
Q: Deterministic statics vs inject-able classes I have in mind several deterministic functions that I'd like to put together, but I'm struggling with the full impllications of doing:

*

*Static class with static methods

*Instance of a class that can be injected into consumers

In both cases, the implementation would be the same, and as they are deterministic with no dependencies, I can unit test both without issue.
My main concern, is when it comes to testing consumers of either the static or injected functions.  I feel that should I go with the inject-able route, I can much more easily test the consumers, but it means another thing to inject into all consumers.  Going the static route, I can just consume them right from any class, but it will be more involved to test specific scenarios, as the consumers will be using literal implementations.
Any thoughts/advice?  More information needed?

A: Rather than hard code, please use defaults.
Making every dependency injectable can lead to a mess. Even small classes soon get large constructors.  The way out of the mess is sensible default values.  The principle is called convention over configuration but it's really just about overrideable defaults.
If you're stuck in a language that doesn't allow named arguments (looking at you Java) you end up having to simulate them using something like the Josh Bloch Builder Pattern.
Once you have named arguments it's easy to use optional arguments because you  can choose one of the many arguments to configure and not all of them.  If you can do that it's much easier to keep up the habit of writing testable code because using it isn't such a pain.

A: Later when your static class needs to have dependencies to support a new feature, converting it from static to injected singleton could be a nightmare.
I recently had to deal with this situation where there were many existing static classes calling each other and one of them needed to be modified to have a dependency injected. This meant that all the static classes that called it also had to be changed, and the rabbit hole just got deeper and deeper.
I have personally been avoiding static classes wherever possible for many years, and was very frustrated when resolving this issue took more than two weeks of valuable development resource.
I would strongly encourage you to take the injection route and save someone in the future from the nightmare I just experienced.


text:
Q: Total Price not update When add and remove row Please check this code. When you can add and remove new row then total amount price not updated.

jQuery(document).on("ready", function() {
  initAddRows();
});
$(document).ready(function() {
  $(".my-activity").click(function(event) {
    var total = 0;
    $(".my-activity:checked").each(function() {
      total += parseInt($(this).val());
    });

    if (total == 0) {
      $('#amount').val('');
    } else {
      $('#amount').val(total);
    }
  });
});

   $('input[name*="ch-skus"]').click(function() {
    var selValue = $(this).parent().find('input[name*="ch-skus"]:checked').attr('data-attr');
    $(this).parent().find('[id^=field]').html('' + selValue + '');
});

function initAddRows() {

  var template = jQuery("#template"),
    dataRows = jQuery("#dataRows")

  jQuery("#btnAdd").on("click", function() {

    var newRow = template.clone(true, true),
      fieldRows = dataRows.find(".fieldRow");

    newRow.attr('id', 'row' + (fieldRows.length + 1)).find('[id]').each(function() {
      jQuery(this).attr("id", jQuery(this).attr("id") + (fieldRows.length + 1));
    });

    newRow.attr('name', 'row' + (fieldRows.length + 1)).find('[name]').each(function() {
      jQuery(this).attr("name", jQuery(this).attr("name") + (fieldRows.length + 1));
    });
    fieldRows.filter(":last").after(newRow);

  });

  dataRows.on("click", ".remove", function() {
    jQuery(this).parent().remove();
  });
}

Total : <input type="text" name="amount" id="amount" value="87" />

     <select class="items field" name="items" id="items">
       <option value="1" selected="selected">Value</option>
       <option value="1">wq</option>
       <option value="1">ewqe</option>
     </select>
     <input id="xyz" class="my-activity" name="ch-skus" type="radio" data-attr="$45.00" value="45">
     <input id="xyz" class="my-activity" name="ch-skus" type="radio" data-attr="$87.30" value="87" checked="">
     <input id="xyz" class="my-activity" name="ch-skus" type="radio" data-attr="$140.00" value="140">
     <input id="xyz" class="my-activity" name="ch-skus" type="radio" data-attr="$240.00" value="240">
     <input type="text" id="abc" name="abc" />
     $87.30/mo
     <input type="button" class="button remove" id="btnDel" value="Remove Row" />

   <input type="button" class="button add" id="btnAdd" value="Add Row" />

A: There is an error in event binding of checkbox click. It only bind event on name matches. You have to select all input which contains that word name.
$('input[name*="ch-skus"]').click(function() {
  var selValue = $(this).parent().find('input[name*="ch-skus"]:checked').attr('data-attr');
  $(this).parent().find('[id^=field]').html('' + selValue + '');
});


text:
Q: What does this code do and why does it compile? I'm creating a Vector2 class in C++ as a template, and I want to define the + operator as a non-member friend function that can simply add two vectors.
This is the friend declaration inside my Vector2 template class:
template <class U>
friend Vector2<T> operator+(const Vector2<T> &lhs, const Vector2<T> &rhs);

This is contained in a .hpp file, but the implementation is in a separate .cpp file:
template <class T>
Vector2<T> operator+(const Vector2<T> &lhs, const Vector2<T> &rhs)
{
    return Vector2<T>(lhs.x_ + rhs.x_, lhs.y_ + rhs.y_);
}

This compiles without any warnings, however, it does not seem to work.
Vector2<int> v1(4, 3);
Vector2<int> v2(3, 4);

Vector2<int> v3 = v1 + v2;

When I try to compile the above snippet, GCC complains:
prog.cpp: In function 'int main(int, char**)':
prog.cpp:26:28: error: no match for 'operator+' in 'v1 + v2'

source/vector2.hpp:31:23: note: template<class U> Vector2<int> operator+(const Vector2<int>&, const Vector2<int>&)
source/vector2.hpp:31:23: note:   template argument deduction/substitution failed:
prog.cpp:26:28: note:   couldn't deduce template parameter 'U'
prog.cpp:26:18: warning: unused variable 'v3' [-Wunused-variable]

What am I doing wrong? How can I correctly define the + operator for my template class?

A: The compiler clearly states what the problem is. It cannot deduce the template parameter 'U'.
Your declaration(the .hpp file) is wrong. Should be
template <class T>
friend Vector2<T> operator+(const Vector2<T> &lhs, const Vector2<T> &rhs);

A: The template for the operator uses a parameter U that isn't used. The signature uses a T instead, that probably comes from a surrounding class template:
template <class U>
friend Vector2<T> operator+(const Vector2<T> &lhs, const Vector2<T> &rhs);

Because U isn't used, the compiler can't automatically deduce what type it should be and gives an error.
Use the template parameter consistently, put the definitions of any templates in the .hpp file, and you should be fine.


text:
Q: Javascript Sort UUID I came across a scenario where I have array of UUID. I want to convert array of UUID to timestamp, sort it in descending order and convert it back to UUID eg. latest timestamp on top.
I am not able to proceed as I am not aware how to convert UUID to timestamp and sort it. Please Help.

// Sort below UUID in desc order by converting them to timestamp

var arr = ['b35086d0-7de3-11ec-aa3a-f3f0af78e321',
'668a6d50-7dea-11ec-aa3a-f3f0af78e321',
'ca189d60-e730-11ec-9306-eb4991e07dcc',
'e944ab30-e734-11ec-8434-f5c328ae6aaa'];

example:
Note: Below Data is just presentation of manually converted UUID to timestamp
b35086d0-7de3-11ec-aa3a-f3f0af78e321 => Tuesday, January 25, 2022 at 1:35:46 PM
668a6d50-7dea-11ec-aa3a-f3f0af78e321 => Tuesday, January 25, 2022 at 2:23:43 PM
ca189d60-e730-11ec-9306-eb4991e07dcc => Wednesday, June 8, 2022 at 1:42:07 PM
e944ab30-e734-11ec-8434-f5c328ae6aaa => Wednesday, June 8, 2022 at 2:11:37 PM
Output I need is UUID in Descending order Latest timestamp on top
668a6d50-7dea-11ec-aa3a-f3f0af78e321
b35086d0-7de3-11ec-aa3a-f3f0af78e321
e944ab30-e734-11ec-8434-f5c328ae6aaa
ca189d60-e730-11ec-9306-eb4991e07dcc


text:
Q: Mailbox Program Java (flipping booleans) I'm tasked with creating a program where the user enters a number, and that will be the total number of mailboxes. All the mailboxes will start in a closed position (boolean true). Then you will flip every other mailbox, then third then fourth then fifth and so on until you get to the last mailbox being the only one flipped. Then you must report back which mailboxes remain closed. I haven't got to return to the user the closed boxes yet. As I am stuck on how to get it to filter through the array.
    scanner  input = new Scanner(System.in);
    System.out.println("This program will close and open mailboxes in a fixed pattern.  How many mailboxes would you like to see?");
    int numOfBoxes = input.nextInt();
    boolean [] boxes = new boolean [numOfBoxes];
    for(int i = 0; i <= numOfBoxes; i++){
      for(int j = 2; j <= numOfBoxes; j++){
        if(boxes.indexOf[i] % j == 0){
           boxes[i] = !boxes[i];
        }
      }
    }

A: How about
for(int i=2; i<=numOfBoxes; ++i) {
    for(int j=i-1; j<numOfBoxes; j+=i) {
        boxes[j] = !boxes[j]
    }
}

Does that do what you want?

Edit
Here's a full working example:
public static void main(String[] args) {
    int numOfBoxes = 5;
    boolean [] boxes = new boolean [numOfBoxes];
    for(int i = 2; i <= numOfBoxes; ++i){
      for(int j = i-1; j < numOfBoxes; j+=i){
        boxes[j] = !boxes[j];
      }
    }
    System.out.println(Arrays.toString(boxes));
}

Running gives me the following output:
[false, true, true, false, true]


text:
Q: How do you check if a value is of type "error" in Scheme? The manual on standard libraries for Scheme r6rs suggests that if I import the library (rnrs exceptions (6)) I should be able to call (error? val) to check if a given value is an &error type. I want to do this for unit testing. I've added the library to my import header and the code compiles, so I know the import is working fine. But DrRacket still recognizes error? as undefined. Does anyone know what's going on here?
My code:
#!r6rs
(import (rnrs base) (rnrs exceptions (6)))
(error? "hello world")

A: You need the conditions library:
#!r6rs
(import (rnrs) (rnrs conditions))
(display (error? "hello world"))

yields
=> #f


text:
Q: Do all servers have operating systems? Do all servers have operating systems?
Can you run applications on any kind of server?
What is an example of an application that can be run on a server?
Believe it or not, I have searched for weeks on Google for answers to these questions, and have come up with nothing. If you can answer any of these I will send good vibes over your way!

A: If it did not have an operating system it would just simply be a box of hardware that did... nothing.
You need an operating system for almost everything- calculators have them,tvs,phones,car park meters,digital cameras and a lot more.
An operating system is what controls the device and makes and delivers the commands which the processor will process and etc.
Maybe you should read up about operating systems as they are quite fascinating in one way :)


text:
Q: How to add character "-" and "`" to the string regex? I'm using the next source:
Matcher mather = Pattern.compile("(\\p{Alnum}*" + subtext + "\\p{Alnum}*)").matcher(ssb.toString());

But if string = "fefrefewre-rfrefrf" or "fefrefewre`rfrefrf"  my mather = "fefrefewre"
I need mather  = "fefrefewre-rfrefrf" or "fefrefewre`rfrefrf"
How add character "-" and "`"  to the  string regex?
subtext = "fefref" - for example

A: It looks like you just want to match the '-' and '`' symbols in addition to the "\p{alpha}".
I think this is the most straightforward solution:
Matcher mather = Pattern.compile("((\\p{Alnum}|[\\-`])*" + subtext + "(\\p{Alnum}|[\\-`])*)").matcher(ssb.toString());

A: Rather than using POSIX character classes that you don't seem to well understand, you could just add the characters you want to allow to a [] character class
Matcher mather = Pattern.compile("[a-zA-Z0-9`-]*" + subtext + "[a-zA-Z0-9`-]*").matcher(ssb.toString());

The - has to be escaped in a character class unless it is at the start or end of it.


text:
Q: git push --all --tags: incompatible When I try to push all branches and tags to a remote, git emits the following error:
# git push origin --all --tags
fatal: --all and --tags are incompatible

However, this works:
# git push origin refs/heads refs/tags
Everything up-to-date

Questions:

*

*Why git names push-all-branches --all but not --branches or --heads? git push origin --all only pushes branches, not all refs. What's the philosophy behind such naming? Does this mean tags are really 2nd-class citizens in a Git repo?

*Why git doesn't allow the use of both --all and --tags?

PS. I know there's a --follow-tags option. I know pushing all tags is not recommended by some people, but this thread is not about that.

man git-push:

--all
Push all branches (i.e. refs under refs/heads/); cannot be used with other <refspec>.
--tags
All refs under refs/tags are pushed, in addition to refspecs explicitly listed on the command line.

A: The message "--all and --tags are incompatible" comes from builtin/push.c#cmd_push()
This was introduced by Marek Zawirski in commit b259f09 in August 2008 (Git v1.6.1-rc1):

Make push more verbose about illegal combination of options
It may be unclear that --all, --mirror, --tags and/or explicit refspecs
  are illegal combinations for git push.
Git was silently failing in these cases, while we can complaint more properly about it.

In 2008, Marek was implementing git push in JGit, and proposed that patch mentioned above, adding:

I forgot about this one, it was reported long time ago.
It seems that it may be really unclear what's going on with git failing on $ git push --tags --all and similar, as it is implementation related perhaps.

While it is possible to configure a remote with:
[remote "origin"]
  push = refs/heads/*
  push = refs/tags/*

Jeff King discovered a bug (kind of deadlock) which is probably why this patch exists.

The sender does a "tellme-more" and then waits for a line back.
  The receiver gets the tellme-more, but never says anything else, presumably
  because he doesn't have that commit (because master is ahead of any
  tags).

In short, pushing branches and tags separately seems easier to support than pushing them together.
See more with "Push git commits & tags simultaneously", with git push --follow-tags, or git config --global push.followTags true.


text:
Q: Select Folder option in Dreamweaver is missing I have a question about Adobe Dreamweaver:
I have two code editors, Sublime and Dreamweaver(CS6 and CC2019 ).
Sublime has the option select folder to include a project at a side panel. But in Dreamweaver I'm unable to find that option. I love to code with Dreamweaver, but this option is missing.
Does Dreamweaver has the same or a similar option?


text:
Q: X axis error with ggplotly and facet_wrap I am trying to create a bar plots with ggplotly and facet_wrap. However, the x-axis looks weird for the second and third subplots. below is my code:
library(plotly)
library(ggplot2)
library(dplyr)

setInfo<- data.frame(sampleNumber=rep(c("A","B","C"),4),
                     Category=rep(c("Class 1", "Class 2","Class 3"),4),
                     Value=rep(1,12))

setInfo %>%
  ggplot(aes(sampleNumber,fill = sampleNumber))+
  geom_bar()+
  facet_wrap(~Category,nrow = 1,scales = "free_x")->plot_this

ggplotly(plot_this)

A: This issue is fixed via PR #1788.
As I figured out this issue was not related to the use of scales="free_x" but happened more generally when using a discrete axis with only one category present in panels > 1 (see my issue #1720 and also #1577).
I have had a look on the issue and was able to come up with a solution to fix this via PR #1788 which was merged on 2020-06-18.
After installing the latest devel version of plotly via devtools::install_github("ropensci/plotly") your example should now be rendered correctly like so:


text:
Q: Smooth transition using background images I am transitioning a couple of background images. However, I am noticing that when if the user acts before the transition has fully taken affect, the transition is instant.
For example, I hover over the div and the image takes 1 second to completely transition. However, I remove the cursor .5s into the transition. So it transitions back to the original image but instead of smoothly transitioning, it changes instantly. How do I make it smooth at all times?

.class {
    width:500px;
    height:500px;
    background-image:url("http://activite-paranormale.net/extended/photo/news/nature-harmony-girl.jpg");
    -webkit-transition: all 1s ease 0;
    -moz-transition: all 1s ease 0;
    -o-transition: all 1s ease 0;
    transition: all 1s ease 0;
}
.class:hover {
    background-image:url("http://images4.fanpop.com/image/photos/22700000/Spring-beautiful-nature-22727146-500-500.jpg");
}

http://codepen.io/john84/pen/vEdPEW

A: fiddle
I changed ease to ease-in-out
edit: Firefox doesn't support this, but there are many workarounds, example:
fiddle
HTML:

CSS:
.class {
    position:absolute;
    width:500px;
    transition:all 500ms;
    height:500px;
    background-image:url("http://activite-paranormale.net/extended/photo/news/nature-harmony-girl.jpg");
}
.class2{
    width:500px;
    height:500px;
    background-image:url("http://images4.fanpop.com/image/photos/22700000/Spring-beautiful-nature-22727146-500-500.jpg");
}
.class:hover {
    opacity:0;
}


text:
Q: What amount of time should be spent on bugs vs original development? This question is a little abstract but I'm hoping someone can point me in the right direction.
My question is what amount of time can one expect to devote to a software project's bugs in relation to the original development time. I realize there are a huge number of determining factors that go into but I was hoping for a typical or average breakdown.
For example, if Project A takes 40 hours to complete and an additional 10 fixing bugs then this project would have a 4:1 ratio.
If another Project (B) takes 10 hours to complete but another 8 on bugs then it would have a 5:4 ratio.
Is this a documented/researched concept?
UPDATE
Thanks for all the informative answers. I understand that it's impossible to put a standard to this kind of metric due to all the variables and environmental factors involved. Before I assign an answer I'd like to know if this metric has an agreed-upon name so I can do further research. I would like to get to a point where I can understand the measurements necessary to generate the metrics myself and eventually come up with a baseline standard for my project.

A: Unfortunately I believe this ratio is highly variable in a given project.  It will drastically be affected by your environment, language, tools, team size and experience.

A: You should spend time on a bug only if what you gain from the fix is greater from what you invest.
Use a matrix like the following (horizontal - time required to fix the bug, vertical - type of bug - impact on users)
              | Few hours | Many hours
--------------+-----------+-------------------------
Minor problem | Might fix | Fix only if time permits
--------------+-----------+-------------------------
Major problem | Fix       | Fix

Example of problems:
              | Few hours                            | Many hours
--------------+--------------------------------------+---------------------------------
              | Window moves 1px every 10            | Windows is painted incorrectly
Minor problem | times when you open the application. | every 100th time the app is open.
              | Fix is: handle window resize event   | Fix: Change the graphical engine.
--------------+--------------------------------------+---------------------------------
Major problem | Application crashes when opening     | Poor performance when >100 users
              | SQL connection.                      | are connected (unusable app)
              | Fix: Fix invalid query + add nice    | Fix: change architecture + DB
              | message                              |

The matrix can be more complex with different levels of severity, effort, risks, etc
You can even create a rank for each bug and fix them based on ranking. Something like:
Bug priority = Risk x Severity x Effort

*Might be (1-x) for some operands, depending on which scale you choose :)
So, to answer your question: depends of the type of bugs, available time/budget, etc.

A: The truly correct answer would be zero hours on bug fixes because your code is perfect. :-)
Realistically, I can't say that I've ever heard someone ask for or offer that type of ratio.  That's not to say that some companies don't track the time for both development and maintenance.  But the development of an application is such a short timeframe when compared to the maintenance that most companies don't go back and calculate that ratio.  They're probably more concerned about learning why an app requires maintenance and applying those findings to new applications.

A: It's highly variable, not only (of course) on the experience and quality of the team, and on the difficulty of the project (it's not the same making another standard web application than a new OS kernel), but also on the management approach you'll use.
For example, on a waterfall model you can set precisely the first bug at the first testing phase, but on an agile environment can be difficult to raise a line saying "from here on, we are correcting bugs", as the features can change (and to me it's not fair counting a feature change as a bug)
From experience, I say that it's something that is ALWAYS underrated, and very easily can spend the same amount of hours than the "original project".

A: Having too broad of a criteria for what is a bug can almost double your time. An over-zealous manager that thinks a client's request to make a button larger (they have mouse issues) is a great way to increase the number of bugs we fixed. It will only take a few seconds to fix because there is no need to consider, testing, recompiling and distributing a patch. Oh, and it gets double-counted as a new feature.

A: The equilibrium percentage of total capacity allocated to defect-fixing is equal to the defect injection rate.
Many factors can affect this rate, among them, of course: what kind of product the team is developing, what technologies and technical practices they use, the team's skill level, the company culture, etc.
Considering Team B, if they create on average 8 units of rework for every 10 units of work they complete, then working those 8 units will create new 6.4 units of rework.  We can estimate the total effort they will eventually have to expend as the sum of a geometric progression:
10 + 8 + 6.4 + 5.12 + ...
The number of bugs will decrease exponentially with time, but Team B has such a coefficient in their exponent that it will go to zero very slowly.  Actually, the sum of the first three terms in the above series is only 24.4; of the first five, 33.6; of the first 10, 45; of the entire series, 50.  So, Team B summary: defect injection rate, 0.8; feature development, 10/50 = 20%; defect-fixing, 80%.  20/80 is their sustainable capacity allocation.
By contrast, Team A is in much better shape.  Their progression looks like this:
40 + 10 + 2.5 + 0.625 + ...
The sum of this series is 53 1/3, so Team A's feature development allocation is 40/(53 1/3) = 75% and defect-fixing allocation is 25%, which matches their defect injection rate of 10/40 = 0.25.
Actually, all terms in Team A's series after the first three are negligibly small.  What this means in practical terms is that Team A can probably squash all their bugs with a couple of maintenance releases, the second release being pretty small in scope.  This also creates an illusion that any team can do that.  But not Team B.
I thought about this equivalence while reading David Anderson's new book, "Kanban".  (The book is on a different subject, but addresses quality concerns, too.)  When discussing software quality, Anderson quotes this book, by Capers Jones, "Software Assessments, Benchmarks, and Best Practices":
"...in 2000... measured software quality for North American teams... ranged from 6 defects per function point down to less than 3 per 100 function points, a range of 200 to 1.  The midpoint is approximately 1 defect per 0.6 to 1.0 function points.  This implies that it is common for teams to spend more than 90 percent of their effort fixing defects."  He cites an example provided by one of his colleagues of a company that spends 90% of the time fixing their bugs.
The fluency with which Anderson goes from the defect injection rate to the defext-fixing capacity allocation (failure demand is the term for it) suggests that the equivalence of the two things is well known to software quality researchers and has probably been known for some time.
The key words in the line of reasoning that I'm trying to present here are "equlibrium" and "sustainable".  If we take away sustainability, then there's an obvious way to cheat these numbers: you do the initial coding, then move on to code somewhere else, and leave maintenance to others.  Or you run up the technical debt and unload it on a new owner.
Obviously, no particular allocation will suit all teams.  If we decreed that 20% must be spent on bugs, then, if a team has an ultra-low defect injection rate, they will simply not have enough bugs to fill the time, and if a team had a very high rate, their bugs will continue to accumulate.
The math I used here is way simplified.  I neglected things like transaction costs (planning and estimation meetings, post-mortems, etc.), which would affect the percentages somewhat.  I also omitted equations simulating sustaining one product and developing another one concurrently.  But the conclusion still stands.  Do what you can, in terms of technical practices, like unit-testing, continuous integration, code reviews, etc., to reduce your defect injection rate and, consequently, your failure demand.  If you can create only one bug for every 10 features, you will have a lot of free time to develop new features and satisfy your customers.

A: The biggest determining factor for this is whether you're working with a new technology or an existing one. If you're working with something new and developing something that hasn't been done or has been done a few times in different circumstances, you're going to spend a lot of time on bugfixes and getting your project to work the way you want. Frequently bugs will be the result of working yourself into a corner, and you'll need to do significant amounts of work to restructure what you've done. Additionally, many bugs will result from an incomplete understanding of user expectations and developer's unawareness of edge cases.
If you're working on an established technology, most problems will have been dealt with by the libraries or by practices in the community, and you should be able to google, buy, or ask your way out of any bugs you run into.

A: On critical sofware, A 1:1 ratio is not unusual. For unit testing alone, I've seen indicators mention 1 day of unit testing for every 10 lines of code.

A: I think that this question is biased : it starts from the presupposition that correcting bugs is a phase similar than developing new functionalities. This is not the case.
A good developer will not spend a lot of time debugging code as his code will be bug-free from the start. A bad developer will spend a lot of time debugging his code because he can't create suitable abstractions to solve real problems.
Note that developers should unit test their own code themselves. It's their job responsibility to deliver bug-free code. So it's hard to separate coding from debugging.
It's also a matter of priority. When developing, the time necessary to correct a bug is related exponentially to the time that has past since the moment you've inserted the bug in the code. So correcting bugs should be of greater priority than developing new functionalities.
So instead of talking about "time spent on bugs", you should talk about "time spent on tests" (integration tests, user acceptance tests...)

A: I think you're right - you're not going to get any meaningful metric due to sher number of influencing factors.
If it helps I can tell you projects I work on (enterprise space, large complex systems, lots of integration to other systems) have a ratio of about 3:2. Most of these are not faults with the code - more usually faults with the interfaces. For example, system A and B talk to each other through interface X. The developers of system A interpret interface X slightly differently than the developers of system B. Comedy ensues.
One observation to make is that development of code and testing/bug fixing of code shouldn't be two distinct phases. If you test as you develop the "cost" of bug fixing is less.

A: I take a purely practical point of view:  What's impeding the practical usefulness of the project more?  If it's bugs in existing functionality, you should fix bugs.  If it's missing features, you should do original development, then go back and fix the bugs once the most severe missing features are implemented.  This requires familiarity with your use cases.  A bug that crashes the program in some odd corner case may be a lower priority than minor usability enhancements that affect everyone.  A small nuisance bug in the most commonly used functionality may be more important than a feature that only benefits people who are pushing your software to the extremes.


text:
Q: "Cannot read property 'match' of undefined" during npm install, but fixing it only works once The solution to the problem is to delete node_modules and package_lock.json. This is great, and it fixes the issue - but only once. I have to do this every single time that I want to install another package. Every time I fix it, the issue returns on the next npm install.
This is my debug log:
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'install'
1 verbose cli ]
2 info using npm@6.14.5
3 info using node@v12.18.1
4 verbose npm-session 32e87fe4b8fbb7a5
5 silly install runPreinstallTopLevelLifecycles
6 silly preinstall client@0.1.0
7 info lifecycle client@0.1.0~preinstall: client@0.1.0
8 silly install loadCurrentTree
9 silly install readLocalPackageData
10 timing stage:loadCurrentTree Completed in 1517ms
11 silly install loadIdealTree
12 silly install cloneCurrentTreeToIdealTree
13 timing stage:loadIdealTree:cloneCurrentTree Completed in 18ms
14 silly install loadShrinkwrap
15 timing stage:rollbackFailedOptional Completed in 0ms
16 timing stage:runTopLevelLifecycles Completed in 1603ms
17 silly saveTree client@0.1.0
18 verbose stack TypeError: Cannot read property 'match' of undefined
18 verbose stack     at tarballToVersion (C:\Program Files\nodejs\node_modules\npm\lib\install\inflate-shrinkwrap.js:87:20)
18 verbose stack     at inflatableChild (C:\Program Files\nodejs\node_modules\npm\lib\install\inflate-shrinkwrap.js:113:22)
18 verbose stack     at C:\Program Files\nodejs\node_modules\npm\lib\install\inflate-shrinkwrap.js:55:12
18 verbose stack     at tryCatcher (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\util.js:16:23)
18 verbose stack     at Object.gotValue (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\reduce.js:155:18)
18 verbose stack     at Object.gotAccum (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\reduce.js:144:25)
18 verbose stack     at Object.tryCatcher (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\util.js:16:23)
18 verbose stack     at Promise._settlePromiseFromHandler (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:517:31)
18 verbose stack     at Promise._settlePromise (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:574:18)
18 verbose stack     at Promise._settlePromiseCtx (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:611:10)
18 verbose stack     at _drainQueueStep (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:142:12)
18 verbose stack     at _drainQueue (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:131:9)
18 verbose stack     at Async._drainQueues (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:147:5)
18 verbose stack     at Immediate.Async.drainQueues [as _onImmediate] (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:17:14)
18 verbose stack     at processImmediate (internal/timers.js:456:21)
19 verbose cwd C:\NodeApps\react-twitch-logs\client
20 verbose Windows_NT 10.0.18363
21 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
22 verbose node v12.18.1
23 verbose npm  v6.14.5
24 error Cannot read property 'match' of undefined
25 verbose exit [ 1, true ]

I need a permanent solution to this. The issue came around when I tried installing webpack, but it was a newer version than what react-scripts was using. And now it's screwed.

A: Turns out this was some kind of conflict with react-scripts.
Running npm run eject, and then removing package_lock.json and node_modules fixes it completely.


text:
Q: Reuse NSpec specification in outer context I am studing NSpec framework.
Here is my example. I've written spec for a simple HttpRequester class:
using Moq;
using NSpec;

namespace FooBrowser.UnitTests.BDD
{
    class HttpRequester_specification : nspec
    {
        private HttpRequester requester;

        private string sentData;
        private int sendTimes;

        private readonly Mock<IConnection> connectionMock;
        private string resource;

        public HttpRequester_specification()
        {
            connectionMock = new Mock<IConnection>();

            connectionMock
                .Setup(x => x.Send(It.IsAny<string>()))
                .Callback<string>(data =>
                {
                    sendTimes++;
                    sentData = data;
                });
        }

        void given_opened_connection_with_no_recent_sends()
        {
            before = () =>
            {
                sendTimes = 0;
            };

            context["when HttpRequester is constructed"] = () =>
            {
                before = () => requester = new HttpRequester(connectionMock.Object);

                it["should not do any request"] = () => sendTimes.should_be(0);

                context["when performing request"] = () =>
                {
                    act = () => requester.Request(resource);

                    context["when resource is not specified"] = () =>
                    {
                        it["should do 1 request"] = () => sendTimes.should_be(1);
                        it["should send HTTP GET / HTTP/1.0"] = () => sentData.should_be("GET / HTTP/1.0");
                    };

                    context["when resource is index.html"] = () =>
                    {
                        before = () => resource = "index.html";

                        it["should do 1 request"] = () => sendTimes.should_be(1);
                        it["should send HTTP GET /index.html HTTP/1.0"] = () => sentData.should_be("GET /index.html HTTP/1.0");
                    };
                };
            };
        }
    }
}

As you can see it["should do 1 request"] = () => sendTimes.should_be(1); is written twice.
I try to move it to outer context like this:
context["when performing request"] = () =>
{
    act = () => requester.Request(resource);

    context["when resource is not specified"] = () =>
    {
        it["should send HTTP GET / HTTP/1.0"] = () => sentData.should_be("GET / HTTP/1.0");
    };

    context["when resource is index.html"] = () =>
    {
        before = () => resource = "index.html";

        it["should send HTTP GET /index.html HTTP/1.0"] = () => sentData.should_be("GET /index.html HTTP/1.0");
    };

    it["should do 1 request"] = () => sendTimes.should_be(1);
};

But this results to it["should do 1 request"] = () => sendTimes.should_be(1); is checked once for outer context, not for inner ones as I want.
So, can I move it to outer context somehow?
Or is it easier to contribute some code to NSpec to enable such behavior?
I found similar question here Reusing NSpec specifications but I want to keep lambda-expression syntax (with no inheritance) to see all specs in 1 place.

A: Sorry to see this is unanswered for two weeks, but I work around it simply by extracting a method like
void ItShouldRequestExactly(int n)
{
    it["should do " + n + " request"] = () => sendTimes.should_be(n);
}

This is DRY enough for me in most cases.
You get however subtle problems when you pass in objects which are actually initialized at spec execution time, but for this simple example it fits perfectly.
I sadly don't see another way to inject such mixin assertions into a context.


text:
Q: Intermittent 502 error code on Apache http proxy I am using Redhat 7 + Apache 2.4.6 to build web proxy.
The issue is 502 error appear in error log, just intermittent.
[Thu Mar 31 01:57:07.080631 2022] [proxy_http:error] [pid 4619] (70014)End of file found: [client 127.0.0.1:57198] AH01102: error reading status line from remote server x.x.x.x
[Thu Mar 31 01:57:07.080668 2022] [proxy:error] [pid 4619] [client 127.0.0.1:57198] AH00898: Error reading from remote server returned by /abc/xyz/

Listen *:8083
NameVirtualHost *:8083

LogFormat "%v %h %l %u %t \"%r\" %>s %b %{MySpecialHeader}i " my_special_format
<VirtualHost *:8083>
    ProxyIOBufferSize 8192
    ServerName mytest.com
    ErrorLog logs/test_error_log
    TransferLog logs/test_access_log
    CustomLog logs/access_log_with_details my_special_format
    LogLevel warn

    SSLProxyEngine on
    SSLProxyVerify none
    SSLProxyCheckPeerCN off
    SSLProxyCheckPeerName off
    SSLProxyCheckPeerExpire off

    SetEnv force-proxy-request-1.0 1
    SetEnv proxy-nokeepalive 1
    SetEnv proxy-initial-not-pooled 1

    <Location "/test">
        SetEnv force-proxy-request-1.0 1
        SetEnv proxy-nokeepalive 1
        SetEnv proxy-initial-not-pooled 1
        ProxyPass https://test.xyz.com:8443/test timeout=30 disablereuse=Off
        ProxyPassReverse https://test.xyz.com:8443/test
    </Location>
</VirtualHost>

My upstream is an AWS NLB, from server I tried curl to upstream is ok, no problem. But when try curl to localhost:8083 502 error intermittent happen.
Any guys can please help to advise.
Thanks


text:
Q: Is it ok to update kernel to 3.19.3 I've got a lab assignment to compile linux kernel , so I wanted to ask if its safe to install latest kernel (3.19.3) on my current Ubuntu 14.04 , I've got important data on my laptop so I cant afford to experiment

A: I wouldn't recommend it.  Not only would you have to reboot the same machine you're developing with (interrupting your work flow), but you might accidentally build a kernel that is missing some hardware drivers your laptop uses.
If you do that, you can hold down Shift during boot to get the grub menu and boot an official kernel instead of your custom one.  So you won't ruin anything.
But I'd recommend instead using a virtual machine like VirtualBox or kvm to boot your kernel inside a safe fake machine.

A: You can always afford to experiment provided you begin with a good disaster recovery plan. muru suggestion (in comments) to use a virtual machine is likely the safest and perhaps easiest solution (to take that approach  see this and this ).
However, provided you have current backups ( see this and this ) and a known good live media of your current system it's highly unlikely that you will lose anything other than a little time (even in the event of an epic failure)
If something kernel related goes wrong, you can always choose to boot your system with your previous version of the kernel from the Advanced Options in the GRUB menu.
I've found experimentation to be one of the best ways to obtain experience and I recommend it whole-heartedly.
source: Experience


text:
Q: Unfortunately, your app stopped working I honestly do not know what is wrong with my code. I have searched for answers here and have done everything and i simply cannot tell what is wrong, Please help?
This is my MainActivity.java,
    package com.example.myname.easternmusic;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import java.util.Timer;
    import java.util.TimerTask;

    public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);
    TimerTask task=new TimerTask() {

        @Override
        public void run() {
            finish();
            startActivity(new Intent(MainActivity.this, Main.class));
        }
    };
    Timer opening=new Timer();
    opening.schedule(task,5000);
}

}

My splash.xml which is the layout for the MainActivity.java
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Sounds of the East"
    android:id="@+id/textView"
    android:layout_alignParentTop="true"
    android:textSize="20dp"
    android:textColor="#000000"
    android:textStyle="bold"
    android:gravity="center_horizontal"
    android:background="@drawable/bell"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentEnd="true" />

My Main.java which is the extra class I created for the main_activity.xml file
    package com.example.myname.easternmusic;

    import android.app.Activity;
    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;

    public class Main extends Activity {

    Button btBamboo, btPalace;
    MediaPlayer mpBamboo, mpPalace;
    int playing;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ImageView imageView=(ImageView)findViewById(R.id.imageView);
    ImageView imageView1=(ImageView)findViewById(R.id.imageView2);
    btBamboo=(Button)findViewById(R.id.button1);
    btPalace=(Button)findViewById(R.id.button2);
    btBamboo.setOnClickListener(bBamboo);
    btPalace.setOnClickListener(bPalace);
    mpBamboo=new MediaPlayer();
    mpBamboo=MediaPlayer.create(this,R.raw.bamboo);
    mpPalace=new MediaPlayer();
    mpPalace=MediaPlayer.create(this,R.raw.palace);
    playing=0;
}
Button.OnClickListener bBamboo=new Button.OnClickListener(){

    @Override
    public void onClick(View v) {
    switch (playing){
        case 0:
            mpBamboo.start();
            playing=1;
            btBamboo.setText("Pause Bamboo Song");
            btPalace.setVisibility(View.INVISIBLE);
            break;
        case 1:
            mpBamboo.pause();
            playing=0;
            btBamboo.setText("Play Bamboo Song");
            btPalace.setVisibility(View.VISIBLE);
            break;
    }
    }
};
Button.OnClickListener bPalace=new Button.OnClickListener(){

    @Override
    public void onClick(View v) {
        switch (playing){
            case 0:
                mpPalace.start();
                playing=1;
                btPalace.setText("Pause Palace Song");
                btBamboo.setVisibility(View.INVISIBLE);
                break;
            case 1:
                mpPalace.pause();
                playing=0;
                btPalace.setText("Play Palace Song");
                btBamboo.setVisibility(View.VISIBLE);
                break;
        }

    }
};
}

and finally, the activity_main.xml file
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Splash">

<ImageView
    android:layout_width="320dp"
    android:layout_height="150dp"
    android:id="@+id/imageView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="20dp"
    android:src="@drawable/band" />

<Button
    android:layout_width="320dp"
    android:layout_height="wrap_content"
    android:text="Play Bamboo Song"
    android:id="@+id/button1"
    android:layout_below="@+id/imageView"
    android:layout_centerHorizontal="true"
    android:textSize="22dp"
    android:layout_marginBottom="10dp" />

<ImageView
    android:layout_width="320dp"
    android:layout_height="150dp"
    android:id="@+id/imageView2"
    android:layout_below="@+id/button1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="20dp"
    android:src="@drawable/drums" />

<Button
    android:layout_width="320dp"
    android:layout_height="wrap_content"
    android:text="Play Palace Song"
    android:id="@+id/button2"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:textSize="22dp"
    android:layout_marginBottom="10dp"
    android:layout_alignParentStart="false" />

When the app is run, it should pull up a splash screen with the splash layout for five seconds, and then display the activity_main layout, but it stops right after it switches screens. Please help.

A: write
startActivity(new Intent(MainActivity.this, Main.class));

then write
finish();

here You first finish your activity and after that you are try to call that activity. That is not possible.


text:
Q: GWT GUI Application not getting loaded on Apache Tomcat 7.0.39 I have a GWT GUI (getmap) application and i have placed it at \Apache Software Foundation\Tomcat 7.0\webapps directory.
Now when i am trying to open it using http://:8080/getmap/GetMap.html>, i am getting an error " Requested Resource is not available"
But when i copy same GWT GUI Application under  \Apache Software Foundation\Tomcat 7.0\examples directory and load it using http://:8080/examples/getmap/GetMap.html>, everything works perfectly !!!
This problem is faced on Windows Vista.
I wold appreciate if anybody could provide some pointers to get rid of this issue ?

A: webapps contains WAR files or their exploded equivalent (i.e. a folder with a WEB-INF subfolder containing a web.xml file). The root of the server (served at the URL /) is a special webapp named ROOT.
So either create a ROOT webapp, or make getmap a webapp by adding the necessary WEB-INF/web.xml.
DISCLAIMER: the above is overly simplified and might not be accurate; plase check the Servlets spec and/or the Tomcat docs about deployment.


text:
Q: ASP.NET MVC Show success message Here is an example method I have that deletes a record from my app:
[Authorize(Roles = "news-admin")]
public ActionResult Delete(int id)
{
    var ArticleToDelete = (from a in _db.ArticleSet where a.storyId == id select a).FirstOrDefault();
    _db.DeleteObject(ArticleToDelete);
    _db.SaveChanges();

    return RedirectToAction("Index");
}

What I would like to do is show a message on the Index view that says something like: "Lorem ipsum article has been deleted" how would I do this? Thanks
Here is my current Index method, just in case:
    // INDEX
    [HandleError]
    public ActionResult Index(string query, int? page)
    {
        // build the query
        var ArticleQuery = from a in _db.ArticleSet select a;
        // check if their is a query
        if (!string.IsNullOrEmpty(query))
        {
            ArticleQuery = ArticleQuery.Where(a => a.headline.Contains(query));
            //msp 2011-01-13 You need to send the query string to the View using ViewData
            ViewData["query"] = query;
        }
        // orders the articles by newest first
        var OrderedArticles = ArticleQuery.OrderByDescending(a => a.posted);
        // takes the ordered articles and paginates them using the PaginatedList class with 4 per page
        var PaginatedArticles = new PaginatedList
(OrderedArticles, page ?? 0, 4);
        // return the paginated articles to the view
        return View(PaginatedArticles);
    }

A: One way would be to use TempData:
[Authorize(Roles = "news-admin")]
public ActionResult Delete(int id)
{
    var ArticleToDelete = (from a in _db.ArticleSet where a.storyId == id select a).FirstOrDefault();
    _db.DeleteObject(ArticleToDelete);
    _db.SaveChanges();
    TempData["message"] = ""Lorem ipsum article has been deleted";
    return RedirectToAction("Index");
}

and inside the Index action you could fetch this message from TempData and make use of it. For example you could pass it as a property of your view model which will be passed to the view so that it can show it:
public ActionResult Index()
{
    var message = TempData["message"];
    // TODO: do something with the message like pass to the view
}

UPDATE:
Example:
public class MyViewModel
{
    public string Message { get; set; }
}

and then:
public ActionResult Index()
{
    var model = new MyViewModel
    {
        Message = TempData["message"] as string;
    };
    return View(model);
}

and inside the strongly typed view:

<%: Model.Message %>


text:
Q: Why didn't Círdan give Narya to another Elf-lord? I just answered the question Why did Gandalf get Narya, of all the Maiar? and in the course of writing up my answer it occurred to me that there's no real reason for Círdan have given his Ring to a Maiar at all.
I'm aware of three other Elf-kingdoms (Besides the Grey Havens themselves) that were active at this point in the Third Age: Rivendell, Lothlórien, and Greenwood/Mirkwood. So why didn't Círdan give Narya to Elrond, Galadriel, or Thranduil?

A: Elrond and Galadriel already had the other two Rings.  Thranduil was inelegible to receive a Ring, since he never went to the West.  Círdan was the only other Lord of the Elves who qualified.  Celeborn qualified, of course, but two Rings in Lothlórien probably would have been noticed by Sauron when he lived in Dol Goldur.

A: Because Círdan wasn't particularly looking to get rid of his Ring at all.
By the Third Age the Havens was one of the major remaining Elf strongholds (the others being Rivendell, Lórien, and — to a lesser extent — Mirkwood) and the power of the Three was mostly to preserve, to prevent decay.  The Ring may have been actively in use in the Havens and the Elves appear to have suspected where the three Rings were, as we see in "The Council of Elrond" (and note that Mirkwood is omitted from this list):

What power still remains lies with us, here in Imladris, or with Círdan at the Havens, or in Lórien.

It's reasonable to surmise that if Gandalf hadn't arrived, or if he had arrived elsewhere, Círdan would have still been holding his Ring at the end of the Third Age.
The answer to your question is therefore:

*

*Círdan didn't give his Ring to Gandalf because he wanted to get rid of it.

*He gave it because he recognized who and what Gandalf was ("for he knew whence he came and whither at last he would return" — "Of the Rings of Power and the Third Age").

*Until that point he actually had no intention of giving it away.

*So therefore he would not have had any reason to give it to anyone else either.


text:
Q: Global Variables in C Between Functions I am trying to get to figure out how to get this print function to work outside of the function the variable is in.
int altitude = 0;

void setup() {
    Serial.begin(9600);
    simulateAltitude();
}

void loop() {
    Serial.println(altitude); // This does not work.
}

int simulateAltitude() {
    int a = 0;
    while ( a == 0 ) {
        altitude += 1;
        Serial.println(altitude); // This does work.
        delay(1);
    }
}

My biggest problem is the void loop() is not getting the value of altitude from the while loop in the int simulateAltitude function. This is being used on an Arduino UNO micro-controller board using C.
I am aware it is an infinite loop, it is for testing purposes only.

A: It's not printing the altitude from within loop() because loop() is never actually being called.
Remember this about Arduino. The setup() function is called once at boot time and, once it returns, the loop() function is called over and over again.
With the way you have it, your setup() function calls simulateAltitude() which goes into an infinite loop, so it never returns. It does not run simulateAltitude() and loop() concurrently.
You might be better off looking at something like:
void loop() {
    Serial.println(altitude);
    increaseAltitude();
}

int increaseAltitude() {
    altitude += 1;
    delay(1);
}

A: You have 2 problems here:
First of all, you need to initialize a and altitude. Give them initial values (say, 0).
Second, you didn't setup your Serial Monitor. Add this line to your setup function:
Serial.begin(9600); //9600 is more common but you can set other update frequencies

A: There are two problems in this code. The first is that simulateAltitude will never be called, so altitude will never update. The second problem is that neither a nor altitude are actually initialized.


text:
Q: Run Time Error 429 - Active X cannot sent email I have created the below macro but when I try to send the error I get the Error on:
 Set OutApp = CreateObject("Outlook.Application")

This was successfully working for a few weeks before I got the below error. This is occuring on several email sending macros that I have created.
Sub SSTrades()

    Rows("1:14").Select
    Selection.Delete Shift:=xlUp
    Columns("R:R").Select
    Selection.Insert Shift:=xlToRight
    Range("R1").Select
    ActiveCell.FormulaR1C1 = "SS ID"
    Range("R2").Select
    Selection.End(xlToLeft).Select
    Selection.End(xlUp).Select
    Selection.End(xlToLeft).Select
    Selection.End(xlUp).Select
    Selection.End(xlToLeft).Select
    Selection.End(xlUp).Select
    Selection.End(xlToLeft).Select
    Selection.End(xlUp).Select
    File Location And Name
    ActiveWorkbook.SaveAs ("File Location " & Format(Now(), "DD-MM-YY") & ".xlsx")

    Dim OutApp As Object
    Dim OutMail As Object
    Dim Filename As String
    Dim strbody As String

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    CarryOn = MsgBox("Do you want to send FX Report ", vbYesNo, "Continue?")

    If CarryOn = vbYes Then

    email body desciption
    strbody = "" & _
              "Hi All,

" & _
              "Please find attached the daily FX report" & "
"

    On Error Resume Next
    With OutMail
        .Display
        .to = "Teams"
        .CC = "TEAM"
        .BCC = ""
        .Subject = " FX Trades " & Date
        .HTMLBody = strbody & .HTMLBody
        .Attachments.Add ActiveWorkbook.FullName
        'You can add other files also like this
        .SentOnBehalfOfName = "team"
        .send
    End With

    MsgBox ("Complete")

    End If

    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing

End Sub

Run TIme Error '429' Active X component cant create object

A: First of all, make sure that you run both applications in the same security context (run as administrators or without admin privileges).
The You receive run-time error 429 when you automate Office applications article describes possible reasons for the error described.
It is not clear which Office version you deal with, so the following information may be helpful:
The Click2Run edition of Office 2010 doesn't support automation. See Office 2010 Click-to-Run compatibility with add-ins for more information. Also, you may find the How to: Verify Whether Outlook Is a Click-to-Run Application on a Computer article.


text:
Q: Change the label for an optiongroup created with ng-options I want to display a HTML select element with optiongroups by using the angularjs select directive.
However I would like to control the value of the optgroup label attribute (every label should be the same '-------------'). Is there any way to achieve this?
Also could it be that there is a problem when using an group by key of '0'?
A working plunker can be found at http://plnkr.co/edit/i8rBdpQYYazYLIbjajjS
EDIT:
I would like the selecto to look like this:
name 2
-------
name 1
-------
name 3
name 4

A: I didn't see any option to change optgroup label from current ngOptions !
There is a workaround with writing your own directive. In your HTML
<select ng-model="selectedItem"
            ng-options="item.text group by item.group for item in data"
            optgroup-label="---"></select>

And the optgroupLabel directive looks like
directive('optgroupLabel', function($timeout){
  return{
    link: function(scope, element, attrs){
      $timeout(function(){
          $(element).find('optgroup').each(function(i,e){
            $(e).prop('label', attrs.optgroupLabel);
          })
      },0);
    }
  }

Demo


text:
Q: Excel Power Query Gives an Error Finding a Named Range When Multiple Workbooks are Open I have a parameterized SQL query (example below of what was typed into the "Advanced Editor") feeding a sheet on an Excel 2016 workbook, "BookA", from an ODBC connection. The parameter is a named range on "BookA". The connection is set to refresh (execute the query) every minute. If the user has only "BookA" open or has multiple workbooks open but has "BookA" as the active workbook, everything works as it should. If the user opens another workbook, "BookB", and has it selected and active when the refresh of "BookA" occurs, an error dialog pops up stating "[Expression.Error] We couldn't find an Excel table named 'MyParamName'." It is as if the query is running in the context of "BookB".
let
    Source = Odbc.Query("dsn=MyConnection",
                        "select 'This Fails With ""MyParamName"" Not Found :" & Excel.CurrentWorkbook(){[Name="MyParamName"]}[Content]{0}[Column1] & "';")
in
    Source

The above assumes that "MyParamName" is defined as a named range with a text value stored in the first cell of the range somewhere in "BookA".
This is a workbook that gets distributed to users by email; they are at liberty to rename it and store it wherever they please. In other words I cannot make use of an absolute path to the workbook in the m-code to give context to the named range so I have to use Excel.CurrentWorkbook()
rather than Excel.Workbook(File.Contents("BookA.xlsx"))
Instructions For Reproducing this bug:
1) Create an ODBC connection (using ODBC Data Sources app) to your favorite SQL flavored database and name it "MyConnection".
2) Create an Excel Workbook and Name it "BookA".
3) Create a named range on sheet1 called "MyParamName" and type some text into the first cell in the range.
4) Go to the "Data" tab in Excel and click "New Query > From Other Sources > From ODBC".
5) In the Dialog select the DSN named MyConnection and click on "Advanced Options" and paste select 'Hello World' as "Test"; into the optional SQL statement area. Click "OK".
6) In the subsequent dialog change the option from "Load" to "Load To...".
7) In the following dialog select "Existing worksheet", choose an appropriate location for the returned data and click "Load".
8) On the "Data" tab click "Show Queries".
9) Double click on "Query1" in the "Workbook Queries" list.
10) Click on "Advanced Editor" (which is the least advanced editor I have ever experienced!)
11) Replace the contents of the editor with the code sample above (let ... source).
12) Click "Done" on the "Advanced Editor" and then click "Close & Load" on the query editor.
13) The query should execute and the data will appear in BookA at the location chosen in 7).
14) On the Excel "Data" tab, choose "Connections" and double click "Query1".
15) Set "Query1" to refresh every 1 minute and click "OK" then close the "Connections" dialog.
16) Now open a second Excel Workbook (anything other than BookA) and leave it  open and active.
17) After a minute an error dialog should pop up: "[Expression.Error] We couldn't find an Excel table named 'MyParamName'."
Has anybody else seen this? Is there a solution/workaround?


text:
Q: Error during run npm install from pom.xml I created java project , in the pom.xml I added section to run npm install
    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.6.0</version>
        <executions>
            <!--node modules are in the project. no need for npm install-->
            <execution>
                <id>npm install my</id>
                <goals>
                    <goal>exec</goal>
                </goals>
                <phase>generate-sources</phase>
                <configuration>
                    <executable>npm</executable>
                    <workingDirectory>${project.basedir}/../</workingDirectory>
                    <arguments>
                        <argument>install</argument>
                    </arguments>
                </configuration>
            </execution>
        </executions>
    </plugin>

and I created also package.json in the root folder.
    The dependencies are from internal nexus and not public nexus
"dependencies": {
 "@test/my": "1.0.13"

        },

When I run mvn on the java module I got error
Unexpected token < in JSON at position 0 while parsing near '
I thought that this error is related that it didn't find the .npmrc .
I tried to add it in different level
How I define in the pom.xml where the .npmrc is needed ?
why does the npm doesn't look for the .npmrc ?