text:
Q: Store value type as a database column in MySQL What I need is, I think, quite common. I want to create a global_variables table to store some variables I need throughout my web app using MySQL. The problem is that every variable has one of multiple types (int, float, string, BLOB, etc.). So I need to be able to create my table with columns like id, program_name, value_type, value where value is going to be a string that I'll convert accordingly on getting/setting the value. So some sample records would be:
[
    ['program_name' => 'invoice_number', 'value_type' => 'int', 'value' => '12345'],
    ['program_name' => 'last_merge', 'value_type' => 'date', 'value' => '10.06.2020'],//etc.
]

What stops me is the lack of a column type Type in MySQL. Any help with any suggestions is greatly appreciated!
P.S. I'm using MySQL MariaDB with Laravel 5.8.

A: Just store them as strings.
In a date context, the string will automatically convert.
In a numeric context, the string will automatically convert.
In a boolean context, the number 0 is false, anything else is true.
If you have counter-examples, let's see them.  There may be a simple workaround.

A: You could write your own constraint :
CREATE TABLE global_variables (
     id serial,
     ...
     value_type varchar(32),
     constraint check (value_type in ("int", "date", "varchar", "boolean" ... ))
);

A: So after some debugging and trials, I came up with a best working solution for my case. I registered the value_type column as an enum of the given allowed types and then created an accessor and a mutator (Laravel features) for my GlobalVariable model on the field value, which convert the values accordingly. Thanks for the suggestions!


text:
Q: Troubles with dynamic and immutable arrays of control In WPF C#, in code behind, I have to dynamically create an Array of Canvas (each Canvas also Children controls like Label, TextBox, Button etc.)
Canvas[] cv = new Canvas[myInt];
Label[] l = new Label[myInt];
TextBox[] tb = new TextBox[myInt];
...
Canvas.Children.Add(...);

Each of the Canvas can be dynamically added or removed. The issue is I have to give the Canvas array a length, and if one of the Canvas is removed the index will still remain and the afterwards elements cannot be pushed upward.  If later on I add new Canvases, the new Canvas may have a possibility to go out of range, unless I instantiate a very large Array from the beginning.
Is there a better solution to that? Would ArrayList, or List or what else?

A: This seems obvious but since you do not know in advance how many elements you have to store you should use a List<Canvas>, List<Label> etc. then you can use the methods list.Add() and list.Remove().
Don't use ArrayList, you want your data strongly typed and be able to add and remove items dynamically - so List<T> would fit the bill.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Download file onto virtual server using python I use a python script to download a file from a website periodically. I want to move this process to my virtual server. How do I do this?
This is the code I use
import webbrowser
url = 'https://www.djppr.kemenkeu.go.id/page/loadViewer?idViewer=9369&action=download'
chrome_path = 'C:/Program Files/Google/Chrome/Application/chrome.exe %s' #Windows
webbrowser.get(chrome_path).open(url)

Visiting the link results in the file being automatically downloaded onto my PC. The issue is that there is no "chrome browser" on my virtual server. I also don't know whether it will save the file as it does on my PC.

A: *

*install Chrome headless on server (Ubuntu, CentOS)

*use python + selenium to run chrome headless in background

*profit

Or just use requests or urllib python libraries if you don't need javascript support on client side.
In other way you may use PhatomJS instead of Chrome browser


text:
Q: Fitting of continuous transfer function I measure a network's transfer function using a network analyzer and therefore have a set of complex data points, representing the network's gain and phase. I wish to fit a continuous, rational transfer function to my measured data to create a model of my network.
To find a discrete-time model, there is the "Frequency Domain Least Squares" algorithm:
http://robotics.itee.uq.edu.au/~elec3004/2014/lectures/Precise%20Filter%20Design%20(chapter).pdf
Several months ago, I found a PDF which presented a very similar method to estimate a continuous transfer function, but I don't remember where it is nor do I remember its name. I only remember that it was also a simple least squares algorithm as in the above link. Does someone have a hint for this?
Update:
Meanwhile I was able to recover the paper I mentioned. It is called 'Practical Transfer Function Estimation and its Application to Wide Frequency Range Representation of Transformers'. In my application, I am not dealing with a transformer but with some other passive electrical network involving RLC components, and I try to fit a transfer function to that. The network analyzer gives me some complex data for logarithmically spaced frequencies. I tried to use the method presented in the paper, but since my frequencies range from several Hz to several 100 MHz, the algorithm is unable to converge because the matrix A involves \$\omega\$, \$\omega^2\$, \$\omega^3\$ and so on - which leads to an ill-conditioned equation system, and therefore it cannot be solved. I wonder whether there are better algorithms than this, or whether this algorithm could be used, though, perhaps with some pre-processing of my frequency data.
Link to the paper I mentioned:
https://ieeexplore.ieee.org/document/252689

A: You'll be jumping down the rabbit hole of system identification and modelling. Generally speaking you will need two things:
The first is a so-called estimator (wiki), that you can use to find the best "fit" of a general rational transfer function. The ones I've encountered most are

*

*Least-Squares Estimator

*Maximum-Likelihood Estimator (wiki)

They work by defining a cost function that you try to minimize using the unknown tranfer function coefficients. For the least-squares estimator, the cost function is simply the sum of the squared errors.
The second one is a model selection criterion (wiki). In order to avoid modelling the noise of your data points, you can use this criterion to formally find the optimal model complexity (order of the system).

A: The goal of Matlab function invfreqs is to identify continuous-time filter parameters from frequency response data. The idea is based on Levi, E. C. "Complex-Curve Fitting." IRE Trans. on Automatic Control. Vol. AC-4, 1959, pp. 37–44. The main problem is to
adjust n and m parameters (the orders from numerator and denominator).


