text:
Q: Достать текст сообщения пользователя и вписать в description embed сообщения Суть такая. Хочу сделать канал с предложениями. @bot.event on_message, если человек в определенный канал отправляет  ЛЮБОЕ сообщение, бот его удаляет и высылает свое с встроенным embed сообщением. Так вот, хочу в description embed сообщение вписать текст сообщения автора, не знаю как сделать, помогите пожалуйста)
А ТАК ЖЕ: аватар автора сообщения не вставляется в эмбед, что делать?
пробовал уже все что можно, облазил каждый сайт с ответами. НИГДЕ НЕТ ОТВЕТА
@bot.event
async def on_message(message):
    channel = bot.get_channel(1022583542552727572)
    if message.channel == channel and not message.author.bot:
        await message.delete()
            embed = discord.Embed(
            description=f"{message.content}",
            color=discord.Colour.blurple(),
        )

        embed.set_footer(text="Голосуйте!")
        embed.set_author(name=message.author.name, url=message.author.avatar)

        message = await channel.send(embed=embed)
        await message.add_reaction('')
        await message.add_reaction('')


text:
Q: When to create thread by extending Generally thread can be created in 2 ways

*

*Extending a thread class

*Implementing a Runnable interface

By reading in all tutorials, all says that implementing a Runnable interface is always good since you cannot extend any other class if you create by extending(1st method) I agree.
And also if we create thread by extending then every thread will create new object whereas if we create thread by implementing all thread will share the same object.
My question is if implementing Runnable is best option and extending thread is bad practice why java have this option? I believe there must be surely some advantage if we create thread by extending ( I believe we should use extending thread method, when there is no other parent class is not the only answer )
Thanks in advance

A: In 2018, the real answer is: you don't use bare metal threads at all.
We have abstractions like the fork/join, futures, or the ExecutorService framework these days.
Avoid doing threads yourself!
If you do, you consider the "good old" Favor Composition over inheritance. Which, in this case boils down to: don't extend thread, but implement Runnable. You do not want to restrict your class by using extends, when you could get away with implements instead!

A: This is a design decision, when you should implement a Runnable interface or when you should extend a thread.

*

*Ask some question yourself - If you want a object that is more specific or specialized version of object. If it adds new functionality to the existing Thread object, then you should go for extending a threda class. Else go for implementing a Runnable interface.

*Implement a Runnable does not create a Thread. Implementing a Runnable interface merely createsa task that should be executed by a thread.

*Another benefit of implementing a task is that task is reusable while object created using the thread extension is not reusable.

A: To correct, thread can be created in 3 ways
3. Using Callable interface
Java does not allow a class to extend multiple class to prevent diamond problem that was there in C/ C++. If you are sure your class will not extend any other class but Thread you can happily extend from Thread class or it is advisable to extend Runnable or Callable interface

I believe there must be surely some advantage if we create thread by extending

You get all the advantages of extending a class, in case you want to provide custom implementation for a method.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Solution to system of nonlinear ODEs I have a specific question regarding how the author of this paper
obtained the following solution for the system of nonlinear DEs.
The system of nonlinear differential equations is: $$
\frac{d{X_{SS}}}{dt}=\Lambda-\beta_IX_{IS}\frac{X_{SS}}{N}-\beta_AX_{AS}\frac{X_{SS}}{N}-\mu X_{SS} \\ \frac{d{X_{IS}}}{dt}=\beta_IX_{IS}\frac{X_{SS}}{N}+\beta_AX_{AS}\frac{X_{SS}}{N}-(\nu_{IS}+\mu)X_{IS} \\ \frac{d{X_{AS}}}{dt}=\nu_{IS}X_{IS}-(\mu+\mu_A)X_{AS} \\ N=X_{SS}+X_{IS}+X_{AS}$$
The solution is: $$X_{SS}=\frac{\Lambda(\nu_{IS}+\mu+\mu_A)}{\beta_I(\mu_A+\mu)+\nu_{IS}(\beta_A-\mu_A)} \\ X_{IS}=\frac{\Lambda(\mu+\mu_A)(R_0^H-1)}{\beta_I(\mu_A+\mu)+\nu_{IS}(\beta_A-\mu_A)} \\ X_{AS}=\frac{\Lambda\nu_{IS}(R_0^H-1)}{{\beta_I(\mu_A+\mu)+\nu_{IS}(\beta_A-\mu_A)}}$$
where $$R_0^H=\frac{\beta_I(\mu+\mu_A)+\beta_A\nu_{IS}}{(\nu_{IS}+\mu)(\mu+\mu_A)}$$
$X_{SS},X_{IS},X_{AS}$ are functions of $t$.
I tried everything - by hand, Maple, Mathematica, MATLAB - with no success. I tried in vain to add the equations and using integrating factors...


text:
Q: Achieve nesting/hierarchy with given XML This is some xml data that I have, a fairly flat structure with itemMapCode=1/itemValue=* values flagging what type of data we have. M=the main section, C=categories, W=workcodes to be nested within categories, and H for header.
<?xml version="1.0" encoding="UTF-8"?>
<EstimateDisplayRequest>
<facXML>
    <faRecord>
        <recordCode>33</recordCode>
        <item>
            <itemMapCode>1</itemMapCode>
            <itemValue>M</itemValue>
        </item>
        <item>
            <itemMapCode>10</itemMapCode>
            <itemValue>CL1</itemValue>
        </item>
        <item>
            <itemMapCode>11</itemMapCode>
            <itemValue>Rodick Client</itemValue>
        </item>
        <item>
            <itemMapCode>12</itemMapCode>
            <itemValue>P1</itemValue>
        </item>
        <item>
            <itemMapCode>13</itemMapCode>
            <itemValue>Rodick Product</itemValue>
        </item>
        <item>
            <itemMapCode>14</itemMapCode>
            <itemValue>AD0242</itemValue>
        </item>
        <item>
            <itemMapCode>15</itemMapCode>
            <itemValue>copy1</itemValue>
        </item>
    </faRecord>
  <faRecord>
     <recordCode>33</recordCode>
     <item>
        <itemMapCode>1</itemMapCode>
        <itemValue>C</itemValue>
     </item>
     <item>
        <itemMapCode>80</itemMapCode>
        <itemValue>0</itemValue>
     </item>
     <item>
        <itemMapCode>81</itemMapCode>
        <itemValue>INTERNAL CREATIVE</itemValue>
     </item>
  </faRecord>
  <faRecord>
     <recordCode>33</recordCode>
     <item>
        <itemMapCode>1</itemMapCode>
        <itemValue>W</itemValue>
     </item>
     <item>
        <itemMapCode>41</itemMapCode>
        <itemValue>0</itemValue>
     </item>
     <item>
        <itemMapCode>42</itemMapCode>
        <itemValue>TI</itemValue>
     </item>
     <item>
        <itemMapCode>43</itemMapCode>
        <itemValue>Time Work Code</itemValue>
     </item>
  </faRecord>
  <faRecord>
     <recordCode>33</recordCode>
     <item>
        <itemMapCode>1</itemMapCode>
        <itemValue>W</itemValue>
     </item>
     <item>
        <itemMapCode>41</itemMapCode>
        <itemValue>0</itemValue>
     </item>
     <item>
        <itemMapCode>42</itemMapCode>
        <itemValue>AD</itemValue>
     </item>
     <item>
        <itemMapCode>43</itemMapCode>
        <itemValue>ART DIRECTION</itemValue>
     </item>
  </faRecord>

    <faRecord>
        <recordCode>33</recordCode>
        <item>
            <itemMapCode>1</itemMapCode>
            <itemValue>H</itemValue>
        </item>
        <item>
            <itemMapCode>90</itemMapCode>
            <itemValue>Text & Talk is a double-blind peer-reviewed journal published by Mouton de Gruyter. It provides an international and interdisciplinary forum for publication of research in "language, discourse, and communication studies".<nl><nl>The journal was first</itemValue>
        </item>
    </faRecord>
    <faRecord>
        <recordCode>33</recordCode>
        <item>
            <itemMapCode>1</itemMapCode>
            <itemValue>H</itemValue>
        </item>
        <item>
            <itemMapCode>90</itemMapCode>
            <itemValue> published under the name TEXT in 1981.</itemValue>
        </item>
    </faRecord>
</facXML>
</EstimateDisplayRequest>

The XSL I have (derived with help from this forum!) works fine with the M section and the nested C/W sections, but I am having trouble with the H/header section. I tried using the generateKey method like I used for C and W but it doesn't work if I try it with M/H.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" />
<xsl:strip-space elements="*" />

<xsl:key name="kWork" match="faRecord[item[itemMapCode = 1]/itemValue = 'W']" use="
generate-id(preceding-sibling::faRecord[item[itemMapCode = 1]/itemValue = 'C'][1])
" />

<xsl:template match="EstimateDisplayRequest">
<MCSResponse>
  <EstimateDisplayResponse>
    <xsl:apply-templates select="*/faRecord[item[itemMapCode = 1]/itemValue = 'M']" />
    <xsl:apply-templates select="*/faRecord[item[itemMapCode = 1]/itemValue = 'C']" />

    <xsl:apply-templates select="*/faRecord[item[itemMapCode = 1]/itemValue = 'H']" />
    <xsl:apply-templates select="*/faRecord[item[itemMapCode = 1]/itemValue = 'F']" />
  </EstimateDisplayResponse>
</MCSResponse>
</xsl:template>

<xsl:template match="faRecord[item[itemMapCode = 1]/itemValue = 'M']">
<EstimateDetail>
  <xsl:apply-templates select="item" />
</EstimateDetail>
</xsl:template>

<xsl:template match="faRecord[item[itemMapCode = 1]/itemValue = 'C']">
<CategoryDetail>
  <xsl:apply-templates select="item" />
  <xsl:apply-templates select="key('kWork', generate-id())" />
</CategoryDetail>
</xsl:template>

<xsl:template match="faRecord[item[itemMapCode = 1]/itemValue = 'W']">
<WorkcodeDetail>
  <xsl:apply-templates select="item" />
</WorkcodeDetail>
</xsl:template>

<xsl:template match="faRecord[item[itemMapCode = 1]/itemValue = 'H']">
<EstimateHeader>
  <xsl:apply-templates select="item" />
</EstimateHeader>
</xsl:template>

<!-- this catches <recordCode> and unknown elements -->
<xsl:template match="faRecord/recordCode" />
<xsl:template match="faRecord/item[itemMapCode=1]" />

<xsl:template match="faRecord/item[itemMapCode!=1]">
<xsl:variable name="elemName">
  <xsl:choose>
    <xsl:when test="itemMapCode = 2">SortKey</xsl:when>
    <xsl:when test="itemMapCode = 3">SideBySideSequential</xsl:when>

    <xsl:when test="itemMapCode = 10">ClientCode</xsl:when>
    <xsl:when test="itemMapCode = 11">ClientName</xsl:when>
    <xsl:when test="itemMapCode = 12">ProductCode</xsl:when>
    <xsl:when test="itemMapCode = 13">ProductName</xsl:when>
    <xsl:when test="itemMapCode = 14">JobCode</xsl:when>
    <xsl:when test="itemMapCode = 15">JobName</xsl:when>

    <xsl:when test="itemMapCode = 41">WorkcodeCategory</xsl:when>
    <xsl:when test="itemMapCode = 42">Workcode</xsl:when>
    <xsl:when test="itemMapCode = 43">WorkcodeName</xsl:when>

    <xsl:when test="itemMapCode = 80">CategoryCode</xsl:when>
    <xsl:when test="itemMapCode = 81">CategoryName</xsl:when>

    <xsl:when test="itemMapCode = 90">HeaderText</xsl:when>

  </xsl:choose>
