text:
Q: Michael Hartl's Rails Tutorial: Rspec's "Expected response to be a redirect to ..." is wrong In Michael Hartl's (wonderful) Rails Tutorial I'm getting an unexpected Rspec test failure of the form:

"Expected response to be a redirect to
  <http://test.host/signin> but was a
  redirect to
  <http://test.host/signin?notice=Please+sign+in+to+access+this+page.>."

(Find this in Section 10.3.) So, from the very error, you can se that the server is redirecting to the appropriate page except that there is an additional notice to "Please sign in".  The code of the test looks like this:
describe "GET 'index'" do

describe "for non-signed-in users" do
  it "should deny access" do
    get :index
    response.should redirect_to(signin_path)
    flash[:notice].should =~ /sign in/i
  end
end

...

Am I doing something wrong here?  How best should I fix this?

Update:
If I change the code to
response.should redirect_to('http://test.host/signin?notice=Please+sign+in+to+access+this+page.')

then I get and actual Ruby error

Failure/Error: flash[:notice].should
  =~ /sign in/i
       expected: /sign in/i,
            got: nil (using =~)

Resolution
The problem was an omitted comma in my deny_access function:
redirect_to signin_path :notice => "Please sign in to access this page."

should have been
redirect_to signin_path, :notice => "Please sign in to access this page."

This fixed it.  Now, the side affect of this fix was interesting wasn't it?  Does this imply that signin_path is itself a function that can take a hash or arguments to be appended to the end of the path?  Weird, wild, and wonderful.

A: What do your authentication methods look like? I haven't seen the flash notice added to the query string like that before :/ It leads me to believe your methods might be incorrect. It should be something like:
def deny_access
  redirect_to signin_path, :notice => "Please sign in to access this page."
end

OR
def deny_access
  flash[:notice] = "Please sign in to access this page."
  redirect_to signin_path
end


text:
Q: Rails 3 Routes issue on form Edit Basically whats happening is I can create a new item that gets saved to my table in my db. but when I go to edit the item, the form opens up, I make the change and then when I go to submit, it takes me to the same url as the edit page and gives me Routing Error No route matches "/support/14/edit" although if you enter that in the address bar it opens the edit form just fine, but doesn't have any of my changes saved. So here is my code.
routes.rb
resources :support

support_controller.rb
def new
  @support_item = Support.new

  respond_to do |format|
    format.html # new.html.erb
    format.xml  { render :xml => @support_item }
  end
end

# GET /support/1/edit
def edit
  @support_item = Support.find(params[:id])
end

# POST /support
# POST /support.xml
def create
  @support_item = Support.new(params[:support_item])

  respond_to do |format|
    if @support_item.save
      format.html { redirect_to("/support", :notice => 'Question was successfully created.') }
    else
      format.html { render :action => "new" }
    end
  end
end

# PUT /support/1
# PUT /support/1.xml
def update
  @support_item = Support.find(params[:id])

  respond_to do |format|
    if @support_item.update_attributes(params[:support_item])
      format.html { redirect_to("/", :notice => 'Question was successfully updated.') }
      format.xml  { head :ok }
    else
      format.html { render :action => "edit" }
      format.xml  { render :xml => @support_item.errors, :status => :unprocessable_entity }
    end
  end
end

support.rb
class Support < ActiveRecord::Base
  belongs_to :role

  scope :admin_available, order("role_id ASC") do
      Support.all
  end

  def self.available(user)
    questions =   where(:role_id => 1)
    questions +=  where(:role_id => user.roles)
    questions
  end
end

_form.html.erb
  <% if @support_item.errors.any? %>

<%= pluralize(@support_item.errors.count, "error") %> prohibited this question from being saved:

      <% @support_item.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

    <%= f.label "Support item for:" %>

    <%= f.collection_select :role_id, Role.find_by_max(5), :id, :name, {:default => 'everyone'} %>

    <%= f.label :question %>

    <%= f.text_field :question, :class => 'genForm_question'%>

    <%= f.label :answer %>

    <%= f.text_area :answer, :class => 'genForm_textarea' %>

    <%= f.label :url %>

    <%= f.text_field :url, :class => 'genForm_question' %>

    <%= f.submit %>

new.html.erb

New Support Item

<% form_for @support_item, :url => { :action => "create" }, :html => { :method => :post } do |f| %>
    <%= render 'form', :f => f %>
<% end %>

edit.html.erb

Editing Support Item

<% form_for @support_item, :url => { :action => "edit" }, :html => { :method => :post } do |f| %>
        <%= render 'form', :f => f %>
<% end %>

I believe thats all the relavent code.

A:
Editing Support Item

<% form_for @support_item do |f| %>
        <%= render 'form', :f => f %>
<% end %>

You are overriding the URL. It should be able to be auto-generated like that if you are doing everything with standard rest. If that doesn't work out, just know you don't want to submit to /support_items/1/edit, you want to submit to /support_items/1.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to define infinite numbers in visual studio 2015? When I used #define INF (1.0/0.0) to define infinite number, it called the error C2124, which means that a constant expression has a zero denominator. It was told that do not divide by zero can avoid it. But I really need to define inifite number, could someone give a simple way to solve it?

A: Not sure if it works in VS, especially such an old version, but STL has special provision for that:
double never = std::numeric_limits<double>::infinity();

A: The C++ standard way is to utilize the function std::numeric_limits<double>::infinity() in the <limits> library.
This is also only meaningful if std::numeric_limits<double>::has_infinity is true (which it usually will be).


text:
Q: Arrayformula + Query in Google Sheets I have one workbook that has daily tracking of bidding dates and amounts and win day and amounts. In another workbook, I access that information to see the totals per day. Then play with that to see week/month/quarter and year performance. The problem I have is that I can not get my query searches to work in an array manner and have to drag the date driven formulas down 364 times for each column of information and all it's done is create a slow database...
=QUERY(importrange('source addresses'!$B$2,"bid tracker!$a$3:$x"),
"SELECT SUM (Col9)
WHERE Col8 = date '"&text(B5,"yyyy-mm-dd")&"'
label sum(Col9) ''   ",0)

Col9 = amount of contract
Col8 = date of win

This formula produces a single data output for the sum of that days wins, I need it to array all 365 days to eliminate the other 364 of THESE formulas I am using due to my inexperience.
I have used arrayformula before query and after and every example I see doesn't seem to apply or work for me...

A: You need group by clause like group by Col8. Try-
=QUERY(importrange('source addresses'!$B$2,"bid tracker!$a$3:$x"),
"SELECT SUM (Col9)
WHERE Col8 <= date '"&text(B5,"yyyy-mm-dd")&"' AND Col8 >= date '"&text(B5-369,"yyyy-mm-dd")&
"' group by Col8 label sum(Col9) '' ",0)


text:
Q: How to change active tab in iframe header when on different page? I have an imported header via iframe on my HTML page. I want a way to make the current page active, but can't just change it to the active class in the header, because it would make it active on all pages.
Thanks!


text:
Q: Return various implementations of a base class in one method So I have a few different implementations of State (StateImplementation and OtherStateImplementation)
And I need to return a new implementation if a certain event happens.
The method can return N amount of different implementations.
public class State() {
    // Contains various methods
}

public class StateImplementation extends State {
    public State onEvent(String event){
        if(event.equals("foo")){
            return new OtherStateImplementation();
        } else {
            return this;
        }
    }
}

public class OtherStateImplementation extends State {
    // Second implementation
}

How would I go about doing this, as the types don't match the return type if I do it like this.


text:
Q: Getting exact maximum daily temperature using remote sensing? I have a problem I want to find the land surface temperature of Bangkok using landsat8.
I have everything to get it but the problem is landsat images are obtained during morning time but the maximum temperature will be afternoon period.
How can I get the exact maximum temperatures of a day?

A: Sun synchronous satellites like Landsat always capture an image at the same time of the day. Furthermore, Landsat "only" repeats its acquisitions every 16 days.
If you want an image in the afternoon, MODIS AQUA has a daily coverage at 1.30 PM, which is a better timing but at a lower spatial resolution (500m).
Finally, you can get the highest temporal resolution with geostationnary satellites like METEOSAT-5 MVIRI, but then you have a spatial resolution of 5 km.
As you can see, the best spatial and temporal resolutions never come together.
As a last remark, land surface temperature is not a direct measurement of the temperature of the air but depends on the emissivity of the observed land cover. This has to be taken into account for some applications.


text:
Q: input of all column names in dplyr case_when and assign to new column based on condition Hello stack overflow community -
In R, I want to generate a new column based on multiple columns in a data frame. I want the new column to assign the column name if a condition is meet for each row. For instance, in the iris dataset below, the new column 'Biggest' either gets 'Sepal.Length' or 'Petal.Length' dependent on condition of size (i.e. Sepal.Length>= 6.1 or Petal.Length< 6.0). This works successfully.
data(iris)
irisOne <- subset(iris, Species=="virginica") %>%
  select("Sepal.Length", "Petal.Length")

irisOne %>%
  dplyr::mutate(Biggest =
                  dplyr::case_when(
                    Sepal.Length >= 6.1 ~ "Sepal.Length",
                    Petal.Length <= 6.0 ~ "Petal.Length"
                  ))

My question is how would one extend this to be agnostic to column names and use those column names in the new column in the case_when section. My actually dataset has > 50 column names and I don't want to code all of that. I thought it would be something including all_vars but have been unsuccessful in implementing this, see below for my attempt.
irisOne %>%
  dplyr::mutate(Biggest =
                  !!all_vars(.),
                  dplyr::case_when(
                    . >= 6.1 ~ .,
                    . <= 6.0 ~ .
                  ))

A: You can take help of max.col -
data$Biggest <- colnames(data)[max.col(data >= 6.1, ties.method = 'first')]


text:
Q: Backup sqlite data programmatically using Monotouch I have developed an iPhone app using Monotouch and am about to do some user testing and run a trial once every 90 minutes on the same task with a different user. Therefore I need to 'zero' the app to avoid biases from the previous user's work. Since the data is stored in SQLite, is there a way to programmatically backup the iPhone data within Monotouch, either to a remote server or to a file persistent on the device?

A: For backup File.Copy(source, destination) is sufficient. As for where, I'd say in the same location where your db is currently located. (I wouldn't recommend this though.) You will need to ship with the app a copy of the empty database that you copy over when a new user starts using the app. You need to figure out what's the identifier of each user (username, hash of their email address, etc..)
If you want to upload the database, then you can do it via a HttpWebRequest, or ftp/sftp (if you have libraries handy).
My opinion is that you need to:

*

*use 1 database

*partition data by user id

*each user gets to see his/her own data

*encrypt the database if you are storing sensitive data


