text:
Q: NLTK is called and got error of "punkt" not found on databricks pyspark I would like to call NLTK to do some NLP on databricks by pyspark.
I have installed NLTK from the library tab of databricks. It should be accessible from all nodes.
My py3 code :
 import pyspark.sql.functions as F
 from pyspark.sql.types import StringType
 import nltk
 nltk.download('punkt')

 def get_keywords1(col):
     sentences = []
     sentence = nltk.sent_tokenize(col)

 get_keywords_udf = F.udf(get_keywords1, StringType())

I run the above code and got:
 [nltk_data] Downloading package punkt to /root/nltk_data...
 [nltk_data]   Package punkt is already up-to-date!

When I run the following code:
 t = spark.createDataFrame(
 [(2010, 1, 'rdc', 'a book'), (2010, 1, 'rdc','a car'),
  (2007, 6, 'utw', 'a house'), (2007, 6, 'utw','a hotel')
 ],
 ("year", "month", "u_id", "objects"))

 t1 = t.withColumn('keywords', get_keywords_udf('objects'))
 t1.show() # error here !

I got error:
 <span class="ansi-red-fg">>>> import nltk

 PythonException:
  An exception was thrown from the Python worker. Please see the stack trace below.
 Traceback (most recent call last):

 LookupError:
 **********************************************************************
 Resource punkt not found.
 Please use the NLTK Downloader to obtain the resource:

 >>> import nltk
 >>> nltk.download('punkt')

 For more information see: https://www.nltk.org/data.html

Attempted to load tokenizers/punkt/PY3/english.pickle

Searched in:
- '/root/nltk_data'
- '/databricks/python/nltk_data'
- '/databricks/python/share/nltk_data'
- '/databricks/python/lib/nltk_data'
- '/usr/share/nltk_data'
- '/usr/local/share/nltk_data'
- '/usr/lib/nltk_data'
- '/usr/local/lib/nltk_data'
- ''

I have downloaded 'punkt'. It is located at
/root/nltk_data/tokenizers

I have updated the PATH in spark environment with the folder location.
Why it cannot be found ?
The solution at NLTK. Punkt not found and this How to config nltk data directory from code?
but none of them  work for me.
I have tried to updated
 nltk.data.path.append('/root/nltk_data/tokenizers/')

it does not work.
It seems that nltk cannot see the new added path !
I also copied punkz to the path where nltk will search for.
cp -r /root/nltk_data/tokenizers/punkt /root/nltk_data
but, nltk still cannot see it.
thanks

A: When spinning up a Databricks single node cluster this will work fine. Installing nltk via pip and then using the nltk.download module to get the prebuilt models/text works.
Assumptions: User is programming in a Databricks notebook with python as the default language.
When spinning up a multinode cluster there are a couple of issues you will run into.

*

*You are registering a UDF that relies on code from another module. In order for this to UDF to work on every node in the cluster the module needs to be installed at the cluster level (i.e. nltk installed on driver and all worker nodes). The module can be installed like this via an init script at cluster start time or installed via the libraries section in the Databricks Compute section. More on that here...(I also give code examples below)
https://learn.microsoft.com/enus/azure/databricks/libraries/cluster-libraries.
Now when you run the UDF the module will exist on all nodes of the cluster.

*Using nltk.download() to get data that the module references. When we do nltk.download() in a multinode cluster interactively it will only download to the driver node. So when your UDF executes on the other nodes those nodes will not contain the needed references in the specified paths that it looks in by default. To see these paths default paths run nltk.data.path.
To overcome this there are two possibilities I have explored. One of them works.

*

*(doesn't work) Using an init script, install nltk, then in that same init script call nltk.download via a one-liner bash python expression after the install like...
python -c 'import nltk; nltk.download('all');'

I have run into the issue where the nltk is installed but not found after it has installed. I'm assuming virtual environments are playing a role here.

*(works) Using an init script, install nltk.

*

*Create the script

dbutils.fs.put('/dbfs/databricks/scripts/nltk-install.sh', """
#!/bin/bash
pip install nltk""", True)

*Check it out

%sh
head '/dbfs/databricks/scripts/nltk-install.sh'

*Configure cluster to run init script on start up
Databricks Cluster Init Script Config

*In the cluster configuration create the environment variable NLTK_DATA="/dbfs/databricks/nltk_data/". This is used by the nltk package to search for data/model dependencies.
Databricks Cluster Env Variable Config
Start the cluster.
After it is installed and the cluster is running check to maker sure the environment variable was correctly created.
import os
os.environ.get("NLTK_DATA")

Then check to make sure that nltk is pointing towards the correct paths.
import nltk
nltk.data.path

If '/dbfs/databricks/nltk_data/ is within the list we are good to go.
Download the stuff you need.
nltk.download('all', download_dir="/dbfs/databricks/nltk_data/")

Notice that we downloaded the dependencies to Databricks storage. Now every node will have access to the nltk default dependencies. Because we specified the environment variable NLTK_DATA at cluster creation time when we import nltk it will look in that directory. The only difference here is that we now pointed nltk to our Databricks storage which is accessible by every node.
Now since the data exists in mounted storage at cluster start up we shouldn't need to redownload the data every time.
After following these steps you should be all set to play with nltk and all of its default data/models.

A: I recently encountered the same issue when using NLTK in a Glue job.
Adding the 'missing' file to all nodes resolved the issue for me. I'm not sure if it will help in databricks but is worth a shot.
sc.addFile('/tmp/nltk_data/tokenizers/punkt/PY3/english.pickle')

A: Drew Ringo's suggestion almost worked for me.
If you're using a multinode cluster in Databricks, you will face the problems Ringo mentioned. For me a much simpler solution was running the following init_script:
dbutils.fs.put("dbfs:/databricks/scripts/nltk_punkt.sh", """#!/bin/bash
pip install nltk
python -m nltk.downloader punkt""",True)

Make sure to add the filepath under Advanced options -> Init Scripts found within the Cluster Configuration menu.

A: The first of Drew Ringo's 2 possibilities will work if your cluster's init_script looks like this:
%sh
/databricks/python/bin/pip install nltk
/databricks/python/bin/python -m nltk.downloader punkt

He is correct to assume that his original issue relates to virtual environments.

A: This helped me to solve the issue:
import nltk
nltk.download('all')


text:
Q: Show action with more than two models I have an invoice model that has many_invoice items
class Invoice < ActiveRecord::Base
  belongs_to :customer, :inverse_of => :invoices
  attr_accessible :approved_by, :due_date, :invoice_date, :reading_ids, :terms, :customer_id, :customer, :status

  validates :invoice_date, presence: true
  validates :due_date, presence: true
  validates :customer, presence: true
  has_many :invoice_items
  accepts_nested_attributes_for :invoice_items
end

Invoice Items Model
class InvoiceItem < ActiveRecord::Base
  belongs_to :invoice
  attr_accessible :amount, :description, :rate, :tax_amount
end

I now have a show action in my Invoices_controller
def show
@invoice = Invoice.find(params[:id])
respond_to do |format|
    format.html
end
end

I want to be able to show the invoice_items like description, tax amount and rate in the show page for the invoices however, it is giving me quite a challenge. Do I have to create a partial in there that deals with the invoice items? Below is my show page

<%= notice %>

 Customer Invoices

      Invoice ID
      Customer Name
      Invoice Date
      Due Date
      Amount

    <%= @invoice.customer.name %>
    <%= @invoice.invoice_date %>
    <%= @invoice.due_date %>

A: using a partial is not a must, but you could do this in either way
1 - with out a partial
in your show.html.erb

#your invoice code
<% invoice_items = @invoice.invoice_items %>
<% invoice_items.each to |invoice_item|%>

  <%= invoice_item.amount%>

<% end %>

2 ) with  a partial
in your show.html.erb

#your invoice code
    <% invoice_items = @invoice.invoice_items %>
    <% invoice_items.each to |invoice_item|%>

         <%= render :partial => 'invoice_item', :locals => {:item => invoice_item}%>

    <% end %>

 in your _invoice_item.html.erb

 <%= item.name %>

HTH

A: You could use a partial to keep things tidy but there is no reason you couldn't do this in your show view template.
<% @invoice.invoice_items.each do |item| %>
 <%= item.amount %>
 <%= item.description %>
 # etc
<% end %>

The invoice items are related to the @invoice object that you have in your view therefore you can access the invoices invoice_items.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Geoxml3 CreatePolygon function I am trying to know how to use the createPolygon function in the parser options.
This is my index file but it gives me this error: Cannot read property 'bounds' of undefined.
<!DOCTYPE html>

<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Geoxml3</title>

I want to know if is correct the way I'm using the 'createPolygon:addMyPolygon' function, or where is the issue, I mean how can I set a click Listener for each polygon using the createPolygon function.
I did it with the createMarker function for a KML with markers, but in the file above the createPolygon doesn't parse my KML file.
My KML/XML file is:
http://www.geocodezip.com/geoxml3_test/testPolygon.xml