</xsl:variable>

<xsl:if test="$elemName != ''">
  <xsl:element name="{$elemName}">
    <xsl:value-of select="./itemValue" />
  </xsl:element>
</xsl:if>
<xsl:if test="$elemName = '' and itemMapCode != 1">
  <xsl:message>Warning: no mapping for itemMapCode '<xsl:value-of select="itemMapCode" />'</xsl:message>
</xsl:if>
</xsl:template>
</xsl:stylesheet>

The output I want is-
<EstimateHeader>
  <HeaderText>xxxxxx</HeaderText>
  <HeaderText>yyyy</HeaderText>
</EstimateHeader>

As an alternative, could the HeaderText items be merged into one HeaderText tag?
<EstimateHeader>
  <HeaderText>xxxxxx yyyy</HeaderText>
</EstimateHeader>

TIA!

A: A minimized example would be much more useful here.
Try changing this:
<xsl:template match="EstimateDisplayRequest">
<MCSResponse>
  <EstimateDisplayResponse>
    <xsl:apply-templates select="*/faRecord[item[itemMapCode = 1]/itemValue = 'M']" />
    <xsl:apply-templates select="*/faRecord[item[itemMapCode = 1]/itemValue = 'C']" />

    <xsl:apply-templates select="*/faRecord[item[itemMapCode = 1]/itemValue = 'H']" />
    <xsl:apply-templates select="*/faRecord[item[itemMapCode = 1]/itemValue = 'F']" />
  </EstimateDisplayResponse>
</MCSResponse>
</xsl:template>

into this:
<xsl:template match="EstimateDisplayRequest">
    <MCSResponse>
        <EstimateDisplayResponse>
            <xsl:apply-templates select="*/faRecord[item[itemMapCode = 1]/itemValue = 'M']" />
            <xsl:apply-templates select="*/faRecord[item[itemMapCode = 1]/itemValue = 'C']" />
            <EstimateHeader>
                <xsl:apply-templates select="*/faRecord[item[itemMapCode = 1]/itemValue = 'H']" />
            </EstimateHeader>
            <xsl:apply-templates select="*/faRecord[item[itemMapCode = 1]/itemValue = 'F']" />
        </EstimateDisplayResponse>
    </MCSResponse>
</xsl:template>

and this:
<xsl:template match="faRecord[item[itemMapCode = 1]/itemValue = 'H']">
<EstimateHeader>
  <xsl:apply-templates select="item" />
</EstimateHeader>
</xsl:template>

into this:
<xsl:template match="faRecord[item[itemMapCode = 1]/itemValue = 'H']">
    <xsl:apply-templates select="item" />
</xsl:template>


text:
Q: Optimize print area of the pdf file generated from Latex I am using document class extarticle for making quizzes, assignments, etc for my class. In the pdf output file, a lot of space remains unused. This results in extra consumption of paper. How we can make the pdf output more compact to avoid paper wastage.
I will really appreciate any help on this.
Shah
A minimal example is given below. The pdf output consists of two pages but the contents are very brief and they should easily fit on single page or even less than this. Reducing the font size is one trick which helps but if I don't want to reduce the font, is there any other way to optimize print area?
\documentclass[a4, 14pt]{extarticle}

\usepackage{extsizes}

\usepackage{amsmath,amssymb,bm}

\begin{document}