text:
Q: How to login Gerrit as Administrator I installed my gerrit on Ubuntu server.
As gerrit said:The first people who logined gerrit is Administrator.
So I logined first with openID (google account),and I am the Administrator indeed.
But,when next day I relogin gerrit with my google account, I become a new register. The id is 100001(Administrator 's id is 100000),but both email are google's email,and are same.
What happened?

A: The easiest way is to temporarily disable authenticated logins.
Edit your [auth] statement in gerrit.config to look like this:
[auth]
type = development_become_any_account

And then force login as the admin, grant yourself access and then restore the [auth] config.
Keep in mind that anyone with access to your server during this time will also be able to be any account, so setup a firewall or something to narrow access down to just your workstation while you complete the above steps.

A: gerrit automatically assign first login as administrator, and treat your google account as another id.
You can either

*

*login with openid and add google account id into administrator group as well

*manual change the database system_config for your google account.

see https://gerrit-documentation.storage.googleapis.com/Documentation/2.12.2/access-control.html#administrators
Hope it gives hints.

A: I faced a similar issue and found Shawn Pearce's reply on the mailing list to be useful:
https://groups.google.com/d/msg/repo-discuss/FkIPsL28OXM/OBJvKaMh-wgJ
HTH,


text:
Q: C#: How to implement an interface with an IReadOnly dictionary containing interface values from a concrete dictionary containing concrete values In my code, I am declaring internal classes and public interfaces, and I have a situation where I want to expose an interface with an IReadonlyDictionary containing values of a an interface type, but I want to implement it with a class having a Dictionary with values of a concrete type.
I need this because I am deserializing some JSON into a concrete type, and I want to expose the deserialized data as readonly.
I have implemented it as shown below, by lazily creating a new dictionary where concrete values are cast into the interface values. Is there a way to do this without having to create a new dictionary?
    // In this code I want to expose an IReadonlyDictionary<string,ISomeValue>.
    // The data is deserialized from JSON by using concrete type with a dictionary
    // with values of type SomeValue which has to have public getter/setters to be deserialized.
    // I would like to do this without copying and casting into a new dictionary as shown here.
    // Is that possible?

    public interface ISomeValue { }
    internal class SomeValue : ISomeValue { }

    public interface IConfiguration {
        IReadOnlyDictionary<string, ISomeValue> Values{ get; }
    }

    internal class Configuration : IConfiguration  {
        public Configuration() {
            _values = new Lazy<IReadOnlyDictionary<string, ISomeValue>>(()
            => Values.ToDictionary(x=>x.Key,x=>(ISomeValue)x.Value));
        }
        public Dictionary<string, SomeValue> Values { get; } = null!;
        private Lazy<IReadOnlyDictionary<string, ISomeValue>> _values;
        IReadOnlyDictionary<string, ISomeValue> IConfiguration.Values=> _values.Value;
    }

A:
I would like to do this without copying and casting into a new dictionary as shown here.

Well, you can't just directly return Value in the explicit interface implementation, because both generic parameters of IReadOnlyDictionary are generically invariant. If only TValue were covariant, you would have been able to directly do this:
public Dictionary<string, SomeValue> Values { get; } = new Dictionary<string, SomeValue>();
IReadOnlyDictionary<string, ISomeValue> IConfiguration.Values => Values;

But TryGetValue uses TValue as a parameter, IReadOnlyDictionary is forced to be invariant on TValue.
I suggest that you make your code look prettier in some other aspects. For example, you could extract that very long line of code that creates a new dictionary into an extension method.

A: You have to create a new object, but you don't have to create a copy of the original dictionary. Instead, you can create a view over the original dictionary, with the new shape. Here's some entirely-untested-but-simple code that I believe should work:
public class ReadOnlyDictionaryWrapper<TKey, TValue, TOriginalValue> : IReadOnlyDictionary<TKey, TValue>
    where TOriginalValue : TValue
{
    private readonly IReadOnlyDictionary<TKey, TOriginalValue> original;

    public ReadOnlyDictionaryWrapper(IReadOnlyDictionary<TKey, TOriginalValue> original) =>
        this.original = original;

    public TValue this[TKey key] => original[key];

    public IEnumerable<TKey> Keys => original.Keys;

    public IEnumerable<TValue> Values => original.Values.Cast<TValue>();

    public int Count => original.Count;

    public bool ContainsKey(TKey key) => original.ContainsKey(key);

    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() =>
        original.Select(pair => new KeyValuePair<TKey, TValue>(pair.Key, pair.Value))
                .GetEnumerator();

    public bool TryGetValue(TKey key, out TValue value)
    {
        bool ret = original.TryGetValue(key, out var originalValue);
        value = originalValue;
        return ret;
    }

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

I'd suggest creating a single instance of this in your Configuration constructor, to wrap _values.


text:
Q: Replace in SQL substring issue I would like to replace the all digits in a number with *, other than the last 4.
Here is my table:
Person
-----------
PersonID PersonBadgeNumber numeric(16,0)

A: Something like this will work...
DECLARE @badgeId Numeric(16, 0) = 1238985495;
SELECT
  REPLICATE('*', LEN(@badgeId) - 4) +
  RIGHT(@badgeId, 4);
-- Produces: ******5495

To use it in a query do this:
SELECT
  REPLICATE('*', LEN(PersonBadgeNumber) - 4) +
  RIGHT(PersonBadgeNumber, 4) RedactedBadgeNumber
FROM Person;

A: Another method is to use STUFF():
DECLARE @n numeric (16, 0);
SET @n = 1234567890123456;
SELECT STUFF(@n, 1, LEN(@n) - 4, REPLICATE('*', LEN(@n) - 4))

The above returns:
----------------
************3456


text:
Q: How to run a circuit with both 5V and 3V3 supply voltage? I'm currently designing a circuit requiring 3V3 (an ARM MCU) which should run on both 5V and 3V3 input.
Since the power requirements are fairly low, a linear voltage regulator should suffice.
I want to use L78L33 but I cannot find information regarding the voltage drop and minimum voltage requirement. Especially the graphs on page 26 only specify output characteristics of L78L05/12/24 but not L78L33.
Which regulator can be used to provide 3V3 with input voltage as low as 3V3?

A: 78Lxx Datasheet does show dropout vs current:

Note the 78Lxx (and 78xx) series chips set output voltage via their internal feedback resistor divider (see datasheet p. 3, R10/R11 on schematic) which is pretty much the only difference between all the output voltage variants in the series. So it is safe to assume the dropout voltage from 78L05 on the graph will be the same for 78L33.
EDIT: I should have read the datasheet a bit better. It's only a typical value,  there is no maximum dropout specified, and both 3.3V and 5V versions spec 2V typical dropout in the characteristics table, which disagrees with the graph.
So you'll have to use a LDO like this one.
If you have two different power inputs for 3.3V and 5V then you can route the 5V input through a regulator to make 3.3V, and route the 3.3V input directly to the circuit, bypassing the regulator. Then use the appropriate power input. This is the best solution.
If you have only one power input then you'll need a regulator with very low dropout voltage. Losing 50-100mV on 3.3V shouldn't be too much of a problem (check the datasheet of your micro and other chips you use for allowed voltage range, and pay special attention if you use VCC as ADC reference).
You can filter and sort LDOs by dropout voltage on digikey.
However, be aware that a 3V3 LDO which is powered from 3V3 will be in dropout mode, it will not regulate the output voltage. It will essentially be a fully turned on FET in series with the supply, ie pretty much a resistor, without any PSRR or voltage regulation.
Vocabulary notes:
1) Dropout voltage is the minimum difference between input voltage and output voltage to maintain proper regulation according to datasheet specs.
2) When the regulator is "in dropout" it means the difference between input and output voltage is too low for it to properly regulate. The output voltage will drop below spec, and the pass transistor will be saturated (if it's a BJT) or fully turned on and behave like a resistor (if it's a FET). The error amp will also be clipped. In this state the LDO no longer functions and does not honor its specifications, there is no regulation and PSRR is non-existent.


text:
Q: как при скроле вставлять в адресную строку ID что бы страница не лагала? я при скроле страницы в window.location.hash вставляю hash  соответствующий id блока до которого доскролил, и в адресной строке он появляется но при этом все лагае особенно при скроле вверх, а без этого кода все норм
    if ( $(document).scrollTop() > refElement.position().top) {
        window.location.hash = this.hash;
    }

реально ли убрать лаги ?
если честно то даже не знаю как сформулировать вопрос (((

$(document).ready(function () {
    $(document).on("scroll", onScroll);

    //smoothscroll
    $('a[href^="#"]').on('click', function (e) {
        e.preventDefault();
        $(document).off("scroll");

        $('a').each(function () {
            $(this).removeClass('active');
        })
        $(this).addClass('active');

        var target = this.hash,
            menu = target;
        $target = $(target);
        $('html, body').stop().animate({
            'scrollTop': $target.offset().top+2
        }, 500, 'swing', function () {
            window.location.hash = target;
            $(document).on("scroll", onScroll);
        });
    });
});

function onScroll(event){
    var scrollPos = $(document).scrollTop();

    $('#menu-center a').each(function () {
        var currLink = $(this);
        var refElement = $(currLink.attr("href"));
        if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
            $('#menu-center ul li a').removeClass("active");
            currLink.addClass("active");
            //console.log(this.hash)
            /*  решение проблемы  */
            if ( $(document).scrollTop() > refElement.position().top) {
                window.location.hash = this.hash;
            }

        }
        else{
            currLink.removeClass("active");
            // window.location.hash = this.hash;
        }
    });
}

Home

Portfolio

About

Contact

A: Попробуйте использовать window.history.pushState. Но это может не решить проблему.
Почитать о нем можно тут
Самое действенное на мой взгляд, это поставить timeout. Дело в том что событие scroll срабатывает очень часто.
1) создайте переменную, например timer
2) оберните ваш код в timeout
// обнуляете таймер
clearTimeout(timer)
// запускаете таймаут
timer = setTimeout(function() {
    clearTimeout(timer);
    if ( $(document).scrollTop() > refElement.position().top) {
        // меняете хэш
        window.location.hash = this.hash;
    }
}, 50)