A: The createPolygon function needs to return the resulting polygon to GeoXml3 so it can manage it.
function addMyPolygon(placemark) {
    var polygon = geoXml.createPolygon(placemark);
    google.maps.event.addListener(polygon, 'click', function(event) {
        var myLatlng = event.latLng;
        infowindow.setContent(""+placemark.name+"
"+placemark.description+"
"+event.latLng.toUrlValue(6));
        infowindow.setPosition(myLatlng);
        infowindow.open(map);
    });
    return polygon;
};

Also, if you are going to use event inside the polygon 'click' listener it needs to be defined.
working example


text:
Q: Automating startproject Django command I have this following method to create project as below.
import os
project_directory = "/Users/home/project_directory/"

def create_function(project_name):
    os.system("django-admin.py startproject {0} {1}".format(
            project_name,
            project_directory
        )
    )

This works well when I use global python shell, But when I try same command using python manage.py shell I encounter following error. I thinking I am messing with python path, Please help me out
 mod = importlib.import_module(self.SETTINGS_MODULE)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
        __import__(name)
    ImportError: No module named mysite.settings


text:
Q: Migrating application from websphere to tomcat I will be migrating a websphere application to tomcat. I've read these online docs - http://blogs.mulesoft.org/how-to-migrate-your-weblogic-or-websphere-app-to-tomcat/ &
http://www.mulesoft.com/downloads/Migrating-from-Websphere-to-Tomcat-Mulesoft.pdf
I also found this helpful - What are the differences when deploying on Tomcat vs. Websphere?
From reading these docs it seems like it's a not too difficult task, at least on the face of it. So any J2ee/EE functionality that the app is using which tomcat does not implement needs to be added manually, this may include changes to the code base to support the tomcat server.

*Are there any technical details/pitfalls I should watch out for during migration?

*How can I effectively estimate the amount of time this migration should take ?

A: Tomcat is just servlet container and lacks most of the WAS features. For any feature you are missing you will have to expand tomcat functionality by adding stuff like transactional managers, jpa, ejb container, mail service....
So your task may or may be not hard to execute. It primary depends on your application (is it a webapp?) and your tomcat skills.
If you have a large Java EE application, and no experience in doing this, I would recommend to change your goal and instead target JBossAS, Glassfish or some other Java EE AS instead.


text:
Q: Get offset right in vanilla JavaScript How do I get the offset of an element from the right side, relative to the window?
I can only find jQuery solutions but I need a solution using vanilla JavaScript.
This is the solution using jQuery
var rt = ($(window).width() - ($whatever.offset().left + $whatever.outerWidth()));

How do I translate this to vanilla JavaScript?

A: You could try using element.getBoundingClientRect() to achieve that behavior. If you wrote your code to use this instead of jQuery, it would look something like:
var rt = window.innerWidth - element.getBoundingClientRect().right;

A: *

*You can get the width of an element using .innerWidth

*You can get the offset values of a element using getBoundingClientRect()

*You can get the outerWidth using offsetWidth
Porting your solution would be something like this:
window.innerWidth - (element.getBoundingClientRect().left + element.offsetWidth)

For more info you can check this link

A: You can get the offset left position using the .offsetLeft attribute on an element.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetLeft
For outer width see this answer:
outerWidth without jquery
So it would be written something like:
var rt = function() {
  var someElement = document.getElementById('someID');
  return window.innerWidth - (someElement.offsetLeft + someElement.offsetWidth);
}

A: Just grab the window size and subtract the x offset plus the width of the element you want to get the offset for.
function windowOffsetRight (ele) {
    let rect = ele.getBoundingClientRect ();
    let width = document.documentElement.getBoundingClientRect().width;
    return  width - ( rect.x + rect.width)
}

A: You just need to translate the jQuery functions in vanilla JS.
$window() // jQuery
window // Vanilla JS

$whatever // jQuery (probably a variable of $('.whatever'))
document.querySelectorAll('.whatever') // Vanilla JS

offset().left // jQuery
offsetLeft // Vanilla JS

outerWidth() // jQuery
offsetWidth // Vanilla JS

const el =  document.getElementById('test');
console.log(window.innerWidth - (el.offsetLeft + el.offsetWidth));

Of course there are many other ways how to do it.

A: None of the above answers returned the correct value in my case, if there was scrolling involved. Here's what did the trick in my case:
var clientRect = document.querySelector("#element").getBoundingClientRect();
var offset = {
    top: clientRect.top + window.scrollY,
    left: clientRect.left + window.scrollX,
};

console.log(offset);


text:
Q: How to load an image into a canvas without CORS issues for ionic iOS hybrid app I want to load images into a canvas that is used for showing custom google map markers. The following code works for browser and Android but not iOS, as the WKWebView does not accept CORS requests for this matter.
let ctx = canvas.getContext('2d');
let img = new Image();
img.crossOrigin = "anonymous";
img.src = url;

img.onload = function () {
    // process and load the image into the canvas map marker
};
img.onerror = function () {
    // handle fallback
};

The images have to be loaded from google maps photos api (and other apis that I do not have control on the CORS settings on the servers). This has to be somehow handled in the app.
What possible solutions exist for this matter?
One thing that I found is ionic-image-loader (https://github.com/zyra/ionic-image-loader) that uses ionic native http requests to load and cache images into an img tag. This works from html though, and I need to use it directly in js/ts, which does not seem to be possible.
If I try to load images via ionic http request, even in browser the request is also blocked by CORS, as opposed to loading the image via img tag. Maybe if (somehow) the following header can be set to the ionic http request so that the request looks the same: Sec-Fetch-Mode: no-cors
[WKWebView]
Even the local images cannot load this way and it shows: Origin null is not allowed by Access-Control-Allow-Origin (Cannot load image: file:/// ... ) and then it's stuck in a loop trying to load the image.

A: Solved by using a fork of ionic-image-loader preload function with cordova native http, bypassing the webview entirely for the http request and handling the cache manually. This is how the http request is done, working on iOS WKWebView as well:
let options = {
    method: 'get',
    responseType: 'blob',
    data: {},
    headers: {}
};

cordova.plugin.http.sendRequest(url, options, (data: any) => {
    let blob = data.data;
    resolve(blob);
}, (error: any) => {
    console.log(error.status);
    console.log(error.error);
    reject(error.error);
});


text:
Q: What's the difference with or without backtick "`"? type level =
[ `Debug
| `Info
| `Warning
| `Error]

Can i remove the "`" here ?
Sincerely!

A: It's hard to answer this question yes or no.
You can remove the backticks and the square brackets.  Then you would have
type level2 = Debug | Info | Warning | Error

In the simplest cases, this type is is very similar to your type level.  It has 4 constant constructors.
In more complex cases, though, the types are quite different.  Your type level is a polymorphic variant type, which is more flexible than level2 above.  The constructors of level can appear in any number of different types in the same scope, and level participates in subtyping relations:
# type level = [`Debug | `Info | `Warning | `Error]
# type levelx = [`Debug | `Info | `Warning | `Error | `Fatal]

# let isfatal (l: levelx) = l = `Fatal;;
val isfatal : levelx -> bool = <fun>
# let (x : level) = `Info;;
val x : level = `Info
# isfatal (x :> levelx);;
- : bool = false

The point of this example is that even though x has type level, it can be treated as though it were of type levelx also, because level is a subtype of levelx.
There are no subtyping relations between non-polymorphic variant types like level2, and in fact you can't use the same constructor name in more than one such type in the same scope.
Polymorphic variant types can also be open-ended.  It's a big topic; if you're interested you should see section 4.2 of the OCaml manual, linked above.


text:
Q: Serre quotient category Let $\mathcal{A}$ be an abelian category. A Serre subcategory of $\mathcal{A}$ is a nonempty full subcategory $\mathcal{C}$ of $\mathcal{A}$ such that given an exact sequence
$$A \longrightarrow B\longrightarrow C$$
with $A$ and $C$ in $\mathcal{C}$, then also $B$ lies in $\mathcal{C}$.
(See the following tag of the Stacks Project:
http://stacks.math.columbia.edu/tag/02MN)
Whenever we have a Serre subcategory $\mathcal{C}$ of an abelian category $\mathcal{A}$, we may form a "quotient category" $\mathcal{A}/ \mathcal{C}$. As far as I understand, there are different equivalent ways of constructing this quotient. Namely, one can look at it as a Gabriel-Zisman localisation of $\mathcal{A}$ at
$$\{f\text{ morphism in }\mathcal{A}: \operatorname{Ker}f \text{ and }\operatorname{Coker}f \text{ are objects in }\mathcal{C}\}.$$
Indeed, this class is supposed to be a left and right multiplicative system, but I am having some trouble in checking the Ore condition.
Indeed, I can understand everything in the proof of the Lemma 12.9.6 in the link pasted above, except the following assertion (in the third paragraph of the proof): "then $\operatorname{Ker}t\longrightarrow \operatorname{Ker}s$ is surjective".
This must be very easy, but I am not seeing why it should be true.

A: It's easy enough using elements. First, $s(b)$ is the class of $(0,b)$ in $(C \oplus B)/\mathrm{Im}(t,-g)$. So given any $b \in \mathrm{Ker}(s)$, we must have $(0,b) \in \mathrm{Im}(t,-g)$, i.e., for some $a \in A$ we have $t(a) = 0$ and $-g(a)=b$. Then $-a \in \mathrm{Ker}(t)$ maps to $b \in \mathrm{Ker}(s)$.

A: As the OP, I also wanted to prove this without using elements. So I wrote it in detail: (sorry for the long proof...)


text:
Q: ManyToOne doing multiple queries to fetch records I have two entities, and dept_id is the foreign key here.
public class Student implements Serializable {
  ...
  @Id
  @Column(name="id")
  private Integer id;

  @ManyToOne
  @JoinColumn(name = "dept_id")
  private Department department;
  ...
}

and
public class Department implements Serializable {
  ...
  @Id
  @Column(name="id")
  private Integer id;

  @Column(name = "name")
  private String name;
  ...
}

Now I am doing the following JPQL where I have around 100 parameters inside in query:
select o from Student o where o.id in(1,2,7,9,15,16, ...)

When I see the JPA log, I found it is fetching 100 records from the Student by one query. After that it is doing 100 separate queries to fetch the Department for each Student. So far my understanding is the I/O operation should be slow. Is there any way so that it fetches everything by a single query?

A: I found this worked for me:
query.setHint("eclipselink.join-fetch", "o.department");

Also, I found this one is handy as it does not make any joining, but fetches the records separately in a bulk.
query.setHint("eclipselink.batch", "o.department");


text:
Q: MotionLayout animation not working properly inside RecyclerView item I use this library StackExpandable to add an Expand/Collapse cardViews as a recyclerview item. Expand/Collapse works fine. But the issue I am facing is that when I expand two items and while scrolling, any item goes out of the screen and comes back, stacked card appears as a normal card. I have tried tracking the expand/collapse states. But, this issue is still there. Here's the video of the issue I am facing: https://drive.google.com/file/d/1MEbMvQXRn9jDNTpbDgzQFtBF78LyczrL/view?usp=sharing
Please let me know figure out whats happening to the Recyclerview item when it goes out of the screen and how can it be prevented?
This is the RecyclerView item_layout:
<it.fabiosassu.stackexpandableview.StackExpandableView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/verticalStackedCardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:shownElements="3"/>


text:
Q: Calling an action updates the other values in the redux store I am updating a state of a redux store variable on a button click from a view. I am aware that when there is a dispatch all the al the reducers are called. In my case when I update a state of a variable it updates the another.
Initial State,

Updated state,

This is the code,
import React, { Component } from "react";
import {
  Button,
  Container,
  Divider,
  Header,
  List,
  Segment
} from "semantic-ui-react";
import { connect } from "react-redux";
import { StepperDesktop } from "./StepperDesktop";
import { AuthResponse } from "../models/auth-response";
import { IStoreState } from "../redux/reducers";
import { QuoteType } from "../models/enums";
import { quoteTypeActions } from "../redux/actions/quoteType-actions";

interface IGettingStartedProps {
  authResponse: AuthResponse;
  history: any;
  updateQuoteType(quoteType: QuoteType): void;
}

export class _GettingStarted extends Component<IGettingStartedProps> {
  render() {
    return (
      <Container className="abg___main_content_wrapper">
        <StepperDesktop activeStep={1} />
        Getting Started

          Our online Farm Insurance service allows you to get an instant quote
          for your client that is valid for up to 45 days, but there are policy
          limits and conditions that will apply if you obtain a quote online. If
          you know proposal falls outside of these limits or conditions you
          should still submit your quote request and presentation through this
          service and one of our team will be in contact.

        <Divider hidden />
        Our online Farm Insurance policy limits:
        <List bulleted>
          <List.Item>Acreage up to 500 acres</List.Item>
          <List.Item>Farm buildings up to £1,000,000</List.Item>
          <List.Item>Machinery up to £500,000</List.Item>
          <List.Item>Cattle up to £1,000,000</List.Item>
          <List.Item>Sheep up to £1,000,000</List.Item>
          <List.Item>Home buildings up to £1,000,000</List.Item>
          <List.Item>Home contents up to £250,000</List.Item>
          <List.Item>Personal belongings up to £50,000</List.Item>
        </List>
        <Divider hidden />
        Our online Farm Insurance policy conditions:
        <List bulleted>
          <List.Item>The current holding insurer in not Aviva;</List.Item>
          <List.Item>
            The proposer, directors or partners in the business have never:
            <List.List>
              <List.Item>
                Been declared bankrupt or insolvent either as private
                individuals or in connection with any business;
              </List.Item>
              <List.Item>
                Been subject of a court judgment in respect of debt either as
                private individuals or in connection with any business;
              </List.Item>
              <List.Item>
                Been officers of a company that has been declared insolvent, or
                had a receiver or liquidator appointed, or entered into
                arrangements with creditors in accordance with the Insolvency
                Act 1986;
              </List.Item>
              <List.Item>
                Been convicted of or charged with but not yet tried for a
                criminal offence other than a motoring offence;
              </List.Item>
              <List.Item>
                Had an insurance contract cancelled or declared void due to a
                breach of a policy condition or due to non-disclosure or
                misrepresentation of a material fact;
              </List.Item>
              <List.Item>
                Within the last 5 years, suffered any loss or made any claim or
                had any claim made against them nor have any accidents occurred
                which are likely to result in a claim being made against them.
              </List.Item>
            </List.List>
          </List.Item>
          <List.Item>
            All insured risks are located at a single premises address;{" "}
          </List.Item>
          <List.Item>
            The buildings insured include no thatched roofs, composite panels
            (unless LPCB approved), glass houses or poly-tunnels;
          </List.Item>
          <List.Item>
            All premises are and will be maintained in a good state of repair;
          </List.Item>
          <List.Item>
            All premises are in an area free from damage by storm or flood;
          </List.Item>
          <List.Item>The premises do not have a reservoir; </List.Item>
          <List.Item>
            All electrical wiring has been tested and inspected in accordance
            with the appropriate guidelines;
          </List.Item>
          <List.Item>
            Not more than 20% of estimated annual revenue is obtained through
            the non-farming and diversified activities listed below, and
            liability cover will not extend to any activity not listed below:
            <List.List>
              <List.Item>Open days farm / house; </List.Item>
              <List.Item>Farm educational visits / farm walks; </List.Item>
              <List.Item>Contracting including Spraying; </List.Item>
              <List.Item>Fishing / fishing rights; </List.Item>
              <List.Item>Shoots - not for profit max 10 guns; </List.Item>
              <List.Item>Rented buildings / loss of rent; </List.Item>
              <List.Item>DIY livery up to 12 horses; </List.Item>
              <List.Item>Caravans / tents; </List.Item>
              <List.Item>Storage of third party boats, caravans; </List.Item>
              <List.Item>Farm weddings / parties; </List.Item>
              <List.Item>Retail (Farm Shops). </List.Item>
            </List.List>
          </List.Item>
        </List>

          Cover will not extend to any activity not listed above.

        <Divider hidden />
        <Divider hidden />

        <Segment secondary>

            Click 'Get online quote' to get an instant quote if your proposal
            meets all of the above, or 'Submit request' to upload your
            presentation and request a quote.

          <Container className="app___footer-with-buttons">
            <Button
              primary
              floated="right"
              onClick={() => {
                this.props.updateQuoteType(QuoteType.Simple);
                this.props.history.push("/quote/start-date");
              }}
            >
              Get online quote
            </Button>
            <Button
              basic
              floated="right"
              onClick={() => {
                this.props.updateQuoteType(QuoteType.Complex);
                this.props.history.push("/quote/start-date");
              }}
            >
              Submit request
            </Button>
          </Container>
        </Segment>
      </Container>
    );
  }
}

const mapStateToProps = ({
  authResponse,
  quoteStartDate,
  quoteType
}: IStoreState): {
  authResponse: AuthResponse;
  quoteStartDate: string;
  quoteType: QuoteType;
} => {
  return { authResponse, quoteStartDate, quoteType };
};

const mapDispatchToProps = (dispatch: any) => {
  return {
    updateQuoteType: (quoteType: QuoteType) => {
      return dispatch(quoteTypeActions.updateQuoteType(quoteType));
    }
  };
};

export const GettingStarted = connect(
  mapStateToProps,
  mapDispatchToProps
)(_GettingStarted);

Start Date Action,
import { Dispatch } from "redux";
import { StartDateActionTypes } from "./types";

export interface StartDateAction {
  type: StartDateActionTypes;
  payload: string;
}

export const startDateActions = {
  addStartDate: (quoteStartDate: string) => {
    return (dispatch: Dispatch) => {
      dispatch<StartDateAction>({
        type: StartDateActionTypes.ADD_DATE,
        payload: quoteStartDate
      });
    };
  }
};

Startdate reducer,
import { StartDateActionTypes } from "../actions/types";
import { StartDateAction } from "../actions/startdate-actions";

export const startDateReducer = (
  state: string = "",
  action: StartDateAction
) => {
  switch (action.type) {
    case StartDateActionTypes.ADD_DATE:
      return action.payload;
    default:
      return state;
  }
};

QuoteType actions,
import { Dispatch } from "redux";
import { QuoteTypeActionTypes } from "./types";
import { QuoteType } from "../../models/enums";

export interface QuoteTypeAction {
  type: QuoteTypeActionTypes;
  payload: QuoteType;
}

export const quoteTypeActions = {
  updateQuoteType: (quoteType: QuoteType) => {
    return (dispatch: Dispatch) => {
      dispatch<QuoteTypeAction>({
        type: QuoteTypeActionTypes.QOUTE_TYPE_UPDATE,
        payload: quoteType
      });
    };
  }
};

QuoteType reducer
import { QuoteTypeActionTypes } from "../actions/types";
import { QuoteTypeAction } from "../actions/quoteType-actions";
import { QuoteType } from "../../models/enums";

export const quoteTypeReducer = (
  state: QuoteType = QuoteType.Simple,
  action: QuoteTypeAction
) => {
  switch (action.type) {
    case QuoteTypeActionTypes.QOUTE_TYPE_UPDATE:
      return action.payload;
    default:
      return state;
  }
};

Combining reducers,
import { combineReducers } from "redux";
import { authenticationReducer } from "./authentication-reducer";
import { AuthResponse } from "../../models/auth-response";
import { quoteReducer } from "./quote-reducer";
import { startDateReducer } from "./startdate-reducer";
import { QuoteRequest } from "../../models/quote-request";
import { QuoteType } from "../../models/enums";
import { quoteTypeReducer } from "./quoteType-reducer";

export interface IStoreState {
  authResponse: AuthResponse;
  quoteRequest: QuoteRequest;
  quoteStartDate: string;
  quoteType: QuoteType;
}

export const rootReducer = combineReducers<IStoreState>({
  authResponse: authenticationReducer,
  quoteRequest: quoteReducer,
  quoteStartDate: startDateReducer,
  quoteType: quoteTypeReducer
});

Configure store,
import { createStore, applyMiddleware, StoreEnhancer, compose } from "redux";
import { rootReducer } from "./reducers";
import thunk from "redux-thunk";
import { routerMiddleware } from "react-router-redux";
import { composeWithDevTools } from "redux-devtools-extension";

export const configureStore = (history: any, initialState: any) => {

  const middleware = [thunk, routerMiddleware(history)];

  return createStore(
    rootReducer,
    initialState,
    composeWithDevTools(applyMiddleware(...middleware))
  );
};

Index.tsx,
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import { App } from "./App";
import { configureStore } from "./redux/configure-store";
import { Provider } from "react-redux";
import { createBrowserHistory } from "history";
import { Router } from "react-router-dom";

declare global {
  interface Window {
    initialReduxState?: any;
  }
}
const initialState = window.initialReduxState;

const baseUrl = "/";
export const history = createBrowserHistory({ basename: baseUrl });

const store = configureStore(history, initialState);
ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <App />
    </Router>
  </Provider>,

  document.querySelector("#root")
);

App.tsx,
import React from "react";
import "./App.css";
import { IStoreState } from "./redux/reducers/index";
import {
  Button,
  Container,
  Divider,
  Header,
  List,
  Segment
} from "semantic-ui-react";
import { Layout } from "./components/Layout";
import { connect } from "react-redux";
import { AuthResponse } from "./models/auth-response";

interface AppProps {
  authResponse: AuthResponse;
}

export class _App extends React.Component<AppProps> {
  render() {
    return (
      <>
        <Layout />
      </>
    );
  }
}

const mapStateToProps = ({
  authResponse
}: IStoreState): { authResponse: AuthResponse } => {
  return { authResponse };
};

export const App = connect(mapStateToProps)(_App);

Not sure what i am doing wrong here?

A: Fix as this:
In your start date reducer replace the switch with that one:
  switch (action.type) {
    case StartDateActionTypes.ADD_DATE:
      return {
        ...state, //Return all the values from the current state
        ...action.payload //Overwrite the values that exist in the payload only
      };
    default:
      return state;
  }

Fix the other reducer the same way.


text:
Q: Does there exist a function $f : X \to Y$ such that $f \in Y$?
Does there exist a function $f : X \to Y$ such that $f \in Y$?

I think this is related to Russell's paradox, but I'm not exactly sure how.

Added Later: As Brian points out, given any function $f : X \to Y_0$, we can just add $f$ to the codomain, that is $f : X \to Y_0\cup\{f\}$ is a function which satisfies my initial request.
However, what if we try to find a surjective function $f : X \to Y$ such that $f \in Y$?

A: Let $X=\varnothing$, $Y=\{\varnothing\}$; the unique function $f:X\to Y$ is $\varnothing$, which is an element of $Y$.
Added: For a slightly less trivial example, let $X=\{0\}$ and $Y=\big\{1,\{\langle 0,1\rangle\}\big\}$; then $\{\langle 0,1\rangle\}$ is a function from $X$ to $Y$ that is an element of $Y$. In general start with any function $f$ from $X$ to some set $Y_0$, and let $Y=Y_0\cup\{f\}$; then $f$, regarded now as a subset of $X\times Y$, is a function from $X$ to $Y$ that is an element of $Y$.

A: Let $V_\omega$ be the set of hereditarily finite sets (i.e. sets which are finite, and all their elements are finite, and so on). It is immediate from this definition that if $x\in V_\omega$ and $y\in x$ then $y\in V_\omega$, and if $x\subseteq V_\omega$ is finite, then $x\in V_\omega$.
It's not hard to show that if $X\in V_\omega$ then $\mathcal P(X)\in V_\omega$, and if $X,Y\in V_\omega$ then $X\times Y\in V_\omega$.
Take any set $X\in V_\omega$, then any function $f$ from $X$ into $V_\omega$ is actually a function into a finite subset of $V_\omega$, therefore there exists a finite $Y\in V_\omega$, such that $f\subseteq X\times Y$. Therefore $f\in V_\omega$.

For the addition, suppose that $f\colon X\to Y$ and $f\in Y$. If there exists some $x\in X$ such that $\langle x,f\rangle\in f$, then this a contradiction to the axiom of regularity because $\langle x,f\rangle =\{\{x\},\{x,f\}\}$ by the Kuratowski definition of an ordered pair, because this  means that $$f\in\{x,f\}\in\langle x,f\rangle\in f.$$
In particular $f$ cannot be surjective.
Note that regularity is necessary for this proof, otherwise we can have a set $X=\{X\}$. Note that in this case: $$\langle X,X\rangle=\{\{X\},\{X,X\}\}=\{\{X\}\}=\{X\}=X.$$
Therefore $X\times X=X$ which is the identity function from $X$ onto itself.

A: This definition of function is from general topology by Engelking:

Any subset of the Cartesian product $X \times Y$ is a relation. The relation $f\subset X\times Y$ is called a function from $X$ to $Y$, or a mapping of $X$ to $Y$, if for every $x\in X$ there exists a $y \in Y$ such that $(x,y)\in f$ and $y$ is uniquely determined by $x$, i.e., $(x,y) \in f$ and $(x,y') \in f$ imply $y=y'$.

If $f \in Y$, then there exists subset of $X\times Y$ such that it is the element of $Y$.
For example, if $Y$ has $\emptyset$, then the answer to the question is always true.


text:
Q: Wamp Error - aestan tray menu the confuguration file contains a syntax error on line 14: I was just installed WAMPServer. After open my pc I have this issue.

My wampmanager.ini
[BigMenu]
BigKey0=NC,0,0
[TextMenu]
TextKey0=NC,0,8,$000ff9f2,$00D77800,NC,NC
[PromptCustom]
PromptKey0=Default,10,$00FCFDFE,$00000000,$00FCFDFE,$00000000
PromptKey1=NC,10,$00F0F0F0,$00000000,$00FCFDFE,$00000000
[Timer]
NumberStart=2
CountStart=0
[Options]
AeTrayMode=64 Bits
AeTrayOldMode=64bit
AeTrayVersion=3.2.3.3

A: @aspectsiz just to clarify what @El Ibrahima Diago has written try the following.
Find your WAMP/SCRIPTS directory
Find where your WAMP > Scripts directory is.
For myself it's located at: C:\wamp64\scripts
Load Command Prompt
Load command prompt and CD into your WAMP > Scripts directory
Execute The Command
Execute: php refresh.php
That should be all that's required to fix it. I had the exact same issue and it has worked for me.

Just to recap, here is the full Command Prompt commands that I used:
cd C:\wamp64\scripts
php refresh.php
I hope that might clear a few things up and help others a bit more.

A: For this problem you juste have to go to wamp/scripts/ and type this command php refresh.php


text:
Q: Finite sigma-algebra; integrating a non-simple function. To help me learn measure theory I have come up with a finite example to work with. We take the set $X=[0,1]$ and the three sets $A_1=[0,0.2]$, $A_2=[0.7,1]$ and $A_3=(0.2,0.7)$ (the idea for this come from  here). The collection of subsets:
$$\{\emptyset, A_1,A_2,A_3,A_1\cup A_2, A_1\cup A_3, A_2 \cup A_3, \Omega\}$$ then forms a sigma-algebra. On which I have defined the measure (analogous to the Lebesgue measure), $\mu$ as:
$$\mu(A_i=[a,b])=b-a,\; \mu(A_i \cup A_j)=\mu(A_i)+\mu(A_j)$$
(where $[a,b]$ may be open or closed). Then using this measure we can perform integration of simple functions e.g.:
$$f=\begin{cases} 1 & \text{for} \; 0\le x \le 0.2 \\ 0 & \text{for}\; 0.2\lt x\lt 0.7\\ 3& \text{for}\; 0.7\le x\le 1\end{cases}=1\chi_{A_1}+3\chi_{A_2}$$
where $\chi_{A_i}$ represents the characteristic function of $A_i$. This means that the integral of $f$ is:
$$\int fd\mu=1\mu(A_1)+3\mu(A_2)=1\times(0.2-0)+3\times(1-0.7)=1.1$$
I am wanting to come up with an analogous example for the integration of a non-simple function. This is defined (see here) using the fact that if $f$ is measurable then there exists a sequence of simple functions $f_n$ such that $f_n(x) \rightarrow f(x)$ as $n\rightarrow \infty$ and we have:
$$\int fd\mu=\lim_{n\rightarrow \infty} \int f_nd\mu$$
Using this sigma-algebra and this measure please could someone help me come up with an example of this? I would like to see both how $f_n(x)\rightarrow f(x)$, how we find $f_n$ and how we use this to find the intergral?

A: You won't be able to construct a non-simple measurable function using a finite $\sigma$-algebra, because the preimage of every measurable set in $\mathbb{R}$ is going to need to be in your $\sigma$-algebra for $f$ to be measurable. Namely, if $f(A_i)$ contains two distinct points $y_1$ and $y_2$, then $f^{-1}(\{y_1\})\cap A_i\neq \emptyset$ and $f^{-1}(\{y_2\})\cap A_i\neq \emptyset$, but $f^{-1}(\{y_1\})\cap f^{-1}(\{y_2\}) = \emptyset$, so $f^{-1}(\{y_1\})\cap A_i\neq A_i$ and $f^{-1}(\{y_2\})\cap A_i\neq A_i$. This implies that $f^{-1}(\{y_1\})$ and $f^{-1}(\{y_2\})$ are not in your $\sigma$-algebra. Thus, we can let $y_i = f(x)$ for all $x\in A_i$, and we will have that $f$ is a simple function taking at most three possible values ($n$ possible values for a $\sigma$-algebra generated by $n$ disjoint sets).


text:
Q: How to access data usage settings of specific app programmatically? I'm developing an Android app which needs to download a lot of data.
I'd like to measure the data traffic of my app for specific period of time (like month).
This option is available on System Settings -> Data Usage.

*

*Is there any way to access this setting programmatically?

*Can I use some of android libs to get traffic?

I know about TrafficStats class but I can not get traffic for specific period of time and when i boot device this data is lost.

A: *

*Is there any way to access this setting programmatically?

try these code below:
public boolean invokeMethod(String methodName, Object[] args) throws Exception {
    ConnectivityManager mcm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    Class ownerClass = mcm.getClass();
    Class[] argsClass = null;
    if (args != null) {
        argsClass = new Class[1];
        argsClass[0] = args.getClass();
    }
    Method method = ownerClass.getMethod(methodName, argsClass);
    return (Boolean)method.invoke(mcm, args);
}

public Object invokeBooleanArgMethod(String methodName, boolean value) throws Exception {
    ConnectivityManager mcm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    Class ownerClass = mcm.getClass();
    Class[]  argsClass = new Class[1];
    argsClass[0] = boolean.class;
    Method method = ownerClass.getMethod(methodName,argsClass);
    return method.invoke(mcm, value);
}

/* use these two method like these */
Object[] arg = null;
try {
    boolean isMobileDataEnable = invokeMethod("getMobileDataEnabled", arg);
    if(!isMobileDataEnable){
        invokeBooleanArgMethod("setMobileDataEnabled", true);
    }
} catch (Exception e) {
    e.printStackTrace();
}

Also, in AndroidManifest.xml, you need to add
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>

*Can I use some of android libs to get traffic?

You can set an alarm or thread in service to get traffic periodically with TrafficStats for all process. If you want to get traffic of each process, I think you can see this answer.


text:
Q: ElasticSearch cannot find analyzer in field? I create an index like this using a PUT http://localhost:9200/test :
{
  "settings": {
    "number_of_shards": 1,
    "analysis": {
      "analyzer": {
        "sortable": {
          "type": "custom",
          "tokenizer": "keyword",
          "filter": [
            "lowercase"
          ]
        }
      }
    }
  },
  "mappings": {
  }
}

This returned:
{"acknowledged":true}

Then make sure that the analyzer is there:
http://localhost:9200/test/_analyze?_analyzer=sortable&text=HeLLo
{"tokens":[{"token":"hello","start_offset":0,"end_offset":5,"type":"<ALPHANUM>","position":0}]}

So I create mappings for it:
By PUT http://localhost:9200/test/_mapping/company
{
  "properties": {
    "name": {
      "type": "string",
      "analyzer": "standard",
      "fields": {
        "raw": {
          "type": {
            "analyzer": "sortable"
          }
        }
      }
    }
}

This returns:
{"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"no handler for type [{analyzer=sortable}] declared on field [raw]"}],"type":"mapper_parsing_exception","reason":"no handler for type [{analyzer=sortable}] declared on field [raw]"},"status":400}

What is wrong?

A: Your company mapping needs to be fixed to this:
{
  "properties": {
    "name": {
      "type": "string",
      "analyzer": "standard",
      "fields": {
        "raw": {
          "type": "string",
          "analyzer": "sortable"
        }
      }
    }
}


text:
Q: $\frac{1}{503}$, $\frac{4}{524}$, $\frac{9}{581}$,... The following question was posed on a national selection competition:
Find the greatest number in the following sequence:
$\frac{1}{503}$, $\frac{4}{524}$, $\frac{9}{581}$, $\frac{16}{692}$...
It took me a long time before I could solve this question, as I could not identify the motif displayed in the above sequence.
Afterwards I realized that the motif is expressed by the function $f(x)=\frac{x^2}{500+3x^3}$.
Once I realized that then, I solved the question as follows:
As $f(x)=\frac{x^2}{500+3x^3}$, then $f'(x)=\frac{2x(500+3x^3)-x^2*9x^2}{(500+3x^3)^2}$
$f'(x)=\frac{1000x-3x^4}{(500+3x^3)^2}$
$f'(x)=\frac{x(1000-3x^3)}{(500+3x^3)^2}$
So all we have to do now is find its maximum. $f'(x)=0$, for $x=\frac{10}{\sqrt[3]{3}}$ and $x=0$, once we analyze the function we find that for $x=\frac{10}{\sqrt[3]{3}}$ we have the maximum value of the function. However since that is a non integral number, we check for $x=6$ and $x=7$, which are the two closest integers to $x=\frac{10}{\sqrt[3]{3}}$.
We have that $f(7)>f(6)$ and hence its maximum is reached for $x=7$ and $f(x)=\frac{49}{1529}$
My question is how do I recognize this motif, as that was my biggest hurdle for this question?

A: The numerators are clearly the squares.
The $503$ starting the denominators and their slow growth suggests subtracting $500$. Then you see
$$
3, 24, 81, 192, \ldots \ .
$$
Perhaps you recognize the triples of the cubes. If not, successive differences soon lead you there.
Granted, this is hindsight.


text:
Q: Unitization of Suspension Let $A$ a C*-algebra (unital or not). Its suspension is defined to be: $$ S(A) \equiv A\otimes C_0((0,1);\,\mathbb{C}) $$where $C_0$ denotes all continuous functions which vanish at infinity.
We know that if $X$ is locally compact and if $X^{+}$ is its one-point compactification, then $$ \widetilde{C_0(X;\,\mathbb{C})}\cong C(X^{+};\,\mathbb{C})$$
My question is:
1) Given two C*-algebras $A$ and $B$ (unital or not), is it true that $$ \widetilde{A\otimes B} \cong \widetilde{A}\otimes\widetilde{B} $$?
2) Does it then follow that $$ \widetilde{S(A)}\cong \widetilde{A}\otimes C(S^1;\,\mathbb{C})$$?

A: As noted in the comments, this is false. Intuitively, on the left-hand side in 1) you add one point to both spaces and then take the cartesian product whereas on the right-hand side you first take the product and then add one point.
For example let $A=B=C_0((0,1))$. Then $\widetilde{A\otimes B}=\widetilde{C_0((0,1)\times (0,1))}=C(S^2)$ and $\tilde A\otimes \tilde B=C(S^1)\otimes C(S^1)=C(\mathbb{T}^2)$.


text:
Q: Ajax call ordering HTML Elements in wrong order I'm making an ajax call to the server code to pull more records onto the page. But it isn't coming back in order I expect it to. Below is the function that makes the Ajax call to the server code. The data from the server side code serves the data in the right order and when the call initially gets the data it's in the right order as well.
function GetPosts()
{
  $.ajax
  ({
      type: 'GET',
      url:  'getposts',
      data: {'pageIndex': JSON.stringify(pageIndex), 'pageSize': JSON.stringify(pageSize) },
      dataType: 'json',
      success: function (data)
      {
          for (var i = 0; i < data.length; i++) {
              $(this).load("showpost/" + data[i], function (result) {
                  $('#container').append(result);
              })
          }
          pageIndex++;
      },

      beforeSend: function () {
          $("#progress").show();
      },
      complete: function () {
          $("#progress").hide();
      },
      error: function () {
          alert("Something went terribly wrong with infinite scrolling " + pageIndex);
      }
  })
}

But This is the data I see when I make the call on the page

This is how the data should look when presented on the html page, the posts should be in descending order, which you can notice with the id numbers and it each time the call is made it comes in a different order.

A: When $(this).load("showpost/" ... are called. You have sent multiple ajax call to load posts. Depending on the load speed, it will return at random.
A work around for this is to prepare dom stubs/placeholder before ajax calls are sent. When it returns, you will update those stubs with each results respectively.
      var stubs = {};
      for (var i in data) {
          stubs[i] = $('

');
          $('#container').append(stubs[i]);
          $(this).load("showpost/" + data[i], function(result) {
              stubs[i].after(result); //insert result after stub
              stubs[i].remove(); // remove the stub
          });
      }


text:
Q: Rental Movie from Iphone to Apple TV I am wondering if my iTunes rental purchased from my iPhone is available on my Apple TV?

A: From Apple's site:
Can I play my rental on more than one device?
If you download a rented movie on your computer: You can transfer it to a device such as your Apple TV (1st generation), iPhone, iPad, or iPod if it's a standard-definition film (movies in HD can only be watched on your computer, iPad, iPhone 4 or later, iPod touch (4th generation or later), or Apple TV). Once you move the movie from your computer to a device, the movie will disappear from your computer's iTunes library. You can move the movie between devices as many times as you wish during the rental period, but the movie can only exist on one device at a time.
If you download a rented movie on your iPhone 4 or later, iPad, iPod touch (4th generation or later), or Apple TV: It is not transferable to any other device or computer.
http://support.apple.com/kb/HT1657


text:
Q: Same condition logic generating two very different byte codes for AtomicBooleans in Java. Why? If I do this, my program works very fine:
if (atomicBoolean1.get() == false && atomicBoolean2.get() == true
     && !atomicBoolean1.compareAndSet(false, true)) {

    continue;
}

Now if I do this, everything breaks:
if (atomicBoolean1.get() == false && atomicBoolean2.get() == true) {

    continue;
}

if (!atomicBoolean1.compareAndSet(false, true)) {

    continue;
}

Am I getting insane?

A: continue jumps to the next iteration.
They both are not same. Same should be
if (atomicBoolean1.get() == false && atomicBoolean2.get() == true) {
  if (!atomicBoolean1.compareAndSet(false, true)) {
      continue;
  }
}

A: Actually you are not doing exactly similar things in above 2 cases.
In case1,
atomicBoolean1.get() == false && atomicBoolean2.get() == true

if above 2 conditions satisfied only,
atomicBoolean1.compareAndSet(false, true)

function is calling.
But in case2,
atomicBoolean1.get() == false && atomicBoolean2.get() == true

if above 2 conditions satisfied, it will go back to loop start.
so will not call
atomicBoolean1.compareAndSet(false, true)

If those 2 conditions failed only, it will call
atomicBoolean1.compareAndSet(false, true)

I think, I may cause any problem.
Lets give more details about your program and what you are trying to do.
It may help to figure out the issue.


text:
Q: Gnuplot: gif unknown terminal I am using Gnuplot v5.0 patchlevel 4.
I tried to use the gif terminal to make a gif animation see here. The problem is that I do not have the gif terminal among all the terminals. When I type set terminal gif animate delay 100 I received the error message: unknown or ambiguous terminal type. Here the list of my terminals
Subtopics available for set terminal:
    cairolatex        canvas            cgm               context
    corel             dumb              dxf               eepic
    emf               emtex             epscairo          epslatex
    fig               hpgl              latex             mf
    mp                pcl5              pdfcairo          pngcairo
    pop               postscript        pslatex           pstex
    pstricks          push              qms               svg
    tek40xx           tek410x           texdraw           tgif
    tkcanvas          tpic              vttek             x11
    xlib              xterm

the tgif one is not working so, my question is, can I use/import in gnuplot a new terminal, such as the gif one ? Thanks


text:
Q: HTML5 Attribute Manipulation: Vanilla JS vs. jQuery How come changing elements' attribute values in vanilla JS and jQuery sometimes don't work similarly? One scenario is the experiment I created, where whenever the "Show password" button is being clicked, the password field's type attribute value is supposed to change into text when it is password, and vice versa. It worked successfully in vanilla JS but not in jQuery. In jQuery, the attribute value changes to text, but when I want to change it back to password, it won't work. Why does such issue occur?
Vanilla JS
document.querySelector('.show-password').onclick = function() {
    if(document.querySelector('#password').type == 'password') {
        document.querySelector('#password').type = 'text';
    } else {
        document.querySelector('#password').type = 'password';
    }
}

jQuery
$('.show-password').click(function() {
    if($('#password').attr('type', 'password')) {
        $('#password').attr('type', 'text');
    } else {
        $('#password').attr('type', 'password');
    }
});

A: Because if($('#password').attr('type', 'password')) is not asking if the type attribute is 'password'. It is setting type=password and returning a jQuery object to the if statement.
When .attr() is used with only one parameter, it gets that attribute from the selected element, so yo can do it using $("#password").attr("type") == "password".


text:
Q: How To Load View In Codeigniter Not In The Views Folder i want to make the different themes for my application . i kept all the theme folders in the http:://example.com/thems/,.. i want to load the views form these themes folder to make the custom template .

A: Just extend the CI_Loader core class.
Create new file at application/core/MY_Loader.php and extend the __construct method

class My_Loader extends CI_Loader
{
   function __construct()
   {
      //Change this property to match your new path
      $this->_ci_view_path = APPPATH.'views/';
      $this->_ci_ob_level  = ob_get_level();
      $this->_ci_library_paths = array(APPPATH, BASEPATH);
      $this->_ci_helper_paths = array(APPPATH, BASEPATH);
      $this->_ci_model_paths = array(APPPATH);
      log_message('debug', "Loader Class Initialized");
   }
}

I am quite interested if this little hack will work :)

A: Have the current theme in a session variable $theme;
then while loading the view, include the session variable in the path,
$this->load->view('themes/'.$theme.'/<page>');

A: Phil Sturgeon and several others have written template libraries that support themes more or less out of the box. This allows you to keep MVC structure and is rather flexible.
More at the docs

A: I made a very simple theme switcher based on an existing library. Although the files are still in the views folder but inside the views folder are theme subfolders.
http://keithics.com/blog/php-programming/a-very-simple-theme-switcher-for-codeigniter


text:
Q: How to return index of several maximum values from pandas dataframe? This is a dataframe of a name occurrences in the text. Names 'Sage', 'Davies' and 'Asplund' occurs equally amount of time. So I need a query to return all three names.
Name,Occurrence
Sage,6
Davies,6
Asplund,6
Goodwin,5
Panula,5
Arnold,4
........

A: Use, to get rows
In [1876]: df[df['Occurrence'] == df['Occurrence'].max()]
Out[1876]:
      Name  Occurrence
0     Sage           6
1   Davies           6
2  Asplund           6

And, to get the Names
In [1878]: df.loc[df['Occurrence'] == df['Occurrence'].max(), 'Name']
Out[1878]:
0       Sage
1     Davies
2    Asplund
Name: Name, dtype: object

In [1879]: df.loc[df['Occurrence'] == df['Occurrence'].max(), 'Name'].values.tolist()
Out[1879]: ['Sage', 'Davies', 'Asplund']

And, to get the index values
In [1880]: df[df['Occurrence'] == df['Occurrence'].max()].index
Out[1880]: Int64Index([0, 1, 2], dtype='int64')


text:
Q: No command executed after performing kill command in shell script Here is my shell script:
#!/bin/bash
PIDS=$(ps -e | grep $1 |grep -v grep| awk '{print $1}')
kill -s SIGINT $PIDS
echo "Done sendings signal"

I am passing the name of the process as command line argument.
The echo command is not getting executed, although the target processes are actually receiving the SIGINT signal and exited.
Any suggestions?
Update:
I changed the code to:
#!/bin/bash
PIDS=$(ps -e |grep $1 | grep -v grep | awk '{print $1}'|grep -v $$)
echo $PIDS
kill -s SIGINT $PIDS
echo "Done sendings signal"
echo "The current process is $$"

Now I am noticing a strange thing:
The script is working but not as expected. Executing following command in command line outside the script
ps -e|grep process-name|grep -v grep|awk '{print $1}'|grep -v $$
gives pid of the process-name but when I execute the same command inside shell script, assign it to variable PIDS and then echo PIDS then it shows one more pid in addition to the pid of process-name. Therefore when the kill command executes it gives an error that the process with second pid doesn't exist. It does echo the remaining sentences in the terminal. Any clue ?

A: There really are only a couple of possibilities.  Assuming you're just running this from the command line, you should see the message ... unless, of course, what you're doing puts the PID of your shell process in PIDS, in which case the kill would kill the (sub) shell running your command before you hit the echo.
Suggestion: echo $PIDS before you call kill and see what's there.  In fact, I'd be tempted to comment out the kill and try the command, just to see what happens.
#!/bin/bash
PIDS=$(ps -e | grep $1 |grep -v grep| awk '{print $1}')
echo $PIDS
# kill -s SIGINT $PIDS
echo "Done sendings signal"

Of course, you can always run the script with bash -x to see everything.

A: Your script works. The only reason I can see for the echo not being executed is that some value of $1 and the script file name combine so that your script PID is also gathered, thereby making the script suicide.
The PIDS line spawns a process running ps, grep, another grep -- so you won't find in PIDS the processes running grep, but what about the parent process itself?
Try:
#!/bin/bash
PIDS=$(ps -e | grep $1 |grep -v grep | awk '{print $1}' | grep -v "^$$\$" )
kill -s SIGINT $PIDS
echo "Done sendings signal"

or run the pipes one after the other with suitable safety greps.
Edit: it is evident that the "$1" selection is selecting too much. So I'd rewrite the script like this:
#!/bin/bash
# Gather the output of "ps -e". This will also gather the PIDs of this
# process and of ps process and its subshell.
PSS=$( ps -e )
# Extract PIDs, excluding this one PID and excluding a process called "ps".
# Don't need to expunge 'grep' since no grep was running when getting PSS.
PIDS=$( echo "$PSS" | grep -v "\<ps\>" | grep "$1" | awk '{print $1}' | grep -v "^$$\$" )
if [ -n "$PIDS" ]; then
    kill -s SIGINT $PIDS
else
    echo "No process found matching $1"
fi
echo "Done sending signal."

A: ps -e is identical to ps -A and selects all processes ( cf. http://linux.die.net/man/1/ps ), i. e. ps -e displays "information about other users' processes, including those without controlling terminals" (Mac OS X man page of ps). This means you will also kill the PID ($$) of your shell process, as already pointed out by Charlie Martin, because you will also grep a line of output of the ps -e command that looks like so:
67988 ttys000    0:00.00 /bin/bash ./killpids sleep
Just log the output of ps -e to a file to see that your script commits suicide:
./killpids sleep 2>err.log
#!/bin/bash
# cat killpids

echo $$

for n in {1..10}; do
   sleep 5000 &
done

sleep 1

unset PIDS
PIDS="$(ps -e | tee /dev/stderr | grep "$1" | grep -v grep | awk '{print $1}')"
#PIDS="$(ps -www -U $USER -o pid,uid,comm | tee /dev/stderr | grep "$1" | grep -v grep | awk '{print $1}')"

wc -l <<<"$PIDS"

#kill -s SIGINT $PIDS
echo kill -s TERM $PIDS
kill -s TERM $PIDS

echo "Done sendings signal"


text:
Q: Unexpected analytic function output in common table expression In SQL Server 2019, analytic functions are not returning the results that I would expect in the context of recursive common table expressions. Consider the following non-recursive T-SQL query:
WITH SourceData (RowNum, Uniform, RowVal) AS (
  SELECT 1, 'A', 'A' UNION ALL
  SELECT 2, 'A', 'B' UNION ALL
  SELECT 3, 'A', 'C' UNION ALL
  SELECT 4, 'A', 'D'
),
RecursiveCte0 (RowNum, Uniform, RowVal, MinVal, SomeSum, RowNumCalc, RecursiveLevel) AS (
  SELECT RowNum, Uniform, RowVal, RowVal, RowNum, CAST(RowNum AS BIGINT), 0
  FROM SourceData
),
RecursiveCte1 (RowNum, Uniform, RowVal, MinVal, SomeSum, RowNumCalc, RecursiveLevel) AS (
  SELECT * FROM RecursiveCte0
  UNION ALL
  SELECT
    RowNum, Uniform, RowVal,
    MIN(MinVal) OVER (PARTITION BY Uniform),
    SUM(RowNum) OVER (PARTITION BY Uniform),
    ROW_NUMBER() OVER (PARTITION BY Uniform ORDER BY RowNum),
    RecursiveLevel + 1
  FROM RecursiveCte0
)
SELECT *
FROM RecursiveCte1
ORDER BY RecursiveLevel, RowNum;

Results:
RowNum Uniform RowVal MinVal SomeSum RowNumCalc RecursiveLevel
1      A       A      A      1       1          0
2      A       B      B      2       2          0
3      A       C      C      3       3          0
4      A       D      D      4       4          0
1      A       A      A      10      1          1
2      A       B      A      10      2          1
3      A       C      A      10      3          1
4      A       D      A      10      4          1

As expected, the MIN, SUM, and ROW_NUMBER functions generate the appropriate values based on all rows from RecursiveCte0. I would expect the following recursive query to be logically identical to the non-recursive version above, but it produces different results:
WITH SourceData (RowNum, Uniform, RowVal) AS (
  SELECT 1, 'A', 'A' UNION ALL
  SELECT 2, 'A', 'B' UNION ALL
  SELECT 3, 'A', 'C' UNION ALL
  SELECT 4, 'A', 'D'
),
RecursiveCte (RowNum, Uniform, RowVal, MinVal, SomeSum, RowNumCalc, RecursiveLevel) AS (
  SELECT RowNum, Uniform, RowVal, RowVal, RowNum, CAST(RowNum AS BIGINT), 0
  FROM SourceData
  UNION ALL
  SELECT
    RowNum, Uniform, RowVal,
    MIN(MinVal) OVER (PARTITION BY Uniform),
    SUM(RowNum) OVER (PARTITION BY Uniform),
    ROW_NUMBER() OVER (PARTITION BY Uniform ORDER BY RowNum),
    RecursiveLevel + 1
  FROM RecursiveCte
  WHERE RecursiveLevel < 1
)
SELECT *
FROM RecursiveCte
ORDER BY RecursiveLevel, RowNum;

Results:
RowNum Uniform RowVal MinVal SomeSum RowNumCalc RecursiveLevel
1      A       A      A      1       1          0
2      A       B      B      2       2          0
3      A       C      C      3       3          0
4      A       D      D      4       4          0
1      A       A      A      1       1          1
2      A       B      B      2       1          1
3      A       C      C      3       1          1
4      A       D      D      4       1          1

For each of the three analytic functions, it appears that the grouping is only being applied within the context of each individual row, rather than all of the rows at that level. This unexpected behavior also happens if I partition over (SELECT NULL). I would expect the analytic functions to apply to the entire recursion level, as per MSDN:

Analytic and aggregate functions in the recursive part of the CTE are
applied to the set for the current recursion level and not to the set
for the CTE. Functions like ROW_NUMBER operate only on the subset of
data passed to them by the current recursion level and not the entire
set of data passed to the recursive part of the CTE.

Why do these two queries produce different results? Is there a way to effectively use analytic functions with recursive common table expressions?


text:
Q: Measuring time-varying inductances I am using a circuit based on an LC tank and Arduino that is used to measure inductances. The amplitude for the current pulse is of 40 mA, approximately the current that an Arduino pin gives at 5V. The values for the pulse rise and fall times are also fixed according to the Arduino ones, from what I read, about 10 ns. The diode would be to protect the output pin of the Arduino from high voltages that could occur at the output of the RLC circuit. The resistor connected to the comparator output is a pull-up resistor, so it is not " floating", since the output is open collector. I have tried it to measure fixed inductances and it works, since the pulse signal from the LM339 comparator is of the same frequency as the resonant frequency of the RLC circuit. We measure the width of the pulse with the "pulseIn()" function of Arduino and from there, performing the appropriate operations, we could obtain the value of the inductance.
But my idea is to use the circuit to measure a time-varying inductance. To simulate this, I assume that the coil flux varies in time as the function f(x)=x. Since LTSpice derives with respect to the variables of the functions we input, we have to use their integral, that is, x^2/2. We replace the variable "x" with the variable "time", since we want the inductance to vary with the simulation time: time^2/2. Finally, in order for its value to vary slowly and give the RLC circuit time to resonate somewhat for each value of inductance, it occurs to me to multiply the function by a very small slope. So the function "0.0001*(time**2)/2" is the expression you finally input as a stream. However, when simulating the output of the RLC circuit, no oscillation is seen and it appears that only the inductance is seen varying with time. Is there a flaw in the approach or just couldn't this circuit be used for this?
Here are the results of the simulation:


text:
Q: How do I prove this Riemann sum equals the definite integral? Let $f$ be Riemann integrable on $[a,b]$ then $$ \int_a^b f(x) \, \mathrm{d}x = \lim\limits_{n \to ∞} \dfrac{b-a}{n} \sum\limits_{r=1}^n f \left(a+\dfrac{r(b-a)}{n} \right) $$
I want to prove this, $$ \lim\limits_{n \to ∞} \dfrac{1}{n} \sum\limits_{t=an}^{bn} f \left(\dfrac{t}{n}\right) = \int_a^b f(x) \, \mathrm{d}x$$

Here's my attempt: Let $a,b \in \mathbb{Z}$ and $K=b-a$ then $$ I= \int_a^b f(x) \, \mathrm{d}x = \lim\limits_{n \to ∞} \dfrac{K}{n} \sum\limits_{r=1}^n f \left(a+\dfrac{rK}{n} \right) = \lim\limits_{n \to ∞} \dfrac{K}{n} \sum\limits_{r=1}^n f \left(\dfrac{an+rK}{n}\right) $$

Since $1≤r≤n$ so if $K>0$ then $an + K ≤ an+rK=t ≤ bn$

$$1) \quad I= \lim\limits_{n \to ∞} \dfrac{K}{n} \sum\limits_{t=an+K}^{bn} f \left(\dfrac{t}{n}\right) =\lim\limits_{n \to ∞} \dfrac{K}{n}\left(\sum\limits_{t=an}^{bn}f\left(\dfrac{t}{n}\right)- \sum\limits_{t=an}^{an+K-1} f\left(\dfrac{t}{n}\right)  \right)= \lim\limits_{n \to ∞}\dfrac{K}{n}\sum\limits_{t=an}^{bn}f\left(\dfrac{t}{n}\right) $$

Similarly, $1≤r≤n$ so if $K<0$ then $an + K ≥ an+rK=t ≥ bn$ so,

$$2) \quad I =  \lim\limits_{n \to ∞}\dfrac{K}{n}\sum\limits_{t=bn}^{an}f\left(\dfrac{t}{n}\right)$$

Almost there, but I don't know how to get rid of $K$ outside the sum in $1$ and $2$. If $K$ is gone, my result is proved. Any help?


text:
Q: Github how to quality control others upstream new commits New to Git and just started to use Github. Just created my first public repo on there. I know that the public can fork my repo at any time. I also know that others can commit new changes and upstream to my repo on Github.
I wanted to know is there a way to quality control the commits coming through? I wouldn't want random commits from people and want to make sure the code is actually up to quality standards. Is there a way to stop others from committing upstream back to my public repo?

A: Others can not push to your repo per se unless you explicitly allow them to.
What they can do is fork your code and file so-called pull requests – basically asking you to merge their changes into your repo – which you can then approve or decline.
More on pull requests in the GitHub help section


text:
Q: Join que mostre vários dados de um só id Eu tenho 3 tabelas: "Terceiros", "Morada_Terceiro", "Contactos_Terceiro".
O objetivo era: seria inserido um terceiro, o mesmo seria listado, fosse-lhe atribuído uma morada e um contacto, no entanto gostaria que fosse possível atribuir várias moradas a um só terceiro. Utilizei primeiro o INNER JOIN nas 3 tabelas e não foi possível, passei para o LEFT JOIN e quando era introduzido mais que uma morada ou contacto a um terceiro era listado a mesma informação mais que uma vez, acabei por utilizar o RIGHT JOIN e o FULL JOIN e nada. `

//Tabela Terceiros

 $sql="SELECT Terceiros.*, Email, Telefone, Telemovel, TipoC, Morada, Localidade, CodPostal FROM ((Terceiros INNER JOIN  Contactos_Terceiro on  Terceiros.Numero = Contactos_Terceiro.Numero ) INNER JOIN Morada_Terceiro on Terceiros.Numero = Morada_Terceiro.Numero )";
 if(isset($pesq))
  $sql.=" where Nome like '$pesq' ";
     $sql.=" limit $ini, $tp";
     $res=$lig->query($sql);

 //Tabela Contactos_Terceiro

  $sql="SELECT  Contactos_Terceiro.*, Nome FROM  Contactos_Terceiro INNER JOIN Terceiros on (Terceiros.Numero =  Contactos_Terceiro.Numero)";
 if(isset($pesq))
 $sql.=" where Nome like '$pesq'";
 $sql.=" limit $ini, $tp";
 $res=$lig->query($sql);

 //Tabela Morada_Terceiro

  $sql="SELECT Morada_Terceiro.*, Nome FROM Morada_Terceiro INNER JOIN Terceiros on (Terceiros.Numero = Morada_Terceiro.Numero)";
 if(isset($pesq))
  $sql.=" where Nome like '$pesq'";
 $sql.=" limit $ini, $tp";
 $res=$lig->query($sql);

`

A: Ao utilizar o inner, as linhas da tabela Terceiros vão se repetir pra cada ocorrência que houver nas outras tabelas.
Exemplo:
Se fizer um inner join da Terceiros* com **Morada_Terceiro, se houverem dois registros do mesmo Terceiro na Morada_Terceiro, a query retornará duas linhas: em ambas as linhas os dados da Terceiros será do mesmo registro.

Uma alternativa é nesta página fazer a query APENAS na tabela Terceiros, e fazer a query nas demais tabelas no momento em que o botão "olho" é clicado.


text:
Q: supertokens revoke other users active sessions I have a webapp that manages authorization and user roles via supertokens. When a session is initialized the app reads user role from database and passes it to supertokens role initialization.
Some users are admins and they may change the roles of other users. When the role of another user is changed I would like to revoke their active sessions, or change their role. This needs to take place immediately, even if the user has active sessions, so changing their roles in my database is not enough.
I know that supertokens have an open issue about "Define DB schema and APIs for UserRoles". Yet, I would expect that there would be some way to revoke active sessions of other users with their current structure.
Any help or explanation about how this might be approached will be appreciated.

A: First, some info about how the sessions for SuperTokens works:

*

*An access token is issue which contains the payload (which has the user's role you added). The access token's verification is stateless (by default).

*A refresh token is issued which is used to get a new access & refresh token when the existing access token expires.
Now, when you change a user's role, you want to propagate that change to all of their sessions. The backend SDK provided by SuperTokens has functions for that. For example, if you are using NodeJS, you can do something like:
let sessionHandles = await Session.getAllSessionHandlesForUser(userId);

// we update all the session's Access Token payloads for this user
sessionHandles.forEach(async (handle) => {
    let currAccessTokenPayload = (await Session.getSessionInformation(handle)).accessTokenPayload;

    await Session.updateAccessTokenPayload(handle,
            { role: "newRole", ...currAccessTokenPayload }
    );
})

Since we are changing the contents of the access token of another session, that session will only know about this after it has refreshed. So by default, there will be a delay in the propagation of this role change for that user.
So here are your options for solving this issue:

*

*Reduce the access token lifetime. This way, sessions are refreshed more often and the propagation of role change can happen more quickly.

*Enable access token blacklisting. This can be done via the core's config.yaml setting (access_token_blacklisting: true flag). If you are using docker, you can pass ACCESS_TOKEN_BLACKLISTING=true. Through this setting, each session verification will query the core and if there is a change in the access token's payload, that will get reflected immediately. The downside to this is that session verification will not be slower due to extra network calls.

Finally, there are hybrid approaches that you can implement yourself:
Maintain a cache (on your own) of changes to roles and during session verification, add a middleware (after verifySession runs) to check your cache. If the role for the current user has changed, return a 401 to the frontend forcing it to refresh the session resulting in the access token's payload being updated immediately.
Hope this helps!


text:
Q: Transforming Java.io.BufferedReader into Python object by using the following code (source: https://learn.microsoft.com/en-us/azure/databricks/kb/python/hdfs-to-read-files)
URI = sc._gateway.jvm.java.net.URI
Path = sc._gateway.jvm.org.apache.hadoop.fs.Path
FileSystem = sc._gateway.jvm.org.apache.hadoop.fs.FileSystem
conf = sc._jsc.hadoopConfiguration()

conf.set(
  "fs.azure.account.key.<account-name>.blob.core.windows.net,
  "<account-access-key>")

fs = Path('wasbs://<container-name>@<account-name>.blob.core.windows.net/<file-path>/').getFileSystem(sc._jsc.hadoopConfiguration())
istream = fs.open(Path('wasbs://<container-name>@<account-name>.blob.core.windows.net/<file-path>/'))

reader = sc._gateway.jvm.java.io.BufferedReader(sc._jvm.java.io.InputStreamReader(istream))

while True:
  thisLine = reader.readLine()
  if thisLine is not None:
    print(thisLine)
  else:
    break

istream.close()

I receive object reader of type java.io.BufferedReader, that I would like to use to read by pandas, geopandas or other libraries (not read and print line by line as in the example).
Could you help me?
Thank you
Lukas

A: I would try to read BufferedReader content into a string and than read this string with pd.read_csv(StringIO(string)):
string = reader.lines().collect(sc._jvm.java.util.stream.Collectors.joining())
df = pd.read_csv(StringIO(string))


text:
Q: Can A Crashed Hard Disk Of A Laptop Be Converted To External HD?? Can I Recover Its Data? I am recently getting a blue screen on my laptop all of a sudden after it boots up...
After booting, windows starts and hangs up after a while, which is followed by a BLUE SCREEN prompting a probable hardware failure....
It some times gives an option to start in safe mode, command prompt or normally.
but even then, the same thing repeats aferb windows starts.
Is It A Hard Disk Crash??
If, so can I convert that HD into an external one, and use it as an external HD?
Is it also possible to get back whatever data I had in it?

A: If you have the correct connector to the disk and plug it in as an aditional drive (SATA, IDE) or external drive(USB) in another computer, it will be read as a normal external drive. You may need a drive conversion set to plug it in as USB (IDE, SATA -> USB)
You will be able to copy any file on it.
If the disk is damaged or any of the files in it, is damaged, you wont be able to copy it.


text:
Q: переадресация всех запросов с одного домена на другой Есть новый сайт new.site.com,
есть старый сайт site.com.
Как сделать так, чтобы все http-запросы на site.com/new/
шли на new.site.com/
(в том числе обращения из .css и .js файлов) ?
Веб-сервер - Apache 2.2, OS - Linux Debian, в public_html есть файл .htaccess, вот его содержимое:
php_value date.timezone Europe/Moscow
AddDefaultCharset utf-8

<IfModule mod_rewrite.c>
  RewriteEngine On

  # When your application folder isn't in the system folder This snippet prevents user access to the application folder
  RewriteCond %{REQUEST_URI} ^application.*
  RewriteRule ^(.*)$ /index.php?/$1 [L]

  # Checks to see if the user is attempting to access a valid file, such as an image or css document, if this isn't true it sends the request to index.php
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
  # If we don't have mod_rewrite installed, all 404's can be sent to index.php, and everything works as normal.
  ErrorDocument 404 /index.php
</IfModule>

Интересуют решения на стороне веб-сервера, код приложения трогать крайне нежелательно.

A: Проще некуда:
RewriteRule ^/new(/.*)$ http://new.site.com/$1 [R=302,L]

Вставьте сразу после
RewriteEngine On


text:
Q: LaPlace transform of $t^2\sin(at)$ $$\int^{\infty}_{0} e^{-st}t^2\sin(at)dt$$
I keep running into a problem when using:
$$u=e^{-st}t^2$$ $$du=2te^{-st}-st^2e^{-st}$$
$$v=\frac{1}{a} \cos(at)$$
$$dv=\sin(at)$$
Anyone have any suggestions for how to proceed?  I've seen a slick substitution using Euler's formula but I'm not sure that it is necessary.

A: Try invoking the Leibnitz rule and differentiating twice under the integral sign with respect to $s$.

A: To expand on what @ncmathsadist means is
$$
\int_0^{\infty}t^2e^{-st}\sin(at)dt
$$
can be solved by using a more well known transform. Consider
$$
\mathcal{L}\{\sin(at)\} = \int_0^{\infty}e^{-st}\sin(at)dt = \frac{a}{s^2 + a^2}
$$
Then
$$
\frac{\partial^2}{\partial s^2}\mathcal{L}\{\sin(at)\} = \text{what integral?} = \frac{\partial^2}{\partial s^2}\frac{a}{s^2 + a^2}
$$


text:
Q: SVG WPF C# Rendering Issue While starting with the SVG Rendering Library 1.7.0 (installed using NuGet) I get an issue that just does not make sense to me.  Using the simplest of SVG content (a filled rectangle with clearly recognizable black border):
<svg  xmlns="http://www.w3.org/2000/svg"
      xmlns:xlink="http://www.w3.org/1999/xlink">
    <rect x="0" y="0" height="50" width="50"
          style="stroke:#000000; fill: #efefef"/>
</svg>

I then proceed to load and display it using a bitmap and a picture box:
        String path = Path.Combine(
            AppDomain.CurrentDomain.BaseDirectory,
            "etc\\simple.svg");

        var svgDocument = SvgDocument.Open(path);
        bitmap = new Bitmap(50, 50, PixelFormat.Format32bppArgb);
        svgDocument.Draw(bitmap);
        var ms = new MemoryStream();
        bitmap.Save(ms, ImageFormat.Png);
        ms.Position = 0;

        var bi = new BitmapImage();
        bi.BeginInit();
        bi.StreamSource = ms;
        bi.EndInit();

        img.Source = bi;

So, rendering a 50 by 50 rectangle to a 50 by 50 bitmap should render me a non-scaled full image consisting of a gray square surrounded by a black border.  What however happens is that the top and left sides of the border is cut off.
Conceptually I am obviously missing something, as playing with the bitmap size, view port and
scaling give me mixed results, one or two working but without any understanding to it.
Here is the amended source that works - tested - thanks to Robert's suggestion:
            bitmap = new Bitmap(51, 51, PixelFormat.Format32bppArgb);
        svgDocument.Transforms.Add(new SvgTranslate(.5f, .5f));
        svgDocument.Draw(bitmap);

Thanks,
Gawie

A: Strokes are drawn 1/2 inside and 1/2 outside the edge so the stroke you are drawing is partially cut off at the edges because your shape is actually 1/2 (the left edge stroke) + 50 + 1/2 (the right edge stroke) = 51 units wide, similarly its also 51 units high.
You could position the rect at 0.5, 0.5 and either make it smaller or make the bitmap larger to display it completely.
The SVG specification says
The 'stroke' property paints along the outline of the given graphical element.


text:
Q: Conditional format in adobe Acrobat I am new at Acrobat, Need some help in conditional Formatting,
I have 2 text fields. If I enter a number >0 but <10 the bg colour of the second box should turns yellow. If I enter a number <20 but >10 it should turns orange.
Please help to understand Acrobat DOM elements.

A: Let's assume the field where you enter the numbers is called "myField". Then, we would add the following to the Calculate event of the field where the background should change:
var mf = this.getField("myField") ;
if (mf.value > 0 && mf.value < 10) {
event.target.fillColor = color.yellow ;
} else {
if (mf.value >= 10 && mf.value < 20) {
event.target.fillColor = ["RGB", 1, 0, 0.2] ;
} else {
event.target.fillColor = ["T"] ;
}
}

and that should do it.
Note that there is no pre-defined orange color, and you'd have to get the correct color value array (I think the one I used is kind of an orange).
If you add the code to the calculate event of another field, you'd have to replace event.target with this.getField("myOtherField") (or whatever the field name is).


text:
Q: Uniqueness of has_many association class User < ApplicationRecord
  has_and_belongs_to_many :profiles

  def add_profile(profile)
    self.profiles << profile unless self.profiles.include?(profile)
  end
end

class Profile < ApplicationRecord
  has_and_belongs_to_many :users
  validates_uniqueness_of :linkedin_id, allow_nil: true
end

For some reason on production I get
ActiveRecord::RecordInvalid: Validation failed: Linkedin has already been taken
on
self.profiles << profile unless self.profiles.include?(profile) line.
And after this I have duplicates in User.profiles records.
What is the problem?

A: Using has_and_belongs_to_many is probably not the best option here.
If you have the quite common scenario where a user may attach several "profiles" or external OAuth credentials to their account you want a one to many relationship.

This example uses a generic uid column instead of linkedin_id so that you can use the exact same logic for Facebook, Twitter or any other sort of account.
class User < ActiveRecord::Base
  has_many :profiles
end

class Profile < ActiveRecord::Base
  belongs_to :user
end

This guarantees that a profile can only belong to a single user. You may want to add some additional uniqueness constraints.
class AddUserProviderIndexToProfiles < ActiveRecord::Migration
  def change
    add_index(:profiles, [:user_id, :provider], unique: true)
    add_index(:profiles, [:uid, :provider], unique: true)
  end
end

This enforces on the database level that a user can only have one profile with a given provider and that there may only be one profile with for a given :provider, :uid combination. Adding indexes in the database safeguards against race conditions and improves performance.
You will also want a application level validation to avoid the application crashing due to database driver errors!
class Profile < ActiveRecord::Base
  belongs_to :user
  validates_uniqueness_of :uid, scope: :provider
  validates_uniqueness_of :user_id, scope: :provider
end


text:
Q: how to fix the "Component definition is missing display name" error?     const IndeterminateCheckbox = React.forwardRef(

    ({indeterminate, ...rest}, ref) => {
      const defaultRef = React.useRef();
      const resolvedRef = ref || defaultRef;

      React.useEffect(() => {
        resolvedRef.current.indeterminate = indeterminate;
      }, [resolvedRef, indeterminate]);

      return <input type="checkbox" ref={resolvedRef} {...rest} />;
    },
);

How to fix "Component definition is missing display name" in line 1

A: To fix this error, you should put a displayName on your component. This happens because your arrow function inside forwardRef doesn't have the context of your function name.
Solution one:
Put this on the final of your file.
    const IndeterminateCheckbox = React.forwardRef(
     ({indeterminate, ...rest}, ref) => {
      const defaultRef = React.useRef();
      const resolvedRef = ref || defaultRef;

      React.useEffect(() => {
        resolvedRef.current.indeterminate = indeterminate;
      }, [resolvedRef, indeterminate]);

      return <input type="checkbox" ref={resolvedRef} {...rest} />;
    },
);

IndeterminateCheckbox.displayName = 'IndeterminateCheckbox'

OR
You can avoid use arrow function inside forwardRef and use named functions.
    const IndeterminateCheckbox = React.forwardRef(
     function Component({indeterminate, ...rest}, ref) {
      const defaultRef = React.useRef();
      const resolvedRef = ref || defaultRef;

      React.useEffect(() => {
        resolvedRef.current.indeterminate = indeterminate;
      }, [resolvedRef, indeterminate]);

      return <input type="checkbox" ref={resolvedRef} {...rest} />;
    }
  },
);


text:
Q: snapshot.data.data() is null
class Profile extends StatefulWidget {
  @override
  _ProfileState createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  Future<DocumentSnapshot> getData() async {
    return await FirebaseFirestore.instance
        .collection('user')
        .doc(FirebaseAuth.instance.currentUser.uid)
        .get();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Profile'),
      ),
      body: FutureBuilder(
        future: getData(),
        builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.data.data() == null)
              return Center(child: Text((snapshot.data.data()).toString()));
            else
              return ListView.builder(
                  shrinkWrap: true,
                  itemCount: 1,
                  itemBuilder: (BuildContext context, int index) {
                    return ListTile(
                      title: Text(snapshot.data.data()['email']),
                    );
                  });
          } else if (snapshot.connectionState == ConnectionState.none) {
            return Text("No data");
          } else
            return CircularProgressIndicator();
        },
      ),
    );
  }
}

This code is always showing 'null' . What is the reason for which snapshot.data.data() is null?
Im new to future builder and Im not understanding what could be the reason for this error.

A: just use snapshot.data==null or !snapshot.exists


text:
Q: vim disable spelling in certain regions When writing latex in vim in the tabular enviroment, example
\begin{tabular}{rl}
  one & two \\
  \multicolumn{2}{c}{what?}
\end{tabular}

the rl is flagged as a miss spell but it should be ignored.
I have added the following to after/ftplugin/tex.vim:
syn region texMyNOHL matchgroup=NONE start='{tabular}{' end='}'
    \ contains=@NoSpell

but it is still marked as a miss spell.
What would be the correct way of ignoring the specific mentioned region?

A: You can't just "overlay" your texMyNOHL region; the existing tex syntax definitions prevent a match, because they are finer-grained.
When inspecting the syntax, you'll see that the item is matched by the texMatcher group. This one allows to include inner matches via the texMatchGroup syntax cluster:
:syn match texRl contained contains=@NoSpell "rl"
:syn cluster texMatchGroup add=texRl


text:
Q: How to create a custom button in Order grid in Magento 1 I want to create a custom button in magento 1 backend in **order tab.**

I want this button to be General(for all orders), but i can't find anything related to my issue. All i find it's this article article, but it not help me to much because they create a button for product catalog tab.
Dose anyone know what steps i need to follow to do this? Any advice will be greatly appreciated

A: Try Below Code :
You need to first overwrite observer :  adminhtml_widget_container_html_before
<adminhtml_widget_container_html_before>
    <observers>
         <add_button_test>
             <class>your_module_name/observer</class>
             <method>addNewButton</method>
         </add_button_test>
    </observers>
</adminhtml_widget_container_html_before>

After This open Observer file from model which is you overwrite :
public function addNewButton($observer)
{
    $container = $observer->getBlock();
    if(null !== $container && $container->getType() == 'adminhtml/sales_order') {
        $data = array(
            'label'     => 'My button',
            'class'     => 'some-class',
            'onclick'   => 'setLocation(\' '  . Mage::getUrl('*/*', array('param' => 'value')) . '\')',
        );
        $container->addButton('my_button_identifier', $data);
    }

    return $this;
}

Clear Cache and Refresh order Grid.
Happy Coding. :)


text:
Q: Cauchy convergent sequences Suppose that $(a_n)$ and $(b_n)$ are convergent sequences and that $b_n > 0$ for all $n$. Is it true that $(a_n / b_n)$ is Cauchy? If it is true, prove it. If it is not true, give a counterexample to show why it is not true.
My approach: let $lim(a_n)$ = $L$ and $\lim(b_n)$ = $M$, with $M \neq 0$.
Since $(a_n)$ and $(b_n)$ converge, then by the property of limits $(a_n / b_n)$ will converge too with $M \neq 0$.
I don't know how to make it so that it is Cauchy.

A: The limit law you've cited is correct when $M \ne 0$, so try a case when $M = 0$. In particular, take $a_n$ to be a constant sequence (e.g. $a_n = 1$ for all $n$) and $b_n =  \frac{1}{n}$, perhaps. Then
$$\frac{a_n}{b_n} = \frac{1}{\frac{1}{n}} = n$$
is an unbounded, and thus divergent sequence.

A: Put $a_n = 1/\sqrt{n}$ and $b_n = 1/n$.  You have $a_n/b_n = \sqrt{n}$.

A: Not necessarily. Take for example, $a_n=\frac{(-1)^n}{n}$, and $b_n=\frac{1}{n}$. Then $a_n/b_n=(-1)^n$, which is not Cauchy.


text:
Q: What does "self.default = default if default else type()" mean? I have always been a .NET guy since I started working (~6 years). Recently, I am working on a project using Django, which requires me to learn Python in parallel. A lot of times I bumped into Python code that looked simple but I just couldn't understand. And here is one of them.
class TypedProperty(object):
    def __init__(self, name, type, default=None):
        self.name = "_" + name
        self.type = type
        self.default = default if default else type()

Can someone kindly explain to me what the last line of the code is doing?
I hope this question is not too trivial, as I am having trouble coming up with a good title for it.

A: a if b else c is a conditional expression that evaluates to a if b evaluates to True, and to c otherwise.  In the given context, this checks if default is "trucy", in which case it is stored in self.default.  Otherwise, a new instance of type is created and stroed in self.default.
Note that this implementation has several issues:

*

*It uses type as a variable name, shadowing the built-in type().  This is considered bad style.

*It uses the condition if default where actually if default is None should be used.  The check is intended to test if the parameter default was actually passed to the constructor.  As it is, the implementation won't accept any default value that evaluates to False.

A: In the function signature you see default=None - this means that if a third argument is not passed in, default will be equal to None.
That last line naively checks to see if default evaluates to true to determine if a default was passed in. If default is true, then self.default will be set to it. Otherwise self.default is set to an instance of the type passed in.
I say naively because default may be 0, or it may be False, or (more likely) it may be an object, but that object evaluates to False somehow. I would prefer
self.default = default if default is not None else type()

Or, to avoid the conditional expression which I don't find the clearest in the world
if default is None:
    self.default = type()
else:
    self.default = default

A: That is Python's ternary operator (aka conditional expression) in action! Something worth nothing is that Python evaluates booleans lazily, so in this case:
self.default = default if default else type()

Is equivalent to this:
self.default = default or type()

If default evaluates to any non-False value, its value would be used, otherwise it would fall through to type().


text:
Q: Git Error fatal: Could not set SSL backend to 'openssl': already set I have been facing an error (fatal: Could not set SSL backend to 'openssl': already set) when I am trying to push my changes from local to remote git repository and cannot push any changes. If anyone knows about this error and how can we resolve it or how can can we reset the http.sslbackend to default please help.

A: You must uninstall the git, clean the temporary files with any cleaner, and reinstall the git with the latest version.
https://git-scm.com/download/

A: This happened to me because i custom compiled git --with-openssl but had my ~/.gitconfig configured with:
[http]
    sslbackend = openssl
[https]
    sslbackend = openssl

Seems that git doesn't like you to specify if it was pre-compiled that way. In any case, removing those global configs worked.


text:
Q: Construct fixed-size array in variadic template I want to construct an array of 8 integers in a variadic function. No problem:
template <typename... Ints>
void foo(Ints... ints) {
    static_assert(sizeof...(Ints) < 8, "some useful error");

    const int my_array[8] = {ints...};
}

That even automatically zero initializes the array, so if I call foo(1, 2, 3) I will get an array like {1, 2, 3, 0, 0, 0, 0, 0}.
Now what if I want to default to something other than zero? Like, say -1. This works:
template <int Def>
struct Int {
    Int() : val(Def) { }
    Int(int i): val(i) { }

    inline operator int() const { return val; }

    int val;
};

template <typename... Ints>
void foo(Ints... ints) {
    const Int<-1> my_array_def[8] = {ints...};
    const int* my_array = reinterpret_cast<const int*>(my_array_def);
}

But is there a simpler way that doesn't rely upon having this extra type?

A: Just use another template:
template <typename... Ints>
auto foo(Ints... ints) -> typename std::enable_if<sizeof...ints==8>::type {
    const int my_array[] = {ints...};
}
template <typename... Ints>
auto foo(Ints... ints) -> typename std::enable_if<sizeof...ints<8>::type {
    return foo(ints..., -1);
}


text:
Q: Crash report from JVM everybody!
I have some crach reports from JVM - hs_err_pid .logs.
So are they caused by mistakes (exceptions) in my java code? This errors arised from AWT-EventQueue-0:
---------------  T H R E A D  ---------------

Current thread (0x4f61b800):  JavaThread "AWT-EventQueue-0" [_thread_in_native, id=9072, stack(0x4f570000,0x4f5c0000)]

siginfo: ExceptionCode=0xc0000005, reading address 0x00000060

The header:
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x761e76d0, pid=8756, tid=9072
#
# JRE version: 6.0_24-b07
# Java VM: Java HotSpot(TM) Client VM (19.1-b02 mixed mode windows-x86 )
# Problematic frame:
# C  [ole32.dll+0x376d0]
#
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#strong text

A: No, this is not the result of an error in Java code. It can be the result of:

*

*Faulty hardware

*A bug in native code called via JNI

*A bug in the JVM

*A bug in the OS

A: Maybe a reinstall of your JVM could help:
http://www.java-forums.org/eclipse/312-exception_access_violation-0xc0000005.html

A: Please look into the "Problematic frame:ole32.dll" crash is happening from ole32.dll.
Please see similar crash reported
http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=e5f1f1011daf96ffffffffdd154dd2e731150?bug_id=6967456


text:
Q: how to get list of previous n values of a column in a new column of current row? My pandas dataframe looks like below:
Index   Score
1       15.5
2       0.0
3       15.5
4       30.0
5       17.5

I want to get the previous 3 scores as a list in new column like below
Index   Score   Pre_Scr
1       15      []
2       0       [15]
3       18      [0,15]
4       30      [18,0,15]
5       17      [30,18,0]
5       5       [17,30,18]

I tried
[x.values.tolist() for x in v.rolling(3)]

But this returns a list including the current value. How do I get it in the above expected format against each record?

A: If you just want to remove the last value, why not do this to remove the current value:
[x.values.tolist()[:-1] for x in v.rolling(4)]

A: If I got your variables right, you can do it this way:
 [[y for y in x.values.tolist() if y != v_no] for x, v_no in zip(v.rolling(4), v.values) ]

or probably (once it is going to be implemented for non-time datatypes):
 [x.values.tolist() for xin v.rolling(4, closed='left')]