{{\begin{center} \Large{ Calculus II (MAT-1205)} \end{center}} {{\begin{center}  Sequences and Series  \end{center}} {{\begin{center}  \bf{Quiz $\# 3$ (5\% Weightage) }\end{center}}
\noindent
\begin{tabular}{@{}p{3in}p{2.5in}}
{\bf{Name: \line(1,0){130}  }} \hspace{0.5cm} & {\bf{Roll No. \line(1,0){80}  }} \\ & \\
{\bf {Summer 2014}} \hspace{0.5cm} & Thursday, Sep 19, 2014 \\ & \\
{\bf{Duration:}} 25 Minutes \hspace{0.5cm} & {\bf{Maximum Points: }} 20 \\
\hline \hline
\end{tabular}

\vspace{2cm}

\noindent
{\bf{Important Note:}} Show all the details of your solutions. Failing to do so may result in deduction of marks.  \\

\noindent
{\bf{Question 1}} \\

\noindent
Determine if the following infinite sequences converge or diverge. If the sequence converges, determine its limit. \\

\noindent
(i) \begin{equation}
\left\{\frac{3n^{2}-1}{10n+5n^{2}}\right\}_{n=2}^{\infty} \nonumber
\end{equation}

\noindent
(ii) %\begin{align}
 \[ \left\{\frac{(-1)^{n}}{n}\right\}_{n=1}^{\infty} \] %$$

\begin{flushright} {\bf{10 points}} \end{flushright}

\noindent
{\bf{Question 2}} \\ %

\noindent
Express the repeating decimal $5.232323...$ as the ratio of two integers.

\begin{flushright} {\bf{10 points}} \end{flushright}

\end{document}

A: *

*Don't use \begin{center}. Use \centering instead within a group

*\bf{text} is wrong. Use \textbf{text} or {\bfseries text}

*Same holds true for \Large{text}, it should be {\Large text}
Having said that, you can reduce the default margins using geometry package.
\documentclass[a4paper, 14pt]{extarticle}
\usepackage[margin=1in]{geometry}
%\usepackage{extsizes}    % not need with this class

\usepackage{amsmath,amssymb,bm}

\begin{document}

{\centering
{\Large Calculus II (MAT-1205)}

\medskip
Sequences and Series

\medskip
\bfseries Quiz $\# 3$ (5\% Weightage)
\par}

\bigskip
\noindent
\begin{tabular}{@{}p{3in}p{2.5in}}
{\textbf{Name: \line(1,0){130}  }} \hspace{0.5cm} & {\textbf{Roll No. \line(1,0){80}  }} \\ & \\
{\textbf {Summer 2014}} \hspace{0.5cm} & Thursday, Sep 19, 2014 \\ & \\
{\textbf{Duration:}} 25 Minutes \hspace{0.5cm} & {\textbf{Maximum Points: }} 20 \\
\hline \hline
\end{tabular}

\vspace{1cm}

\noindent
{\textbf{Important Note:}} Show all the details of your solutions. Failing to do so may result in deduction of marks.  \\

\noindent
{\textbf{Question 1}} \\

\noindent
Determine if the following infinite sequences converge or diverge. If the sequence converges, determine its limit. \\

\noindent
(i) \begin{equation}
\left\{\frac{3n^{2}-1}{10n+5n^{2}}\right\}_{n=2}^{∞} \nonumber
\end{equation}

\noindent
(ii) %\begin{align}
 \[ \left\{\frac{(-1)ⁿ}{n}\right\}_{n=1}^{∞} \] %$$

\begin{flushright} {\bf{10 points}} \end{flushright}

\noindent
{\textbf{Question 2}} \\ %

\noindent
Express the repeating decimal $5.232323...$ as the ratio of two integers.

\begin{flushright} {\textbf{10 points}} \end{flushright}

\end{document}

A: There are ofcourse some great packages for quizes, but you can create your own style. Here I've set the paper in to columns, as an A4-page is not really wellsuited for printing wide lines, and to use the space effectively, more columns are nessasary.
I've also created a few macros for ease of use, and for better consistancy. Now, you just use \Question{points}{question} instead of lots of formatting and redundant code. I've also used no parskip-package to remove indentation, as tou clearly don't want this here.
The maximum points and total numbers available are now automaticly calculated and put in the headertable.
The output of numbering for equation have been changed, so that it uses roman numbering instead, as you intended. You don't need to add it manually.
Output

Code
\documentclass[a4paper, 14pt,twocolumn]{extarticle}

\usepackage[
  margin=1cm,
  includefoot,
  footskip=20pt
  ]{geometry}
\usepackage{parskip}% To remove indent on paragraphs for whole document
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{bm}
\usepackage{totcount}% To display the total number of points for this quiz.
\usepackage{tabularx}

\newtotcounter{points}
\newcommand{\Points}[1]{%
  \addtocounter{points}{#1}% Store how many points we have in total
  \par\hfill{\bfseries#1 points}\par%
}
\newtotcounter{question}
\newcommand{\QuestionTitle}{%
  \par\bigskip%
     \stepcounter{question}%
    {\bfseries Question \thequestion}
    \medskip%
}

\newcommand{\Question}[2]{%
  \QuestionTitle

  #2

  \Points{#1}
}
\renewcommand{\theequation}{\roman{equation}}

\begin{document}
\makeatletter
\twocolumn[
\begin{@twocolumnfalse}%{\textwidth}
{\centering
{\Large Calculus II (MAT-1205)}

\medskip
Sequences and Series

\medskip
\bfseries Quiz $\# 3$ (5\% Weightage)
\par}

\bigskip
\renewcommand{\arraystretch}{1.5}% A factor for extra space between lines
\begin{tabularx}{\textwidth}{@{\hspace{2cm}}lXl@{\hspace{2cm}}}
  \textbf{Name: \line(1,0){130}} && {\textbf{Roll No. \line(1,0){80}  }} \\
  \textbf{Summer 2014} && Thursday, Sep 19, 2014 \\
  \textbf{Duration:} \textbf{25} Minutes \hspace{0.5cm} && \textbf{\total{points}} points, with \textbf{\total{question}} questions. \\
  \hline \hline
\end{tabularx}
\vspace{.5cm}
\end{@twocolumnfalse}
]
\makeatother

\framebox[\columnwidth]{\parbox{.9\columnwidth}{{\textbf{Important Note:}} Show all the details of your solutions. Failing to do so may result in deduction of marks.}}

\Question{10}{%

Determine if the following infinite sequences converge or diverge. If the sequence converges, determine its limit.

\begin{equation}
  \left\{ \frac{ 3n^{2}-1 }{ 10n + 5n^{2} } \right\}_{ n=2 }^{ \infty }
\end{equation}
\begin{equation}
  \left\{ \frac{ (-1) ?}{ n } \right\}_{ n=1 }^{ \infty }
\end{equation}
}

\Question{10}{%

Express the repeating decimal \(5.232323\ldots\) as the ratio of two integers.
}

\Question{20}{What is the meaning of life?}
\Question{25}{How much wood would a woodchuck chuck if a woodchuck could chuck wood?}
  \vfill\eject% Manulal columnbreak. For `\multicols`, you could use `\columnbreak`
\Question{50}{How many ducks are there on \texttt{tex.stackexchange.com}?}
\Question{5}{Does a duck produce an echo?}
\Question{10}{Are tigers better than ducks?}
\Question{15}{What about donkeys?}

\end{document}


text:
Q: How to get all the hyperlinks but ignore the links of images I want to get all the hyperlinks of a webpage with Jsoup. Meanwhile, I want to ignore all the hyperlinks of images. Is it possible to add more restrictions for getElementsByTag?
Document doc = Jsoup.connect(url).timeout(1000).get();
links = doc.getElementsByTag("a").not("[src]");

A: If your images are linked with a tags using src-attribute (while normal links use href) use this:
Document doc = Jsoup.connect(url).timeout(1000).get();
Elements links = doc.select("a[href]"); // Only select 'a'-tags with 'href' attribute

See here for jsoup selector api.


text:
Q: password validation form in rails I'm new to rails and i want to make a signup login and forget password functionality from scratch so i have been following railscast 250 and 274 episodes..so the problem is, the validations on password and password confirmation fields are working fine on signup form but on the reset password form those validations are not working at all..code is below
model:
    class User < ActiveRecord::Base
      attr_accessible :email, :password, :password_confirmation, :signup_token
      attr_accessor :password
      before_save :encrypt_password
      before_create {generate_token(:auth_token)}
      before_create {generate_token(:signup_token)}
      validates :password, length: {minimum: 8}, confirmation: true, presence: true,:on       => :create
      validates :email, presence: true, uniqueness: true
      validates :email, format: {with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, message: "not valid"}

      def generate_token(column)
        begin
          self[column] = SecureRandom.urlsafe_base64
        end while User.exists?(column => self[column])
      end

      def self.authenticate(email, password)
        user = find_by_email(email)
        if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt) && user.active == true
          user
        else
          nil
        end
     end

     def encrypt_password
       if password.present?
         self.password_salt = BCrypt::Engine.generate_salt
         self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
       end
     end

      def send_password_reset
        generate_token(:password_reset_token)
        self.password_reset_sent_at = Time.zone.now
        save!
        UserMailer.password_reset(self).deliver
      end
    end

password_resets_controller:
    class PasswordResetsController < ApplicationController
      def new
      end

      def create
    user = User.find_by_email(params[:email])
    user.send_password_reset if user
    redirect_to root_url, :notice => "Email sent with password reset instructions."
      end

      def edit
    @user = User.find_by_password_reset_token!(params[:id])
      end

      def update
        @user = User.find_by_password_reset_token!(params[:id])
        if @user.password_reset_sent_at < 2.hours.ago
          redirect_to new_password_reset_path, :alert => "Password reset has expired."
        elsif @user.update_attributes(params[:user])
          redirect_to root_url, :notice => "Password has been reset."
        else
          render :edit
        end
      end
     end

and views under password reset are
new.html.erb:

Reset Password

    <%= form_tag password_resets_path, :method => :post do %>

        <%= label_tag :email %>
        <%= text_field_tag :email, params[:email] %>

<%= submit_tag "Reset Password" %>

    <% end %>

edit.html.erb:

Reset Password

    <%= form_for @user, :url => password_reset_path(params[:id]) do |f| %>
      <% if @user.errors.any? %>

Form is invalid

            <% for message in @user.errors.full_messages %>

<%= message %>

            <% end %>

      <% end %>

        <%= f.label :password %>
        <%= f.password_field :password %>

        <%= f.label :password_confirmation %>
        <%= f.password_field :password_confirmation %>

<%= f.submit "Update Password" %>

    <% end %>


text:
Q: Java inheritance appending a function instead of overwriting it public class Cls1{
    public foo(){
        doX();
    }
}

public class Cls2{
    public foo(){
        doY();
    }
}

Cls2 cls = new Cls2();
cls.foo();

Is there a way to do inheritance in java that java runs both doX and doY when the user calls the function with foo?

A: Yes, but you have to do it explicitly:
public class Cls1{
    public foo{
        doX();
    }
}

public class Cls2 extends Cls1 {
    public foo{
        super.foo();
        doY();
    }
}

Note: I assume you meant for Cls2 to extend Cls1, otherwise your question makes no sense at all.

A: public class Cls1 {
    public foo{
        doX();
    }
}

public class Cls2 extends Cls1 {
    public foo{
        super.foo();
        doY();
    }
}

Cls2 cls = new Cls2();
cls.foo();

A: private class Cls2 extends Cls1 {
    public void foo {
        doY();
        super.foo();
    }
}

A: first of all, I assume you mean:
public class Cls2 extends Cls1{

and yes, there is:
public (something?) foo(){
    super.foo();
    doY();
}

The super keyword allows access to the super-class's methods. If it's simply called on its own:
super(...);

then it calls the super-class's constructor.

A: Assuming that Cls1 and Cls2 inherit from each other in some way, you can use the keyword super to call the superclass's implementation of a method if you want to, for instance, in the derived class perform both functions.

A: If doX() and doY() were statically imported (which, as they were not defined in Cls1 or in Cls2 is the only way I can think of for this program to compile), then you can make a new class with a method foo that calls doX and doY without using inheritance.  Those methods named foo would have nothing to do with each other, however.


text:
Q: What does it mean that the depth of an image is zero? In the below code, I am reading an image and displaying the number of channels it has and its depth.
The result is channels:3 and depth:0
As far as I know, the depth should represent the number of bits per channel.
What does it mean that the depth is zero?
Code:
public static void main(String[] args) {
    System.loadLibrary(org.opencv.core.Core.NATIVE_LIBRARY_NAME);

    Mat imgSrc = new Mat();
    imgSrc = Highgui.imread(PATH);

    if (imgSrc.empty()) {
        System.out.println("image is empty");
        return;
    }

    System.out.println("channels: " + imgSrc.channels());
    System.out.println("depth: " + imgSrc.depth());
}

}

A: As you can read here: http://docs.opencv.org/modules/core/doc/basic_structures.html#mat-depth
The depth field does not contain the actual count of bits. It contains a value of a constant defined in the opencv lib. You would have to check those constants in your version to answer, what a 0 means.
Edit: In my version CvType.CV_8U == 0. So you can expect an unsigned char.


text:
Q: How to push a notification after specific time even the when the application is closed in android? i want to ask you :
How to push a notification after specific time even when the application is closed?
like after 10 minutes, the application will push notification to the user.put it is not from the server so i can not use C2DM!
any code or tutorial or link will be helpful, Thank you

A: Use the AlarmManager to set an alarm which is fired after 10 minutes. Then react to the alram e.g. by sending the notification. Here is more information about the AlarmManager: http://developer.android.com/reference/android/app/AlarmManager.html


text:
Q: echoing a php string with a wordpress include with the following code
<?php
if (qtrans_getLanguage() == "en") {
   echo <?php include( TEMPLATEPATH . '/slider_en.php' ); ?>;

}else{
      echo <?php include( TEMPLATEPATH . '/slider_de.php' ); ?>;
   }
?>

i'm trying to include a file, based on the chosen language of the website. guess my idea is right but i'm totaly wrong on the syntax of using include in an echo..
can someone please oint me in the right direction?
many thanks,
tobi.

A: You are already in PHP mode, so you don't need to re-open the PHP tags (<?php). Remove them, and it should work. You don't even need the echo, since PHP drops out of PHP mode and back in HTML mode when it includes a file.
<?php
if (qtrans_getLanguage() == "en") {
   include( TEMPLATEPATH . '/slider_en.php' );

} else {
   include( TEMPLATEPATH . '/slider_de.php' );
}
?>

A: You can't echo an include.  Try just including the file, otherwise you can try the get_file_contents function, which returns the file as a string.
echo get_file_contents( TEMPLATEPATH . '/slider_de.php');

More info on get_file_contents: http://php.net/manual/en/function.file-get-contents.php


text:
Q: Optimising C code Here is my C code..
void Read(int t,char* string1)
{
    int j,i,p,row,count=0;
    for(i=0;i<t;++i,string1=strchr(string1,')')+2)
    {
        sscanf(string1,"(%d,%d)",&p,&row);
        CallFunction(p,row);
    }
}

Here is how i have to call this function:
Read(2,"(3,5),(7,8)")

Is this a good way to deal with such kind of input parameters? Is it time consuming?
Is there any other good way (optimised way) of reading the same input parameters?

A: You could use the %n format-specifier for sscanf(), which allows you to omit the strchr() function. The speed improvement is probably marginal.
BTW: dont' call a function "Read", not even if you can assume a case-sensitive compiler and linker.
#include <stdio.h>

#define CallFunction(a,b) fprintf(stderr, "p=%d row=%d\n", a, b)

void do_read(int cnt,char *input)
{
    int i,err,p,row,res;

    for(i=0; i<cnt ; i++,input += res )
    {
        err = sscanf(input,"(%d,%d)%n",&p,&row, &res);
        if (err < 2) {
                fprintf(stderr, "%s:%d: input='%s', err=%d\n"
                        , __FILE__ , __LINE__,  input, err );
                break;
                }
        CallFunction(p,row);
        if (input[res] == ',') res++;
    }
}

int main(void)
{
do_read(2,"(3,5),(7,8)"); /* this should succeed */
do_read(2,"(3,5)#(7,8)"); /* this must fail ... */

return 0;
}

A: This code is reasonably fast. But how fast it needs to be depends on your constrainsts which are unknown to me.
I hope that your input data is already checked because string1=strchr(string1,')')+2 (and what follows) is not safe.
Reading your code makes me think that, if you really need bare to the metal speed, you should ditch the function calls and do the job manually (parsing the string yourself).
But given the 'API' you have published, the question of the speed may be defeated ABOVE and BELOW this code snippet.
Reaching the optimal code chain then depends on... all the chain: the whole will not run faster than the slowest function in the chain.
Sorry not to be more specific but this is really a more global question than the information you provide lets me address it (I don't have the whole picture).


text:
Q: "The Ruby way" (mixins and class reopening) vs. dependency injection In studying mixins vs. dependency injection, I often hear the phrase "the Ruby way." Often developers say something along the lines of

Ruby lets you reopen classes and redefine methods means that you can
  easily "inject" new references into your code at test-time.

(see #6 at http://weblog.jamisbuck.org/2007/7/29/net-ssh-revisited)
But testing is not my main concern; my concern is class reuse. I want classes I can reuse in multiple enterprise-scale Rails applications.
So what happened to REUSING classes? Using mixins and reopening classes does not seem to provide a way to write classes in such a way that they are decoupled from application-specific details without a bunch of extra work. But Perhaps I am wrong. If I am, can someone provide a link to an article containing sample code that clearly explains how to accomplish this properly using mixins and reopening of classes?
As an example, the class Foo here is coupled to the class Logger:
class Foo
  def initialize
    @logger = new_logger
  end

  def new_logger
    Logger.new
  end
end

Yes, I can reopen Foo and redefine new_logger, but I just cannot believe this is considered a realistic, standard approach to writing reusable classes usable by multiple Rails applications.

A: Actually when I came from Java world to ruby world the first thing that I was interested in is how do they manage dependencies. At that time I was using Google Guice in all java projects and I was really inspired by its clever design and ease of use. The first thing that I've done in ruby was my very own DI container that had approximately the same set of features as Google Guice - (it is still here on github but it is very outdated).
But now after 2 years of working with Rails/Ruby I think that DI is not needed here. The good article on DI in ruby is http://weblog.jamisbuck.org/2008/11/9/legos-play-doh-and-programming it is actually an article about why DI is not needed by author of one of the first DI containers for ruby. It is definitely worth reading.

A: Well just because we can reopen classes in Ruby doesn't mean we always have to, you can think of reopening classes as the method of last resort. You have a library which does everything you need except for one method, rather than forking the whole library patching it and using your fork, you can simply reopen the class, redefine the method and you're in business again. This is not something you would do willy-nilly, but having the ability to do this is extremely useful.
Having said all of that, in Ruby we have a concept that can almost always be a good substitute for dependency injection - duck typing. Since there is no type checking you can pass any object into a function and as long as the object has the methods that the function would expect, everything will work fine.
Let us look at your example - it is not really class that is conducive to dependency injection, you would not write it like this in Java, for example, if you wanted to inject some dependencies. You can only inject through the constructor or through getters and setters. So let's rewrite this class in that way:
class Foo
  def initialize(logger)
    @logger = logger
  end
end

Much better we can now inject/pass in a logger into our Foo class. Let's add a method that would use this logger to demonstrate:
class Foo
  def initialize(logger)
    @logger = logger
  end

  def do_stuff
    @logger.info("Stuff")
  end
end

In java if you wanted to create Foo objects with different types of loggers, all those loggers would have to implement the same interface in very literal sense (e.g. public class logger implements Loggable), or at least be child classes. But in Ruby as long as the object has an info method that accepts a string, you can pass it into the constructor and Ruby keep chugging along merrily. Let's demonstrate:
class Logger
  def info(some_info)
  end
end

class Widget
  def info(some_widget_info)
  end
end

class Lolcat
  def info(lol_string)
  end
end

Foo.new(Logger.new).do_stuff
Foo.new(Widget.new).do_stuff
Foo.new(Lolcat.new).do_stuff

With all 3 of the above instances of the Foo class calling the do_stuff method, everything will work fine.
As you can see from this example adhering to the principles of OO design is still important, but Ruby is somewhat less restrictive about what it will accept, as long as the right methods are there everything will be fine.
Depending on how you look at it duck typing either makes dependency injection totally irrelevant or makes it more powerful than ever.

A: The simple answer is that nothing in the Ruby language prevents you from writing re-usable classes. The common approach to using mix-ins and class reopening doesn't necessarily promote it, but the language doesn't actually prevent other approaches. Think of "The Ruby Way" as a subset of "The Things Ruby Can Do."
That said, I know that it's usually preferable to enforce a design decision with language constructs, and to my knowledge (which I will warn you is far from complete on the subject) DI isn't currently a core Ruby-ism. A bit of Googling found me some articles on the subject, though, leading me to believe that there are libraries to be found to add DI to Ruby, if you so desire (even though they seem to receive criticism from many Rubyists). Informative articles included these two, and this SO question. Hope that helps.

A: Article about how to use IoC in Ruby You underestimate the power of IoC
With working samples.
UPDATE
Link is dead by now, here's the source https://github.com/alexeypetrushin/rubylang/blob/master/draft/you-underestimate-the-power-of-ioc.md
I used that IoC as a part of my web framework, I kinda re-created Ruby on Rails and it worked, but, it won't give significant advantage over RoR, had similar characteristics. So, it became a burden and I abandoned it, some details http://petrush.in/blog/2011/rad-web-framework .

A: I totally agree. Dynamic languages are no substitutes for dependency injection. And nothing stops you from writing one for a dynamic language. Here's a dependency injection framework for Smalltalk: http://www.squeaksource.com/Seuss.html


text:
Q: Visual Studio 2022 version 17.1.0 Update - Floating Windows no longer merge together to form a tabbed layout This is doing my nut in!
Simply updating VS 2022 to ver. 17.1.0 has broken the ability to drag the header of a floating window towards the header of another window and allow them to merge into one single floating window with a tabbed view layout.
This has ruined my productivity in being able to have multiple files open between a multi monitor layout. Is anyone aware of a option/setting that might have been disabled from the update?
The screenshot below shows where I would usually drag one floating window towards another an if i left go of the mouse in the right place, the two windows would usually snap tpgather into one window with multiple tabs:

Edit: Futher observations conclude the latest VS 17.1.0 have changed the way we can group floating windows together.
By default, my tabs are configured to display along the top, however the only way i can group together the windows is if i change the tab location from the TOP to the Side, but this changes the tab layout in the main IDE as well as floating windows, so it screws eveything up.

Merging the windows together:

Incidentally if I revert back to displaying the Tabs at the TOP, then we have the affect i wanted BUT I stil cannot merge any further windows in that mode:

A: Its just occured to me that the you can snap together the floating windows into a tabbed view by dragging one window with the mouse over the top of another window and then you see the following icon appear:

If you then drag the window and move your mouse cursor over the center point of this icon set then it will in fact merge the two windows together into a tabbed view.

Well this wanst the most intelligent question I'd ever asked! I just hadnt done it this way before and the previous way in doing this had stopped working foo me since upgrading VS22 to latest 17.1.0 from 17.0.1


text:
Q: See the count of suggested edits currently pending review Yesterday I asked followed question - How can I check how many edits suggested by me are currently pending review? - and I received an answer that it is impossible to see how many of my suggested edits are currently pending review. I am requesting to add a field in user profile how many his suggested edits are currently pending review. Why ? To see how many reputation can you earn and simply for curiosity :) I will be not hard to implement, but fine for SE's users. I am doing a lot of suggestions and I wanna know how many of it has been currently approved/rejected and how many are currently for review waiting.

A: Good idea, but I prefer to see the actual status of the suggested edit i.e. approved/rejected/pending:

(mockup only, all the above were actually approved)
Related:

*

*Improving how suggested edits are displayed in your activity history

*Decision on rejected edits should be displayed as a notification to the editor

A: I like this idea.
It could work in a similar way to helpful flags page where you can see all your flags with their status. For rejected edits, it will be important for the users to see why they were rejected.


text:
Q: CSS - Fill remaining height (dynamic content)

My

Header

In the above markup, how can I get the content to fill the rest of the screen (no-scrolling)?
I know how to do this with absolute positions if the header was of a fixed height, but my header's height is dynamically set by its contents (so the site is responsive on mobile devices.)
Btw: I'm looking for a CSS only solution, because I think JavaScript is not made for this kind of task.
Thanks a lot,

A: The simpliest way is to draw the background in body and keep #content translucide. DEMO 1.
This way, you do not mind #header nor #content heights.

If you do not mind about IE7 and less, then display:table/table-row/table-cell taken from defaut display of HTML table elements can be what you need , in the case header has unknown height. DEMO 2
Your structure will need a bit of update in order to act as wished and to avoid gaps in layout render from header part to the content part.
If you reset display to be used as table properties, it will do so and can draw cols and rows.
Since it is only the row properties that will be usefull, Structure must be rendering as one single col and multiple rows.
Basic structure needs to turn this way :

My

Header than can grow

My Content that will fill remaining space untill page has to scroll

And basic CSS turns this way :
html, body {
    height:100%;
    width:100%;
    margin:0;
}
body {
    display:table;/* it will allow to grow over initial width specified */
    /* table-layout:fixed; only if you want to control width within value specified*/
    background:#edc;
}
.row {
    display:table-row;/* we want these elements to stack on top of each other, not to become cells aside each other */
}
.single {
    display:table-cell;/* this 'buffer' element is used to avoid layout to turn into multiple cols */
}
#content {
    height:100%;/* since layout is the one taken from table properties, it means  fill all space avalaible that #header doesn't use */
    background:#cde;
}

In the case, *#header has a known*** height, it can be set in fixed or absolute position.
#content can be 100% height DEMO 3, better: min-height:100%; DEMO 4
display:flex could be useful too but for real young browser only :).

Example with display:flex;
html {
    height:100%;
}
body {
    margin:0;
    min-height:100%;
    background:#edc;
    display:flex;
    flex-direction:column;
}
#header {
/* nothing needed here */
}
#content {
    flex:1;/* since it is the only one getting a flex attitude, it will fill up all space avalaible*/
    background:yellow;
}


text:
Q: Renaming rows under Specific column to a common name - pyspark I have a column name for "country" and in this column I have 20 or so countries, however they are in many different languages, thus coming up several times in different languages. For example, Switzerland comes up as Suiza, Schweiz, Suisse and Switzerland.
How do I rename the duplicated countries in the "country" column to be under a common name, Switzerland, while also keeping the values in the other columns?

A: Just use a CASE statement:
df = spark.sql(
SELECT
  CASE
    WHEN country IN ('Suiza', 'Schweiz', 'Suisse','Switzerland')
    THEN 'Switzerland'
    WHEN ... -- other translations
    ELSE country
  END AS country,
  ... -- other columns
FROM your_table
)

A: If you have a mapping table you can join it to your table
countryList = [
    ("Suiza",),
    ("Allemagne",),
    ("Schweiz",),
    ("Suisse",),
    ("Switzerland",),
    ("Suisse",),
    ("Suisse",),
    ("Germany",)
    ]

schema = ["country",]
df_countries = spark.createDataFrame(data=countryList, schema = schema)

countryMap = [
    ("Suiza","CH"),
    ("Schweiz","CH"),
    ("Suisse","CH"),
    ("Switzerland","CH"),
    ("Germany","DE"),
    ("Allemagne","DE")
    ]

schema = ["country","unified_country"]
df_map = spark.createDataFrame(data=countryMap, schema = schema)

df_countries.show()
df_map.show()

df_result=(df_countries
          .join(df_map,on="country",how="left")
          )

df_result.show()

looks like this
+-----------+---------------+
|    country|unified_country|
+-----------+---------------+
|      Suiza|             CH|
|    Schweiz|             CH|
|    Germany|             DE|
|     Suisse|             CH|
|     Suisse|             CH|
|     Suisse|             CH|
|  Allemagne|             DE|
|Switzerland|             CH|
+-----------+---------------+


text:
Q: ARSCNView's root node's "heading" doesn't match the device heading I want a node which I add to my scene to point north. I get the heading data from Core Location, so that represents the direction the device is currently facing at the point my scene was created (and thus the direction my root node faces), and then I add the heading to my new sceneNode's eulerAngles.y, to rotate it so it faces north.
func renderer(_ renderer: SCNSceneRenderer, didRenderScene scene: SCNScene, atTime time: TimeInterval) {
    if sceneNode == nil,
        let heading = self.locationManager.heading {
        sceneNode = SCNNode()
        sceneNode.eulerAngles.y += Float(heading).degreesToRadians
        sceneView.scene.rootNode.addChildNode(sceneNode)
    }
}

The heading information is correct, and so rotating it by that much does rotate it by the required amount, presuming that the heading is the same direction that my root node is facing. But I'm finding that my root node's direction is not equivalent to where the device's heading is, and can sometimes by wildly off. So that means the assumption that the heading is the same as the scene node's "heading" is incorrect, and I need to be able to know how far out from the heading it is, so I can then correct it properly within my sceneNode.

A: Change your session configuration's worldAlignment to .gravityAndHeading.
With the default .gravity alignment, there's no absolute reference for where the x and z axes of the AR world coordinate system point — their directions are based on the initial orientation of your device when the session starts.
With the .gravityAndHeading option, the x and z axes are aligned to compass directions, so you can safely orient content relative to compass directions.


text:
Q: realtek r8168 driver compile errors on kernel 5.8.0-50, (On 20.04.1 LTS) I'm trying to get r8168-dkms to install on a fresh install of 20.04.1, to my new AMD Ryzen pc, but it's getting a compile error.
uname -a output:
Linux terry-pc 5.8.0-50-generic #56~20.04.1-Ubuntu SMP Mon Apr 12 21:46:35 UTC
2021 x86_64 x86_64 x86_64 GNU/Linux

dpkg -i  r8168-dkms_8.048.00-1_all.deb
make.log:

DKMS make.log for r8168-8.048.00 for kernel 5.8.0-50-generic (x86_64)
Fri 23 Apr 2021 12:09:08 PM PDT make: Entering directory
'/usr/src/linux-headers-5.8.0-50-generic' AR
/var/lib/dkms/r8168/8.048.00/build/built-in.a CC [M]
/var/lib/dkms/r8168/8.048.00/build/r8168_n.o CC [M]
/var/lib/dkms/r8168/8.048.00/build/r8168_asf.o CC [M]
/var/lib/dkms/r8168/8.048.00/build/rtl_eeprom.o CC [M]
/var/lib/dkms/r8168/8.048.00/build/rtltool.o
/var/lib/dkms/r8168/8.048.00/build/r8168_n.c: In function
'rtl8168_proc_init':
/var/lib/dkms/r8168/8.048.00/build/r8168_n.c:1670:47: error: passing
argument 4 of 'proc_create_data' from incompatible pointer type
[-Werror=incompatible-pointer-types] 1670 | &rtl8168_proc_fops,
f->show)) { | ^~~~~~~~~~~~~~~~~~ | | | const struct file_operations *
In file included from /var/lib/dkms/r8168/8.048.00/build/r8168_n.c:92:
./include/linux/proc_fs.h:103:31: note: expected 'const struct
proc_ops *' but argument is of type 'const struct file_operations *'
103 | extern struct proc_dir_entry *proc_create_data(const char ,
umode_t, | ^~~~~~~~~~~~~~~~
/var/lib/dkms/r8168/8.048.00/build/r8168_n.c: At top level:
/var/lib/dkms/r8168/8.048.00/build/r8168_n.c:25825:31: error:
initialization of 'void ()(struct net_device , unsigned int)' from
incompatible pointer type 'void ()(struct net_device *)'
[-Werror=incompatible-pointer-types] 25825 | .ndo_tx_timeout
= rtl8168_tx_timeout, | ^~~~~~~~~~~~~~~~~~ /var/lib/dkms/r8168/8.048.00/build/r8168_n.c:25825:31: note: (near
initialization for 'rtl8168_netdev_ops.ndo_tx_timeout') cc1: some
warnings being treated as errors make[1]: ***
[scripts/Makefile.build:284:
/var/lib/dkms/r8168/8.048.00/build/r8168_n.o] Error 1 make: ***
[Makefile:1783: /var/lib/dkms/r8168/8.048.00/build] Error 2 make:
Leaving directory '/usr/src/linux-headers-5.8.0-50-generic'

Has anyone hit this, and fixed it?

A: 06 Dec 2021: Updating answer for version 8.049.02
17 Feb 2023:  One of the newest drivers from Realtek versions 8.050.03 will not work with the newest LTS Kernel of 5.19.0-32-generic. Version 8.051.02 will work fine.  However, I do recommend the use of the r8168-dkms package and that will install the 8.049.02 driver that works fine with the 5.15 and the 5.19 Kernels.

Make sure to change your version of the driver and kernel as needed.
Now that you have the r8168-8.049.02 driver installed from Realtek it unfortunately does not contain the DKMS info for the driver to be taken over into new kernel updates.
To resolve this, we are going to create a dkms.conf file for this driver.
Create a directory for the new driver:
sudo mkdir /usr/src/r8168-8.049.02

Then go to the folder with the r8168 driver (or download and extract the driver from here) that was extracted and copy all of its contents to the newly created directory:
sudo cp * /usr/src/r8168-8.049.02/

or the src/ directory contents if it exists (this should also contain a Makefile in that directory as well).
sudo cp src/* /usr/src/r8168-8.049.02/

Then create a new dkms.conf file in the new source directory:
sudo nano /usr/src/r8168-8.049.02/dkms.conf

and add the following lines to the file:
PACKAGE_NAME="r8168"
PACKAGE_VERSION="8.049.02"
BUILT_MODULE_NAME[0]="$PACKAGE_NAME"
DEST_MODULE_LOCATION[0]="/updates/dkms"
AUTOINSTALL="YES"
REMAKE_INITRD="YES"

Then save and close the file.
Now we're going to add the dkms driver to the kernel:
sudo dkms add -m r8168 -v 8.049.02
sudo dkms build -m r8168 -v 8.049.02
sudo dkms install -m r8168 -v 8.049.02

Then check the driver with dkms status.  If you see something about the driver that is built being different than the currently installed driver, run the following line to correct it:
sudo dkms uninstall -m r8168 -v 8.049.02 -k 5.8.0-50-generic && sudo dkms install -m r8168 -v 8.049.02 -k 5.8.0-50-generic --force

From now on with new kernel updates and upgrades the driver should now install automatically into the new kernel.
Hope this helps!


text:
Q: Regular polygon with vertices on grid Constructing regular polygons on a sheet of an orthogonal lined paper - a regular maths notebook - I pondered on what would it take for the polygon to have it's vertices at the intersection of the grid lines.
(We could consider the paper infinitely spanning in all directions)

A: The only regular polygon that you can draw with vertices on the standard integer lattice is I'm afraid the square. I won't explain how to draw that!
We might as well consider polygons drawn in the Cartesian plane with vertices at rational points, and we might as well take the centre of
our polygon to be the origin. Let $P$ and $Q$ be adjacent vertices
with position vectors $v$ and $w$. Then $v\cdot v=w\cdot w=a$ say and $v\cdot w=a\cos(2\pi/n)=b$ say. We need $a$ and $b$ to be rational, so that $\cos(2\pi/ n)$ must be rational. But $2\cos(2\pi /n)$ is an algebraic
integer, so it must be an ordinary integer. We reduce to the cases
$n=3$, $4$ or $6$.
If we can draw a regular hexagon in $\mathbb{Q}^2$ we can draw an
equilateral triangle, so let's focus on that. Embed our plane in three
dimensional space, and consider the vector product $v\wedge w$.
Then $|v\wedge w|^2=(v\cdot v)(w\cdot w)-(v\cdot w)^2=a^2(1-\cos^2\pi/3)
=\frac34 a^2$. But $v\wedge w$ is a rational multiple of a unit vector
perpendicular to our plane, so $|v\wedge w|^2$ is a square of a rational. Oops!
I suppose one could look at good approximations to regular polygons
drawn on the integer lattice, or regular polygons in integer lattices
in dimensions $3$ or more.


text:
Q: Disabling Android home button for industry application I'm writing an industry application which will be used by traffic wardens to register offences through my program using forms.
The app is using a webview so it is just a container for an external webpage. We don't want our users to exit the application so we have to disable all buttons. I succeeded in disabling them except for the home button.
I read some threads about this topic, but I don't have any solutions yet. The idea is that I am able to make the app the default home app so if the user presses the home button it launches my app and does not exit. How can I accomplish that? If we must we are able to tamper with android itself (when we install the app), but if there is some solution through configuration it would be appreciated.

A:
The idea is that I am able to make the app the default home app so if the user presses the home button it launches my app and does not exit. How can I accomplish that?

There is a sample Home application in your Android SDK. Mirror its manifest entry, notably putting the HOME category in the activity's <intent-filter>.
The first time the, er, traffic warden taps HOME after installing your app, a chooser will appear for which home app to run. Checking the checkbox and tapping your app will then mean the HOME button will run your app forevermore.
Beyond creating a custom home app, though, there is no way to intercept the HOME button except through firmware modifications.

A: /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    getWindow().addFlags(  WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

}
@Override
public void onBackPressed() {

   return;
}

@Override
public void onAttachedToWindow()
{

       this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
       super.onAttachedToWindow();

}


text:
Q: How to get around using eval in python I have a game I've been working on for awhile. The core is C++, but I'm using Python for scripting and for Attacks/StatusEffects/Items etc.
I've kind of coded myself into a corner where I'm having to use eval to get the behaviout I want. Here's how it's arising:
I have an xml document that I use to spec attacks, like so:
<Attack name="Megiddo Flare" mp="144" accuracy="1.5" targetting="EnemyParty">
    <Flags>
        <IgnoreElements/>
        <Unreflectable/>
        <ConstantDamage/>
        <LockedTargetting/>
    </Flags>
    <Components>
        <ElementalWeightComponent>
            <Element name="Fire" weight="0.5"/>
        </ElementalWeightComponent>
        <ConstantDamageCalculatorComponent damage="9995" index="DamageCalculatorComponent"/>
    </Components>
</Attack>

I parse this file in python, and build my Attacks. Each Attack consist of any number of Components to implement different behaviour. In this Attack's case, I implement a DamageCalculatorComponent, telling python to use the ConstantDamage variant. I implement all these components in my script files. This is all well and good for component types I'm going to use often. There are some attacks where that attack will be the only attack to use that particular Component Variant. Rather then adding the component to my script files, I wanted to be able to specify the Component class in the xml file.
For instance, If I were to implement the classic White Wind attack from Final Fantasy (restores team HP by the amount of HP of the attacker)
<Attack name="White Wind" mp="41" targetting="AnyParty">
    <Flags>
        <LockedTargetting/>
    </Flags>
    <Components>
        <CustomComponent index="DamageCalculatorComponent">
            <![CDATA[
                class WhiteWindDamageComponent(DamageCalculatorComponent):
                    def __init__(self, Owner):
                        DamageCalculatorComponent.__init__(self, Owner)

                    def CalculateDamage(self, Action, Mechanics):
                        Dmg = 0
                        character = Action.GetUsers().GetFirst()
                        SM = character.GetComponent("StatManagerComponent")
                        if (SM != None):
                            Dmg = -SM.GetCurrentHP()
                        return Dmg
                return WhiteWindDamageComponent(Owner)
            ]]>
        </CustomComponent>
    </Components>
</Attack>

I was wondering if there might be a better way to do this? The only other way I can see is too put every possible Component variant definition into my python files, and expand my Component creators to check for the additional variant. Seems abit wasteful for a single use Component. Is there a better/safer alternative to generating types dynamically, or perhaps another solution I'm not seeing?
Thanks in advance

A: Inline Python is bad because

*

*Your source code files cannot be understood by Python source code editors and you will miss syntax highlighting

*All other tools, like pylint, which can be used to lint and validate source code will fail also
Alternative
In element <CustomComponent index="DamageCalculatorComponent">
... add parameter script:
<CustomComponent index="DamageCalculatorComponent" script="damager.py">
Then add file damager.py somewhere along the file system.
Load it as described here: What is an alternative to execfile in Python 3?
In your main game engine code construct the class out of loaded system module like:
 damager_class = sys.modules["mymodulename"].my_factory_function()

All Python modules must share some kind of agreed class names / entry point functions.
If you want to have really pluggable architecture, use Python eggs and setup.py entry points

*

*http://wiki.pylonshq.com/display/pylonscookbook/Using+Entry+Points+to+Write+Plugins
Example

*

*https://github.com/miohtama/vvv/blob/master/setup.py


text:
Q: Need to generate an JSON Array for HTML Elements in Javascript Use case 1:
boldSubscriptContent

Output JSON:
[{
    "subscript": true,
    "content": "boldSubscriptContent",
    "bold": true
}]

Use case 2:
withoutAnyHTMLboldContentboldSubscriptContent

Output JSON :
[{
    "content": "WithoutAnyHTML"
}, {
    "bold": true,
    "content": "boldContent"
}, {
    "bold": true,
    "subscript": true,
    "content": "boldSubscriptContent",
    "outerHTML": "subscriptContent"
}]

Use case 3:
ItalicContentsubscriptContentsupscriptContent

Output JSON:
[{
    "italic": true,
    "bold": true,
    "content": "ItalicContent",
    "outerHTML": "ItalicContent"
}, {
    "subscript": true,
    "bold": true,
    "content": "subscriptContent",
    "outerHTML": "subscriptContent"
}, {
    "superscript": true,
    "bold": true,
    "content": "supscriptContent",
    "outerHTML": "supscriptContent"
}]

A: Here is the solution:
JSFiddle working link

        <input type="text" id="str" value="contentsuperTestsubTesttestItalic" />
        <button onclick="calculate()">Parse</button>


text:
Q: Interaction with Kubuntu Irc channel crashes Quassel I use Quassel as my irc client and have lately run into the following problem.  The Kubuntu IRC network will not connect and if ever I go into the Configure Networks menu to delete it, the second that I click on the Kubuntu channel, Quassel crashes.  So long as I don't go near anything that says "Kubuntu IRC," it works fine.
Question:  Is there a way that I can manually delete the channel manually?  Either by editing a configuration file or a database record?
Thanks in advance


text:
Q: Dynamically modified value of input not reflected in DOM How can I get the DOM to reflect the modified input value?

  <input value='0'>

A: Try changing the DOM directly. For example:

  <input id="myInput" value='0'>

<input type="button" onclick="javascript:alert(document.getElementById('myDiv').innerHTML);" value="Click to see DOM" />

A: The following seems to work for me:
http://jsfiddle.net/h8AP8/1/
All credit to gnarf here and his formhtml:
jQuery html() in Firefox (uses .innerHTML) ignores DOM changes
So your modified code would be:

  <input value='0'>

A: I'm sorry, but the problem is not in the example code you supplied.
Or when this is the only html in your page, then you're missing the starting and closing tags.
This clean page runs perfectly on my machine:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<input value='0'>

Or are you testing in Internet Explorer? In that case, remove the line which is logging to your error console:
console.log('div.html(): ', $('div').html())


text:
Q: DNS query with bad logic I built a script that queries the domain registry. Just a disclaimer, this is NOT a hacking attempt. I am trying to gather a list of domains that my company does NOT host. Lets assume that the NameServer my company owns is ns.foo.net and my script does the following:

*

*Checks whois to find the Name Server of each domain.

*Then checks to see if the A record (querying the NameServer found) matches our IP address.

*If the Name Server is not ours AND the A record of the domain is not ours, add to a list. Otherwise, ignore it and move on through the list.

Let us also assume the list of domains are as follows:
example.net
exampleagain.org
blah.org
whatever.com

Here is my script:
#!/bin/bash

FILE=sites.txt
REGEX="Name Server"
OUR_IP="192.168.5.10"

#Read from Text file
while read -r line; do
        SERVER=`whois "$line" | grep -m 1 "$REGEX" | awk '{print $3}'`
        shopt -s nocasematch
        HOST=`host -ta "$line" "$SERVER"`
        if [[ ! "$SERVER" =~ foo.net && ! "$HOST" =~ "$OUR_IP" ]]; then
                echo "$line" >> results.txt
        fi
        sleep 1;
done<"$FILE"

I am noticing that the domains being added contains an A record of $OUR_IP and sometimes foo.net (my domain). What could be wrong with the if statement that is breaking the logic?


text:
Q: Cones and Dot Product Let $V$ = {$v_1$, $v_2$,......,$v_k$} be a collection of $k$ vectors in $R^n$. Prove that a vector $z$ in $R^n$ is not in the cone of $V$ if and only if there is a vector $w$ in $R^n$ such that $z$ is less than $90$ degrees from $w$ but every $v_i$ in $V$ is at least $90$ degrees from $w$.
I know that $z$ would be in the cone of $v$ if and only if $z=\sum _{m=0}^k\:x_iv_i$, where all $x_i$ are a set of non-negative numbers. I also see that it is being implied here that the dot product of $w$ and $z$ is greater than $0$ and the dot product of all $v_i$ and $z$ is less than $0$.
But I am not sure how to proceed further than this. I was thinking about utilizing the distributive property of the dot product and how it would lead to a contradiction if the above condition holds. But I am not entirely sure on how to proceed.
Any input would be greatly appreciated!

A: Prove the contrapositive.
Suppose that $z = \sum x_iv_i$ for $x_i$ non negative. Let $w$ be a vector such that every $v_i$ has an angle of at least $90^\circ$ with $w$. This implies that $v_i \cdot w \leq 0$ for all $i$.
Now,
$$
z \cdot w =\left(\sum x_iv_i \right)\cdot w =  \sum x_i (v_i \cdot w) \leq 0
$$
because each term $x_i(v_i \cdot w)$ is a product of a $+$ and a $-$ term, so is non-negative. Therefore, there is no way that $z$ can be less than $90^\circ $ from $w$.
Therefore, no such $w$ as mentioned in the question exists.


text:
Q: Tensorflow: make custom Conv2d Layer with custom gradient I'd like to have a Conv2d layer, that is able to return a gradient with values at certain indices multiplied with 0.2. The original functionality should remain.
My idea was to subclass the Conv2d class and have a setter method to save the indices where the groundtruth is 0:
import tensorflow as tf

class BackpassFilter(tf.keras.layers.Layer):
    def __init__(self, kernel_initializer, num_filter=48, kernel_size=3, stride=1, padding='same', name='keypoints_3_4'):
    super(BackpassFilter, self).__init__()
    self.fc = tf.keras.layers.Conv2D(kernel_initializer, num_filter, kernel_size, stride, padding, name, kernel_initializer=kernel_initializer)

    def call(self, input):
        return self.fc(input)

    def add_filter_indices(self, ground_truth):
        self.tmp_indices = tf.where(tf.equal(ground_truth, 0))

    @tf.custom_gradient
    def custom_gradient(self, x):
        ...

I have found that @tf.custom_gradient is something I could use. How can I implement the method to access the original gradients, manipulate and return them? Do I have to register the custom gradient somehow to be used in the class?


text:
Q: Android app button text disappears after months of working fine I have a field service reporting android app that I created in Oracle MAF. it has been in use for almost a year now with no UI issues, Over the last few days, I have been getting reports from our end users that the button text is disappearing. so - anywhere where there is a button with text inside it, the text is not visible. same font is being used elsewhere in the app with no issues. All the end users are running this on the Samsung Tab A 8.1. The last android update for the device was a few weeks ago. The problem is slowly propagating, like only 4-5 users a day are reporting that they go to use the app and the text is gone. luckily they are used to the app and know what all the buttons do, but I have to eventually fix it. I can't get any straight answers from Our IT department or Samsung as to why it is happening like this, and the update didn't seem to have anything in it that could do this. A factory reset fixes it for a day or two, and then the issue comes back.
What it is supposed to look like
Example of missing text
Like I said, this has been working fine for a while now. I'm mainly looking to see if anyone is aware of an Android update that would cause this, or if there was anything in the Samsung security update that would do it.

A: Google pushed an update to Chrome that they have discovered caused problems like this, and many others.
I was able to instruct my end users to disable chrome and let it roll back to the factory version.
this fixed the issue.


text:
Q: Full-height sidebar I have the following page with sidebar: https://www.slagerijrudi.be/product/broodje-ham/
I was wondering if there is a simple way to make my sidebar have the same height of the content next to the sidebar. So the sidebar should stretch from header to footer, instead of stopping halfway the page.

A: In order to allow the aside (or sidebar) to reach its full height, you can make it have an absolute position. Do remember though to turn it off for smaller screen sizes (where you'd want to collapse the sidebar). The best design practice at the moment is to declare specific behaviour for larger screens: @media screen and (min-size:667px) { .. your code for big screens here .. }
Add the following to solve the issue:
.wf-wrap {
  position: relative;
}

.sidebar {
  position: absolute;
  left: 0;
  height: 100%;
}

Edit: as a comment on the question put it, a flexbox is a neater solution, but not a 'quick fix'.


text:
Q: Adopt a protocol for Array and Dictionary I have the following protocol:
protocol MyProtocol {

    var stringValue: String { get }
}

I also implemented it's methods for some classes and structures in extensions:
extension Int: MyProtocol {

    var stringValue: String {

        return "IntValue"
    }
}

extension String: MyProtocol {

    var stringValue: String {

        return "StringValue"
    }
}

extension Array: MyProtocol where Element == Dictionary<String, Any> {

    var stringValue: String {

        return "ArrayValue"
    }
}

extension Dictionary: MyProtocol where Key == String, Value == Any {

    var stringValue: String {

        return "DictionaryValue"
    }
}

When I tried to test it with the following code:
let dict = [["key":"value"]]
let stringValueResult = dict.stringValue
print(stringValueResult)

I received an error with text "[[String : String]] is not convertible to Array<Dictionary<String, Any>>". However my code works fine when I set type of the variable dict like that:
let dict: Array<Dictionary<String, Any>> = [["key":"value"]]

Can someone explain me why the first version of my code is not compiling?

A: You should change your Array and Dictionary implementation constraint like this:
extension Array: MyProtocol where Element: MyProtocol {

    var stringValue: String {

        return "ArrayValue"
    }
}

extension Dictionary: MyProtocol where Key == String {

    var stringValue: String {

        return "DictionaryValue"
    }
}

Now if you run following code it will print: ArrayValue
let dict = [["key":"value"]]
let stringValueResult = dict.stringValue
print(stringValueResult)

A: The reason for this error is the conflict between the dict type inferred by the compiler and the one you mentioned while conforming Array to your protocol.
When you write this line
let dict = [["key":"value"]]

For compiler it will become as below where type is Array<Dictionary<String, String>>
let dict: Array<Dictionary<String, String>> = [["key":"value"]]

Now when you are doing dict.stringValue, compiler will first match the type of the calling object i.e dict with the type you defined during conformance of Array with MyProtocol
As the compiler inferred type i.e, Array<Dictionary<String, String>> is different than the type you mentioned in conformance i.e, Array<Dictionary<String, Any>> so compiler throws error.
But when you declare dict variable with explicit type i.e, Array<Dictionary<String, Any>> same as you defined in conformance of MyProtocol then compiler does not see any issue and your code works just fine.
While conforming Array/Dictionary to MyProtocol you can just ignore setting the Element type as below,
extension Array: MyProtocol {

    var stringValue: String {

        return "ArrayValue"
    }
}

extension Dictionary: MyProtocol {

    var stringValue: String {

        return "DictionaryValue"
    }
}


text:
Q: In Facebook Comments, how to disable the mobile ver of it? And, what decide if a device is mobile or not? I'm now designing Facebook Comments for my personal Wordpress. But I got stuck for the setting on mobile version of it.

Desktop version of Facebook Comments

Mobile version of Facebook Comments
According to the Docs of Facebook Developer, the setting mobile is set to be "auto-detect" by default. Since the mobile Facebook Comments lacks good design, I'd like to make it the same as the desktop version. Then I set the attribute mobile to false, but this didn't work when I opened the site in mobile device. It's still the mobile ver of it. A temp demo is here
So now, how to make Facebook Comments always the desktop version?
Also, how does it decide whether the device is mobile? I can also pretend the browser to be mobile in dev tools. Just pretty curious about this.
UPDATE:
@björn-kaiser, the following is my HTML code for Facebook Comments. Too bad it did not work still. Temp demo as before
<div class="fb-comments" data-mobile="false" data-width="100%" data-numposts="3" data-href="http://<?php echo $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"] ?>" mobile="false">

A: The attribute is actually called data-mobile not mobile. I just tried it and it seems to work. Setting it to false rendered the "desktop" version and setting it to true forced it to be the mobile one.


text:
Q: When querying over many lquery, should I query an array of lqueries or join them using '|'? When using the ltree PostgreSQL extension, there are these two operators (among others) at our disposal to compare ltree columns to lquerys.
ltree ~ lquery
ltree ? lquery[]

It seems that you should use ~ for single queries and ? for multiple queries. However, you can also join queries with the use of the | logical OR operator.
So, these two are equivalent when it comes to the queried results:
ltree ~ lquery1 || "|" || lquery2
ltree ? {lquery1, lquery2}

Which of these forms should I prefer?


text:
Q: What is the default TextStyle for label in TextField in Flutter? I want to have the same TextStyle for the DropdownButton hint and items (Text) as that of the label in TextField widget. In my case, the dropdown item is as follows -
DropdownMenuItem<String>(
     value: value,
     child: Text(value),
);
// where the value is a String

A: You can set the style of the DropDownButton hint and items to:
Theme.of(context).inputDecorationTheme.labelStyle

Example:
Text(
  'sample text',
  style: Theme.of(context).inputDecorationTheme.labelStyle,
)


text:
Q: Jumbotron cuts the text My Jumbotron cut's the text and button, when I have a low resolution.
Do I need to solve this problem with a media query?
Or is there a "nicer" solution for this? at the moment I have only media query for the width.
.hero-bg {
    background-color: #2e82b0;
}

.img-logo {
    max-width: 100%;
}

.jumbotron {
    height: 100vh;
}

Willkommen in meiner Welt:

                        Mit emotionalen Worten und kreativen Konzepten die passende Bühne bereiten.

                        Überzeugen. Begeistern. Bewegen – und der Star sind SIE!

                        <large></large>

A: You should use min-height instead of height...
.jumbotron {
    min-height: 100vh;
}


text:
Q: How to import files from github and host it on any other site I guess this is not the best place to post this. Please if it is not accepted here can you point me to another StackOverflow site where I can post this.
Here is what I am asking.
I have an index.html which I want to import and host to my openshit Redhat account.
https://github.com/areaboy/myfirstdata/tree/master/adminmanager/index.html
my issue is that when I entered the above url in my openshift redhat Import source location.
It throws errors.
Please what is the proper way of cloning the git files and then upload to openshift
Below is the screenshot of the openshift Import Git repository url:

A: You will have to give the .git url of your repository not the path of your index.html file for importing.

Go to url:- https://github.com/areaboy/myfirstdata
Click on the clone or download button you will get the url for your git repository now give this url while importing.

Copy the url and give it while importing the project in openshift.

A: It's asking for a repository URI, in your case it would be

https://github.com/areaboy/myfirstdata

Then I don't know if your file needs to be at the root of your repository or if you can give him a path later on.
Also note that it's asking for a http URI and Github is using https.


text:
Q: How to properly remove timestamp from date? I have a data set that originally has a time stamp like this:
'9/9/21 9:55'

I would like it to look like this:
'9/9/21'

However after using this code:
final$Date <- format(as.POSIXct(final$Date, format='%m/%d/%Y %H:%M'),
                     format='%m/%d/%Y')

I end up with this:
'09/09/0021'

A: as.character() works here. You might also be interested in the lubridate package.
> date.time <- as.POSIXct('9/9/21 9:55', format = '%m/%d/%Y %H:%M')
> as.character(date.time, format = '%m/%d/%Y')
[1] "09/09/21"

And in this specific case, gsub() is an even simpler solution, as Mikael Jagan suggested in a comment above. Note that there is a space before the '.', i.e., gsub(' .+$', '', '9/9/21 9:55').


text:
Q: How to re-use a mediaplayer after release() and null? My app has a button which is playing a short mp3 file when clicked. I want to release and reuse the mediaplayer object properly (so it will not interfere other apps)  when e.g. user gets a phone call, or home button is being clicked.
If I implement onPause and onStop this way:
@Override
public void onPause() {
    super.onPause();
    mp.release();
    mp = null;
}

@Override
public void onStop() {
    super.onStop();
    mp.release();
    mp = null;
}

then how do I re-use mp when onRestart is being called? is it the right way to do that? maybe I should use mp.stop()?
thanks
Edit: I found a solution myself. re-creating the object again:
@Override
publib void onResume() {
    super.onResume();
    mp = new MediaPlayer();
}

does the job. still a noob...:)  thanks

A: Use onCompletion
@Override
                                public void onCompletion(MediaPlayer mp) {
                                    // TODO Auto-generated method stub
                                    myStereo.setLooping(true);
                                    myStereo.release();
                                    try {
                                        myStereo.prepare();
                                    } catch (IllegalStateException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    } catch (IOException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                    myStereo.start();

                }


text:
Q: MySQL Error 1349 SELECT in SubQuery Issue Having spent quite some time getting my head around how to get the results out of a couple of table correctly I'm absolutely back to square one as the Views in MySQL won't allow me to create one with a SubQuery...
I found a similar thread that states I can write separate views for the sub query but having attempted this I have got myself in a bit of a muddle.
My original query is:
SELECT a.*
    FROM (SELECT H.username,
    H.variety,
    IFNULL(SUM(H.weight),0) - IFNULL(HU.weight,0) As qty
        FROM harvest H
            LEFT JOIN harvest_used HU
            ON H.variety = HU.variety AND H.username = HU.username
            WHERE H.username = 'palendrone'
            GROUP BY H.variety
            ORDER BY H.variety ASC
     ) a

Now this works perfectly, but as described I cannot figure out what I need to do in order to convert it to make it run as a view on my MySQL server...
Any guidance or help would be much appreciated, Thanks.

A: Your outer query isn't doing anything, so just remove it:
SELECT H.username, H.variety,
       COALESCE(SUM(H.weight), 0) - COALESCE(SUM(HU.weight, 0)) As qty
FROM harvest H LEFT JOIN
     harvest_used HU
     ON H.variety = HU.variety AND H.username = HU.username
WHERE H.username = 'palendrone'
GROUP BY H.variety
ORDER BY H.variety ASC;

MySQL does not allow subqueries in the from clauses for views.  This is a peculiar limitation of MySQL that doesn't seem to exist in any other databases.

A: Saw that the above solution had a SUM missing and also duplicated the results. Using DISTINCT seemed to fix the issue, Here's my answer:
SELECT H.username,
     H.variety,
     SUM(distinct(H.weight)) - SUM(distinct(HU.weight)) As qty
           FROM harvest H
                LEFT JOIN harvest_used HU
                ON H.variety = HU.variety AND H.username = HU.username
                WHERE H.username = 'palendrone'
                GROUP BY H.variety
                ORDER BY H.variety ASC


text:
Q: How can i deploy ssrs report one server to another server When I create a sample ssrs report and I deploy it, I get the following error:

The specified report server URL http://localhost/reports could not be
  found. verify the syntax of the URL and that report server exits.

A: The URL you are currently using is for the report manager.
Report RDLs are deployed to the report server URL, so change the path to http://localhost/reportserver.
Alternatively, you can find the correct URL for your server configuration in the Reporting Services Configuration Manager > Web Service URL (generally located in the Start menu > All Programs > Microsoft SQL Server {Version} > Configuration Tools).
For more information: TechNet: How To Publish Reports


text:
Q: Where would I put my call to wp_remote_get? I have a sidebar is supposed to loop through a bunch of job postings that are fetched from a GET request. The resulting HTML should look like this:

Related Positions

Job title really really long

Location

Job title really really long

Location

Let's say for now that the API URL is https://jsonplaceholder.typicode.com/todos.
I found wp_remote_get ( https://developer.wordpress.org/reference/functions/wp_remote_get/ ) but I'm not sure where I put it. Should I just put it in the view file?
I'm guessing I should make a function that:

*

*Calls wp_remote_get("https://jsonplaceholder.typicode.com/todos")

*Returns the array of job posting objects

in functions.php, but I'm not sure how I would export it so it would be available in the view.

A:
I'm guessing I should make a function that:

*

*Calls wp_remote_get("https://jsonplaceholder.typicode.com/todos")

*Returns the array of job posting objects

Yes, that still leaves the question of where to call it

in functions.php, but I'm not sure how I would export it so it would be available in the view.

Functions in functions.php are available in templates, making it available in the view isn't an issue if you're using WordPress theme templates correctly
As for where you would call this function? In the place you want to display it. However, there are downsides to your approach:

*

*Doing a remote request in PHP to another server on the frontvend is one of the worst things you can do for performance and scalability

*If it's just a remote GET request with no authentication, you can do that in JS

Doing it in javascript instead would shift the work to the browser, and make page caching better as it wouldn't cache stale results.
So you could do something like this in javascript:
fetch('https://jsonplaceholder.typicode.com/todos')
    .then(function(response) {
        return response.json(); // decode the JSON
    })
    .then(function(json) {
        // create a container dom node, and fill it with todo items
        const container = jQuery('
', { id: "todos"
        const todos = json.map( todo =>
            jQuery( '

', text: todo.title)
        );
        container.append( todos );
        // add it to the page inside a div with an ID, we're adding it all at once for performance reasons
        jQuery('#sidebartodos').append( container );
    });


text:
Q: Django: how to map the results of a raw sql query to model instances in admin list view? Consider the simple model:
class Item(models.Model):
    name                = models.CharField(...)
    unit_cost           = models.DecimalField(...)
    unit_price          = models.DecimalField(...)

It has the following admin class:
class ItemAdmin(admin.ModelAdmin):
    def queryset(self, request):
        qs = self.model._default_manager.get_query_set()
        qs2 = self.model._default_manager.raw('''
        SELECT
            "stock_item"."id",
            "stock_item"."name",
            "stock_item"."unit_cost",
            "stock_item"."unit_price"
        FROM
            "stock_item"
        ''')
        qs3 = RawQuerySet('''
        SELECT
            "stock_item"."id",
            "stock_item"."name",
            "stock_item"."unit_cost",
            "stock_item"."unit_price"
        FROM
            "stock_item"
        ''', self.model)
        return qs   # WORKS
        return qs2  # DOESN'T WORK
        return qs3  # DOESN'T WORK

I am overriding the queryset() method so as to control the behavior of the admin list view. I want to perform a raw sql query in queryset(), map the results back to the Item model before sending them to the list view.
The problem is that returning qs2 or qs3 generates the following error in the template (without throwing an exception):
Database error
Something's wrong with your database installation. Make sure the appropriate database tables have been created, and make sure the database is readable by the appropriate user.

Mind you that running the raw query in a separate script works, for example:
items = Item._default_manager.raw('''
    SELECT
        "stock_item"."id",
        "stock_item"."name",
        "stock_item"."unit_cost",
        "stock_item"."unit_price"
    FROM
        "stock_item"
    ''')

for item in items:
    print item.name, item.unit_price # WORKS!

In fact, I have a bigger ambition, to be able to create a sort of a 'virtual model' that should not have a corresponding database table the purpose of which is to encapsulate sql projection queries in its admin class (so that the model can be displayed in it's admin list view).
I have tried another approach, not using ItemAdmin at all but instead using:
class ItemManager(models.Manager):
    def get_query_set(self):
        return Item._default_manager.raw('''
        SELECT
            "stock_item"."id",
            "stock_item"."name",
            "stock_item"."unit_cost",
            "stock_item"."unit_price"
        FROM
            "stock_item"
        ''')

with:
class Item(models.Model):
    objects = ItemManager()
    etc...

But now I am getting a template exception in admin list view:
'RawQuerySet' object has no attribute 'complex_filter'
What to do? Thanks...

A: Solved.
The simplest approach was to create a database view in sqlite3 (the db backend I'm using) and then add a normal model with a name compatible with the view. The model must have a set of fields with similar names to those of fields returned by the view. No admins or managers are necessary for my purposes.
View creation db script:
CREATE VIEW <view_name> AS SELECT etc...

View dropping db script (run as a preliminary step in case you need to re-create the view):
DROP VIEW <view_name>

The only thing you gotta be careful about when creating the view is to make sure you set:
class Meta:
    managed = False
    #ordering = ( '-date', )

so as not to create the table when syncdb is run.
One more thing, you need to pick a unique field in your view as a primary key (and reflect that in the model) otherwise django will complain with something like:
no such column: stock_itemdbview.id

Cheers!

A: Well looking at the src, QuerySet and RawQuerySet are similar but very different classes where a QuerySet trumps a RawQuerySet in terms of provided functionality.
If I understand this correctly the last error you mention is understandable as a RawQuerySet does not have the complex_filter method and I presume you are at somepoint calling model.objects.filter which I believe invokes the aforementioned.
It is also understandable how you can iterate over a RawQuerySet, because, for want of a better term, the 'core model' is still represented in a RawQuerySet as it would be in a QuerySet.
Would using extra() not suffice?
I'm still pondering over the first issue will come back if/when I find one.


text:
Q: wpf programatically set combobox selected item when bound to dictionary I have a combobox which is bound do a dictionary
Dictionary<String, myClass> boxItems;

The combobox has the following dataTemplate:
<DataTemplate>
    <TextBlock Text="{Binding Path=Key}"></TextBlock>
</DataTemplate>

This works fine for loading the values and getting the selected value, however I can't figure out how to set the selected value from codebehind.
any pointers?
I've tried setting selectedItem and selectedValue to a Key (which I know is in the dictionary), but when I load the page, the combobox hasn't selected anything.

A: Add this to your ComboBox
<ComboBox SelectedItem="{Binding SelectedBoxItem}"/>

And use this in a class that implements INotifyPropertyChanged:
private myClass _selectedBoxItem;
public myClass SelectedBoxItem
{
    get { return _selectedBoxItem; }
    set
    {
        _selectedBoxItem = value;
        OnPropertyChanged("SelectedBoxItem");
    }
}

A: You need to create a KeyValuePair with the key you want to select.
You can do something like this:
 myCombo.SelectedItem = new KeyValuePair<string, int>("myKey", boxItems["myKey"]);


text:
Q: Dependency Injection/IoC container practices when writing frameworks I've used various IoC containers (Castle.Windsor, Autofac, MEF, etc) for .Net in a number of projects. I have found they tend to be frequently abused and encourage a number of bad practices.
Are there any established practices for IoC container use, particularly when providing a platform/framework? My aim as a framework writer is to make code as simple and as easy to use as possible. I'd rather write one line of code to construct an object than ten or even just two.
For example, a couple of code smells that I've noticed and don't have good suggestions to:

*

*Large number of parameters (>5) for constructors. Creating services tends to be complex; all of the dependencies are injected via the constructor - despite the fact that the components are rarely optional (except for maybe in testing).

*Lack of private and internal classes; this one may be a specific limitation of using C# and Silverlight, but I'm interested in how it is solved. It's difficult to tell what a frameworks interface is if all the classes are public; it allows me access to private parts that I probably shouldnt touch.

*Coupling the object lifecycle to the IoC container. It is often difficult to manually construct the dependencies required to create objects. Object lifecycle is too often managed by the IoC framework. I've seen projects where most classes are registered as Singletons. You get a lack of explicit control and are also forced to manage the internals (it relates to the above point, all classes are public and you have to inject them).
For example, .Net framework has many static methods. such as, DateTime.UtcNow. Many times I have seen this wrapped and injected as a construction parameter.
Depending on concrete implementation makes my code hard to test.
Injecting a dependency makes my code hard to use - particularly if the class has many parameters.
How do I provide both a testable interface, as well as one that is easy to use?
What are the best practices?

A: The only legitimate dependency injection anti-pattern that I'm aware of is the Service Locator pattern, which is an anti-pattern when a DI framework is used for it.
All of the other so-called DI anti-patterns that I've heard about, here or elsewhere, are just slightly more specific cases of general OO/software design anti-patterns. For instance:

*

*Constructor over-injection is a violation of the Single Responsibility Principle. Too many constructor arguments indicates too many dependencies; too many dependencies indicates that the class is trying to do too much. Usually this error correlates with other code smells, such as unusually long or ambiguous ("manager") class names. Static analysis tools can easily detect excessive afferent/efferent coupling.

*Injection of data, as opposed to behaviour, is a subtype of the poltergeist anti-pattern, with the 'geist in this case being the container. If a class needs to be aware of the current date and time, you don't inject a DateTime, which is data; instead, you inject an abstraction over the system clock (I usually call mine ISystemClock, although I think there's a more general one in the SystemWrappers project). This is not only correct for DI; it is absolutely essential for testability, so that you can test time-varying functions without needing to actually wait on them.

*Declaring every life cycle as Singleton is, to me, a perfect example of cargo cult programming and to a lesser degree the colloquially-named "object cesspool". I've seen more singleton abuse than I care to remember, and very little of it involves DI.

*Another common error is implementation-specific interface types (with strange names like IOracleRepository) done just to be able to register it in the container. This is in and of itself a violation of the Dependency Inversion Principle (just because it's an interface, does not mean it's truly abstract) and often also includes interface bloat which violates the Interface Segregation Principle.

*The last error I usually see is the "optional dependency", which they did in NerdDinner. In other words, there is a constructor that accepts dependency injection, but also another constructor that uses a "default" implementation. This also violates the DIP and tends to lead to LSP violations as well, as developers, over time, start making assumptions around the default implementation, and/or start new-ing up instances using the default constructor.
As the old saying goes, you can write FORTRAN in any language. Dependency Injection isn't a silver bullet that will prevent developers from screwing up their dependency management, but it does prevent a number of common errors/anti-patterns:

*

*Abstraction inversion

*Circular dependencies

*Spaghetti code (sort of)

...and so on.
Obviously you don't want to design a framework to depend on a specific IoC container implementation, like Unity or AutoFac. That is, once again, violating the DIP. But if you find yourself even thinking about doing something like that, then you must have already made several design errors, because Dependency Injection is a general-purpose dependency-management technique and is not tied to the concept of an IoC container.
Anything can construct a dependency tree; maybe it's an IoC container, maybe it's a unit test with a bunch of mocks, maybe it's a test driver supplying dummy data. Your framework shouldn't care, and most frameworks I've seen don't care, but they still make heavy use of dependency injection so that it can be easily integrated into the end user's IoC container of choice.
DI isn't rocket science. Just try to avoid new and static except when there's a compelling reason to use them, such as a utility method that has no external dependencies, or a utility class that could not possibly have any purpose outside the framework (interop wrappers and dictionary keys are common examples of this).
Many of the problems with IoC frameworks come up when developers are first learning how to use them, and instead of actually changing the way they handle dependencies and abstractions to fit the IoC model, instead try to manipulate the IoC container to meet the expectations of their old coding style, which would often involve high coupling and low cohesion. Bad code is bad code, whether it uses DI techniques or not.


text:
Q: Finding functional extremals So my problem is as follows: find the extremals of the functional
$$I[x_1(t), x_2(t)]=\int_{0.5}^1(\dot{x}_1^{2}-2x_{1}\dot{x}_2t)dt,$$
given:
$$x_1(0.5)=2, \ \ \ \  x_2(0.5)=15, \  \ \ \  x_1(1)=1, \ \ \ \  x_{2}(1)=1.$$

A: Your Lagrange function is
$$L(x_1,x_2,\dot{x_1}, \dot{x_2},t)=\dot{x_1}^2-2x_1\dot{x_2}$$
And the Euler-Lagrange equations are
$$\frac{\partial L}{\partial x_1}-\frac{\mathrm{d}}{\mathrm{d}t}\left(\frac{\partial L}{\partial \dot{x_1}}\right)=0$$
$$\frac{\partial L}{\partial x_2}-\frac{\mathrm{d}}{\mathrm{d}t}\left(\frac{\partial L}{\partial \dot{x_2}}\right)=0$$
Which will give you a system of differential equations. And your second Euler-Lagrange equation will be a bit easier, because the Lagrange function is independent of $x_2$:
$$\frac{\mathrm{d}}{\mathrm{d}t}\left(\frac{\partial L}{\partial \dot{x_2}}\right)=0$$
$$\frac{\partial L}{\partial \dot{x_2}}=\text{constant}$$


text:
Q: Проблема с относительным импортом в python Вот структура файла:
modules
|-__init__.py
|-folder_swicher_user_agent
  |-__init__.py
  |-swicher_user_agent_v1.py
|-log_functions
  |-__init__.py
  |-create_one_error_log_f.py

Верхний init.py
from .folder_swicher_user_agent import *
from .log_functions import *

__all__ = ['folder_swicher_user_agent', 'log_functions']

Первый init.py
from .swicher_user_agent_v1 import *

__all__ = ['swicher_user_agent_v1']

Второй init.py
from .create_one_error_log_f import *

__all__ = ['create_one_error_log_f']

файл swicher
from ..log_functions.create_one_error_log_f import *
create_error_one_log('Привет')

файл error
import os
import datetime

def create_error_one_log(text_for_type_of_error):
    now_time_in_function_create_error_one_log = datetime.datetime.now().strftime('Время: %H:%M:%S')
    now_date_in_function_create_error_one_log = datetime.datetime.now().strftime('Дата: %d.%m.%Y')
    way_to_file = os.path.join(os.path.dirname(__file__), 'tables_user_agent', 'table_user_agent_1.txt')
    ready_message_in_error_log = f'\n\n{now_date_in_function_create_error_one_log}\n{now_time_in_function_create_error_one_log}\nПуть к файлу: {way_to_file}\nТип ошибки:{text_for_type_of_error}'
    with open('test_log_2.txt', 'a') as log_now:
        log_now.write(ready_message_in_error_log)

Пробема в том, что при запуске swicher выдается ошибка - attempted relative import with no known parent package - как ее решить?


text:
Q: Multiple button enabling I have 9 disabled buttons.  Is there any method to enable them at once instead of doing something like this:
button1.Enabled=True
button2.Enabled=True
...

A: Maybe this will work:
foreach(Button b in Controls){
   b.Enabled = true;
}

Here you select all your buttons, represented by b and then you enabled all of of them
Hope it helps

A: button1.enabled = button2.enabled = ... = true

A: Assuming you've grouped them well...
foreach(var button in parent.Controls.OfType<Button>())
   button.Enabled = true;

A: private void EnableButtons(bool enabled)
{
    var myButtons = new Button[] { button1, button2, button3 };

    foreach (var x in myButtons)
    {
        x.Enabled = enabled;
    }
}

This allows you to add and remove buttons to and from your button array as you see fit. nachogsiri's solution is great if you want to enable/disable every button on your form, if it is only certain related buttons, this gives you more control.

A: Linq does it quite pretty:
Controls.OfType<Button>().ToList().ForEach(c => c.Enabled = true);