text:
Q: Event Listeners on Dynamic Buttons I've been struggling with this for a while, I'm trying to build a program that makes use of the MVC pattern, that dynamically creates a grid of buttons (nxn) based on user input. I can't however get it right to attach listeners to them.
EDIT: I meant that I wanted to handle the event inside of the Controller class to conform to the MVC pattern
View
public class AIGameView extends javax.swing.JFrame {

private AIGameModel model;
private JButton[][] btn_arr;

public AIGameView(AIGameModel m) {
    model = m;
    initComponents();
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {...}

private void startBtnActionPerformed(java.awt.event.ActionEvent evt) {
    options.setVisible(false);
    int size = Integer.parseInt(size_field.getText());
    model.setSize(size);
    btn_arr = new JButton[size][size];
    GameGUI.setLayout(new java.awt.GridLayout(size, size));
    for(int y = 0; y < size; y++)  {
        for(int x = 0; x < size; x++)  {
            btn_arr[y][x] = new JButton();
            btn_arr[y][x].setBackground(Color.white);
            GameGUI.add(btn_arr[y][x]);
            btn_arr[y][x].setVisible(true);

        }
    }
    GameGUI.setVisible(true);
    GameGUI.revalidate();
    GameGUI.repaint();
}

Controller
public class AIGameController {

private AIGameView view;
private AIGameModel model;
private JButton[][] buttons;

public AIGameController(AIGameModel m, AIGameView v)    {
    view = v;
    model = m;
}

I've tried several things, but nothing seems to work for this and I mostly just end up with a null pointer exception. Any advice on this ?

A: From the code that you posted so far, it seems that you could add a call
btn_arr[y][x] = new JButton();
btn_arr[y][x].addActionListener(createActionListener(y, x));
...

With a method like
private ActionListener createActionListener(final int y, final int x)
{
    return new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            System.out.println("Clicked "+y+" "+x);

            // Some method that should be called in
            // response to the button click:
            clickedButton(y,x);
        }
    };
}

private void clickedButton(int y, int x)
{
    // Do whatever has to be done now...
}

A: When you're going through your initialisation loop :
for(int x = 0; x < size; x++)  {
  btn_arr[y][x] = new JButton();
  btn_arr[y][x].setBackground(Color.white);
  GameGUI.add(btn_arr[y][x]);
  btn_arr[y][x].setVisible(true);
  btn_arr[y][x].addActionListener( new YourListener() );
}


text:
Q: Display loading animation on the visible part of the page center I have a page with a container with a vertical scroll, and I want to add a loading animation on the visible part of page above the container. I tried div with class:
.loading-animation {
    height:100vh;
    background: url(img/loading.gif) 50% 50% / 100px 100px fixed no-repeat;
}

but it appeared at the bottom of the page, below my container. Then I tried
.loading-animation {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 10;
    background: url('img/loading.gif') 50% 50% / 100px 100px no-repeat;
}

and this appeared above my container but in the middle of all the page, not the visible area. Any ideas how to achieve this appreciated
Edit1, javascript:
var loading_animation;

function showLoadingAnimationModal() {
    loading_animation = document.createElement("div");
    loading_animation.style.cursor = "progress";
    loading_animation.className = "loading-animation";

    document.body.appendChild(loading_animation);
}

function hideLoadingAnimationModal() {
    if (loading_animation.parentNode == document.body) {
        document.body.removeChild(loading_animation);
    }
}

html template (using emberjs):

A: here is fiddle
css
.maindiv{
 position: relative;
}
.loader
{
  position:absolute;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%;
   z-index: 10;
   background: rgba(0,0,0,0.5);
}
.loader span
{
  height:30px;
  width:100px;
  padding:10px;
  margin:auto;
  top:0px;
  right:0px;
  left:0px;
  bottom:0px;
  position:absolute;
  background:#ddd;

}
.scrolldiv
{
  height:200px;
  overflow:auto;

}

HTMl

          Loading

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.


text:
Q: Delete ActionResult .Net Core I get error 'Operator '==' cannot be applied to operands of type 'string' and 'int?' on this line
      .FirstOrDefaultAsync(m => m.Id == id);

I haven't tried anything except this method so far.
  public class EditProfileController : Controller
{

    private readonly ApplicationDbContext db;
    private object _context;

    public EditProfileController(ApplicationDbContext Db)
    {
        db = Db;
    }
    public IActionResult Index()
    {
      List<ApplicationUser> listdata = db.Users
        .Select(user => new ApplicationUser()
        {
            Id =  user.Id,
            UserName = user.UserName,
            NormalizedUserName = user.NormalizedUserName,
                            Email = user.Email

            // Add the remainder properties
        }).ToList();
    return View(listdata);
    }
    [HttpGet]
    public ActionResult Edit(string id)
    {
        //Get user and return the Edit View
        ApplicationUser user = db.Users.Where(u => u.Id == id)
      .Select(u => new ApplicationUser()
      {
          Id = u.Id,
          UserName = u.UserName,
          NormalizedUserName = u.NormalizedUserName,
          Email = u.Email

          // Add the remainder properties
      }).FirstOrDefault();
        return View(user);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(ApplicationUser listdata)
    {
        if (ModelState.IsValid)
        {
            db.Entry(listdata).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(listdata);
    }

    public async Task<IActionResult> Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var user = await db.Users
            .FirstOrDefaultAsync(m => m.Id == id);
        if (user == null)
        {
            return NotFound();
        }

        return View(user);
    }

    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
     {
        var user = await db.Users.FindAsync(id);
        db.Users.Remove(user);
        await db.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
     }
  }

My expected results are when i click on the Delete link on the View page that it asks to confirm deletion and then once I click Yes or No it performs the DeleteConfirmed Action. What do I need to fix this error?

A: Change Delete(int? id) to Delete(string id) and DeleteConfirmed(int id) to DeleteConfirmed(string id) as follows:
public async Task<IActionResult> Delete(string id) // <-- Here it is
{
    if (id == null)
    {
        return NotFound();
    }

    var user = await db.Users.FirstOrDefaultAsync(m => m.Id == id);
    if (user == null)
    {
        return NotFound();
    }

    return View(user);
}

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id) // <-- Here it is
{
    var user = await db.Users.FindAsync(id);
    db.Users.Remove(user);
    await db.SaveChangesAsync();
    return RedirectToAction(nameof(Index));
}


text:
Q: htaccess http to https for domain and domain/paths I need to convert all http access to a domain including its potential pages under the main page, to its https equivalent. What I have now just directs all Domain and www.Domain access to https://Domain but not pages that are off the main page. How can I modify the htaccess commands so in addition I can get http://Domain/other-web-pages to go to https://Domain/other-web-pages
RewriteEngine On
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule (.*) https://example.com [L,R=301]

A: You are close. The redirection works, but you need to actually hand over the requested path too:
RewriteEngine On
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^ https://example.com%{REQUEST_URI} [QSA,L,R=301]

Such general should get implemented in the actual http server's central host configuration. If you have no access to that you can use a distributed configuration file instaed. Such file has to be placed inside the http server's DOCUMENT_ROOT folder.

A: (An alternative to @arkascha's answer, that builds on your existing code.)

:
RewriteRule (.*) https://example.com [L,R=301]

You are already capturing the requested URL-path (ie. (.*)) but not passing this through to the substitution string. So, all you need is the corresponding backreference ($1) that contains the URL-path. For example:
:
RewriteRule (.*) https://example.com/$1 [L,R=301]

And, if you have other directives, this needs to go near the top of the .htaccess file before any existing rewrites.
You will need to clear your browser cache before testing, since any erroneous 301 (permanent) redirects to the homepage will have been cached by the browser. Test with 302 (temporary) redirects to avoid such caching issues.


text:
Q: BeautifulSoup isn't recognizing UTF-8 characters even after using "fromEncoding=UTF-8" I wrote a simple script that just takes a webpage and extracts the contents of it to a tokenized list. However, I'm running into an issue where when I convert the BeautifulSoup object to a String, the UTF-8 characters for ",', etc. won't convert. Instead, they remain in the unicode format.
I'm defining the source as UTF-8 when I create the BeautifulSoup object, and I've even tried running a unicode conversion separately, but nothing works. Any have any idea why this is happening?
from urllib2 import urlopen
from bs4 import BeautifulSoup
import nltk, re, pprint

url = "http://www.bloomberg.com/news/print/2013-07-05/softbank-s-21-6-billion-bid-for-    sprint-approved-by-u-s-.html"
raw = urlopen(url).read()
soup = BeautifulSoup(raw, fromEncoding="UTF-8")
result = soup.find_all(id="story_content")
str_result = str(result)
notag = re.sub("<.*?>", " ", str_result)
output = nltk.word_tokenize(notag)
print(output)

A: The characters you're having trouble with aren't " (U+0022) and ' (U+0027), they're curly quotes " (U+201C) and " (U+201D) and ' (U+2019). Convert those to their straight versions first, and you should get the results you're expecting:
raw = urlopen(url).read()
original = raw.decode('utf-8')
replacement = original.replace('\u201c', '"').replace('\u201d', '"').replace('\u2019', "'")
soup = BeautifulSoup(replacement)  # Don't need fromEncoding if we're passing in Unicode

That should get the quote characters into the form you're expecting.


text:
Q: Compute; $\lim_{x\to\infty}\frac{(1-y^{x-1}\frac{x-1}{2})xy^{x-1}}{1-xy^{x-1}}$ with $0 \leq y <1$.
Prove that $$\lim_{x\to\infty}\frac{(1-y^{x-2}\frac{x-1}{2})xy^{x-1}}{1-xy^{x-1}}=1$$ where $x \in \mathbb{N}$ ($x \neq 0$) and $0 \leq y <1$.

I have managed to to multiply by $\frac{2}{2}$ to get
$$\lim_{x\to\infty}\frac{[2-y^{x-1}(x-1)]xy^{x-1}}{2-2xy^{x-1}}$$
And then, through expanding and rearranging :
$$\lim_{x\to\infty}\frac{(2-2xy^{x-1})xy^{x-1}+x^{2}y^{2x-2}+xy^{2x-2}}{2-2xy^{x-1}}$$
Which obviously results in :
$$\lim_{x\to\infty}\bigg(\frac{xy^{x-1}}{2-2xy^{x-1}}+\frac{x^{2}y^{2x-2}+xy^{2x-2}}{2-2xy^{x-1}}\bigg)$$
However I don't know how to go on from here.

A: The case $y=0$ trivialy gives zero. Let $y>0$

Now since $0<y<1\implies \ln y<0$ then
$$\color{red}{\lim_{x\to\infty } (x-1)\ln y =-\infty}$$
then, we have,
$$ \lim_{x\to\infty}   \frac{x-1}{2}y^{x-1} = \lim_{x\to\infty}\frac{x-1}{2}\exp\left((x-1)\ln y\right) \\\overset{\color{blue}{u=(x-1)\ln y}}{=}\frac{1}{2\ln y}\lim_{\color{red}{u\to-\infty}}u\exp\left(u\right) =0.$$
Similarly,  $$ \lim_{x\to\infty}xy^{x-1}  =0$$
Hence,
$$\color{blue}{\lim_{x\to\infty}\frac{(1-y^{x-1}\frac{x-1}{2})xy^{x-1}}{1-xy^{x-1}}=0} $$


text:
Q: How to get the html5 text box error mesage with selenium webdriver I wonder about how I can use selenium webdriver to find the error message text of a html5 input box ?

<input class="_input--inputElement--2mQgjB0b theme--inputElement--2WvFsoYo" role="input" type="text" value="" xpath="1">

Required

I tried different way but none seems working!!
String Emessage = Driver.driver.FindElement(By.XPath("//span[contains(text(),\'Required\')]")).getAttribute("Required");

String Emessage = Driver.driver.FindElement(By.XPath("//span[contains(text(),'Required')]")).Text;

A: Try this in Xpath - "//*[contains(@class,'_input--error') and contains(@class,'theme--error')]"


text:
Q: Как сделать выпадающее окно поверх текста? Есть кнопка button. Под ней текст. Как сделать, чтобы при наведении на нее плавно выпадало окно drop поверх этого текста, не отодвигая его вниз, а при отведении исчезало.

A: Можно как-нибудь так сделать, например (без js):

.drop {
  position: absolute;
  background-color: blue;
  height: 0;
  overflow: hidden;
  width: 100px;
  transition: .5s;
}
.drop p {
  text-align: center;
  color: white;
  margin-top: 35px;
}
button:hover ~ .drop {
  height: 100px;
}
<button>
Кнопка
</button>

Дроп

Тут какой-то текст

A: Мне вот эта реализация по душе. На чистом css+html5

/* Стили модального окна */
.modal-header h2 {
    color: #555;
    font-size: 20px;
    font-weight: normal;
    line-height: 1;
    margin: 0;
}
/* кнопка закрытия окна */
.modal .btn-close {
    color: #aaa;
    cursor: pointer;
    font-size: 30px;
    text-decoration: none;
    position: absolute;
    right: 5px;
    top: 0;
}
.modal .btn-close:hover {
    color: red;
}
/* слой затемнения */
.modal-wrap:before {
    content: "";
    display: none;
    background: rgba(0, 0, 0, .3);
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 101;
}
.modal-overlay {
    bottom: 0;
    display: none;
    left: 0;
    position: fixed;
    right: 0;
    top: 0;
    z-index: 102;
}
/* активация слоя затемнения и модального блока */
.modal-open:checked ~ .modal-wrap:before,
.modal-open:checked ~ .modal-wrap .modal-overlay {
    display: block;
}
.modal-open:checked ~ .modal-wrap .modal-dialog {
    -webkit-transform: translate(-50%, 0);
    -ms-transform: translate(-50%, 0);
    -o-transform: translate(-50%, 0);
    transform: translate(-50%, 0);
    top: 20%;
}
/* элементы модального окна */
.modal-dialog {
    background: #fefefe;
    border: none;
    border-radius: 5px;
    position: fixed;
    width: 80%;
    max-width: 500px;
    left: 50%;
    top: -100%;
    -webkit-box-shadow: 0 15px 20px rgba(0,0,0,.22),0 19px 60px rgba(0,0,0,.3);
    -moz-box-shadow: 0 15px 20px rgba(0,0,0,.22),0 19px 60px rgba(0,0,0,.3);
    box-shadow: 0 15px 20px rgba(0,0,0,.22),0 19px 60px rgba(0,0,0,.3);
    -webkit-transform: translate(-50%, -500%);
    -ms-transform: translate(-50%, -500%);
    -o-transform: translate(-50%, -500%);
    transform: translate(-50%, -500%);
    -webkit-transition: -webkit-transform 0.4s ease-out;
    -moz-transition: -moz-transform 0.4s ease-out;
    -o-transition: -o-transform 0.4s ease-out;
    transition: transform 0.4s ease-out;
    z-index: 103;
}
.modal-body {
  padding: 20px;
}
.modal-body p {
    margin: 0;
}
.modal-header,
.modal-footer {
    padding: 20px 20px;
}
.modal-header {
    border-bottom: #eaeaea solid 1px;
}
.modal-header h2 {
    font-size: 20px;
    margin: 0;
}
.modal-footer {
    border-top: #eaeaea solid 1px;
    text-align: right;
}
/* адаптивные картинки в модальном блоке */
.modal-body img {
    max-width: 100%;
    height: auto;
}
/* кнопки */
.btn {
    background: #fff;
    border: #555 solid 1px;
    border-radius: 3px;
    cursor: pointer;
    display: inline-block;
    font-size: 14px;
    padding: 8px 15px;
    text-decoration: none;
    text-align: center;
    min-width: 60px;
    position: relative;
}
.btn:hover, .btn:focus {
    background: #f2f2f2;
}
.btn-primary {
    background: #428bca;
    border-color: #357ebd;
    color: #fff;
}
.btn-primary:hover{
    background: #66A1D3;
}

Открыть

  <input class="modal-open" id="modal-1" type="checkbox" hidden>

Заголовок

        ×

Здесь размещаете любое содержание...

        Отлично!

A:

$('.btn').on('mouseover', function(){
  $('.wnd').show(400)
})

$('.btn').on('mouseout', function(){
  $('.wnd').hide(400)
})
.wnd {
  display: none;
  position: absolute;
  z-index: 100;
  padding:5px;
  background:#fff;
}

.btn-wrapper {
  position: relative;
}

    <button class="btn">Я кнопка</button>

А я всплывающее окно

    Привет, я текст под кнопкой


text:
Q: JIT Optimization float problems Background
So I'm making a simple game of unfair hangman in C# (there's a list of words that are valid solutions based on the information I've to the player (e.g. word length) which dwindles down over time, and the player only wins when there's only one possible solution and they've guessed all the letters).
Anyway, the important thing to know is I have a line of code that looks like this:
availableWords.RemoveAll(word => AmountInCommon(word) != lowestInCommon);
(I remove all the words from the availableWords that have more letters in common with the letters the user has guessed than the word in availableWords with the least letters in common)
The problem is that this code only works when compiler optimizations are turned off.
Demo code showcasing the problem
class Program {
    static void Main() {
        float randomPowerOf2 = (float)Math.Pow(2, new Random().Next(-4, 5));

        float foo1 = Foo(3f); // some non power of 2
        float foo2 = Foo(randomPowerOf2);
        float baz = Baz();

        // prints false with compiler optimizations; true without compiler optimizations
        Console.WriteLine(Math.Round(Foo(3f), 2) == Math.Round(foo1, 2));

        // prints true with and without compiler optimizations
        Console.WriteLine(Math.Round(Foo(3f), 2) == Math.Round(foo1, 2));

        // prints true with and without compiler optimizations
        Console.WriteLine(Foo(randomPowerOf2) == foo2);

        // prints true with and without compiler optimizations
        Console.WriteLine(Baz() == baz);

        Console.ReadLine();
    }
    static float Foo(float divisor) {
        return 1 / divisor;
    }
    static float Baz() {
        return 1 / 3f;
    }
}

I assume this has something to do with how floating-point numbers work, but what confuses me is why toggling on and off compiler optimizations affects it. I'm guessing what I should do is just round the floats to 3 or so decimals of precision, since that's all I really need. Why does this happen and is my solution best-practice?
Edit:
I realized that in this case since the word length doesn't change I could just have AmountInCommon return the integer representing how many letters are in common instead of a float that represents the ratio of letters in common to word length. Your answers are still helpful though.

A: The short story
Don't compare floating point values for equality.
The first thing programmers usually do after making this remark, is to recommend using an Epsilon. However it's wrong. float.Epsilon is the smallest possible float greater than zero, however (and more importantly) it does not mean that it's the smallest difference between any two arbitrary floats. When comparing floats, the better practice is to choose a reasonable value to determine if two floats are "close enough" to be equal.
The problem with your code you are rounding the numbers first, which may include a significant differences that pops the round one way or the other.
The long story
From the ECMA Specs
9.3.7 Floating-point types

C# supports two floating-point types: float and double. The float and
double types are represented using the 32-bit single-precision and
64-bit double-precision IEC 60559 formats...
...
Floating-point operations may be performed with higher precision than
the result type of the operation. [Example: Some hardware
architectures support an "extended" or "long double" floating-point
type with greater range and precision than the double type, and
implicitly perform all floating-point operations using this higher
precision type.
...

Further more
The IEC 60559 standard doesn't specify exact values for the parameters of the extended floating-point format. It only specifies minimum values. The extended format used by Intel processors since the 8087 is 80 bits long, with 15 bits for the exponent and 64 bits for the significand. Unlike other formats, the extended format does leave room for the leading bit of the significand, enabling certain processor optimizations etc.
Example

The compilers
Now comes in the compilers. The compiler and jitter will try to optimise code at various points before it's executed on the CPU depending on how it is set to optimize (among other things).
Those optimisation will affect what is stored in memory, how, and what is set in registers and reorganise, as well as many other subtle instructions that may or may not happen (depending on a range of factors). Each one of these optimisation has the potential to non-deterministically change the result of floating point calculation. Which is your exact problem.
In Summary
When it comes to floating point arithmetic, don't ever rely on floating point equality. Additionally don't try and deterministically rely on results from the compiler, the jitter, your Cpu, the architecture, the platform, the release or the bitness of the application.
Compare floating point types within an expectable range (to you).


text:
Q: Cannot play RTSP video in VideoView in Samsung Galaxy S2 I'm trying to play a live RTSP video (from rtsp://media2.tripsmarter.com/LiveTV/BTV/) using VideoView, and here's my code:
public class ViewTheVideo extends Activity {
    VideoView vv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        vv = (VideoView) this.findViewById(R.id.VideoView);

        Uri videoUri = Uri.parse("rtsp://media2.tripsmarter.com/LiveTV/BTV/");
        vv.setMediaController(new MediaController(this));
        vv.setVideoURI(videoUri);
        vv.requestFocus();
        vv.setOnPreparedListener(new OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                vv.start();
            }
        });
    }
}