text:
Q: Formatting front matter title and page number in ToC to be single spaced and roman I want to achieve the following (ignore the artifacts, it's from a university reference for their thesis style),

I have the following MWE,
\documentclass[12pt, a4paper, oneside, parskip=full]{memoir}

\setulmarginsandblock{2.5cm}{3cm}{*} % Upper-Lower margins
\setlrmarginsandblock{3.8cm}{2.5cm}{*} % Left-Right margins
\checkandfixthelayout

%******************************
%      Table of con../fig../tab..
%*************************
\renewcommand{\contentsname}{TABLE OF CONTENTS}
\renewcommand{\listfigurename}{LIST OF FIGURES}
\renewcommand{\listtablename}{LIST OF TABLES}
\renewcommand{\printtoctitle}[1]{\centering\Large\bfseries #1}
\renewcommand{\printloftitle}[1]{\centering\Large\bfseries #1}
\renewcommand{\printlottitle}[1]{\centering\Large\bfseries #1}
\renewcommand{\chapternumberline}[1]{\MakeTextUppercase{\chaptername\
\numtoName{#1}: }}

\setcounter{tocdepth}{3}
\renewcommand\cftchaptername{\chaptername~}
\renewcommand{\cftchapterdotsep}{\cftdotsep}% Chapters should use dots in ToC
\usepackage{times} % Use Times font

%******************************
%      Spacing
%*************************
\usepackage{parskip}
\setlength{\parindent}{1.2cm} % Paragraph indent
\frenchspacing % Use single space after end of sentence

%******************************
%      Others
%*************************
\usepackage{pdfpages}
\usepackage{lipsum}

\begin{document}
%******************************
\frontmatter
%*************************
\includepdf[addtotoc={1,chapter,1,First Page,First Page}]{SamplePage.pdf}
\includepdf[addtotoc={1,chapter,1,Second Page,Second Page}]{SamplePage.pdf}
\includepdf[addtotoc={1,chapter,1,Third Page,Third Page}]{SamplePage.pdf}

\tableofcontents*
\listoftables
\listoffigures

%******************************
\mainmatter
%*************************
\DoubleSpacing
\chapter{Introduction}
\lipsum[4-5]

%******************************
\backmatter
%*************************

\end{document}

Here is the code for SamplePage.tex:
\documentclass{article}
\title{Sample Page}
\usepackage{lipsum}
\begin{document}
\maketitle
\lipsum[4-5]
\thispagestyle{empty}
\end{document}

I've got the following so far,

I've already read Customising ToC appearance of chapter titles in front and back matter but I don't think it applies here since I'm using memoir.
My questions:

*

*How to make front matter titles and respective numbers be roman (un-bold)? and have trailing dots in between them?

*How can I have single spacing between the front matter entries in the ToC?

*How can I have "List of Figures" and "List of Tables" in the ToC but full caps in the \title{} and thus the page?

*How can I make Chapter headings along with their titles in full caps?

*and also make chapter, and all sections, subsections, etc. have trailing dots to their respective page numbers?


text:
Q: Validate a form using model and no table How can I validate a form (such as a contact form) using a model that doesn't have a database table (so not standard record validation).
I've tried this, but I get the error:
undefined methodvalid?' for Contact:Class`
class Contact
  include ActiveModel::Validations
  attr_accessor :subject, :query
  validates :subject, { :presence => { message:'Please select a subject' } }
  validates :query, { :presence => { message:'Please enter your message' } }
  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end
  def persisted?
    false
  end
end

and then the methods:
def contact
  @page_title = 'Contact Us'
end

def contact_email
  if Contact.valid?
    message = "#{params[:subject]}: #{params[:query]}"
    current_user.send_contact_message(message)
    redirect_to '/contact', notice: 'Thank you for your message, we will be in touch shortly.'
  else
    render :contact
  end
end

A: valid? is an instance method. You can only call it on an instance of the class and not on a class. You need to change this line
if Contact.valid?

to this
contact = Contact.new(subject: 'some subject', query: 'some query')
if contact.valid?

Hope that helps!

A: One the new features of Rails 4 was ActiveModel::Model which makes it extremely easy to create table-less models. It gives you validations, translations through the I18n module, form bindings, polymorphic routing etc. Pretty much everything ActiveRecord::Base does except persistence.
class Contact < ActiveModel::Model
  attr_accessor :subject, :query
  validates :subject, presence: { message:'Please select a subject' }
  validates :query, presence: { message:'Please enter your message' }
end

Apart from that your error is caused by the fact that you are calling .valid? on the Contact class and not an instance.
The rails way would be to do:
# config/routes.rb
resources :contacts, only: [:new, :create]

# app/controllers/contacts_controller.rb
class ContactsController < ApplicationController

  def new
    @contact = Contact.new
  end

  def create
    @contact = Contact.new(contact_params)
    if @contact.valid?
      message = "#{params[:subject]}: #{params[:query]}"
      current_user.send_contact_message(message)
      redirect_to '/contact', notice: 'Thank you for your message, we will be in touch shortly.'
    else
      render :new
    end
  end

  private

    def contact_params
      params.require(:contact).permit(:foo, :bar)
    end
end


text:
Q: Accessing values of XML using Linq I have been trying to parse and extract some values from xml (starts off as a string) which I retrieved from a web service but i'm struggling to iterate through it. Here is the format of the xml string (sorry it's a bit dense):
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetInstantaneousFlowDataResponse xmlns="http://www.NationalGrid.com/EDP/UI/">
      <GetInstantaneousFlowDataResult>
        <ReportName xmlns="http://www.NationalGrid.com/EDP/BusinessEntities/Public">string</ReportName>
        <PublishedTime xmlns="http://www.NationalGrid.com/EDP/BusinessEntities/Public">dateTime</PublishedTime>
        <EDPReportPage xmlns="http://www.NationalGrid.com/EDP/BusinessEntities/Public">
          <PageName>string</PageName>
          <CurrentGasDay>dateTime</CurrentGasDay>
          <EDPEnergyGraphTableCollection>
            <EDPEnergyGraphTableBE xsi:nil="true" />
             <ItemPosition>1</ItemPosition>
                     <EDPObjectCollection>
                        <EDPObjectBE>
                           <EDPObjectName>ALDBROUGH</EDPObjectName>
                           <EnergyDataList>
                              <EDPEnergyDataBE>
                                 <ApplicableAt>2014-09-24T12:00:00</ApplicableAt>
                                 <FlowRate>0</FlowRate>
                                 <QualityIndicator />
                                 <ScheduleTime>2014-09-24T12:12:00</ScheduleTime>
                              </EDPEnergyDataBE>
                           </EnergyDataList>
                        </EDPObjectBE>
            <EDPEnergyGraphTableBE xsi:nil="true" />
          </EDPEnergyGraphTableCollection>
          <NoteCollection>
            <EDPNoteBE xsi:nil="true" />
            <EDPNoteBE xsi:nil="true" />
          </NoteCollection>
        </EDPReportPage>
      </GetInstantaneousFlowDataResult>
    </GetInstantaneousFlowDataResponse>
  </soap:Body>
</soap:Envelope>

I was trying to get just the name of each report for the moment then getting the rest of the values later but i'm not sure why it isn't working. This is the code I have been trying to get to work:
    Dim xmlDoc As XDocument = XDocument.Parse(xml)

    Dim reports = From flowData In xmlDoc...<EDPObjectBE> _
            Select flowData

    For Each flowData In reports
        MsgBox(flowData .<EDPObjectName>.Value)
    Next

Here is the answer that I was trying to emulate as it seemed most suitable for what I need:
LINQ to XML in VB.NET

A: You are missing a namespace:
Dim ns As XNamespace =
  XNamespace.Get("http://www.NationalGrid.com/EDP/BusinessEntities/Public")

For Each e As XElement In xmlDoc.Descendants(ns + "EDPObjectBE")
  Console.WriteLine(e.Element(ns + "EDPObjectName").Value)
Next

With XML, if you have a prefixed element, such as soap:Envelope, you need to be looking for namespace of xmlns:soap, which is http://schemas.xmlsoap.org/soap/envelope/, declared at the root in your XML. For non-prefixed, which is your case, look at the nearest parent element, which is EDPReportPage.
More explanation on the topic here:

*

*What does "xmlns" in XML mean?

A: If you wish to use namespaced XML literals, you have to import the namespace.
At the top of your module, declare the namespace:
Imports <xmlns:ns="http://www.NationalGrid.com/EDP/BusinessEntities/Public">

Then your query becomes:
Dim names =
    From obj in xml...<ns:EDPObjectBE>
    Select obj.<ns:EDPObjectName>.Value


text:
Q: Unprovable sentence, but provably it is provable. Work in Peano Arithmetic, PA. Let Prov(n) be a standard proof predicate, so that $PA \vdash Prov(\ulcorner \phi \urcorner) \text{ iff } PA \vdash \phi$ .
By Löb's theorem, we know that if $PA \vdash Prov(\ulcorner \phi \urcorner) \rightarrow \phi$ then $PA \vdash \phi$. The fact that this is a theorem  psychologically implies that we do not get the stronger result - if $PA \vdash Prov(\ulcorner \phi \urcorner)$ then $PA \vdash \phi$.
I am looking for counterexamples for the latter implication. Can anyone provide a sentence $\phi $ in PA such that $PA \vdash Prov(\ulcorner \phi \urcorner)$ and $PA \not\vdash \phi$?

A: No such $\varphi$ is known, nor is such (generally) believed to exist.
It is generally believed - similarly to how it is generally believed that PA is consistent - that no such $\varphi$ exists. Specifically, it is generally believed that PA is $\Sigma_1$-sound (= every $\Sigma_1$ sentence provable in PA is true), and indeed fully sound (= only proves true sentences). Of course, this tends to invoke at least a limited amount of Platonism; I'm not trying to argue the philosophical point, I just want to make it clear that the vast majority of mathematicians do not expect such a $\varphi$ to exist.
This is a nontrivial assumption, however: even PA+"PA is consistent" does not prove "PA is $\Sigma_1$-sound. So the phenomenon you're looking for, even though almost everybody thinks it won't happen, is still plausible at least in a very limited sense.

If we look beyond PA, however, we can easily find examples of this phenomenon. For instance, consider the theory $T=$ PA+"PA is inconsistent." By Godel's second incompleteness theorem, if PA is consistent then so is $T$, so $T\not\vdash 0=1$. However, we clearly have $T\vdash Prov_T(\ulcorner 0=1\urcorner)$.
That is, if PA is consistent, then PA has a consistent $\Sigma_1$-unsound extension.


text:
Q: One Edit Distance Away I  am currently doing some coding in the break to be fresh ready for semester 2 at university.
I have encountered a CTCI problem which I am struggling to understand, I have also looked at the hints, but still am a bit clueless on how to approach it
The question
One Away: There are three types of edits that can be performed on strings: Insert a character, remove a character or replace a character. Given two strings write a function to check if they are one or zero edits away
Sample INPUT AND OUTPUT

*

*Input -> pale, ple  Output-> true

*Input -> pales, pale Output -> true

*Input -> pale, bale Output -> true

*Input -> pale, bake Output -> false

PLEASE DO NOT GIVE ME THE SOLUTION
I have read the hints, and still do not understand how I should approach this problem, I understand that in order for an insertion to be valid, the length of String word1 and word2 must have a difference of 1.
Can someone please give me some hints on where I should start, when completing this problem. Thank you.

A: Start by breaking the problem into smaller pieces.
If the strings are the same, there has been no change, so first check equality.
If the strings are different, there are 3 different outcomes:

*

*a character has been replaced

*a character has been removed

*a character has been added

Treat each case separately. Add a new method that tries to detect each case, and call these methods from the main method of your solution. This will make the code structure easier to understand and to test.
In each case, you will use a loop to compare the characters in the two strings.
To find if one character has been replaced, count how many positions have different characters. If exactly 1, it's a replacement. If more than 1, it's a different edit.
Make sure that you can detect 1 character replacements before you continue with the remove and add cases.
To find if a character has been removed, count the number of positions with different characters like above, but with a slight modification: when you find a difference, increment the position of one of the counters so that you skip over a character in one of the string. This sounds confusing now, but it will be clearer  once you have written working code to detect the replacement case above. If you get stuck, you can always post a new a question here and get help with your code.

A: Hint but not solution does not make a good SO question! Here it is though: https://en.wikipedia.org/wiki/Levenshtein_distance

A: Compare the strings starting at the front to find the length of their common prefix.
Compare the strings starting at the end to find the length of the common suffix.
Now you can determine the answer entirely from the two string lengths and the common prefix and suffix lengths.


text:
Q: Puma not working with Rails 5 I am upgrading my Rails app from 4.1.1 to 5.1.4. Previously it was using webrick in application server, but as Rails 5 is using Puma as default server so I installed it but getting error.
config/puma.rb
# Change to match your CPU core count
workers 2

# Min and Max threads per worker
threads 1, 6

app_dir = File.expand_path("../..", __FILE__)
shared_dir = "#{app_dir}/shared"

# Default to production
rails_env = ENV['RAILS_ENV'] || "development"
environment rails_env

# Set up socket location
bind "unix:/home/system/project/shared/sockets/puma.sock"
# bind "unix:#{shared_dir}/sockets/puma.sock"

# Logging
stdout_redirect "#{shared_dir}/log/puma.stdout.log", "#{shared_dir}/log/puma.stderr.log", true

# Set master PID and state locations
pidfile "#{shared_dir}/pids/puma.pid"
state_path "#{shared_dir}/pids/puma.state"
activate_control_app

on_worker_boot do
  require "active_record"
  ActiveRecord::Base.connection.disconnect! rescue ActiveRecord::ConnectionNotEstablished
  ActiveRecord::Base.establish_connection(YAML.load_file("#{app_dir}/config/database.yml")[rails_env])
end

I have created a folder root path 'shared/sockets' with appropriate permissions:
drwxrwxrwx 1 system system 4096 Sep 19 10:35 tmp
drwxr-xr-x 1 system system 4096 Sep 19 10:37 sockets
drwxr-xr-x 1 system system 4096 Sep 19 10:51 shared

When I run rails s or try to run puma on foreground mode, getting the below error:
system@system /home/system/project (rails_upgrade_5 *) $ rails s
=> Booting Puma
=> Rails 5.1.4 application starting in development
=> Run `rails server -h` for more startup options
[28725] Puma starting in cluster mode...
[28725] * Version 3.10.0 (ruby 2.4.1-p111), codename: Russell's Teapot
[28725] * Min threads: 1, max threads: 6
[28725] * Environment: development
[28725] * Process workers: 2
[28725] * Phased restart available
[28725] * Listening on unix:/home/system/project/shared/sockets/puma.sock
Exiting
/home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/puma-3.10.0/lib/puma/binder.rb:367:in `initialize': Operation not permitted - connect(2) for /home/system/project/shared/sockets/puma.sock (Errno::EPERM)
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/puma-3.10.0/lib/puma/binder.rb:367:in `new'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/puma-3.10.0/lib/puma/binder.rb:367:in `add_unix_listener'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/puma-3.10.0/lib/puma/binder.rb:141:in `block in parse'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/puma-3.10.0/lib/puma/binder.rb:88:in `each'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/puma-3.10.0/lib/puma/binder.rb:88:in `parse'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/puma-3.10.0/lib/puma/cluster.rb:420:in `run'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/puma-3.10.0/lib/puma/launcher.rb:183:in `run'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/puma-3.10.0/lib/rack/handler/puma.rb:69:in `run'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/rack-2.0.3/lib/rack/server.rb:297:in `start'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/railties-5.1.4/lib/rails/commands/server/server_command.rb:44:in `start'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/railties-5.1.4/lib/rails/commands/server/server_command.rb:135:in `block in perform'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/railties-5.1.4/lib/rails/commands/server/server_command.rb:130:in `tap'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/railties-5.1.4/lib/rails/commands/server/server_command.rb:130:in `perform'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/thor-0.20.0/lib/thor/command.rb:27:in `run'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/thor-0.20.0/lib/thor/invocation.rb:126:in `invoke_command'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/thor-0.20.0/lib/thor.rb:387:in `dispatch'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/railties-5.1.4/lib/rails/command/base.rb:63:in `perform'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/railties-5.1.4/lib/rails/command.rb:44:in `invoke'
    from /home/system/.rvm/gems/ruby-2.4.1@rails_5/gems/railties-5.1.4/lib/rails/commands.rb:16:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>

I tried some solution given on stackoverflow but couldn't work.
Please let me know if I am doing something wrong.

A: Update your puma.rb to this file
# Puma can serve each request in a thread from an internal thread pool.
# The `threads` method setting takes two numbers a minimum and maximum.
# Any libraries that use thread pools should be configured to match
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum, this matches the default thread size of Active Record.
#
threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i
threads threads_count, threads_count

# Specifies the `port` that Puma will listen on to receive requests, default is 3000.
#
port        ENV.fetch("PORT") { 3000 }

# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }

# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked webserver processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }

# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory. If you use this option
# you need to make sure to reconnect any threads in the `on_worker_boot`
# block.
#
# preload_app!

# The code in the `on_worker_boot` will be called if you are using
# clustered mode by specifying a number of `workers`. After each worker
# process is booted this block will be run, if you are using `preload_app!`
# option you will want to use this block to reconnect to any threads
# or connections that may have been created at application boot, Ruby
# cannot share connections between processes.
#
# on_worker_boot do
#   ActiveRecord::Base.establish_connection if defined?(ActiveRecord)
# end

# Allow puma to be restarted by `rails restart` command.
plugin :tmp_restart

A: Issue is with following line
config/puma.rb
# Set up socket location
bind "unix:/home/system/project/shared/sockets/puma.sock"

Modify it as below:
# Set up socket location
bind "unix:///home/system/project/shared/sockets/puma.sock"


text:
Q: How to pass an async variable to option in Vue Plugin (VueGoogleMaps) Before I use package 'vue2-google-maps' in my app like that
// app.js

import apiKey from './apiKeyGoogleMap';
import * as VueGoogleMaps from "vue2-google-maps";

Vue.use(VueGoogleMaps, {
  load: {
    key: apiKey, //google map api key, load from apiKeyGoogleMap.js
    libraries: "places"
  }
});

new Vue({
  el: '#app',
  i18n,
  template: '<app/>',
  // Register App Component
  components: {
    app: App,
    ...
  }
});

// apiKeyGoogleMap.js
const apiKeyGoogleMap = '';
export default apiKeyGoogleMap;

And now, How I can load variable apiKey from an API instead load from apiKeyGoogleMap.js ?
// app.js
import * as VueGoogleMaps from "vue2-google-maps";
Vue.use(VueGoogleMaps, {
  load: {
    key: apiKey, // I want to load this variable from API
    libraries: "places"
  }
});

A: You can defer adding the plugin until your data has been loaded but then you should also defer creating the root Vue instance.
For example
import * as VueGoogleMaps from "vue2-google-maps";

fetch("/api")
  .then(res => res.json())
  .then(data => {
    Vue.use(VueGoogleMaps, {
      load: {
        key: data.apiKey,
        libraries: "places"
      }
    })

    new Vue({
      // router, store, render, etc
    }).$mount("#app")
  })

A: This is the same as Phil's answer but using a async/await function.
(I'm slow, but since I got this far, I might as well post it.)
import Vue from 'vue'
import App from './App.vue'
import axios from 'axios' // Or fetch or similar.
import * as VueGoogleMaps from "vue2-google-maps";

async function run () {

  // This placeholder api does not have an apiKey of course.
  const apiUrl = 'https://jsonplaceholder.typicode.com/todos/1'
  const apiResponse = await axios.get(apiUrl)
  const { apiKey } = apiResponse.data

  Vue.use(VueGoogleMaps, {
    load: {
      key: apiKey,
      libraries: "places"
    }
  })

  new Vue({
    render: h => h(App)
  }).$mount('#app')
}

run()

If you don't want to wait for the request before you mount your app, then you can do the same inside a component and remove Vue.use(), which is only there to make the plugin global. (for example: https://dev.to/terrierscript/example-for-google-map-with-vuejs-without-vue-library--3gf5)


text:
Q: Adjoint on $C([0,1])$ I am self-studying $C^{*}-$ algebra and the material I read tells me that if $C([0,1])$ represents a set of continuous functions $[0,1]\to\mathbb{C}$, then the adjoint on $C([0,1])$ is: $$f\in C([0,1]), f^{*}=\overline{f}$$
I don't get why taking adjoint on $C([0,1])$ is to take the complex conjugate. Any explanation?

A:
Any explanation?

Here are three rather immediate explanations.

*

*In a C$^*$-algebra you want elements of the form $f^*f$ to be positive. In $C[0,1]$ you have a natural notion of positivity which is $f\geq0$ if $f(t)\geq0$ for all $t$. So you need $f^*(t)f(t)\geq0$ for all $t$. What recipe can you give me, given a complex number $z$, to choose a number $z^*$ that depends on $z$ and such that it always gives you $z^*z\geq0$? I'm fairly sure you'll come up with $z^*=\overline z$.

*It is typical to see $C[0,1]$ as a subalgebra of $L^\infty[0,1]$ and to implement the latter as multiplication operators on $L^2[0,1]$. That is, there is a (very) natural way to see $C[0,1]$ as bounded linear operators $M_f$ on a Hilbert space, with $\|M_f\|=\|f\|_\infty^{\vphantom f}$. It is then an easy exercise to check that $M_f^{*\vphantom f}=M_{\overline f}$.

*If instead of $C[0,1]$ you consider $C(X)$ for a finite set $X$, you have $C(X)\simeq\mathbb C^{|X|}$ as vector spaces, as algebras, and as $*$-algebras if you consider $(x_1,\ldots,x_n)^*=(\overline{x_1},\ldots,\overline{x_n})$, which is the natural adjoint in $\mathbb C^{|X|}$. This corresponds again with $f^*=\overline f$.


text:
Q: How can I read a spark TextArea implicit line breaks? I have a TextArea where the user can enter text and also change the width and height of the TextArea. When resizing, the text is breaking where expected. I need to find where the TextArea skin added the implicit line breaks after resizing.
ENVIRONMENT

*

*FlexBuilder 4.6

*Flex SDK 4.6.0

*Flash Player 11.1

EXAMPLE
This is just plain text that
breaks after the word "that".

Any ideas on how to find the position of the line break when the TextArea lineBreak property is toFit and the text has no CR or LF characters? In the example above, it would be position 28.

A: You can split up the text into line components and return their individual text lengths pretty easily, but you'll have to use some 'text layout framework' magic.

*

*First access your TextArea's textFlow property (not the text property), which will return a TextFlow instance. This is a model for the text inside your TextArea.

*This object has a flowComposer which takes care of the layout of the text and carries a lot of information with it.

*Its type is IFlowComposer, but you'll have to cast it to a StandardFlowComposer in order to access the individual lines.

*Now you have access to the lines property, which is a collection of TextFlowLine

*Each of these lines has a textLength property.

So the following
var composer:StandardFlowComposer =
    myTextArea.textFlow.flowComposer as StandardFlowComposer;
for each (var line:TextFlowLine in composer.lines)
    trace(line.textLength)

would yield (with your example)
29
30


text:
Q: HTML Symbols magic just realized that html symbols like:
&

will be also recognized by browser WITHOUT
;

I had problem because of that:
&current

was replaced with
¤t

can you clarify - why?

A: Because any & in HTML should be encoded as &. So any & on its own will be interpreted as the start of a HTML entity and browsers attempt error correction (the parser may attempt to interpret the entity if a character falls outside of its allowable sequence, such as the space character).
Whenever you use a & in your HTML, encode it as &.

A: Some named character references are, for backward compatibility reasons, recognised without needing a trailing semicolon. &curren is one of them.
A full list of named character references, which shows those that don't need a trailing semicolon is given here: https://www.w3.org/TR/html51/syntax.html#named-character-references

A: Browsers try hard to make sense of garbage when they can. There's no rule that says they should do this, or that they have to, or even that it's a good idea. But if some browsers do this, then they just do.


text:
Q: Can I use String Join func with other function let sendData = '';
sendData = `${sendData}email=${currentUser.email}`;
sendData = `${sendData}&first_name=${first_name}`;
sendData = `${sendData}&last_name=${last_name}`;
sendData = `${sendData}&nationality=${nationality}`;
sendData = `${sendData}&date_of_birth=${date_of_birth}`;
sendData = `${sendData}&gender=${gender}`;
sendData = `${sendData}&id_type=${id_type}`;
sendData = `${sendData}&photoid_res=${photoid_res}`;
sendData = `${sendData}&selfie_res=${selfie_res}`;
sendData = `${sendData}&kyc_level=L1`;

I am trying to shorten this code by using Join func! Can you give me some idea to shorten this with that function?

A: Just put everything in an array and then join them:
let sendDataArray = [
    `email=${currentUser.email}`,
    `first_name=${first_name}`,
    `last_name=${last_name}`,
    `nationality=${nationality}`,
    `date_of_birth=${date_of_birth}`,
    `gender=${gender}`,
    `id_type=${id_type}`,
    `photoid_res=${photoid_res}`,
    `selfie_res=${selfie_res}`,
    `kyc_level=L1`
];

let sendData = sendDataArray.join('&');

I used a separate variable in the example above for clarity. But once you understand the code you can just do it in a single expression:
let sendData = [
    `email=${currentUser.email}`,
    `first_name=${first_name}`,
    `last_name=${last_name}`,
    `nationality=${nationality}`,
    `date_of_birth=${date_of_birth}`,
    `gender=${gender}`,
    `id_type=${id_type}`,
    `photoid_res=${photoid_res}`,
    `selfie_res=${selfie_res}`,
    `kyc_level=L1`
].join('&');


text:
Q: runas requested operation requires elevation on active directory I am having trouble understanding what is going on with "runas".
Situation:

*

*CLIENT is W10 Pro joined & logged in to Active Directory Domain FOODOM.

*USER is member of FOODOM and default Domain-User, nothing elevated.

*MYADMIN is member of FOODOM and member of Organization-Admin, Domain-Admin, etc. A typical Domain-Admin User.

*UAC is enabled.

*FOODOM\USER is logged in on CLIENT.

Problem:
FOODOM\MYADMIN is not allowed to runas with admin rights: from inside FOODOM\USER's session:
runas /user:FOODOM\MYADMIN cmd fails with "The requested operation requires elevation"
Hoewever, the built in administrator account works:
runas /user:FOODOM\Administrator cmd -> ok
FOODOM\MYADMIN can successfully login on CLIENT. When logged in, MYADMIN can run things with Domain Admin priveledges local and remote.
Thoughts:
Am I missing some flag? None of the adminiatrive users we usually use can successfully invoke runas except built in administrator...? I suspect it only works because the local workstation is mixing up FOODOM\Administrator with .\Administrator?
Edit:
As the comments seem to ignore the real question, here as clarification: I am aware of elevation issues with UAC and are refering to DOMAIN Administrator, not the local one. What is the reason domain\Administrator actually CAN circumvent runas elevation while domain\someAdmin can NOT? LDAP Flag? Delegation? if(username==*\administrator) { do.secretElevationHack(); } ?

A: While you can run a command as elevated by right-click and choosing
"Run As Administrator", this does not work for runas.
The reason is that runas was created before elevation was invented,
so it has no switch for running an elevated command.
An alternative is to invoke the UAC dialogue by calling the VBScript
ShellExecute function.
For example, to run a batch script (.vbs) with elevated permissions, use
the flag runas:
Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute "cmd.exe","/k echo test", "", "runas", 1


text:
Q: pass localStorage value into php I have a page which generates a chart. I have a button which generates a pdf report for it. I wanted to create an image of this chart and insert it into the pdf. To create the image, I use  html2canvas and get the dataurl which I store in the localstorage.
chart.php

   Report
   ..more code to generate the chart

The download button calls the pdfGen.php script which uses fpdf to generate a report.
pdfGen.php
<?php
    echo $_POST['data']; //gives error
    /*$pdf = new FPDF();
    $pdf->AddPage();

    //over here I want to add the image from the chart.php page whose data url is now in the localstorage.
    ..more code to generate report
    $pdf->output();*/
 ?>

How do I get the image inside the php script? I try to make the ajax call but I get undefined index data in pdfGen.php script. I got the alert HI but could not get the data on the server.
It does not seem to work.

A: Your ajax call is wrong.
Your call should be like this to get value hello in data variable/key
$('#download').click(function(e) {
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "pdfGen.php",
       data: 'data=hello',
       success: function(data) {
           alert("hi");
       }
   });
});

To learn more about the jQuery Ajax refer this link.

A: Here is an example passing localstorage from js to php session, assume using jQuery as ajax requester.
Handle
In root, add file: retrieve.php (This will RETRIEVE AND SYNC localstorage from js with session from php)
<?php

session_start();
$key = 'my-car'; // Your localstorage key
$client = (isset($_GET[$key]) && $_GET[$key] !== 'null') ? $_GET[$key] : null;
$server = isset($_SESSION[$key]) ? $_SESSION[$key] : null;
$_SESSION[$key] = $client; // Now stored in php´s session variable $_SESSION['my-car']

echo $client === $server ? 'true' : 'false'; // Tells js to reload if data was not synced

Set
In your index.html / index.php add this script: (This will PASS localstorage to php and reload if not synced after php´s session data is set)
<?php
  session_start(); // Dont forget this line
  $key = 'my-car';
  if (isset($_SESSION[$key]) && $_SESSION[$key] !== null) {
     $car = json_decode($_SESSION[$key], true);
     echo $car['name']; // Will print 'Tesla'
  }
?>

Use
And last, passing session from PHP to localstorage in js ->
In ANY php file:
<?php

start_session();
$key = 'my-car';

if (isset($_SESSION[$key]) && $_SESSION[$key] !== null) {
   // Print old value
   $car = json_decode($_SESSION[$key], true);
   echo $car['name']; // 'Tesla'

   // Update object
   $car['name'] = 'Honda';
   $_SESSION[$key] = json_encode($car);

   // Pass to js:
   echo "";

   // Prints the updated object with name 'Honda'
   echo "


text:
Q: Integrate from zero to infinity 1/(xe^x) I cannot solve the integral
$$\int_{x=0}^{\infty}\frac{dx}{xe^x}.$$
I tried it by use integration by parts and gama function.

A: As David Mitra commented,
the integral diverges
at zero.
More precisely,
for any $c > 0$,
$\begin{array}\\
\int_{c}^{1}\frac{dx}{xe^x}
&\gt \int_{c}^{1}\frac{dx}{ex}
\qquad\text{since }e^x \le e \text{ for }0 \le x \le 1\\
&= \frac1{e}\int_{c}^{1}\frac{dx}{x}\\
&= -\frac1{e}\ln(c)\\
&= \frac1{e}\ln(\frac1{c})\\
&\to \infty
\text{ as } c \to 0\\
\end{array}
$

A: $$\Gamma(s)=\int_{0}^{\infty}x^{s-1}e^{-x}dx $$
Your integral results for $s\to 0$, which is not convergent.

A:
In THIS ANSWER, I showed that the function $I(x)$ as given by $I(x)=\int_x^\infty \frac{e^{-t}}{t}\,dt$ satisfies the inequalities
$$\frac{1}{2}e^{-x}\ln\left(1+\frac{2}{x}\right)<\int_{x}^{\infty}\frac{e^{-t}}{t}dx<e^{-x}\ln\left(1+\frac{1}{x}\right) \tag 1$$
for $x>0$.

Note from the left-hand side inequality in $(1)$ that
$$\begin{align}
\lim_{x\to 0^+}\left(\frac{1}{2}e^{-x}\ln\left(1+\frac{2}{x}\right)\right)&<\lim_{x\to 0^+}I(x)
\end{align}$$
Therefore, $\lim_{x\to 0^+}I(x)=\infty$ and the integral fails to exist as an improper integral.


text:
Q: Program type already present: org.apache.commons.codec.BinaryDecoder I am using some .jar files as Vuforia and apache for my application. When I compile the application,
I face with Program type already present: org.apache.commons.codec.BinaryDecoder and I do not know to fix it. I searched many times but could not found same example with me.
This is my dependencies:
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:26.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
implementation 'com.android.support:support-annotations:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.android.support:design:26.1.0'
implementation files('src/main/java/Vuforia.jar')
implementation files('libs/mail.jar')
implementation files('libs/additionnal.jar')
implementation files('libs/activation.jar')
implementation files('libs/commons-io-2.6.jar')
implementation files('libs/commons-io-2.6-javadoc.jar')
implementation files('libs/commons-io-2.6-sources.jar')
implementation files('libs/commons-io-2.6-test-sources.jar')
implementation files('libs/commons-io-2.6-tests.jar')
implementation files('libs/commons-codec-1.11-javadoc.jar')
implementation files('libs/commons-codec-1.11-sources.jar')
implementation files('libs/commons-codec-1.11-test-sources.jar')
implementation files('libs/commons-codec-1.11-tests.jar')
implementation files('libs/commons-codec-1.11.jar')
implementation 'org.mnode.ical4j:ical4j:1.0.5'
implementation 'com.android.support:multidex:1.0.3'

}
Can you guys help me to fix problem?
Thank you

A: I experience the same error. I was using a jar which included:
implementation files('libs/commons-io-2.6.jar')

And in my app I too had included:
implementation files('libs/commons-io-2.6.jar')

So all I had to do was to remove that line from my app and not include the commons-io-2.6.jar file in my libs folder.

A: change:
implementation 'com.android.support:appcompat-v7:26.0.0'

to:
implementation 'com.android.support:appcompat-v7:26.1.0'

it might help


text: Q: issue with dashboard duplicates in superset I am a beginner at Superset. While working I came across an issue i.e. when I am creating a same dashboard but not creating in the same name dashboards.  Any help on this will be much appreciated.


text:
Q: ng-click function is not working on tabs in AngularJs? Hello sir i have to call function for get the list of albums but in my case ng-click is not working no action will be performed what's wrong in my code?

 //Our controller code here
  /**
  * @Summary: getAlbumsBySellerUserTypeKeyId function, get the productsAlbum list
  * @param: NA
  * @return: allAlbums
  * @Description:
  */
 $scope.allAlbums = [];
 $scope.sellerUserTypeKeyId = [];
 $scope.getAlbumsBySellerUserTypeKeyId = function() {
  //Enable class fadeAndDisable call the getAlbumsBySellerUserTypeKeyId() function
  $("#loadingAlbums").toggleClass("fadeAndDisable", true);

  $scope.sellerUserTypeKeyId = Number(AUTH.userTypeKeyId);
  var PRODUCT_DB_REF = firebase.database().ref('datastore/productsAlbum');

  //Re-enable class fadeAndDisable after response is received
  $("#loadingAlbums").toggleClass("fadeAndDisable", false);

  PRODUCT_DB_REF.orderByChild("sellerUserTypeKeyId").equalTo($scope.sellerUserTypeKeyId)
  .on("value", function(snapshot) {
    var value = snapshot.val();
    if(value != null) {
    $scope.allAlbums = objToArray(value);
    //USED FOR SET THE ALBUM LENGTH IN THE ALBUM TABS SECTION
    $rootScope.allAlbums = $scope.allAlbums;
    }
  });
 }

        Album
       0">({{allAlbums.length}})


text:
Q: Calculating Inverse Fourier Transform I can't quite get an inverse Fourier Transform to match up with a statement in my textbook.  At one point, my textbook writes:
"If $g$ is a function that is one on the interval $(- \pi, \pi]$ and zero otherwise, then $\mathcal{F}^{-1}g(\xi) = \sqrt{2 \pi} \text{sinc}(\xi)$"
I tried to calculate to verify this statement, but do not get the same answer.  The inverse Fourier transform is defined as:
$$\mathcal{F}^{-1}[g](x) = \frac{1}{\sqrt{2 \pi}} \int_{-\infty}^{\infty} g(\lambda) e^{i \lambda x} d \lambda$$
In this case we have $g = 1$ in the interval $[- \pi, \pi]$.  So my calculation will be:
$$\mathcal{F}^{-1}g(\xi) = \frac{1}{\sqrt{2 \pi}} \int_{- \pi}^{\pi} e^{i \lambda \xi} d \lambda$$
However, when I calculate this, I get the answer:
$$\frac{\sqrt{\frac{2}{\pi}} \sin(\pi \xi)}{\xi}$$
which does not correlate with the book.  Wolframalpha also gives this answer.  So is the book wrong here?  I would really apprecaite some input here!

A: $\operatorname{sinc}(x)$ is defined in two different ways; one of them is $$\operatorname{sinc}(x)=\begin{cases}\frac{\sin(\pi x)}{\pi x},&x \neq 0,\\1,&x = 0.\end{cases}$$ So, multiply your answer by $\frac{\pi}{\pi}$, simplify, use the definition above, and enjoy!


text:
Q: Prove or disprove that if $A$ and $B$ are dense, then $A \cdot B$ is dense There's this test question I'm having difficulty with. Let $A\subseteq \mathbb{R}$ and $B\subseteq \mathbb{R}$ be two sets in $\mathbb{R}$. Prove or disprove that if $A$ and $B$ are dense, then $A \cdot B$ is dense.
Note: If $A$ is dense then $\forall a_1, a_2 \in A, $ such that $ a_1 < a_2$ there exists $a_3 \in A$ such that $a_1 < a_3 < a_2$.
Also, we define $A\cdot B$ = $\{a \cdot b \mid a\in A$ and $b \in B\}$.

A: Initial hint: Given $a_1 b_1$ and $a_2 b_2$ in $A*B$, you need to find $a_3 b_3$ with $a_1 b_1 < a_3 b_3 < a_2 b_2$. How do you think you should pick $a_3$ and $b_3$?
Hint 2: Once you think this works, there's probably more to do.
Post-comment addition:
OP writes:

Well I've tried to define $a_3=\frac{a_1+a}{2}$ and $b_3= \frac{b_1+b_2}{2}$ so $a_1 b_1<a_3 b_3<a_2b_2$ but this isn't true for $a_1=−1,a_2=0,b_1=1,b_2=5$, for example. How can I find those $a_3$ and $b_3$such that $a_1b_1<a_3b_3<a_2b_2$?

Doing that gives you a number $a_3$ that is between $a_1$ and $a_2$, but how do you know that $a_3 \in A$? (Answer: you don't, for its entirely possible that it's not.) You need some other way to produce $a_3$ and $b_3$.
But as you note, that doesn't quite work -- negative numbers give you a problem. And now you have to think about whether the statement is actually true in cases where $A$ and $B$ have some negative numbers in them, or whether maybe it's false in those cases.
By the way: nothing you described actually used the given fact that $A$ and $B$ are dense, and that's a bad sign, because the claim that $A*B$ is dense is certainly not in general true if $A$ and $B$ are not dense.
Also: You might want to address the question raised in the comments in the original posting --- what definition of "dense" are you using? If it's "Dense in $\Bbb R$," then the claim is much easier to prove.

A: Here is another point of view :
Given $A\subset\mathbb{R}$, we have :
$A$ is dense iff for all $x\in\mathbb{R}$, there exists a sequence of elements of $A$ which converges to $x$.
Now suppose $A,B$ are dense subsets of $\mathbb{R}$ and take $x\in\mathbb{R}$. There exist $(a_n)\in A^\mathbb{N}$ and $(b_n)\in B^\mathbb{N}$ such that $\lim_{n\to\infty}a_n=x$ and $\lim_{n\to\infty}b_n=1$; hence $\lim_{n\to\infty}a_nb_n=x$, which proves that $AB$ is also a dense subset of $\mathbb{R}$.


text:
Q: Why are autoload, load_all! and require all used in active_support.rb? I was looking at active_support.rb to try to understand the load process it uses. It uses three loading methods: load_all!, autoload and require.
Why use three different ways of loading in the same file?
module ActiveSupport
  def self.load_all!
    [Dependencies, Deprecation, Gzip, MessageVerifier, Multibyte, SecureRandom, TimeWithZone]
  end

  autoload :BacktraceCleaner, 'active_support/backtrace_cleaner'
  autoload :Base64, 'active_support/base64'
  autoload :BasicObject, 'active_support/basic_object'
  autoload :BufferedLogger, 'active_support/buffered_logger'
  autoload :Cache, 'active_support/cache'
  autoload :Callbacks, 'active_support/callbacks'
  autoload :Deprecation, 'active_support/deprecation'
  autoload :Duration, 'active_support/duration'
  autoload :Gzip, 'active_support/gzip'
  autoload :Inflector, 'active_support/inflector'
  autoload :Memoizable, 'active_support/memoizable'
  autoload :MessageEncryptor, 'active_support/message_encryptor'
  autoload :MessageVerifier, 'active_support/message_verifier'
  autoload :Multibyte, 'active_support/multibyte'
  autoload :OptionMerger, 'active_support/option_merger'
  autoload :OrderedHash, 'active_support/ordered_hash'
  autoload :OrderedOptions, 'active_support/ordered_options'
  autoload :Rescuable, 'active_support/rescuable'
  autoload :SecureRandom, 'active_support/secure_random'
  autoload :StringInquirer, 'active_support/string_inquirer'
  autoload :TimeWithZone, 'active_support/time_with_zone'
  autoload :TimeZone, 'active_support/values/time_zone'
  autoload :XmlMini, 'active_support/xml_mini'
end

require 'active_support/vendor'
require 'active_support/core_ext'
require 'active_support/dependencies'
require 'active_support/json'

I18n.load_path << "#{File.dirname(__FILE__)}/active_support/locale/en.yml"

A: I don't know exactly why Rails uses three different loading methods (actually two - see below). But I know, in general, why someone might.
Require means "load this right now". autoload means "load this when you need to use it". The usual reason to use both is that you have some files that you pretty much assume will be used in every program invocation; and others that are optional. For example, in a Rails application that uses no deprecated methods, you'll never need Deprecation; so why slow down the initial setup by loading that file?
In other cases, you might distinguish between files that will be needed early in the program's execution, and files that can wait. For example, you're not likely to need Gzip until the first request comes in. So by using autoload, you can trim some time off the initial setup, at the cost of a slight slowdown for the first request.
You might ask, well, why not just use autoload for everything? Why load anything before it's absolutely needed? One reason is that autoload only works for constants. So, for example, active_support/core_ext adds a bunch of methods to Numeric so you can write code like 3.days, 6.minutes, and 16.seconds.ago. There's no constant in 3.days, so you can't trigger an autoload on that expression. (And you can't autoload Numeric, because the base class has already been loaded - it's just the extensions you want to add.)
Finally, this class doesn't actually use three loading methods; it uses two, and provides one (sort of). load_all! is used by Rails::Initializer to

# Preload all frameworks specified by the Configuration#frameworks.
# Used by Passenger to ensure everything's loaded before forking and
# to avoid autoload race conditions in JRuby.

I don't know the details, and I don't know why these specific modules are preloaded (and not the others). But since this is meant to support specific environments, you can see why it might require code separate from the default loading mechanism.

A: The autoload ruby method can be used to associate a constant with a filename that will be loaded the first time you reference said constant. This keeps you from having to load the entire framework at startup.
It looks like the load_all! method is called from the rails initializer.rb, and is utilized to preload all of the frameworks that are configured to be pre-loaded.  This works by calling each frameworks load_all! method, which is simply references an array of constants... which will trigger the autoload.
According to the comments in initializer.rb for preload_frameworks...
# Preload all frameworks specified by the Configuration#frameworks.
# Used by Passenger to ensure everything's loaded before forking and
# to avoid autoload race conditions in JRuby.

The require is to load the core required files for the particular framework.


text:
Q: Ubuntu 20.04 Bluetooth Broken I paired some headphones via Bluetoot the other day and it has been working correctly for a while.
Today, when I booted the laptop (which has 20.04), Blueman wouldn't start anymore.
On a cold start, Blueman throws the following error.
Bluez daemon is not running, blueman-manager cannot continue.
This probabil means that there were no Bluetooth adapters detected or Bluetooth daemon was not started.

The output of dmesg | grep -i blue
[    5.926932] systemd[1]: Mounting Mount unit for bluez, revision 266...

The output of lspci -knn | grep Net -A3; lsusb is:
Network controller [0280]: Qualcomm Atheros QCA9377 802.11ac Wireless Network Adapter   [168c:0042] (rev 31)
Subsystem: Dell QCA9377 802.11ac Wireless Network Adapter [1028:1810]
Kernel driver in use: ath10k_pci
Kernel modules: ath10k_pci

At this point the result of rfkill list is
0: phy0: Wireless LAN
Soft blocked: no
Hard blocked: no

The result of systemctl | grep -i blue
run-snapd-ns-bluez.mnt.mount                                                           loaded active     mounted   /run/snapd/ns/bluez.mnt
snap-bluez-266.mount                                                                   loaded active     mounted   Mount unit for bluez, revision 266
● snap.bluez.bluez.service                                                               loaded failed     failed    Service for snap application bluez.bluez
● snap.bluez.obex.service                                                                loaded failed     failed    Service for snap application bluez.obex

The result of systemctl status snap.bluez.bluez.service is:
snap.bluez.bluez.service - Service for snap application bluez.bluez
 Loaded: loaded (/etc/systemd/system/snap.bluez.bluez.service; enabled; vendor preset: enabled)
 Active: failed (Result: exit-code) since Thu 2020-12-17 18:35:38 EET; 5min ago
Process: 1337 ExecStart=/usr/bin/snap run bluez (code=exited, status=1/FAILURE)
Main PID: 1337 (code=exited, status=1/FAILURE)

The status of the bluetooth service at this point is:
bluetooth.service - Bluetooth service
 Loaded: loaded (/lib/systemd/system/bluetooth.service; enabled; vendor preset: enabled)
 Active: inactive (dead)
   Docs: man:bluetoothd(8)

Dec 17 18:35:37 Roxy systemd[1]: Condition check resulted in Bluetooth service being skipped.

The output of lsbusb is:
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 002: ID 0bda:5520 Realtek Semiconductor Corp. Integrated_Webcam_HD
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

After this if I load the module with modprobe btusb and start the service, the bluetooth service will be shown with green
bluetooth.service - Bluetooth service
 Loaded: loaded (/lib/systemd/system/bluetooth.service; enabled; vendor preset: enabled)
 Active: active (running) since Thu 2020-12-17 18:44:47 EET; 2s ago
   Docs: man:bluetoothd(8)
Main PID: 3893 (bluetoothd)
 Status: "Running"
  Tasks: 1 (limit: 9168)
 Memory: 1.9M
 CGroup: /system.slice/bluetooth.service
         └─3893 /usr/lib/bluetooth/bluetoothd

Dec 17 18:44:47 Roxy systemd[1]: Starting Bluetooth service...
Dec 17 18:44:47 Roxy bluetoothd[3893]: Bluetooth daemon 5.53
Dec 17 18:44:47 Roxy systemd[1]: Started Bluetooth service.
Dec 17 18:44:47 Roxy bluetoothd[3893]: Starting SDP server
Dec 17 18:44:47 Roxy bluetoothd[3893]: Bluetooth management interface 1.14 initialized

This time the output dmesg | grep -i blue is
[    6.603768] systemd[1]: Mounting Mount unit for bluez, revision 266... [20988.422158] Bluetooth: Core ver 2.22 [20988.422180] Bluetooth: HCI device and connection manager initialized [20988.422182] Bluetooth: HCI socket layer initialized [20988.422184] Bluetooth: L2CAP socket layer initialized [20988.422186] Bluetooth: SCO socket layer initialized [20988.467613] Bluetooth: BNEP (Ethernet Emulation) ver 1.3 [20988.467614] Bluetooth: BNEP filters: protocol multicast [20988.467618] Bluetooth: BNEP socket layer initialized

At this point when I try to start Blueman again, I get the following:
blueman-manager 18.45.16 ERROR    Manager:118 on_dbus_name_appeared: Default adapter not found, trying first available.
blueman-manager 18.45.16 ERROR    Manager:122 on_dbus_name_appeared: No adapter(s) found, exiting

As you can see I tried quite a few things, I spent an hour trying to diagnose the problem, but the issue is starting to be at a lower level than I'm comfortable with.
I'd really like to stay with Ubuntu on this machine, so please help me out.
Thanks!


text:
Q: Have I explained that a tiled rectangle has at least one integer side properly? I am trying to explain why if a rectangle can be tiled by smaller rectangles each of which has at least one integer side, then the tiled rectangle has at least one integer side.
My attempt:
For the integer case, when a tile is placed the tile covers a region whose squares have a summed value of $0$, whereas for the continuous case the integral of a line of integer length from $(x_1, y_1)$ to $(x_1, y_1 + \Delta y)$ or from $(x_1, y_1)$ to $(x_1 + \Delta x, y_1)$ is $0$. This is because when we integrate a line of an integer length which is parallel to either the $x$ (tile width) or $y$ (tile height) axis, it is the same thing as when we place a $1 \times h$ tile anywhere on a region of integer dimensions, recalling that the sum of the values of the squares covered by the tile is $0$. If a tiling is possible, this means the integral of the individual tile heights or widths are $0$. Then it follows that the integral of the region is also $0$ since the sum of the tile areas makes up the region, therefore the sum of the integrals of the tiles make up the integral of the region.
$$\int_{a}^{b} \int_{c}^{d} f \,dy\,dx = \int_{a}^{b} e^{2\pi ix} \,dx \int_{c}^{d} e^{2\pi iy} \,dy = \bigg(\frac{e^{2\pi ib} - e^{2\pi ia}}{2\pi i}\bigg)\bigg(\frac{e^{2\pi id} - e^{2\pi ic}}{2\pi i}\bigg)$$
I feel like it is not correctly explained and not completely explained.
Can anyone help me?

A: As you doubted, your explanation isn't quite clear and complete yet. You should start by defining the function $f$ appearing in the integral.
Also, the part:

the tile covers a region whose squares have a summed value of $0$

What are the "squares of the region"?
Maybe you want something like: The integral over the whole rectangle can be calculated by summing the integrals over the tiles, or on the other hand as a single double integral over the whole rectangle.
I guess the key words are "the integral of $f$ over a rectangle is $0$ if and only if that rectangle has an integer side". And you have already shown this by calculating the integral (one of the factors must be $0$ and this means the exponentials must be equal which in turn leads to the corresponding difference of numbers e.g. $b-a$ being an integer).


text:
Q: What does it mean by client in the software design patterns? What does it mean by client in the software design patterns? For instance I see this word has been mentioned a lot in design patterns, such as in this PHP Visitor Design Pattern tutorial. It even has a class called Client (is it a design pattern as well?)
//Client.php
error_reporting(E_ALL | E_STRICT);
ini_set("display_errors", 1);
// Autoload given function name.
function includeAll($className)
{
    include_once($className . '.php');
}
//Register
spl_autoload_register('includeAll');

class Client
{
    private static $shapeElement;
    private static $color;
    private static $package;

    //client request
    public static function request()
    {
      self::$shapeElement= array();
      self::$shapeElement=$_POST['shape'];
      self::$color=$_POST['color'];
      self::$package= array();

      $obStructure = new ObjectStructure();
      $colorVisitor= new self::$color();

      //Attach concrete elements to array & accept visitor
      foreach (self::$shapeElement as $shapeNow)
      {
        $obStructure->attach(new $shapeNow,$colorVisitor);
      }

      //Display selected shapes
      self::$package=$obStructure->getElements();
      foreach (self::$package as $colorShape)
      {
        echo $colorShape->showShape();
      }
    }
}
Client::request();

From wikipedia, the client in client–server networks, which is what I usually understand it as,

A client is a piece of computer hardware or software that accesses a
  service made available by a server. The server is often (but not
  always) on another computer system, in which case the client accesses
  the service by way of a network. The term applies to programs or
  devices that are part of a client–server model.

Is this then the definition for client in the software design patterns as well?
If the client is made into a class,
class Client
{
    ...
}

then, can I have many clients as well and where should I keep these clients in MVC architectural pattern? Should/ can I create a directory called client and keep all client classes in it?

A: The client is the 'code' that will be executed in the client machine. However, if we are talking about web applications, the client is probably the browser. So, no back-end code (e.g. PHP) will be executed in the client. There are also occasions, where the client machine is not a browser, for example the occasion of ATMs functionality. On this occasion, the client code is the one that will be executed in the ATM machine when a specific transaction is made by the end user (withdrawal, deposit etc.).
Now, regarding the 'many clients', it depends if you refer to different instances or types. If you refer to different types of clients (e.g. different client for each company's ATM), then you can make an generic Client class and create one class for each company that will inherit the basic functionality from the generic class. If you are referring to instances, then you do not have to do anything, since when a new transaction is to be made by a client machine, a new instance of the suitable Client class will be initialised and this one will be used. You can just create a class understanding the type of the client machine and initializing the suitable kind of Client.
It would be wise to create a different directory for the Client class and a separate sub-directory for all the different sub-classes that inherit.

A: The client is the generic name for a class or classes that normally benefit from the pattern. In real applications, it's probably not called Client.
Many patterns provide protected variations and the Client is the class that is protected from variations in the part of the design that is open to extension. In the case of Visitor, the code in Client should not require any (or many) changes if you add a new Visitor functionality.
Another way to look at it is that programming is done for two reasons:

*

*developing applications

*developing frameworks (or code to facilitate developing applications -- the first reason)

Design patterns fall into the second aspect. In this case, think of design patterns as having a Client programmer, whose goal is developing applications quickly and easily. Any of the classes in the code she develops could be the client classes, particularly if they use the patterns.


text:
Q: Add class only for the element in view I was looking for something like the affect of this page (I'm looking for the trigger that start the animations with the scroll of the page)
Some people help me here in StackOverFlow with this code:
function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

$(window).scroll(function(){

    if (isScrolledIntoView('.class') === true) {
        $('.class').addClass('in-view')
    }
});

The result can be found here: http://jsfiddle.net/z3xTU/
But now I got another problem. I have a page with several DIVs, I want to animate all of them, but if I set every with ".class", this code add the "in-view" for all of they, at the same time. This trigger all the animation to start when the first div come to view, isn't what I'm looking for.
Anyone have a better idea that can help me?

A: Try this:
$(window).scroll(function () {
   $('.class').each(function () {
      if (isScrolledIntoView(this) === true) {
          $(this).addClass('in-view')
      }
   });
});

Loop through all your elems and pass the current context in the function isScrolledIntoView(this), so here this is your current elem which is available in view.
Fiddle

A: Use different classes for the different elements or use ids.
$(window).scroll(function(){

    if (isScrolledIntoView('.class1') === true) {
        $('.class1').addClass('in-view')
    }
    if (isScrolledIntoView('.class2') === true) {
        $('.class2').addClass('in-view')
    }

});

or
$(window).scroll(function(){

    if (isScrolledIntoView('#id1') === true) {
        $('#id1').addClass('in-view')
    }
    if (isScrolledIntoView('#id2') === true) {
        $('#id2').addClass('in-view')
    }

});


text:
Q: 2 пакета с одинаковым названием Maven Имеет Maven проект, где в pom имеются зависимости:
   <dependency>
        <groupId>ru.company</groupId>
        <artifactId>jpos</artifactId>
        <version>1.4.8.2</version>
    </dependency>
   <dependency>
        <groupId>org.jpos</groupId>
        <artifactId>jpos</artifactId>
        <version>1.9.0</version>
    </dependency>

мне нужно использовать методы из org.jpos.iso.ISOMsg
так уж получилось, что пакет ru.company включает в себе org.jpos
если я в pom укажу только ru.company, то все работает как нужно, но мне нужен еще и другой пакет.
Как бы мне решить данную проблему?
p.s. так как один пакет включает в себе другой, то можно использовать именно этот пакет. но хотелось бы получить ответ как быть в данной ситуации

A: Можно исключить с помощью Maven Dependency Exclusions, примерно должно быть так:
  <dependency>
      <groupId>ru.company</groupId>
      <artifactId>jpos</artifactId>
      <version>1.4.8.2</version>
      <exclusions>
          <exclusion>
              <groupId>org.jpos</groupId>
              <artifactId>jpos</artifactId>
          </exclusion>
      </exclusions>
  </dependency>
  <dependency>
      <groupId>org.jpos</groupId>
      <artifactId>jpos</artifactId>
      <version>1.9.0</version>
  </dependency>


text:
Q: Fetch data request to nested JSON object error - React/Next.JS I'm having problems fetching data from my API and I get this error. I have attached the JSON format below as I believe it is an issue with my structure. When I use a different res URL with objects nested inside an array, it works. But for my data, it is not. Can anyone help me please?
"Index.getInitialProps()" should resolve to an object. But found undefined instead"
import Layout from '../comps/Layout';
import Link from 'next/link';
import fetch from 'isomorphic-unfetch';

const Index = props => (
<Layout>
    //List of movies here
</Layout>
);

Index.getInitialProps = async function() {
    const res = await fetch('https://www.what-song.com/api/recent-movies')
    const data = await res.json()

    console.log(`Data: ${data}`)

}

export default Index;

A: The getInitialProps method basically supposed to set your component initial props. But, in your case you are returning nothing.
So, change your code to
Index.getInitialProps = async function() {
    const res = await fetch('https://www.what-song.com/api/recent-movies')
    const data = await res.json()

    console.log(`Data: ${data}`)
    return { data }; // <-- set whatever key you want.
}

For your reference


text:
Q: How to insert multi line text from .csv file to sqlite database the problem i'm facing is as follows
In CSV file in one column i'm having a text which is in multiple line format, how to insert that same text with multi line indent preserved into sqlite database.
For example
Id  Column1  Column2
 1      Hello        this is                     multi line                      text to be                      inserted into database

A: For multiline fields in csv you need to enclose them in double quotes:
field1,"this is first line
this is second line
this is third line",field3

Double quotes inside those fields should be escaped with another double quote:
field1,"this is first line
24"" monitor
this is third line",field3


text:
Q: How to check for non-zero results in json response object using jQuery ajax? I just need to check if there are some non-zero results in my response object, without having to run a loop ($.each or something) and increment a counter (although I can break the counting after the first iteration). I guess I can use jQuery's $.size() which returns 1 and 0 if there were results and there were no results respectively. I searched in http://api.jquery.com/size/ but did not find the confirmation. Any ideas ?
Here is my simple code -
         $.ajax({
            type: "POST",
            data: postdata,
            async: false,
            url: posturl,
            dataType: "json",
            success: function(response)
            {
                var results = response.allResults;
                alert($(results).size()+" and "+results.length);

                //alerts "0 and 0" - when no results
                //alerts "1 and undefined" - when there are 1 or more results

            }
        });

In the backend PHP logic -
//some array with key value pairs
$results = $this->_something($idsArray);
echo json_encode(array("allResults" => $results));

Update
I have already tried with the length property and you can see in my code example that it alerts undefined when there are non-zero results.
Output of console.log(response.allResults);
When there are non-zero results -
Object { 109="add_offline_pack_test", 110="add_offline_pack_test1", 111="add_offline_pack_test2", more...}

When no results -
[]

A: Your problem appears to be that although you're thinking of allResults as being an array, it actually isn't - it's still a key-value pair object - except when it's empty!
This happens because PHP's json_encode only treats an array as a "real" array if the keys are all integers, and contiguous starting from zero, or if the array is empty.  Otherwise it treats the array as an associative array of key-value pairs.
Hence your test can simply be does the length property exist?
if (results.length === undefined) {
    // results is an object of key:value pairs
} else {
    // results is an array
    if (results.length) {
        throw "expected empty array isn't!";
    }
}

As you're using jQuery you could also use $.isArray() to test whether you've received an (empty) array instead of an object.

A: Try length instead of size..

A: Because $results is an array of key-value pairs (instead of just values), json_encode will encode it to an object (since objects have key-value pairs) when you have any results, but an empty array when there are none (because $results is an array).
So when there are no results, the result you get from response.allResults is an empty array (thus its length is 0). When there are results, the result you get is an object with those results. Objects do not have a length member, so it's undefined.
When you do $(obj), where obj is some object (not array), the result is an object like this:
{ 0: obj, length: 1 }

When you do $(arr), where arr is some array, the result is an object like this:
{ length: arr.length, 0: arr[0], 1: arr[1], etc. }

Because your result is an empty array when there are no results, the object returned by $(result) will then be like this:
{ length: 0 }

So if you have results, $(result)'s length will be 1 (because it was given an object), and if you don't have results, it will be 0 (because it was given an empty array). $.size simply returns $.length, as stated in the doc page you linked to.

A: Simple use this code:
$.ajax({
        type: "POST",
        data: postdata,
        async: false,
        url: posturl,
        dataType: "json",
    success: function (response) {
        if (response.d.results == undefined) {
           //do that
        }
        else {
           //do that
        }
    },
    error: function (response) {
        // do that
    }
});

I hope that helps. With response.d.results.length You can get a number of rows from query.


text:
Q: How to identify the custom-element that started a core-ajax call (from the core-ajax response) I'm using Polymer to generate a list o custom elements (post-card).
Inside each custom element there is a thumbnail of an image that will expand and show the "original image" when clicked.
The "original image" link is obtained from a response to an ajax call to imgur API (with a core-ajax component).
I tried this two routes... but I'm still unsure about the best solution:
1. Using a core-ajax component inside each post-card element.
This solution seems to work but it's far from elegant in my opinion.
2. Using a single core-ajax component to manage every API request.
Post-list.html
<core-ajax
  url="{{imgur_url}}"
  handleAs="json"
  on-core-response="{{handleResponse}}">
</core-ajax>

<template repeat="{{post, postIndex in posts}}">
    <post-card post={{post}} id={{postIndex}} on-img-tap={{imgurRequest}}>
</template>

The main problem I'm facing with this solution is that when I get the response back from core-ajax I'm not able to identify the custom element (post-card) which sent the request.
I thought about creating a new custom element extending core-ajax, allowing me to pass as a parameter (and get it back in the response) the id of the post-card which sent the request... but I think there must be a  simpler solution, right?
Thank you in advance.

A: I assume that you have something like this.$.ajaxId.go(); in your imgurRequest function (regarding your second solution). What you could do is sending the postIndex through ajax parameters. Your imgurRequest would look somewhat like this:
imgurRequest: function(e, detail, sender) {
  var postIndex = e.target.templateInstance.model.postIndex;
  // Set a property (to postIndex) which is bound to ajax parameter list here ...
  this.$.ajaxId.go();
}

This way you can distinguish between your post cards while using the same function and same core-ajax element. The server should of course send the received id back to client.


text: Q: Adding Linked Lists to a BST if key is identical I have built a BST dict in C. Now I have to tweak it to make it more efficient by making a linked list of equal keys. The data for each key is a struct. I am rewriting the code but I am confused as to how I will implement it in C. Can someone help?


text:
Q: PyAudio import error : ImportError: DLL load failed: The specified module could not be found I encountered an import problem by PyAudio.
I have a winodws 10, 64 bit, and use Anaconda and Spyder IDE with python 3.7.
I installed PyAudio in Ananconda, ran as administrator, with these commands :
cd
conda install -c conda-forge PyAudio
The installation ran without any problems.
I then restarted both Anaconda and SPYDER. PyAudio now shows up in Anaconda's list of installed packages.
When I try to import Pyaudio in Spyder (IPython console), I encounter this error message :
[1]: import pyaudio
Could not import the PyAudio C module '_portaudio'.
Traceback (most recent call last):
File "", line 1, in
import pyaudio
File "C:\ProgramData\Anaconda3\lib\site-packages\pyaudio.py", line 116, in
import _portaudio as pa
ImportError: DLL load failed: The specified module could not be found.
I tried to fix it by answers to similar ImportError message issued, while other users tried to import other packages like SKlearn ... , but with no success.

A: Your problem (and mine) are the same. The issue is, unfortunately, the version of python you're running (in tandem with your OS).
Check out this link:
https://people.csail.mit.edu/hubert/pyaudio/#:~:text=Note%3A%20As%20of%20this%20update,4.
Under the INSTALLATION section in the link for WINDOWS, PyAudio's latest version (0.2.11)  is compatible with Python versions: 2.7, 3.4, 3.5, 3.6.
My current python is 3.8.5, so you (and I) could never use PyAudio unless they added compatibilities or we revert to an above python version.

A: I tried to install portaudio using
conda install portaudio

but it seems like it didn't work as it should be. However,
conda install -c anaconda portaudio

solved the problem.
see the official anaconda page


text:
Q: How can I get ASP.NET AJAX to send its JSON response with GZip compression? I have compression enabled within IIS7 and it works as expected on all responses except for those constructed by ASP.NET AJAX.  I have a web service that provides data to the client.  When the web service is called directly, it is properly compressed.  However, when it is called via ASP.NET AJAX, the JSON response is not compressed.
How can I get ASP.NET AJAX to send its JSON response with GZip compression?

A: IIS7 uses the content-encoding to decide whether to compress the response (assuming of course that the browser can accept gzip). They're set in applicationHost.config, and by default the list is
<dynamicTypes>
     <add mimeType="text/*" enabled="true" />
     <add mimeType="message/*" enabled="true" />
     <add mimeType="application/x-javascript" enabled="true" />
     <add mimeType="*/*" enabled="false" />
</dynamicTypes>

If you call the web service directly, the XML response has a content-type of text/xml, which gets compressed. When called by AJAX, the JSON response has a content type of application/json, so it isn't compressed. Adding the following to applicationHost.config should fix that...
     <add mimeType="application/json" enabled="true" />

A: What browser are you using? There's a bug in IE 6 that causes errors in compression. So ASP.NET AJAX turns off compression to IE 6 browsers:
http://weblogs.asp.net/scottgu/archive/2005/06/28/416185.aspx
Also, did you enable compression for ASMX files?

A: Last I checked, the gzipping was something that IIS does (when setup correctly) - and of course when the browser sends the required headers

A: In general you don't want to do this unless you wouldn't mind throwing orders of magnitudes the amount of server power into your apps...
Also not only server-CPU but also client-CPU becomes a problem when you do this....
This concludes with that your app becomes WAY slower if you GZip all your Ajax Responses...!


text:
Q: consulta sql, contar por compañia telefonica Tengo una estructura de db de la siguiente forma:, una db llamada pruebas, y una tabla llamada tblusuarios
 - id INT usuario VARCHAR(20),
 - usuario VARCHAR(20),
 - nombre VARCHAR(20),
 - sexo VARCHAR(1),
 - nivel    TINYINT,
 - email VARCHAR(50),
 - telefono VARCHAR(20),
 - marca VARCHAR(20),
 - compañia VARCHAR(20),
 - saldo FLOAT,
 - activo BOOLEAN

No se hacer la consulta siguiente:

Contar el número de usuarios por compañía telefónica

SELECT COUNT(ID) FROM TBLUSUARIOS WHERE

A: *

*Usa una función de agregación COUNT() para contar las coincidencias por el nombre de la compañia ya que es el dato que buscas identificar

*Usa GROUP BY para poder agrupar los datos por alguna regla

*A la operación con la función COUNT asignale un alias

Lo anterior contará todas las compañias coincidentes, las agrupará y las ordenará por el nombre de dicha compañía
Necesitas agrupar los datos ya que las funciones de agregación solo devuelven un campo calculado; entonces al agrupar te mostrará en n renglones los grupos que coinciden por nombre
Finalmente tu código debería ser así
SELECT compañia, COUNT(compañia) AS PorCompañia
FROM pruebas
GROUP BY compañia
ORDER BY compañia;


text:
Q: Multiple testing when considering a second coin Recently, I'm reading the book "Doing bayesian data analysis" written by John K. Kruscheke. In chapter 11, which mainly discuss about the null hypothesis significance testing, there is a section confusing to me.
I was very confused about the sampling distribution in Figure 11.6.
Is there anyone who can help explain how the sampling distribution is simulated and why the second coin flips can affect the sampling distribution of multiple tests.
Below are the snapshots about this section.


text:
Q: Refresh gallery on Android 7 downwards? I can use MediaScannerConnection.scanFile() as of SDK 2.2+.
After taking an image and saving it on the sd card, how can I trigger scanning of images in SDKs lower than 2.2 (2.1 downwards)?

A: There are two MediaScannerConnection.scanFile(..) methods. Use the one available since API 1.
// available since API 1
scanFile (String path, String mimeType)

// available since API 8
scanFile (Context context, String[] paths, String[] mimeTypes, MediaScannerConnection.OnScanCompletedListener callback)


text:
Q: Каков уровень востребованности ресурсов для каждого layout? В процессе разработки столкнулся с вопросом: сколько ресурсов требует каждый layout? (Linear, Relative, Tab, Constraint, Coordinator)
В сложных view-представлениях приложения оправдано ли использование исключительно маловесных layout?

A: В общем случае, при одноуровневой верстке, в порядке возрастания потребления ресурса:
FrameLayout - LinearLayout  - RelativeLayout - ConstraintLayout
Однако, при вложенности одного контейнера в другой, потребление ресурса существенно увеличивается. Так как на практике встречается очень мало таких версток, где достаточно одного простого контейнера (как Frame или Linear), то в большинстве случаев оптимальным решением будет ConstraintLayout, как контейнер, изначально задуманный, как одноуровневый и имеющий большое количество атрибутов для комфортной реализации практически любой верстки, без вложенности одного контейнера в другой. В этом его преимущество перед более простыми контейнерами, если же вложить в него другие - оно будет утрачено.
С другой стороны, если макет можно сверстать в одноуровневый FrameLayout (например, контейнер для Fragment) или LinearLayout (например, айтем списка), то это будет гораздо более оптимальное решение в плане потребления ресурсов.
TableLayout это двухуровневый LinearLayout (вертикальный, в который вложены горизонтальные)
RelativeLayout с одной стороны несколько легче ConstraintLayout, с другой стороны существенно проигрывает ему в возможностях позиционирования виджетов и, наверное, в настоящее время не сильно востребован.
такие вещи, как CoordinatorLayout, AppBarLayout не имеют альтернатив реализации и потребление ими ресурсов оценивается только с позиции использовать или нет, хотя особого аппетита к ресурсам за ними вроде не замечено.
Несколько тестов различных разметок: сравнение производительности разных контейнеров, контейнер с вложенными контейнерами против ConstraintLayout
Так же для оценки производительности разметки вы можете использовать инструмент Hierarchy Viewer. С версии студии 3 он объявлен устаревшим и в качестве замены предлагается Layout Inspector, но он не показывает время на рендеринг разметки.
Теперь запустить Hierarchy Viewver можно из Android Device Monitor, который в свою очередь можно запустить из папки
 .../android_sdk/tools/monitor.bat

PS: Сейчас google рекомендует оценивать производительность UI через Systrace, однако результаты ее не так просты и наглядны, как у Hierarchy Viewr


text:
Q: Trying to make a formula that recognizes if another is blank and then adds a number [Excel] I'm new to Excel. My only programming knowledge comes from a C course in college.
I'm trying to create a sheet that will check if a group of cells are blank. When one of them is, then nothing happens, and when one of them has content then the cell with the formula will add 1400 to itself. For example, if it checks 10 cells, and 3 of them have content inside, the main cell will showcase 4200.
Here's an image of the sheet. The formula goes at the bottom and makes a sum with each column

In my head, the formula would be something like =if(isblank(B2:B17;" ";+1400)).
What would be the correct formula?

A: Instead of looking for empty cells, count the number of non-empty cells with COUNTA then multiply the result by 1400:
=COUNTA(B2:B17)*1400


text:
Q: If $X$~$U(0,1)$, and $Y=2x-4$. What is the density function of Y? If $X$ is uniformly distributed $\mathcal{U}(0,1)$
, then what is the distribute density function of $Y$?
I thought that if $$fx(x) = 1/(1-0), \; \mbox{for} \; 0<x<1$$
then $$fy(Y=2x-4)=fx((y+4)/2) = 1(1-0), \; \mbox{for} \; -2<(y+4)/2<2$$
Am I right?

A: No:
The cdf of $2X-4$ is
$$F_{2X-4}(x)=P(2X-4<x)=P\left(X<\frac{x+4}2\right)=
\begin{cases}
0,& \text{ if } x<-4\\
\frac{x+4}2,& \text{ if } -4\le x\le -2\\
1,&\text{ if } x>-2
\end{cases}.$$
The density is
$$f_{2X-4}(x)=\frac{dF_{2X-4}(x)}{dx}=
\begin{cases}
\frac 12,& \text{ if } -4\le x\le -2\\
0,&\text{ otherwise }
\end{cases}.$$

A: Hint:
If $X$ is uniformly distributed and $a,b\in\mathbb R$ with $a\neq0$ then $Y:=aX+b$ is also uniformly distributed. This in the meaning that its PDF has a positive constant value on a certain set and takes value $0$ on the complement of that set.
If you know that the PDF of $Y$ takes constant positive value $c$ on e.g. some interval $(p,q)$ and takes value $0$ otherwise then you can find the determining constant on base of $$1=\int f_Y(y)dy=\int_{(p,q)}cdy=c(q-p)$$
In your case $X$ takes values in $(0,1)$ so that $2X-4$ takes values in $(-4,-2)$ leading to $1=c((-2)-(-4))=2c$ hence $c=\frac12$.

A: For a random variable $ X $ distributed according to the pdf $ p_X $ and a differentiable function $ f $ with positive derivative, you can show that the random variable $ f(X) $ is distributed according to
$$
p_{f(X)}(y) = \frac{p_X(f^{-1}(y))}{f^\prime(f^{-1}(y))}.
$$
In your case, you have that $ p_X(x) = \chi_{[0, 1]}(x) $ (with $ \chi_{A} $ the indicator function of set $ A $), $ f^{-1}(y) = (y + 4)/2 $ and $ f^\prime(y) = 2 $, hence
$$
p_{f(X)}(y) = \chi_{[-4, -2]}(y)/2
$$
(since $ \chi_{[0, 1]}((y + 4)/2) = \chi_{[-4, -2]}(y) $).


text:
Q: Confused about MW to MWh conversion I have various datasets of energy production in MW.
I need to present everything in MWh. I need to know if my data is already by the hour (logging a value for each hour of each day of an entire year), if the sum of all those values in MW also equals the value in MWh.
To make the conversion, does that depend on whether the data is in 5-minute, 15-minute, or 1-hour increments? For example, if the data is registered in 5-minute increments, I think I would have to add all MW and then divide by 12 (because there are 12 5-minute periods in 1 hour).
Thus, if 1 MW produced every 5 minutes for a 2-hour period, then the calculation to obtain MWh is (1x2X12)/12 = 2 MWh? Is that correct? Add all MW and divide by number of periods in one hour?
If in 15 mins, it would be (1x24)/4 = 6 MWh.
If data is already by the hour, then (1x24)/1 = 24 MWh? So in this case, MW = MWh?

A: Watts are a unit of power, energy consumed per unit time.  Watt-hours are a unit of energy.  Finding Watt-hours given time-discrete point readings depends on what assumptions you want to make about what happens between the readings.  It's kind of like trying to figure out how far you've driven from a speedometer reading every 5, 15, 30 minutes etc.  If you're cruising on the highway, assuming that the speed between readings is constant is probably going to get you a fairly accurate answer.  If you're in stop-and-go traffic, it will probably be wildly off.  You just need to decide what your assumption is going to be and state it clearly.
For example, if you have a power reading of 1MW at noon and a power reading of 1.1MW at 12:05, you might assume that from the first reading to the second one, the power was constant at 1MW and for that 5-minute period, the energy produced was 0.083MWh.  For the next 5-minute period, the energy produced was 0.092MWh, and so forth.

A:
I have various datasets of energy production in MW.

That's the source of your problem. That should read either,
"I have various datasets of power production in MW, or
"I have various datasets of energy production in MWh."
I'd go back to the source and get clarification.

For example, if the data is registered in 5-minute increments, I think I would have to add all MW and then divide by 12 .

Correct.

Thus, if 1 MW produced every 5 minutes for a 2-hour period, ...

That would be badly worded. "If I averaged 1 MW continuously **for each 5 minute perio ..." would be much better.

... then the calculation to obtain MWh is (1 x 2 x 12) / 12 = 2 MWh? Is that correct? Add all MW and divide by number of periods in one hour?

That's correct but it can be simplified to "I produced 1 MW continuously (or average) for two hours so MW × hours = 2 MWh.

If in 15 mins, it would be (1x24)/4 = 6 MWh.

No, you're mixing power and energy again. It's just average power × time. 1 MW for 2 hours = 2 MWh.

If data is already by the hour, then (1 x 24) / 1 = 24 MWh? So in this case, MW = MWh?

No. A MW is not the same as a MWh (same as a km is not the same as a km/h). The numeric value might work out the same but the concept is different.

simulate this circuit – Schematic created using CircuitLab
Figure 1. Average power vs time.

*

*In the first hour the energy used is (0.5 + 1 + 1 + 0.5) / 4 = 0.75 MWh.

*In the second hour the energy used is (1.5 + 2 + 1 + 1) / 4 = 1.375 MWh.

*Total for the two hour period is 2.125 MWh.

*The energy used is the integral of power with respect to time and is represented graphically by the area under the curve.

A: Watts (W) or in your case megawatts (MW) is a measure of power (P) (heat flow).
Watt-hour (Wh) is a measure of energy (E) delivered over a period of time.
If the power MW is constant over 2 hours, then the total energy consumed or delivered over the 2 hours is$$E_{2hours} = P\Delta t$$
If the power is 1MW then$$E_{2hours}=2\text{ MWh}$$
If the power changes over the total measuring period and is measured say every 5 minutes or 1/12 of an hour, then you must average the power measured for 2 consecutive periods, then multiply by the time of the period. Over two hours there would be 24, 5 minute periods.$$E_{2hours}= \Sigma \frac {P_{i}-P_{i-1}}{2}\Delta t$$$$E_{2hours}= \sum_{i=1}^{24}  \frac {P_{i}-P_{i-1}}{2}\frac {1}{12}\text{ MWh}$$

A: In order to avoid confusion between power and energy, or between 5min values and 1h values, I like to explicitly write measurements as
$$\frac{\mathrm{energy}}{\mathrm{time}}$$
for example : $$10 \frac{\mathrm{MWh}}{\mathrm{h}}$$
This seems redundant at first, but it makes it clear that it's an energy amount, which has been converted/delivered/used in an hour. If you simplify the unit by removing both h, you notice that it's actually an average power : $$10 \mathrm{MW}$$
The advantage becomes clear with other time ranges, for example:
$$2 \frac{\mathrm{MWh}}{\mathrm{15min}}$$
An energy amount of 2MWh, delivered in 15 minutes. If you simplify, you notice that it represents an average power of 8MW.
And if you have four consecutive measurements (e.g. 2, 3, 1 and 4 MWh/(15min)), you can simply add the energy amounts in order to get MWh (10 in this example), and convert them back to average power (in MWh/h) if you want.

A: MW is a unit of power, it's instantaneous, it's the rate at which energy is being delivered. MWh is a unit of energy, and is absolute.
Think of it like speed and distance, where power (W) is speed and energy (Wh) is distance.

if 1 MW produced every 5 minutes

would be like saying

if I go 1km/h every 5 minutes

it doesn't make much sense. Our speed/distance example should read

if I go 1km/h for 5 minutes (then I would cover 1km/h * 5 minutes * (1/60 minutes/hour) = 1/12 km)

or for power/energy

if 1 MW is produced for 5 minutes
(there would be 1MW * 5 minutes * (1/60 minutes/hour) = 1/12 MWh)

If all your units are in MW and you want to convert to MWh, you can add them all together and multiply by the time to get total MWh.
e.g. if you have 3 sources generating 250W, 100W, and 150W and you want to know how many MWh this is equivalent to, multiply their sum (500W) by the amount of time they will be running for.

in 1 hour: 500W*1h=500Wh

in 1 day 500W*24h=12000Wh

So you can't say that 1W = 1Wh, because it depends on the amount of time that the power is being delivered for. (in the special case that it is being delivered for 1h, the W and Wh will be equal, but that is not a general rule)


text:
Q: How 0X00020000 get converted to 131072? I am performing some bit wise operations(& and |) on hexadecimal numbers.
Integer number1 = 0X00020000;
Integer number2 = 0X00000001;

System.out.println(number1);
System.out.println(number1 | number2);
System.out.println(number1 + number2);

Output :
131072
131073
131073

0X00020000 automatically got converted to 131072.
I am getting right answer but I am curious to know how & WHY Java converts hexadecimal number to decimal number.
I know how to convert hexadecimal number to decimal number.
0X00020000 will be converted to decimal as follows,
(2 X 16^4) + (0 X 16^3) + (0 X 16^2) + (0 X 16^1) + (0 X 16^0)
= (2 X 65536) + 0 + 0 + 0 + 0
= 131072

A: The right way to look at this is not as something being converted, but rather the way something is being displayed.
There is only one value stored for the variable, no matter how to write it in your source code. Write it anyway you like; once it is stored in memory, Java neither knows or cares what it looked like in your source code.
System.out.println renders the integer value, as a string, using decimal by default. Try System.out.printf("%x\n", number1); to see it rendered in hex.
Just keep in mind there is a big difference between the integer value and its string representation. If there is anything "converted" here, it's a conversion from an string (in your source) to an integer value (represented in memory) to a string (written to standard output).  The last step uses decimal numerals by default.