This code works fine on Samsung Galaxy Y, and even on the emulator too, but it doesn't run on Samsung Galaxy S2 (Sorry, this video cannot be played)! Both the devices and the emulator are running Gingerbread.
Here's the LogCat messages:
07-30 10:48:28.310: I/MediaPlayer(24573): uri is:rtsp://media2.tripsmarter.com/LiveTV/BTV/
07-30 10:48:28.310: I/MediaPlayer(24573): path is null
07-30 10:48:28.310: D/MediaPlayer(24573): Couldn't open file on client side, trying server side
07-30 10:49:13.025: W/MediaPlayer(24573): info/warning (1, 26)
07-30 10:49:13.025: I/MediaPlayer(24573): Info (1,26)
07-30 10:49:13.075: E/MediaPlayer(24573): error (1, -1)
07-30 10:49:13.075: E/MediaPlayer(24573): Error (1,-1)
07-30 10:49:13.075: D/VideoView(24573): Error: 1,-1

I could not figure out what those error codes are about.
Is there any issues with Samsung Galaxy S2 with streaming? I also tried with a YouTube stream (rtsp://v2.cache2.c.youtube.com/CjgLENy73wIaLwm3JbT_9HqWohMYESARFEIJbXYtZ29vZ2xlSARSB3Jlc3VsdHNg_vSmsbeSyd5JDA==/0/0/0/video.3gp), but it's all the same.
Update:
Later I recorded a video with Galaxy S2 (Format: 3GP, Encoder: H.264, Bitrate: 56kbps, Framerate: 15fps) and streamed the video from the PC using VLC media player. This one can be viewed in Galaxy S2 (and others) without any error. However, no other video could be played on S2.

A: @Andro Selva this is how I streamed his link
 video_url = "rtsp://media2.tripsmarter.com/LiveTV/BTV/";
try {
            videoView =(VideoView)findViewById(R.id.videoView1);
            //Set video link (mp4 format )
            Uri video = Uri.parse(video_url);
            videoView.setVideoURI(video);
            videoView.setOnPreparedListener(new OnPreparedListener() {
            public void onPrepared(MediaPlayer mp) {

                videoView.start();
                }
            });
         }catch(Exception e){
         }


text:
Q: Redirect any non-existing page on domain, to Main Page WordPress I want to redirect any page that the user can type wrong to Main page.
Example:
I have pages
mydomain.com/home
And
mydomain.com/contact
any other pages i want to be redirected to Home.
I heard about 404.php and .htaccess files, but i don´t know how to make a simple redirect.

A: Insert this into your .htaccess (place it into the web root if not present):
ErrorDocument 404  "insert home page (index.php)"

https://httpd.apache.org/docs/2.4/custom-error.html


text:
Q: After updating to Creators Update, the lock screen forgets my username This is a new one on Windows for me:
After I upgraded my Windows 10 install to Creators Update, any time I sign out or lock the screen (Win+L), I have to enter not only my password, but also my username.
Before this update, this only happened after poweroffs and reboots (which also was  a bit weird to me).
Is this a Creators Update issue, or somehow related to a company wide IT policy? (I prefer not to ask them as they're useless).


text:
Q: Encoded Absolute URL missing last character I'm trying to get the encoded absolute URL for a newsfeed post. however if the Title of the newsfeed post has a special character at the end, eg ! (exclamation point), it does not include that to an hyperlink in Sharepoint Designer.
example:
https://mycompany.sharepoint.com/Lists/NewsFeed/HelloWorld!
it only makes the link without the ! (exclamation point), hence when the recipient of the link in email clicks on it, it does not go to the actual URL
Any workarounds for this?


text:
Q: How to find this function's discontinuity points? I came across this function:
$$f(x)=\lim_{n\to \infty}{({e^{\frac{1}{x}})\arctan{1\over{1+x}}}\over{x^2+e^{nx}}}$$
To get rid of the limit, we treating $x$ as a constant,when $x >0, e^{nx} \to +\infty,  \ f(x)=0$.
However, what confuses me is that $x$ is not a constant at its essence. when $x\to0^+$, $e^{1 \over x} $ goes to infinity and simply conclude $e^{nx} \to+\infty$ is a bit reckless to me. Is there any explanation for that?

A: \begin{align*}
f(1)&=\lim_{n\rightarrow\infty}\dfrac{e^{1/1}\tan^{-1}(1/(1+1))}{1^{2}+e^{n}}=0\\
f(0.5)&=\lim_{n\rightarrow\infty}\dfrac{e^{1/0.5}\tan^{-1}(1/(1+0.5))}{(0.5)^{2}+e^{(0.5)n}}=0\\
f(x)&=\lim_{n\rightarrow\infty}\dfrac{e^{1/x}\tan^{-1}(1/(1+x))}{x^{2}+e^{nx}}=0
\end{align*}
for $x>0$ is then perceived in the similar way.

A: Well if $x$ is fixed, no matter how close to $0^+$ and no matter how large $e^{1/x}$ is, the function is defined as a limit when $n\to\infty$. $n$ acts here as a dummy variable, and to see why the limit is 0 just take an enormous value, like for instance $n=1/x^3$ in your case. You'll see that for every $x$ you take, there is an $n$ such that the expression inside the limit is arbitrarily small.


text:
Q: Getting Error in config.txt file of NetSim Simulator When I open NetSim's Config.txt file after Simulation I get the following error:
Error in config file ---
1) Unknown xml tag "UPDATE_TIMER" in line number 166.
Tag path: TETCOS_NETSIM/NETWORK_CONFIGURATION/DEVICE_CONFIGURATION/DEVICE
[3] /LAYER [2]/ROUTING_PROTOCOL/PROTOCOL_PROPERTY

However, Simulation runs Successfully. What does this mean?

A: You need to specify the missing parameters in the Configuration file which are mentioned in the "ConfigLog.txt". Since, NetSim will crash if all the required parameters are not configured, NetSim addresses this issue by enabling default values where ever required. Error produced in the "ConfigLog.txt" because the value for the "UPDATE_TIMER" for "ROUTING_PROTOCOL" is not specified in the Configuration file. In order to obtain accurate metrics for the desired scenario you need to update your Configuration.xml file.


text:
Q: Inner join query returning empty set I have two tables with  varchar columns having common values.
I am trying to perform a simple inner join on the tables on those varchar columns but I am getting empty set as a result.
There are null values present in these columns.
Collation for both columns are same.
I googled for it but cant find a solution.
The query is a simple join query and doesn't have any syntax issues.
When I change the inner to left join I get a resultset but all the columns in the right table are empty even for the rows passes the join condition.
I created two dummy tables with a common varchar to run a join query and it works.
So it is not a bug.So what are the possible reasons for getting empty sets any guesses.
The server is mysql version 5.5.37
update a set  a.id=x where a.col in(Select col from b where .....);

Another issue is that i have a query like above but when I run it It kind of hangs...On running
    SHOW PROCESSLIST;
the status is sending data...
What does it mean?
Can anyone help me.
Edit 1
The query is like this
UPDATE table1 bo INNER JOIN table2 ae
ON bo.joincol=ae.joincol AND ae.criteriaFieldName='UNSPSC' AND ae.taskId=4     AND ae.batchId = 44
SET  bo.taskid=ae.taskId WHERE bo.procesId = 44 AND (taskid IS NULL OR taskid = 0);

Table1 contains 50+ columns
Table2 contains 8 columns
Unfortunately I can't disclose the data.
Interesting fact is if I join them using taskId I get a resultset.

A: For your second issue, try doing it as a JOIN instead of using IN:-
UPDATE a
INNER JOIN b
ON a.col = b.col
WHERE ........
SET  a.id=x


text:
Q: prime ideals in regular local rings Suppose $R$ is a regular local ring. Let $m$ be the maximal ideal. Then, if the dimension of $R$ is $n$, there is a regular sequence of size $n$, say $x_1,x_2,...,x_n$ s.t. $m=(x_1,x_2,...,x_n)R$. Further, the ideals $(x_{i_1},...,x_{i_j})$ with $i_1,...,i_j\in {1,...,n}$, are prime.
Can we make similar statements about any other kind of prime ideals in a regular local ring $R$? Specifically, do any other prime ideals satisfy the condition: if the ideal is minimally generated by a certain set of generators, then every subset of the generators defines a prime ideal? One example in light of the first paragraph, are the prime ideals generated by a subset of the regular sequence that generates the maximal ideal.
Also, when does a regular sequence define a prime ideal in a regular local ring $R$, and when does a maximal regular sequence define a maximal ideal?

A: As Sandor pointed out, a necessary condition is that the prime ideal $P$ is a complete intersection. Here is a proof that it is also sufficient. It will suffice to prove the following:
Claim: Let $(R,m)$ be a Noetherian local ring and $x\in m$ a regular element on $R$. If $R/(x)$ is a domain, then so is $R$.
Proof: Suppose $ab=0$ in $R$. Then modulo $x$, one of them say $a$, must be $0$. So $a=xa_1$, thus $x(a_1b)=0$. As $x$ is regular, $a_1b=0$, and continuing in this fashion one of $a,b$ must be divisible by arbitrary high power of $x$, so it must be equal to $0$.
As for an example which is not a part of a regular s.o.p, take something like $P=(x^2+y^2+z^2, u^2+v^2+w^2)$ in $\mathbb C[[x,y,z,u,v,w]]$.

A: EDIT: Rephrased the answer in light of Koose's comment.
Claim. Any ideal satisfying the required property  has to be a complete intersection.
Proof. Let $\mathfrak p\subset R$ be a prime ideal. Assume that the minimal number of generators for $\mathfrak p$ is $r$ and let $a_1,\dots,a_r\in\mathfrak p$ be a set of generators. Let $I_t=(a_1,\dots,a_t)$ and one has the sequence of ideals:
$$
0\subsetneq I_1 \subsetneq \dots \subsetneq I_t\subsetneq I_{t+1}\subsetneq \dots\subsetneq I_r=\mathfrak p
$$
The containments cannot be equalities, because that would make the corresponding $a_i$ unneeded to generate $\mathfrak p$. If all the $I_t$'s are prime, then $\mathfrak p$ has height at least $r$, but it cannot be more than that, so the claim is proven. $\square$
Example. Take an irreducible projective variety (say the twisted cubic curve) that is not a complete intersection (in projective space). Then the ideal of the affine cone over this in the affine cone over projective space will be a prime, but if you take away one of the generators, that will not be.


text:
Q: passing JavaScript array of long to code behind? I have returned object from signature device and when i make quick watch on it, it told me that its an array of long and when i pass it to web method in my code behind (vb.net) it gives me nothing.
i need some help..
note: i'm using an activeX to capture the signature from the device.
this is javascript code :
function OnSave() {
    var sign = document.FORM1.SigPlus1.SignatureString;
    PageMethods.Save(sign);
    }

this is my webmethod:
<WebMethod()> _
Public Shared Function Save(ByVal obj As Object) As String

    Dim obj1 As New PFSIGNATURELib.SigniShellSignature
    obj1.SignatureMime = obj
    obj1.SaveBitmapToFile(System.AppDomain.CurrentDomain.BaseDirectory() & "\sign1.bmp", 200, 200)

    Return "\sign1.bmp"
End Function

A: I don't know much about ASP.Net, but it seems like the PageMethods.Save function can't handle an array of long. Another possibility is that the sign variable is null in the javascript code.
Try adding
alert(sign);

in the middle your Javascript function, or better yet, install firebug and do
console.log(sign);

instead. This way you'll make sure the sign var actually contains what you think it does.
If it indeed contains an array of numbers (javascript doesn't have a long type), maybe you need to convert it to something else before calling the PageMethods.Save function.
For example, this javascript snippet will convert sign into a space-separated string of numbers:
s = ""
for (i in sign) {
    s += sign[i] + " ";
}
sign = s

If you manage to pass this string to your webmethod, you can use some string parsing to get back the original array.


text:
Q: List users in a dropdown for login I have a loginscript that works. Now I want to expand the login functions with a dropdown filled with all users.
This is the login:

<?php
    $login  = (isset($_GET['login']) ) ? $_GET['login'] : 0;
    if ( $login === "failed" ) {
        echo '
ERROR: users/pass doesn't match
';
    } elseif ( $login === "empty" ) {
        echo '
ERROR: user/pass empty
';
    } elseif ( $login === "false" ) {
        echo '
 logged out.
';
    }
?>
<?php
    $args = array(
        'redirect' => get_bloginfo('url'),
        'id_username' => 'user_login',
        'id_password' => 'user_pass',
        'remember'    => false,
        'label_log_in' => __( 'Login' ),
        )
    ;?>
    <?php wp_login_form( $args ); ?>

With the help of the WP-codex I created the following:
<?php
    $blogusers = get_users( 'blog_id=1&orderby=nicename&role=subscriber' );
    echo '<select>';
    foreach ( $blogusers as $user ) {
        echo '<option value="'. esc_html( $user->user_login ).'">' . esc_html( $user->user_login ) . '</option>';
        }
    echo '</select>';
?>

This gives me all the users by login name.
The only thing I can't figure out is how to let the drop-down be the login part.
Hope it's something small!
M.
---------------------- UPDATE ----------------------
So this happend:
$blogusers = get_users( 'blog_id=1&orderby=nicename' );
$return = ' ';
foreach ( $blogusers as $user )
    {
        $login = $user->user_login;
        $return .= '<option value="'.$login.'">' . $login . '</option>';
    }

This returns the values in a variable.
I use the variable in the $args like this.
id_username' => '<select>'.$return.'</select>',

The problem is that the wp_login_form expects an <input> element and not an <select> element.
This is stupid. It only adds the value to the id of the element..... Do'h!!!
I found that the  is hardcoded in the form. Can I change this?


text:
Q: Tree Traversal to swap two nodes I just came across this problem and was wondering if I could come up with a right solution. The problem involves in swapping two nodes of a binary tree not just by value but by node. So this means that we have to change the right and left values too.

So lets say that we have a binary tree something like the above image. What I thought initially was to make an inorder traversal of the nodes so that I could flatten the tree and then just swap the elements and then reconstruct the tree from the swapped list. So literally the solution goes something like this
For the above mentioned tree, the inorder traversal would generate a list like this,
1,3,4,6,7,8,10,13,14.
Now I swap 8 and 13.
=> 1,3,4,6,7,13,10,8,14
But the problem here is, since I have flattened the tree now when I try to reconstruct I am not able to do so because I don't know the position of individual nodes , like whether the particular node is a left subchild or if it is a root. So literally the tree cannot be regenerated like the same as it was initially with the swapped nodes.
Now the question is whether I could modify my traversal algorithm to hold the position information of each of the nodes so that when I swap the elements and reconstruct I come up with the same binary tree with the desired nodes swapped? Can we store the state/position of individual nodes during inorder traversal?
PS. I recognize that doing a post-order would make my list with first and last nodes to be swapped but the two nodes that needs to be swapped need not necessarily be at the root and right most element, it can be any two.

A: There are few ambiguities in your question. The tree in your example in BST ( though a BST is also a Binary Tree) and the final answer can break the BST property. I presume thats what the answer needs to be. Correct me if I am wrong.
As far as answer is concerned, there are 2 solutions.
One, I can think of, talking in terms of traversal and flattening, you cannot re-contruct a tree with just one traversal. You need 2 traversals to construct a tree. It could be either of the below

*

*Pre order and an In order

*Post order and an In order

*Level order and an In order

So do the swapping on any of the 2 traversals and recontruct. That should give the answer.
The second solution is a much better and efficient solution because the Time Comp is O(n). In this method, make a traversal on the whole tree and get the reference pointers to the 2 candidate nodes. Once you have the references , use a temp variable to swap the information..This method is complex but both space and time efficient than the previous approach.

Hope it is not a HW question, if so please tag it !
Eg :
            4
        2       6
      1   3   5   7

The order traversal for this tree looks like this:
Pre : 4 2 1 3 6 5 7
Inorder : 1 2 3 4 5 6 7
Now you know that 4 is the root of this tree (Since root gets printed as the first element for Preorder). Based on 4 now split the traversals.
Now the left sub-tree becomes
Pre : 2 1 3 ; Inorder : 1 2 3
and the right sub-tree becomes
Pre : 6 5 7 ; Inorder : 5 6 7
Keep doing this recursively , that will the answer !


text:
Q: ansible: how to execute a custom module that is only installed on the delegate_to and not on the controller? I ran into a (for me) unexpected issue with ansible when trying to execute the following:
# myplaybook.ansible.yml
- hosts: myhost2

  tasks:
  - name: Execute pgsql query
    community.postgresql.postgresql_query:
      ...

where myhost1 is the controller executing ansible-playbook -v myplaybook.ansible.yml.
On the target host myhost2 community.postgresql.postgresql_query is installed with ansible-galaxy install and the dependencies (notably psycopg2) satisfied.
The problem:
ansible bombs out before actually evaluating the playbook because it can't find the postgresql_query module on the controller, but the whole purpose of running this on myhost2 is to avoid having to install such dependencies on the controller in the first place.
Similarly, I'd also like to be able to execute the above like this, which obviously doesn't work for the same reason:
# myplaybook.ansible.yml
- hosts: myhost3

  tasks:
  - name: Execute pgsql query
    delegate_to: myhost2
    community.postgresql.postgresql_query:
      ...

The Question
How to only evaluate an ansible module called in a task on the target or delegate host?


text:
Q: Silverlight: use GradientBrush resource for state animation I have a set of controls (Button, ToggleButton) I want to have the same style, so I have created a few gradient brushes for normal/disabled/enabled states in my ResourceDictionary, e.g. "ButtonFillBrush", "ButtonFillMouseOverBrush" etc. These are defined as global reusable Brush Resources.
I know it is possible to change individual stops of a gradient in a animation inside a state, for example:
<VisualState x:Name="MouseOver">
   <Storyboard>
      <ColorAnimation Duration="0" To="#FF041D06" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[1].(GradientStop.Color)" Storyboard.TargetName="path" d:IsOptimized="True"/>
      <ColorAnimation Duration="0" To="#FF118519" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[0].(GradientStop.Color)" Storyboard.TargetName="backgroundRectangle" d:IsOptimized="True"/>
    </Storyboard>
</VisualState>

Now, I know it is possible in the VisualState Manager to do something like:
<VisualState x:Name="MouseOver">
   <Storyboard>
      <ColorAnimation Duration="0" To="ButtonFillMouseOverBrush" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush)" Storyboard.TargetName="backgroundRectangle" d:IsOptimized="True"/>
    </Storyboard>
</VisualState>

Thanks!
Update: using the answer about the referring with the StaticResource and some more searching: http://wildermuth.com/2008/07/18/Animating_Brushes_with_ObjectAnimationUsingKeyFrames
<VisualState x:Name="MouseOver">
  <Storyboard>
    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="backgroundRectangle"
Storyboard.TargetProperty="Fill">
      <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{StaticResource ButtonFillMouseOverBrush}" />
    </ObjectAnimationUsingKeyFrames>
  </Storyboard>
</VisualState>

So, it would be nice to have a BrushAnimation or something...
Rogier

A: You can find more information regarding Resource Dictionaries & the use of them here. However for your color animation question a lot of information regarding Silverlight animations (including color animations) can be found on this link Silverlight Animations Quickstart


text:
Q: Prove the orthogonal complement of a nonempty subset of a Hilbert space is closed. Statetment
Let $M \subset H$ be nonempty, and $H$ is a Hilbert space. Then $M^\perp$ is a subspace, and $M^\perp $ is closed.
Proof
To show that $M^\perp$ is a subspace we let $x,y \in M^\perp$, $a,b \in \mathbb{R}$, and let $v \in M$ be arbitrary. Then
$$\langle ax + by , v \rangle = a\langle x, v \rangle + b \langle y, v \rangle = 0$$
which implies $ax + by \in M^\perp$.
Now, to show $M^\perp$ is a closed subspace of $X$, we must show that if $x$ is a limit point of $M^\perp$ that $x$ is in $M^\perp$. So, let $x$ be a limit point of $M^\perp$. By definition of a limit point, there exists a sequence $(x_n)$ in $M^\perp$ such that $x_n \longrightarrow x$ as $n \longrightarrow \infty$. And, since $x_n \in M^\perp$, we have $\langle x_n, v \rangle = 0$ for all $n = 1, 2, ...$ and $v \in M$. So, by continuity of the inner product we observe
\begin{equation}
0 = \langle x_n, v \rangle \tag{$v\in M$}\\ \text{
} \\
\implies 0 = \lim_{n\to \infty} \langle x_n, v \rangle = \langle \lim_{n\to \infty} x_n ,v \rangle = \langle x, v \rangle
\end{equation}
where $v \in M$ is arbitrary. So, $x \perp M$, and therefore $x \in M^\perp$. And since $x$ is an arbitrary limit point of $M^\perp$, we conclude that $M^\perp$ is closed.

Just looking for verification and/or comments on clarity. Thank you.


text:
Q: how do you build one of those tab style buttons in flutter? I mean this which only allows one option to be selected

A: You can use CupertinoSegmentedControl https://api.flutter.dev/flutter/cupertino/CupertinoSegmentedControl-class.html


text:
Q: MRTK V2.2 - Access Speech Command via Script In my scenario, buttons are created during runtime. These are to be clicked by a voice command. For this reason I try to find out how I can add voice commands during runtime. But I can't find any approach.
What I tried:
I have extended the interface IMixedRealitySpeechSystem with two methods, RefreshRecognition and AddSpeechCommand:
/// <summary>
/// Refresh recognition after adding new commands
/// </summary>
void RefreshRecognition();

/// <summary>
/// Add command to already existing commands[]
/// </summary>
/// <param name="command"></param>
void AddSpeechCommand(SpeechCommands command);

I have implemented these in the class WindowsSpeechInputProvider: MixedRealitySpeechSystem. But there are two problems.
First: I can't get to the WindowsSpeechInputProvider. I thought I could get it by trying this:
private IMixedRealitySpeechSystem SpeechSystem
{
    get
    {
        if(_speechSystem is null)
        {
            MixedRealityServiceRegistry.TryGetService(out _speechSystem);
        }
        return _speechSystem;
    }
}

public void SomeMethod()
{
    SpeechCommands command = new SpeechCommands("TestCommand", default, default, null);
    SpeechSystem.AddSpeechCommand(command);
    SpeechSystem.RefreshRecognition();
}

But the problem is that MixedRealityServiceRegistry does not contain an instance of that service or to be precise, it is not even a service.
Second: Even if this would work, it is not a good way to go. Because with this I change the MRTK and with another upgrade to a new version, these lines are overwritten.
My Question:
So how can I access and add commands on runtime?

A: There's an open feature request to allow adding dynamic speech commands in Github: Add keywords dynamically to MRTK speech commands #6369. It is not currently possible.
This thread has some suggestions for alternative ways to approach the overall scenario. In summary, it is recommended that you use a Grammar Recognizer and use an SRGS XML file to define your speech recognition rules. Voice input in Unity and Hologram 212 has an example showing how to use it.


text:
Q: Image Description on Hover Image Link I have a page with 9 images. Each image links to page about that project. I want the project name and a faded color to appear when one hovers over the image. I cannot figure out if this is something that I can do with the hover definition of the link style, or if I need to use javascript. I also do not know if I need multiple divs overlapped-- expecially because I want the fade color to cover the entire image, but the text to be left-indented.
Below you will find the divs of the top row of images as just place holders.

PROJECT TITLE

PROJECT TITLE

PROJECT TITLE

A: Click for Demo
Html

    Image Description

Css
#Descprition{
    display:none;
}

img:hover + #Descprition{

    display:block;
}

A: You could do something like this: http://jsfiddle.net/y3Vyb/
HTML

This is a caption

This is a caption

This is a caption

CSS
.thumbnail{
  float: left;
  margin: 10px;
  position: relative;
}

.thumbnail-caption{
  background: red;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0.6;
  display: none;
}

.thumbnail:hover .thumbnail-caption {
  display: block;
}


text:
Q: Trying to have Vue.js show options answers in two areas what I have read Vue.js Options allows you to have two items in the array and bind them together. So you can pick one and the other array value is connected. What I am trying to do is attach the third option in the array and have it show on the webpage.

    Select year of rain fall<select v-model="selected" v-model="information">
        <option v-for="option in options" :value="option.value" :copy="option.copy">{{ option.text }}</option>
    </select>

    Amount of rain: {{ selected }}

    Information: {{ information }}

I have a jsfiddle

A: it doesn't work like that natively, but it's easy to implement with a bit of javascript
http://jsfiddle.net/0k1uq7u9/3/

Chicago's Top Ten Wettest Years

    Select year of rain fall<select v-model="selected" @change="updateInformation">
        <option v-for="option in options" :value="option.value">{{ option.text }}</option>
    </select>
    Amount of rain: {{ selected }}
    {{ information }}

var vm;
vm = new Vue({
    el: "#rain_fall",
    data: {
        selected: '50.86',
        information: 'test',
        options: [
            {text: "2008", value: "50.86", copy: "test"},
            {text: "2011", value: "49.83", copy: "test2"},
            {text: "1983", value: "49.35", copy: "test3"},
            {text: "1970", value: "46.09", copy: "test4"},
            {text: "1954", value: "45.92", copy: "test5"},
            {text: "1883", value: "45.86", copy: "test6"},
            {text: "2001", value: "45.77", copy: "test7"},
            {text: "1993", value: "44.90", copy: "test8"},
            {text: "1982", value: "44.58", copy: "test9"},
            {text: "1885", value: "44.37", copy: "test10"}
        ]
    },
    computed: {
        // a computed getter
      copyInformationGetter: function () {
        return this.information
      },
    },
    methods: {
        updateInformation() {
        const index = this.options.findIndex(option => option.value === this.selected)
        this.information = this.options[index].copy
    }
   }

});

A: I would probably do it this way: use the whole data item as your selected and then you have the elements available to pull as you need them.
Setting the initial value takes a little special handling; if the options were available outside the Vue, you could initialize with options[0] (or whatever). You could also just do that in the created rather than looking for a specific value.

var vm;
vm = new Vue({
  el: "#rain_fall",
  props: {
    initialValue: {
     type: String,
      default: '50.86'
    }
  },
  data: {
    selected: null,
    information: 'test',
    options: [{
      text: "2008",
      value: "50.86",
      copy: "test"
    }, {
      text: "2011",
      value: "49.83",
      copy: "test2"
    }, {
      text: "1983",
      value: "49.35",
      copy: "test3"
    }, {
      text: "1970",
      value: "46.09",
      copy: "test4"
    }, {
      text: "1954",
      value: "45.92",
      copy: "test5"
    }, {
      text: "1883",
      value: "45.86",
      copy: "test6"
    }]
  },
  methods: {
    setSelected(value) {
      this.selected = this.options.find(o => o.value === value);
    }
  },
  created() {
    this.setSelected(this.initialValue);
  }
});

Chicago's Top Ten Wettest Years

  Select year of rain fall
  <select v-model="selected">
    <option v-for="option in options" :value="option">{{ option.text }}</option>
  </select>
  Amount of rain: {{ selected.value }}
  {{ selected.copy }}


text:
Q: Prove that $\frac{10^n-1}{9n}$ is integer when $n=3^k$ I have no idea how to go about proving this. The furthest I've gotten is to say that the sequence equals 1/1, 11/2, 111/3, etc.
So that means that $\frac{10^a-1}{9}$ must be divisible by 3.
$\frac{10^a-1}{9} = 3b \implies 10^a-1 = 27b \implies 27b+1 = 10^a$.
When is that last statement true?

A: You can use induction to prove
$$\frac{10^n-1}{9n} \tag{1}\label{eq1A}$$
is an integer when $n = 3^k$. The base case of $k = 0$ gives $3^k = 1$, with \eqref{eq1A} becoming $\frac{10-1}{9} = 1$. Next, assume \eqref{eq1A} is an integer for $k = m$ for some integer $m \ge 0$. Then, for $k = m + 1$,
$$\begin{equation}\begin{aligned}
\frac{10^{3^{m+1}} - 1}{9(3^{m+1})} & = \frac{\left(10^{3^{m}}\right)^3 - 1}{\left(9(3^{m})\right)3} \\
& = \frac{(10^{3^{m}} - 1)(10^{3^{2m}} + 10^{3^{m}} + 1)}{\left(9(3^{m})\right)3} \\
& = \left(\frac{10^{3^{m}} - 1}{9(3^{m})}\right)\left(\frac{10^{3^{2m}} + 10^{3^{m}} + 1}{3}\right)
\end{aligned}\end{equation}\tag{2}\label{eq2A}$$
The first factor above is an integer based on the induction hypothesis, i.e., \eqref{eq1A} being an integer for $n = 3^{m}$. For the second factor, note
$$10 \equiv 1 \pmod{3} \implies 10^{3^{2m}} \equiv 10^{3^{m}} \equiv 1 \pmod{3} \tag{3}\label{eq3A}$$
This means
$$10^{3^{2m}} + 10^{3^{m}} + 1 \equiv 3 \equiv 0 \pmod{3} \implies 3 \mid 10^{3^{2m}} + 10^{3^{m}} + 1 \tag{4}\label{eq4A}$$
i.e., the second factor is also an integer. With the product of $2$ integers being an integer, \eqref{eq2A} shows \eqref{eq1A} is an integer for $n = 3^{m+1}$. This proves by induction that \eqref{eq1A} is an integer for $n = 3^k$ for all integers $k \ge 0$.

A: Using induction,
If $10^r=1+3^sk$ where $3\nmid k$
$$10^{3r}=(10^r)^3=(1+3^sk)^3=1+3^{s+1}k+3^{2s+1}k^2+3^{3s}k^3\equiv1\pmod{3^{s+1}}$$
for $s+1\le2s+1\iff  s\ge0,3s\ge s+1\iff 2s\ge1$
Now for the base case $r=1=3^0, s=2$
So, by using weak induction, $$10^{3^a}-1$$ is divisible by $3^{a+2}$ for $a\ge0$

A: The statement is equivalent to proving $$10^{3^k}-1\equiv_{3^{k+2}}0$$
Notice that $\phi(3^{k+2})=3^{k+2}-3^{k+1}=2\cdot 3^{k+1}$, so that for a unit $a$ we have $$a^{2\cdot 3^{k+1}}\equiv_{3^{k+2}}1$$ We also have

Claim: $$10^{3^k}\equiv_{3^{k+2}}10^{3^{k+1}}$$

Proof: $$10^{3^k}\equiv_{3^{k+2}}10^{3^{k+1}-2\cdot 3^{k}}\equiv_{3^{k+2}}10^{3^{k+1}}$$
Let $t=10^{3^k}$, then the above claim may be written as $$t^3\equiv_{3^{k+2}}t\iff t(t+1)(t-1)\equiv_{3^{k+2}}0$$ Both $t,t+1$ are units since $t,t+1\not\equiv_{3}0$, therefore we must have $t-1\equiv_{3^{k+2}}0$.

A: Recall a simple form (with simple proof)  of  LTE = Lifting The Exponent is
$$a\equiv b\!\!\! \pmod{kn}\,\Rightarrow\, a^k\equiv b^k\!\!\!\! \pmod{k^2n}$$
Applied inductively for $\,k=3\,$ (i.e. repeatedly cubing) yields the claim as follows
$$\begin{align}
&10^{\large 3^\color{#c00}0}\! \equiv 1\!\!\! \pmod{3^{2+\color{#c00}0}}\\
\Rightarrow\ &10^{\large 3^\color{#c00}1}\! \equiv 1\!\!\! \pmod{3^{2+\color{#c00}1}}\ \ \rm by\ \ LTE\\
\Rightarrow\ &10^{\large 3^\color{#c00}2}\! \equiv 1\!\!\! \pmod{3^{2+\color{#c00}2}}\ \ \rm by\ \ LTE\\
&\ \ \ \ \ \ \ \ \ \vdots\\
\Rightarrow\ &10^{\large 3^\color{#c00}k}\! \equiv 1\!\!\! \pmod{3^{2+\color{#c00}k}}\ \ \rm by\ \ LTE\\[.1em]
\Rightarrow\ &9\cdot 3^k\mid 10^{3^k}\!\!-1\\[.1em]
\Rightarrow\ & 9\cdot n\ \mid 10^n-1
\end{align}\qquad$$


text:
Q: LastPwdSEt is Not Updating by Updating a password I like to calculate the passowrd expiration date for the user in active directory
I am able to get the MaxPWdAge and LastPwdSet attributes.
But the problem is whenever i am changing the password of one of a user for testing purposes, lastPwdSet is not updating and it is still showing the old date?
Can anybody tell me why is this happen ?
public bool CheckPassWordExpiryDate(string LdapPath, string Username, string Password)
        {
            DomainConfiguration domainConfig = new DomainConfiguration();
            // Configuration(web.config) changes
            DirectoryEntry de = new DirectoryEntry("LDAP://" + LdapPath, domainConfig.UserName, domainConfig.Password);
            DirectoryEntry entry = new DirectoryEntry();
            entry.Username = Username;
            entry.Password = Password;

            //Function to get maximum password age from the active directory
            int maxPwdAge = GetMaxPasswordAge();

            // Function to get last password set date for the use.
            DateTime pwdLastSet = GetPwdLastSet("pwdLastSet", Username);

            //Add maximum password age days to Last password set days , if it is less than today's date means that password has been expired else it is not expired
            if (pwdLastSet.AddDays(maxPwdAge) < DateTime.Now)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static int GetMaxPasswordAge()
        {
            DomainConfiguration domainConfig = new DomainConfiguration();
            using (new SPMonitoredScope("AD Properties"))
            {
                using (DirectoryEntry domain = new DirectoryEntry("LDAP://" + domainConfig.DomainName, domainConfig.UserName, domainConfig.Password))
                {
                    DirectorySearcher ds = new DirectorySearcher(
                        domain,
                        "(objectClass=*)",
                        null,
                        SearchScope.Base
                        );

                    SearchResult sr = ds.FindOne();
                    TimeSpan maxPwdAge = TimeSpan.MinValue;
                    if (sr.Properties.Contains("maxPwdAge"))
                        maxPwdAge = TimeSpan.FromTicks((long)sr.Properties["maxPwdAge"][0]);
                    return maxPwdAge.Duration().Days;
                }
            }
        }
        public DateTime GetPwdLastSet(string attr, string UserName)
        {

            DomainConfiguration domainConfig = new DomainConfiguration();
            using (new SPMonitoredScope("AD Properties"))
            {
                using (DirectoryEntry domain = new DirectoryEntry("LDAP://" + domainConfig.DomainName, domainConfig.UserName, domainConfig.Password))
                {
                    //DirectorySearcher searcher = new DirectorySearcher(domain, "(|(objectClass=organizationalUnit)(objectClass=container)(objectClass=builtinDomain)(objectClass=domainDNS))");
                    DirectorySearcher searcher = new DirectorySearcher(domain);
                    searcher.PageSize = 1000;
                    searcher.Filter = "(SAMAccountName='" + UserName + "')";
                    searcher.Filter = "(|(objectCategory=group)(objectCategory=person))";
                    var user = searcher.FindOne();
                    DateTime pwdLastSet = DateTime.FromFileTime((Int64)user.Properties["PwdLastSet"][0]);
                    return pwdLastSet;
                }
            }
        }
    } }


text:
Q: Rabbitmq Fanout Exchange C# I have a problem about Rabitmq fanout exchange my problem is that I want to a publish subscribe example with rabbitmq and c#.So I created 2 project one them is Publisher and it is that
static void Main(string[] args)
{
      try
      {
          var factory = new ConnectionFactory() { HostName = "localhost" };
          using (var connection = factory.CreateConnection())
              using (var channel = connection.CreateModel())
              {
                  channel.ExchangeDeclare("example.exchange", ExchangeType.Fanout, true, false, null);
                  var message = GetMessage(args);
                  var body = Encoding.UTF8.GetBytes(message);
                  channel.BasicPublish(exchange: "example.exchange", routingKey: "", basicProperties: null, body: body);
                  Console.WriteLine(" [x] Sent {0}", message);
              }
        }
        catch (Exception ex)
        {
            Console.Write($"bir hata oluştu{ex.Message}");
        }
}

private static string GetMessage(string[] args)
{
    return ((args.Length > 0)
           ? string.Join(" ", args)
           : "info: Hello World!");
}

And i have a Consumer it is
    static void Main(string[] args)
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using (var connection = factory.CreateConnection())
        using (var channel = connection.CreateModel())
        {
            channel.ExchangeDeclare(exchange: "example.exchange",
            type:"fanout",durable:true);

            var queueName = channel.QueueDeclare().QueueName;
            channel.QueueBind(queue: queueName, exchange: "foo.exchange",
            routingKey: "");

            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                var body = ea.Body;
                var message = Encoding.UTF8.GetString(body);
                Console.WriteLine(" [x] {0}", message);
            };
            channel.BasicConsume(queue: queueName, autoAck: true, consumer: consumer);

            Console.ReadLine();
        }
    }

But i can't get messages.Why it could be?

A: So I find your issue. First of all your exchange declaration in your consumer is wrong.
You declare exchange as "example.exchange" in your publisher :
channel.ExchangeDeclare("example.exchange", ExchangeType.Fanout, true, false, null);

But "foo.exchange" in your consumer :
channel.QueueBind(queue: queueName, exchange: "foo.exchange", routingKey: "");

Change "foo.exchange" to "example.exchange".
For your consumer, I'm able to consume messages with following lines:
public static void Main(string[] args)
{
    ConnectionFactory factory = new ConnectionFactory();
    factory.UserName = "guest";
    factory.Password = "guest";
    factory.HostName = "localhost";
    factory.VirtualHost = "/";

    var connection = factory.CreateConnection();
    var channel = connection.CreateModel();

    var queueName = "test-queue";
    channel.QueueDeclare(queueName, false, false, false, null);
    channel.QueueBind(queueName, "example.exchange", "", null);

    var consumer = new EventingBasicConsumer(channel);
    consumer.Received += (model, ea) =>
    {
        var bodyy = ea.Body;
        var messagee = Encoding.UTF8.GetString(bodyy);
        Console.WriteLine("received [x] {0}", messagee);
    };
    channel.BasicConsume(queue: queueName, autoAck: true, consumer: consumer);

    Console.ReadLine();
}


text:
Q: Laravel error putting 2 controllers to the same route and i need it to show my data to the frontend(i divided it into 2 controller to clean my code) Route::get(
'/',
[FrontendIntroController::class, 'index'],
[FrontendInfoController::class, 'index'],
)->name('intros.index','infos.index');

A: You cannot have one route pointing to two different controllers. It's not possible in Laravel and besides that is poor code practice. Rather what you should do is point the route to one controller and handle the data accordingly, depending if it is Intro or Info.


text:
Q: How to access ListItem position from contextMenu I'm working on a project that has list of ice cream flavors. When you long-click on a flavor you see a context menu with some options : picture, ingredients, price ect. If chocolate is long-clicked and you select picture, you should see a picture of chocolate ice cream...if you did the same for vanilla, you'd see vanilla ice cream.
Here's the problem. The selection you make within the context menu is related to the original flavor you long-clicked. I need to be able to access the position of the flavor within the flavor array. -- in the OnListItemClicked() method the position of my flavors array is accessible, however...the OnContextItemSelect() method is only aware of it's own selection items (picture,ingredient, price ).
You can see I had created a listPosition variable, but I've realized that this would only work if a flavor was clicked quickly using the OnListItemClicked() as opposed to long-clicked using OnContextItemSelect().
the ApplyMenuChoice() is where the problem code can be found.
I would be so grateful for help,
Thanks :)
MenuDemo.java
public class MenuDemo extends ListActivity {

    TextView selection;
    TextView displayText;
    String[] flavorItems;
    String[] colors;
    ImageView myImage;
    int currentMenu;
    int listPosition = 0;

    int[] ItemImageSource  = {R.drawable.vanilla,R.drawable.chocolate,R.drawable.strawberry};

    private final String TAG = "Main Activity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        selection=(TextView)findViewById(R.id.selection);
        displayText=(TextView)findViewById(R.id.displayText);
        myImage=(ImageView)findViewById(R.id.myImage);
        flavorItems = getResources().getStringArray(R.array.flavors);
        colors = getResources().getStringArray(R.array.colors);

        setListAdapter(new ArrayAdapter<String>(this, R.layout.flavor_menu_style, flavorItems));
        registerForContextMenu(getListView());
        displayText.setText("Welcome! Click and hold flavor to learn more about it.");
    }

    public void onListItemClick(ListView parent, View v,int position, long id)
    {

        if (currentMenu == 1){selection.setText(colors[position]);}
        else {selection.setText(flavorItems[position]);}

        String strI = Integer.toString(position);
        displayText.setText("teeesst" + strI);

        listPosition = position;
        Log.i(TAG,"!!!!!!!!!!!!!!");
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo)
    {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_menu_demo, menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_new, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) { //item is the menu item chosen

        boolean ret = applyOptionMenuChoice(item);
        if ( ret == false)
            ret = super.onOptionsItemSelected(item);

        return ret;

    }

    @Override
    public boolean onContextItemSelected(MenuItem item)
    {
        boolean ret = applyMenuChoice(item);
        if ( ret == false)
            ret = super.onContextItemSelected(item);

        return ret;
    }

    private boolean applyMenuChoice(MenuItem item) {
        switch (item.getItemId())
        {
        case R.id.picture:

        //this would work if listPosition was linked to the flavors array position
            myImage.setImageResource(ItemImageSource[listPosition]);

            return(true);

        case R.id.ingredients:

            String [] ingredients;
            ingredients = new String [3];

            ingredients[0] = "VANILLA -- these are the ingredients VANILLA";
            ingredients[1] = "CHOCOLATE -- these are the ingredients";
            ingredients[2] = "STRAWBERRY -- these are the ingredients";

            displayText.setText(ingredients[listPosition]);

            return(true);

        case R.id.order:
            //I will add stuff here later
            return(true);

        case R.id.price:
            //I will add stuff here later
            return(true);

        }

        return(false);

    }

    private boolean applyOptionMenuChoice(MenuItem item) {
        switch (item.getItemId())
        {
        case R.id.color_menu:
            setListAdapter(new ArrayAdapter<String>(this, R.layout.color_menu_style, colors));
            currentMenu = 1;
            return(true);

        case R.id.flavor_menu:

            setListAdapter(new ArrayAdapter<String>(this, R.layout.flavor_menu_style, flavorItems));
            currentMenu = 2;
            return(true);

        }

        return(false);

    }

}

A: You can get the position of the list item you long-pressed via the MenuItem
    @Override
    public boolean onContextItemSelected(MenuItem item) {
         AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
         int listPosition = info.position;
         //pass this to your applyMenuChoice method. ice cream nom nom nom
    }


text:
Q: Why did I have a random Frost Troll attack in town? I was waiting in Dawnstar to allow the Khajiit merchant's gold to reset. When it stopped, half the town was dead and a random Frost Troll had appeared. Dawnstar no longer has a blacksmith, nor do the mines have owners.
Does anyone know why this has happened?

A: This is probably just the AI being AI.
There is a spawn point for frost trolls right next to the town of Dawnstar on the other side of the hill near the road that leads into town. If you stand on top of the hill you should be able to see the trolls easily. There are also different types of creatures that spawn in the area that the troll would try to attack. Chances are while you were waiting for the Khajiit merchants to reset the troll followed the creature AI up towards the town close enough to start locking on to the people in the town.
If you are wondering if there is some kind of scripted event for a troll attack on the town, the answer as it currently stands is No. This is just some of the randomness that comes along with the world of Skyrim.


text:
Q: Prove the assertion on the game theory.

if a dominant strategy for player1  is added to finite normal form game then the payoff to player1 at any equlibrium of the new game must be at least as great as any nash equlibrium payoff of player1 in the orginal game.

This statement is true or not? Please show me its proof. Thank you.

A: I think this is false.
Consider a two-player game where player $1$ has only one action $L$ and player $2$ has two actions, $A$ and $B$. Let payoffs be as follows:
$\begin{array}{lcl}
 & L \\
A& (1^*,1)\\
B & (5^*,5^*)
\end{array}
$
Now, add the following dominant strategy $R$ for player $1$
$\begin{array}{lccc}
 & L & R\\
A& (1,1) & (2^*,500^*)\\
B & (5,5^*) & (6^*,0)\\
\end{array}
$
Player $1$ is worse off in the only Nash equilibrium of the new game.


text:
Q: Cannot replace string with sed. Getting unknown option I am trying to replace a string with sed (stream editor), however I am getting errors thrown back. Probably because I am not using the string correctly, because of the symbols.
I am trying to replace the following string:
<VirtualHost |IP|:|PORT_80| |MULTI_IP|>

with
<VirtualHost 127.0.0.1:8080 |IP|:8080 |MULTI_IP|>

In the file called virtual_host2.conf
Buw when I try several things, I always get errors back like:
sed: -e expression #1, char 90: unterminated `s' command
sed: -e expression #1, char 20: unknown option to `s'

I am not that experienced with sed, but I can replace text strings normally. But I think because of the symbols in the current string, like |, < and > it doesn't work like I would.
Can someone please give me a working example on how to replace the above?
Or point me in the right direction.
I tried the following myself:
sed -i 's<VirtualHost |IP|:|PORT_80| |MULTI_IP|>/<VirtualHost 127.0.0.1:8080 |IP|:8080 |MULTI_IP|>' /virtual_host2.conf

sed -i 's|<VirtualHost |IP|:|PORT_80| |MULTI_IP|>|<VirtualHost 127.0.0.1:8080 |IP|:8080 |MULTI_IP|>|g' /virtual_host2.conf

But both give the error as mentioned above.
Any idea?

A: You omit / in sed 's///' pattern. Try this:
sed 's/<VirtualHost |IP|:|PORT_80| |MULTI_IP|>/<VirtualHost 127.0.0.1:8080 |IP|:8080 |MULTI_IP|>/' /virtual_host2.conf

And if everything is ok, add -i option to execut real replacement in file.
g option in 's///g' pattern perform global replacement of all occurances, not the first in each line.

You can use some other symbols as delimeter, such as 's|||', but it not make sense in your example because you need to quote each | symbol. This command will get the same output:
sed 's|<VirtualHost \|IP\|:\|PORT_80\| \|MULTI_IP\|>|<VirtualHost 127.0.0.1:8080 \|IP\|:8080 \|MULTI_IP\|>|' /virtual_host2.conf


text:
Q: How to limit resources for specific roles Kubernetes? I am currently setting up a cluster for a team. I've setup a hierarchial role based authentication. I've used the Kuberentes role API to define the roles. However, you can only restrict the CRUD operations for the roles.
How can I limit resources like cpu or memory based on roles?
EDIT:
Seems like there is no way to do that directly. Namespaces would have to be created for each role and then ResourceQuotas will have to be applied on them.

A: I think you need to use Resource Quotas Policy in Kubernetes.
Refer to this link - Resource Quotes

A: Create different namespace for each team. you should be using ResourceQuota to limit the resources at namepsace level.
Follow the link for help --> ResourceQuota in Kubernetes


text:
Q: New Members Of Stack Exchange Family Where, what, how, when, is the correct place, time, and environment to discuss other Stack Exchange sites? I'm thinking that there are probably one zillion ideas floating around in the minds of the users; now how could any of these become concrete and useful as Stack Overflow ?
Or, is this the place ?
I haven't been here even a month, and I'm guessing that 90% (and then some) of my time has been in Stack Overflow trying to learn from the experts.

A: There is such a place, it's called http://Area51.stackexchange.com