text:
Q: Selenium Webdriver halting with [Errno 10054] I am trying to run a Python 2.7.0 routine that uses Selenium 2.37.2 to launch Firefox 26.0 browsers and submit queries to the Google n-grams site (all on my Windows 8 machine). The program works perfectly for the first ten entries in an input file, then halts with the following traceback:
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
    return self.func(*args)
  File "C:\Users\Douglas\Desktop\n-grams\n_gram_api.py", line 43, in query_n_gra
ms
    driver.get("https://books.google.com/ngrams")
  File "C:\Python27\lib\site-packages\selenium-2.37.2-py2.7.egg\selenium\webdriv
er\remote\webdriver.py", line 176, in get
    self.execute(Command.GET, {'url': url})
  File "C:\Python27\lib\site-packages\selenium-2.37.2-py2.7.egg\selenium\webdriv
er\remote\webdriver.py", line 162, in execute
    response = self.command_executor.execute(driver_command, params)
  File "C:\Python27\lib\site-packages\selenium-2.37.2-py2.7.egg\selenium\webdriv
er\remote\remote_connection.py", line 355, in execute
    return self._request(url, method=command_info[0], data=data)
  File "C:\Python27\lib\site-packages\selenium-2.37.2-py2.7.egg\selenium\webdriv
er\remote\remote_connection.py", line 402, in _request
    response = opener.open(request)
  File "C:\Python27\lib\urllib2.py", line 391, in open
    response = self._open(req, data)
  File "C:\Python27\lib\urllib2.py", line 409, in _open
    '_open', req)
  File "C:\Python27\lib\urllib2.py", line 369, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 1173, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "C:\Python27\lib\urllib2.py", line 1148, in do_open
    raise URLError(err)
URLError: <urlopen error [Errno 10054] An existing connection was forcibly close
d by the remote host>

I found a number of informative sites that discuss the error message, but I haven't been able to figure out why my own process is halting after ten interations through the for loop. Here is the code that I'm running (sorry it's a bit long, I didn't want to trim it, in case the culprit is hidden in the GUI):
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from Tkinter import *
import Tkinter as tk
from tkFileDialog import askopenfilename
import time

#out
out = open("n_grams_outfile.txt", "w")
out.write("search string" + "\t" + "pub year" + "\t" + "frequency" + "\n")

#create a function that will return the filepath for a file provided by the user
user_defined_filepath = {}
def selectfile():
    user_defined_filepath['filename'] = askopenfilename(filetypes=[("Text","*.txt")]) # user_defined_filepath['filename'] may now be accessed in the global scope.

#create function we'll call when start button is pressed
def query_n_grams(event = "<Button>"):

    #create binary switch we'll use to only start new browser in first pass. Set default to true
    first_pass = 1

    #identify the input file
    inputfile = user_defined_filepath['filename']
    readinputfile = open(inputfile).read()
    stringinputfile = str(readinputfile)

    #assume input file = tsv. Left hand column = string of len <= 6; right hand column = pub year of text
    split_by_row = stringinputfile.split("\n")
    for row in split_by_row:
        search_terms = row.split("\t")[0]
        actual_pub_year = row.split("\t")[1]
        pub_year_minus_five = int(actual_pub_year) - 5
        pub_year_plus_five = int(actual_pub_year) + 5

        #you now have terms and pub yaer. Fire up webdriver and ride, cowboy
        if first_pass == 1:
            driver = webdriver.Firefox()
            first_pass = 0

        #otherwise, use extant driver
        driver.implicitly_wait(10)
        driver.get("https://books.google.com/ngrams")
        driver.implicitly_wait(10)

        #send keys
        driver.implicitly_wait(10)
        keyword = driver.find_element_by_class_name("query")
        driver.implicitly_wait(10)
        keyword.clear()
        driver.implicitly_wait(10)
        keyword.send_keys(str(search_terms))
        driver.implicitly_wait(10)

        #find start year
        driver.implicitly_wait(10)
        start_year = driver.find_element_by_name("year_start")
        driver.implicitly_wait(10)
        start_year.clear()
        driver.implicitly_wait(10)
        start_year.send_keys(str(pub_year_minus_five))
        driver.implicitly_wait(10)

        #find end year
        driver.implicitly_wait(10)
        end_year = driver.find_element_by_name("year_end")
        driver.implicitly_wait(10)
        end_year.clear()
        driver.implicitly_wait(10)
        end_year.send_keys(pub_year_plus_five)
        driver.implicitly_wait(10)

        #click enter
        driver.implicitly_wait(10)
        submit_button = driver.find_element_by_class_name("kd_submit")
        driver.implicitly_wait(10)
        submit_button.click()
        driver.implicitly_wait(10)

        #grab html
        driver.implicitly_wait(10)
        html = driver.page_source
        driver.implicitly_wait(10)

        #if you run a search that yields no hits, can't split the html, so use try/except
        try:

            #we want the list object that comes right after timeseries and before the comma
            desired_percent_figures = html.split('"timeseries": [')[1].split("]")[0]

            #now desired_percent_figures contains comma-separated list of percents (which we still need to convert out of mathematical notation). Convert out of mathematical notation (with e)
            percents_as_list = desired_percent_figures.split(",")

            #convert to ints
            percent_list_as_ints = [float(i) for i in percents_as_list]

            #take your list and find mean
            mean_percent = sum(percent_list_as_ints) / float(len(percent_list_as_ints))

            out.write(str(search_terms) + "\t" + str(actual_pub_year) + "\t" + str(mean_percent) + "\n")

        #you'll get IndexError if you run a query like "Hello Garrett" for which there are no entries in the database at all. (Other queries, like 'animal oeconomy' for year 1700, yields result 0, but because search string is in database elsewhere, won't throw IndexError)
        except IndexError:

            mean_percent = "0.0"

            #because we got an index error, we know that the search yielded no results. so let's type 0.0 as percent
            out.write(str(search_terms) + "\t" + str(actual_pub_year) + "\t" + str(mean_percent) + "\n")

        time.sleep(6)

#create TK frame
root = tk.Tk()
canvas = tk.Canvas(root, width=157, height=100)
canvas.pack()

#create label for tk
ngram_label = tk.Button(root, text = "Google N-Gram API", command = "", anchor = 'w', width = 14, activebackground = "#33B5E5")
ngram_label_canvas = canvas.create_window(20, 20, anchor='nw', width = 119, window=ngram_label)

#create a button that allows users to find a file for analysis
file_label = tk.Button(root, text = "Input file", command = selectfile, anchor = 'w', width = 7, activebackground = "#33B5E5")
file_label_canvas = canvas.create_window(20, 60, anchor='nw', window=file_label)

#create a start button that allows users to submit selected parameters and run the "startviewing" processes
start_label = tk.Button(root, text = "Go!", command = query_n_grams, anchor = 'w', width = 3, activebackground = "#33B5E5")
start_label_canvas = canvas.create_window(107, 60, anchor='nw', window=start_label)

root.mainloop()

Does anyone know why this script would generate the error message I posted above? I would be very grateful for any advice others can offer on this question.

A: I was facing the same issue... the problem was in new Firefox Update(from 46 to 47) this was a big mistake :)
anyway i did fix the issue this way ..
Download&Install Firefox 46: Downgrade from 47.0 to 46.0
you can do it from this link :
If you have 32Bit : Click here | or if you have 64bit: Click here

Note Before installing the old Version you need to delete your current firefox .. :) Watch out its really important

That's it pretty mush you're now ready :)
if you have any issue with the urls you can find your way using this link
Have fun.

A: I invoked Firefox 23 instead of 26, and that resolved the issue.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from Tkinter import *
import Tkinter as tk
from tkFileDialog import askopenfilename
import time
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

#out
out = open("n_grams_outfile.txt", "w")
out.write("search string" + "\t" + "pub year" + "\t" + "frequency" + "\n")

#create a function that will return the filepath for a file provided by the user
user_defined_filepath = {}
def selectfile():
    user_defined_filepath['filename'] = askopenfilename(filetypes=[("Text","*.txt")]) # user_defined_filepath['filename'] may now be accessed in the global scope.

#create function we'll call when start button is pressed
def query_n_grams(event = "<Button>"):

    #create binary switch we'll use to only start new browser in first pass. Set default to true
    first_pass = 1

    #identify the input file
    inputfile = user_defined_filepath['filename']
    readinputfile = open(inputfile).read()
    stringinputfile = str(readinputfile)

    #assume input file = tsv. Left hand column = string of len <= 6; right hand column = pub year of text
    split_by_row = stringinputfile.split("\n")
    for row in split_by_row:

        #because the program will yelp if it reaches the end of the input file and then tries to split an empty line on "\t", wrap call in try/except
        try:
            search_terms = row.split("\t")[0]
            actual_pub_year = row.split("\t")[1]
        except IndexError:
            pass

        pub_year_minus_five = int(actual_pub_year) - 5
        pub_year_plus_five = int(actual_pub_year) + 5

        #you now have terms and pub yaer. Fire up webdriver and ride, cowboy
        if first_pass == 1:

            binary = FirefoxBinary('C:\Text\Professional\Digital Humanities\Programming Languages\Python\Query Literature Online\LION 3.0\Firefox Versions\Firefox23\FirefoxPortable.exe')
            driver = webdriver.Firefox(firefox_binary=binary)

            first_pass = 0

        #otherwise, use extant driver
        driver.implicitly_wait(10)
        driver.get("https://books.google.com/ngrams")
        driver.refresh()
        driver.implicitly_wait(10)

        #send keys
        driver.implicitly_wait(10)
        keyword = driver.find_element_by_class_name("query")
        driver.implicitly_wait(10)
        keyword.clear()
        driver.implicitly_wait(10)
        keyword.send_keys(str(search_terms))
        driver.implicitly_wait(10)

        #find start year
        driver.implicitly_wait(10)
        start_year = driver.find_element_by_name("year_start")
        driver.implicitly_wait(10)
        start_year.clear()
        driver.implicitly_wait(10)
        start_year.send_keys(str(pub_year_minus_five))
        driver.implicitly_wait(10)

        #find end year
        driver.implicitly_wait(10)
        end_year = driver.find_element_by_name("year_end")
        driver.implicitly_wait(10)
        end_year.clear()
        driver.implicitly_wait(10)
        end_year.send_keys(pub_year_plus_five)
        driver.implicitly_wait(10)

        #click enter
        driver.implicitly_wait(10)
        submit_button = driver.find_element_by_class_name("kd_submit")
        driver.implicitly_wait(10)
        submit_button.click()
        driver.implicitly_wait(10)

        #grab html
        driver.implicitly_wait(10)
        html = driver.page_source
        driver.implicitly_wait(10)

        #if you run a search that yields no hits, can't split the html, so use try/except
        try:

            #we want the list object that comes right after timeseries and before the comma
            desired_percent_figures = html.split('"timeseries": [')[1].split("]")[0]

            #now desired_percent_figures contains comma-separated list of percents (which we still need to convert out of mathematical notation). Convert out of mathematical notation (with e)
            percents_as_list = desired_percent_figures.split(",")

            #convert to ints
            percent_list_as_ints = [float(i) for i in percents_as_list]

            #take your list and find mean
            mean_percent = sum(percent_list_as_ints) / float(len(percent_list_as_ints))

            out.write(str(search_terms) + "\t" + str(actual_pub_year) + "\t" + str(mean_percent) + "\n")

        #you'll get IndexError if you run a query like "Hello Garrett" for which there are no entries in the database at all. (Other queries, like 'animal oeconomy' for year 1700, yields result 0, but because search string is in database elsewhere, won't throw IndexError)
        except IndexError:

            mean_percent = "0.0"

            #because we got an index error, we know that the search yielded no results. so let's type 0.0 as percent
            out.write(str(search_terms) + "\t" + str(actual_pub_year) + "\t" + str(mean_percent) + "\n")

#create TK frame
root = tk.Tk()
canvas = tk.Canvas(root, width=157, height=100)
canvas.pack()

#create label for tk
ngram_label = tk.Button(root, text = "Google N-Gram API", command = "", anchor = 'w', width = 14, activebackground = "#33B5E5")
ngram_label_canvas = canvas.create_window(20, 20, anchor='nw', width = 119, window=ngram_label)

#create a button that allows users to find a file for analysis
file_label = tk.Button(root, text = "Input file", command = selectfile, anchor = 'w', width = 7, activebackground = "#33B5E5")
file_label_canvas = canvas.create_window(20, 60, anchor='nw', window=file_label)

#create a start button that allows users to submit selected parameters and run the "startviewing" processes
start_label = tk.Button(root, text = "Go!", command = query_n_grams, anchor = 'w', width = 3, activebackground = "#33B5E5")
start_label_canvas = canvas.create_window(107, 60, anchor='nw', window=start_label)

root.mainloop()


text:
Q: unable to open MS-Access ADO connection I am trying to open an Access Database connection using ADODB.Connection object through excel VBA but I am receiving an error when opening the connection.
The error is "Object variable or With block variable not set"
I am using excel 2010, my database is in Access 2010 and I have also added the reference to "Microsoft ActiveX Data Objects 2.8 library"
Any help would be highly appreciated
Dim con As ADODB.Connection

con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\vk10084\Desktop\Jobs\PnL\MyDatabaseFiles\Database1.accdb;Persist Security Info=False;"

Edit:
Below is the whole code
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sconString As String
Dim sdbpath As String
Dim sCommand As String

sdbpath = ThisWorkbook.Path & "\Database1.accdb"
sCommand = "INSERT INTO Employees VALUES('Vikas Kumar', '263763')"

Dim cmd As New ADODB.Command

con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\vk10084\Desktop\Jobs\PnL\POC on Access\Database1.accdb;Persist Security Info=False;"

cmd.ActiveConnection = con

cmd.CommandText = sCommand
cmd.Execute

con.Close

A: I just added a New to the connection and slightly reordered the code to make it more readable. Does this work?
Dim Con As New ADODB.Connection
With Con
    .ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\vk10084\Desktop\Jobs\PnL\POC on Access\Database1.accdb;Persist Security Info=False;"
    .Open
End With

Dim Cmd As New ADODB.Command
With Cmd
    .ActiveConnection = Con
    .CommandType = adCmdText
    .CommandText = sCommand
    .Execute
End With

redpajama_set_name: RedPajamaStackExchange


text:
Q: Instruction on how to use POST PUT GET DELETE, Couchbase Lite on Cordova I am trying to implement Couchbase Lite on my Cordova Project and need some help.
How do I Test if the values submitted are correct, and how should I read the values?
I need some proper documentation on how to use the
config.db.post
config.db.get
config.db.delete
config.db.put

but sadly I can't find any.
For example when I do the Following, I get 2 alerts in the following exact order:
Alerts:
null

object, object // how can I read this?

For Code:
config.db.post(composition, function(err, ok) {
    alert(err);
    alert(ok);
}

does this mean the JSON File was created? I can't seem to find any JSON Files on my Phone..

A: Based on the alert values, there is no error (first alerted value is null) & the returned data is an object. You can alert "through" the object like this
config.db.post(composition, function(err, ok) {
    for (var i in ok) {
        //if (ok.hasOwnProperty(i)) {
            alert(ok[i]);
        //}
    }
}

Also if you take out the comments, you can see only the attributes that are actually set to the result object instead of seeing all of JavaScript functions that exist for every object in JS. Also, if you can use debugger, it is much easier to see what the ok variable contains. GapDebug is perfect choice for debugging PhoneGap applications, but may require some effort to get up and running.


text:
Q: Efficient Delete in Hibernate I know that the following code will delete the record with id = 5 from database:
 Query query = session.createQuery("delete from Class where id = 5");
 query.executeUpdate();

But before i delete it, need to save this record's data in a variable.
So I want to select id = 5, and after some code, I delete it.
It's not efficient if i use two distinct query for them. Because in this way we search database for this item two times.
query = session.createQuery("from Class where id = 5");
//somecode
query = session.createQuery("delete Class where id = 5");
...

So i need a more efficient way to do this, and do it better.

A: No need to create query to delete a record.
query = session.createQuery("from Class where id = 5");
List list=query.list();
if(list.size()!=0)
 {
   ClassName obj = (ClassName)list.get(0);
   session.delete(obj);
  }

A: Hibernate has a Session.delete() method. Use it if you already have a reference to the entity to remove. No need for a query.
This would also apply the potential cascades configured on associations, which a delete query does not.


text:
Q: OneToMany and ManyToOne Report generate through hibernate I have two class
@Entity
@Table(name="AFFILIATES")
class Affiliate implements Serializable {

    @Id
    @Column(name= "affiliate_id")
    private String affiliateId;

    @OneToMany(mappedBy="affiliate", fetch=FetchType.LAZY)
    private Set<AffiliateInvoice> affiliateInvoice;

    @OneToMany(mappedBy="affiliate", fetch=FetchType.LAZY)
    private Set<Payments> payments;

    @Column(name="customer_id")
    private Integer customerId;

    public String getAffiliateId() {
        return affiliateId;
    }

    public void setAffiliateId(String affiliateId) {
        this.affiliateId = affiliateId;
    }

    public Set<AffiliateInvoice> getAffiliateInvoice() {
        return affiliateInvoice;
    }

    public void setAffiliateInvoice(Set<AffiliateInvoice> affiliateInvoice) {
        this.affiliateInvoice = affiliateInvoice;
    }

    public Set<Payments> getPayments() {
        return payments;
    }

    public void setPayments(Set<Payments> payments) {
        this.payments = payments;
    }

    public Integer getCustomerId() {
        return customerId;
    }

    public void setCustomerId(Integer customerId) {
        this.customerId = customerId;
    }

}

@Entity
@Table(name="AFFILIATE_INVOICE")
class AffiliateInvoice implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="invoice_id")
    private Integer invoiceId;

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name="affiliate_id")
    private Affiliate affiliate;

    @OneToOne
    @JoinColumn(name="payment_id")
    private Payments payments;

    public Integer getInvoiceId() {
        return invoiceId;
    }

    public void setInvoiceId(Integer invoiceId) {
        this.invoiceId = invoiceId;
    }

    public Affiliate getAffiliate() {
        return affiliate;
    }

    public void setAffiliate(Affiliate affiliate) {
        this.affiliate = affiliate;
    }

    public Payments getPayments() {
        return payments;
    }

    public void setPayments(Payments payments) {
        this.payments = payments;
    }

}

@Entity
@Table(name= "PAYMENTS")
class Payments implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="payment_id")
    private Integer paymentId;

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name="merchant_id", referencedColumnName="customer_id")
    private Affiliate affiliate;

    @OneToOne
    @JoinColumn(name="payment_id", nullable=true)
    private AffiliateInvoice affiliateInvoice;

    @Column(name="amount")
    private Double amount;

    public Integer getPaymentId() {
        return paymentId;
    }

    public void setPaymentId(Integer paymentId) {
        this.paymentId = paymentId;
    }

    public Affiliate getAffiliate() {
        return affiliate;
    }

    public void setAffiliate(Affiliate affiliate) {
        this.affiliate = affiliate;
    }

    public Double getAmount() {
        return amount;
    }

    public void setAmount(Double amount) {
        this.amount = amount;
    }

    public AffiliateInvoice getAffiliateInvoice() {
        return affiliateInvoice;
    }

    public void setAffiliateInvoice(AffiliateInvoice affiliateInvoice) {
        this.affiliateInvoice = affiliateInvoice;
    }
}

Now I there may be chance that affiliate may or may not have the invoices.
Now Affiliate has Payments, but some affiliate may yet not generate the invoice.
so How can I retrieve all the details that how many affiliate has generate the invoice and how many are pending?
I did some thing like as follows.
Session s = connection.getSession();
            String hql = "from Affiliate as a " +
                    " inner join fetch a.payments as mp " +
                    " inner join fetch a.affiliateInvoice as ai " +
                    " where ai.invoiceId = 270";
                    Query q = s.createQuery(hql);

                    AffiliateInvoice ai = (AffiliateInvoice) q.uniqueResult();

                    System.out.println(ai);

But it is not giving the resule
I want something like follow.

AffiliateId    PaymentId   isInvoiceGenerated
aaa              111             Y
bbb              222             N
ccc              333             N
ddd              444             Y

How can i Get such Result ?
If I do something like as follow
Session s = connection.getSession();
            String hql = "from com.infibeam.test.oneToMany.Affiliate as a " +
                    " inner join fetch a.payments as mp " +
                    " left join fetch a.affiliateInvoice as ai "

then it gives me
java.lang.ClassCastException: Affiliate cannot be cast to java.lang.String
at org.hibernate.type.StringType.toString(StringType.java:44)
    at org.hibernate.type.NullableType.toLoggableString(NullableType.java:168)
    at org.hibernate.pretty.MessageHelper.collectionInfoString(MessageHelper.java:284)


text:
Q: GeoServer ImageMosaic OpenLayers strange layer duplication at Scale = 1 : 34K I have made a simple ImageMosaic out of 2x GeoTIFF (+ .ovr +.msk for each).
In the map preview at Scale = 1 : 34K, the TIFFs are duplicating as per the image.
This only happens at this zoom level. Does not occur at any other zoom level.
How can I fix this / prevent this from happening?
I cannot share the files as they are over 25mb


text:
Q: Use evaluate option of \foreach to display integers not floats in TikZ \documentclass{article}
\usepackage{tikz}
\begin{document}

 \begin{tikzpicture}
      \draw[->] (-2,0) -- (2,0) node[right] {$x$};
      \draw[->] (0,-2) -- (0,2) node[above] {$y$};
      \foreach \x in {-3,...,3}
               \draw (\x/2,1pt) -- (\x/2,-2pt);
      \foreach \y in {-3,...,3}
               \draw (1pt,\y/2) -- (-2pt,\y/2);
      \draw[thick,db] (0,0) circle (1.5cm);
      \foreach \x [evaluate=\x as \r using \x/1.5] in {-1.5, 1.5}
               \draw (\x cm,1pt) -- (\x cm,-1pt)
                      node[anchor=north, fill=white] {\tiny $\r$};

\end{tikzpicture}%
\end{document}

The result is

I want it to display -1  and 1 instead of -1.0 or 1.0. How can it be done?

A: Just for completeness. In this case there is no need to evaluate anything since coordinates get parsed automatically, so you could simply do
\foreach \X in {-1, 1}
               \draw (\X*1.5cm,1pt) -- (\X*1.5cm,-1pt)
                      node[anchor=north, fill=white,font=\tiny] {$\X$};

Please note also that \x may not be a good loop variable if you ever intend also to make use of calc.
\documentclass{article}
\usepackage{tikz}
\begin{document}

 \begin{tikzpicture}
      \draw[->] (-2,0) -- (2,0) node[right] {$x$};
      \draw[->] (0,-2) -- (0,2) node[above] {$y$};
      \foreach \X in {-3,...,3}
               \draw (\X/2,1pt) -- (\X/2,-2pt);
      \foreach \y in {-3,...,3}
               \draw (1pt,\y/2) -- (-2pt,\y/2);
      \draw[thick,blue!80!black] (0,0) circle (1.5cm);
      \foreach \X in {-1, 1}
               \draw (\X*1.5cm,1pt) -- (\X*1.5cm,-1pt)
                      node[anchor=north, fill=white,font=\tiny] {$\X$};

\end{tikzpicture}%
\end{document}

A: To get integer results, use the TikZ function int(...) when computing \r for the node text:
\documentclass{article}
\usepackage{tikz}
\begin{document}

 \begin{tikzpicture}
      \draw[->] (-2,0) -- (2,0) node[right] {$x$};
      \draw[->] (0,-2) -- (0,2) node[above] {$y$};
      \foreach \x in {-3,...,3}
               \draw (\x/2,1pt) -- (\x/2,-2pt);
      \foreach \y in {-3,...,3}
               \draw (1pt,\y/2) -- (-2pt,\y/2);
      \draw[thick,blue] (0,0) circle (1.5cm);
      \foreach \x [evaluate=\x as \r using int(\x/1.5)] in {-1.5, 1.5}
               \draw (\x cm,1pt) -- (\x cm,-1pt)
                      node[anchor=north, fill=white] {\tiny $\r$};

\end{tikzpicture}%
\end{document}


text:
Q: TextInput Component suddenly not working in production Laravel 10 Reactjs I got weird problem with TextInput Component from laravel reactjs.
I got the component from laravel breeze reactjs.
The problem is I cant type anything on the <TextInput>, but if i change it to <input> tag it works fine. It was working fine till today suddenly <TextInput> stop working, I didnt change anything because it comes with laravel and it works fine in local development exactly same code except I didnt do npm run build on local.
I already did npm run build and restart ssr server, no luck.
Here is one of the TextInput from Login.jsx
> <TextInput
>    id="email"
>    type="email"
>    name="email"
>    value={data.email}
>    className="mt-1 block w-full"
>    autoComplete="username"
>    isFocused={true}
>    handleChange={onHandleChange}
>
> />

If I change it to this input, it works
<input
    type="email"
    name="email"
    id="email"
    value={data.email}
    className={
    'border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm mt-1 block w-full'
    }
    autoComplete="username"
    required
    onChange={onHandleChange}
/>

It seems the component works again by making any changes to the component files, TextInput.jsx and CheckBox.jsx (was broken too). then run npm run build again.
Any idea what went wrong?


text: Q: keycloak - add success flow execution / identity providers into access token I want to add the flow executions and the identity provider used to authenticate users into token claims, is there anyway to achieve that wihout modifying keycloak code ?


text:
Q: Regular expression pattern. Get fields from string I can not write a regular expression pattern
string:
25,4.6,4%,32,"text1","text2, text3","text4,,t"

result array:
25 |
4.6 |
4% |
32 |
"text1" |
"text2, text3" |
"text4,,t" |

A: I would not use regex (or String.Split) to parse CSV but an available csv-parser. The TextFieldParser is the only parser which is already built-in .NET. You can use it also in C#:
string csv = "25,4.6,4%,32,\"text1\",\"text2, text3\",\"text4,,t\"";
var reader = new StringReader(csv);

List<string[]> allLineFields = new List<string[]>();
using (var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(reader))
{
    parser.Delimiters = new string[] { "," };
    parser.TrimWhiteSpace = true;
    parser.HasFieldsEnclosedInQuotes = true; // <--- !!!
    string[] fields;
    while ((fields = parser.ReadFields()) != null)
    {
        allLineFields.Add(fields);
    }
}
foreach (string[] arr in allLineFields)
    Console.WriteLine(string.Join("|", arr));

Output: 25|4.6|4%|32|text1|text2, text3|text4,,t
Of course there are other available parsers like this: A Fast CSV Reader

A: RegEx is not the way to go with this because it isn't designed to handle quoted strings well (or balancing paranthesis).
However, it looks like your data is CSV. If this is true, .NET has a TextFieldParser that parses CSV (including quotes).
You will have to add a reference to Microsoft.VisualBasic in your project to use this.
Look at this SO question for an example using C# and quoted values.


text:
Q: Sum array values I'm making a shipping service app to Shopify and my callback URL have this JSON post using json_decode to make an array. The value I want to sum is grams and putting into variable and then compare with the value of another variable using if ($weight <= $maxweight).
{
   "rate": {
       "items": [
           {
               "name": "My Product 3",
               "sku": null,
               "quantity": 1,
               "grams": 1000,
               "price": 2000,
               "vendor": "TestVendor",
               "requires_shipping": true,
               "taxable": true,
               "fulfillment_service": "manual"
           },
           {
               "name": "My Product 1",
               "sku": null,
               "quantity": 1,
               "grams": 500,
               "price": 1000,
               "vendor": "TestVendor",
               "requires_shipping": true,
               "taxable": true,
               "fulfillment_service": "manual"
           },
           {
               "name": "My Product 2",
               "sku": null,
               "quantity": 1,
               "grams": 2000,
               "price": 3000,
               "vendor": "TestVendor",
               "requires_shipping": true,
               "taxable": true,
               "fulfillment_service": "manual"
           }
       ],
       "currency": "CAD"
   }
}

A: You just need a simple foreach then under the loop, just add the value. Consider this example:
$total_weight = 0;
$json_string = '{ "rate":{ "items":[ { "name":"My Product 3", "sku":null, "quantity":1, "grams":1000, "price":2000, "vendor":"TestVendor", "requires_shipping":true, "taxable":true, "fulfillment_service":"manual" }, { "name":"My Product 1", "sku":null, "quantity":1, "grams":500, "price":1000, "vendor":"TestVendor", "requires_shipping":true, "taxable":true, "fulfillment_service":"manual" }, { "name":"My Product 2", "sku":null, "quantity":1, "grams":2000, "price":3000, "vendor":"TestVendor", "requires_shipping":true, "taxable":true, "fulfillment_service":"manual" } ], "currency":"CAD" }}';
$json_data = json_decode($json_string, true);

$max_weight = 10000;
foreach($json_data['rate']['items'] as $key => $value)  {
    $total_weight += $value['grams'];
}

echo $total_weight; // 3500
// then just compare whatever $max_weight value has to $total_weight
// rest of your desired code

A: First, your example JSON didn't have commas between items, so I added that.
But instead of a foreach loop, you can use array_map and array_sum to quickly get a sum of items. The magic is in these three simple lines at the bottom of the example code; placing here for easy review:
// Convert the raw json to an array with json_encode & the 'true' option.
$json_array = json_decode($raw_json, true);

// Now use array_map to return and array of just the value of grams.
$grams_array = array_map(function ($item) { return intval($item['grams']); }, $json_array['rate']['items'] );

// Echo the sum of the grams array with by using array sum.
echo array_sum($grams_array);

And here is the full working example with the JSON as you presented it.
// Set the raw JSON.
$raw_json = <<<EOT
{
   "rate": {
       "items": [
           {
               "name": "My Product 3",
               "sku": null,
               "quantity": 1,
               "grams": 1000,
               "price": 2000,
               "vendor": "TestVendor",
               "requires_shipping": true,
               "taxable": true,
               "fulfillment_service": "manual"
           },
           {
               "name": "My Product 1",
               "sku": null,
               "quantity": 1,
               "grams": 500,
               "price": 1000,
               "vendor": "TestVendor",
               "requires_shipping": true,
               "taxable": true,
               "fulfillment_service": "manual"
           },
           {
               "name": "My Product 2",
               "sku": null,
               "quantity": 1,
               "grams": 2000,
               "price": 3000,
               "vendor": "TestVendor",
               "requires_shipping": true,
               "taxable": true,
               "fulfillment_service": "manual"
           }
       ],
       "currency": "CAD"
   }
}
EOT;

// Convert the raw json to an array with json_encode & the 'true' option.
$json_array = json_decode($raw_json, true);

// Now use array_map to return and array of just the value of grams.
$grams_array = array_map(function ($item) { return intval($item['grams']); }, $json_array['rate']['items'] );

// Echo the sum of the grams array with by using array sum.
echo array_sum($grams_array);

A: *

*Isolate the desired column of data with array_column().

*Call array_sum() on that returned array.

Code: (Demo)
var_export(
    array_sum(
        array_column(
            $array['rate']['items'],
            'grams'
        )
    )
);

Output:
3500


text:
Q: Sorting a multi-dimensional, non associative array in PHP So i've been looking throughout Stack Overflow looking for a solution for this problem. I have a multidimensional, non associative array in php and i want to sort it by one of its values, while maintaining the rest of the values within the same child array.
In the next example i want to sort the array by $fruits[This value][0].
This is what i have:
$fruits = array
(
array(2, apple),
array(1, orange),
array(4, banana),
array(3, kiwi),
);

This is what im looking for:
$fruits = array
(
array(1, orange),
array(2, apple),
array(3, kiwi),
array(4, banana),
);

This is what i dont want:
$fruits = array
(
array(1, apple),
array(2, orange),
array(3, banana),
array(4, kiwi),
);

A: You can use array_multisort to sort the array by column 0
array_multisort($fruits, array_column($fruits, 0));

Example: http://sandbox.onlinephpfunctions.com/code/4b8bef53eeb9bf7b1cb93ab93e27de6f7ac60174


text:
Q: MessageBox on the top from all threads When the application starts, splash screen is shown from another thread.
But, in case an error during start up - message box will be shown. The problem is: messagebox is shown under the splash. I have used IWin32Window owner property, even tried to use MessageBoxOptions.DefaultDesktopOnly property, but id did not help.
How can I manage this situation ?
PS:
Tried to create invisible window, set TopMost - and show MessageBox. Did not work.

A: I created a similar situation using multi-threading and used this code to keep the MessageBox on top of the window. Basically this code makes the message box top most.
MessageBox.Show(this,
    "Your text",
    "Settings Needed",
    MessageBoxButtons.YesNo,
    MessageBoxIcon.Question,
    MessageBoxDefaultButton.Button1,
    (MessageBoxOptions)0x40000); // this is MB_TOPMOST flag


text:
Q: Sum of digits in C++ program asked is sum of digits :
Input data are in the following format:
first line contains N - the number of values to process;
and then N lines will follow describing the values for which sum of digits should be calculated by 3 integers A B C;
for each case you need to multiply A by B and add C (i.e. A * B + C) - then calculate sum of digits of the result.
Answer should have N results, also separated by spaces
MY CODE IN C++ :
#include <iostream>

using namespace std;

int main ()
{
    int n, a, b, c, t, sum = 0;
    cin >> n;

    for (int i = 0; i < n; i++)
    {
        cin >> a >> b >> c;
        t = a * b + c;

        while (t % 10 != 0)
        {
            sum = sum + t % 10;
            t = t / 10;
        }

        while (t % 10 == 0)
        {
            sum = sum;
            t = t / 10;
        }
    }

    cout << " ";
    cout << sum;
    cout << " ";

    return 0;
}

I'm having hard time correcting my code.
Any help is appreciated.
My assumption is there should be a better way to code this other than using 2 while loops.
PS : I checked other topics just want somebody that could help with my code thank you.

A: You don't need second while loop, and first one should be corrected to while (t != 0). After that your program for computing sum works correctly.
Try it online!
#include <iostream>

using namespace std;

int main ()
{
    int n, a, b, c, t, sum = 0;
    cin >> n;

    for (int i = 0; i < n; i++)
    {
        cin >> a >> b >> c;
        t = a * b + c;

        while (t != 0)
        {
            sum = sum + t % 10;
            t = t / 10;
        }
    }

    cout << " ";
    cout << sum;
    cout << " ";

    return 0;
}

Input:
1
123 456 789

Output:
33

Just noticed that you need N separate outputs instead of single sum (like you did), so then your program becomes like this:
Try it online!
#include <iostream>

using namespace std;

int main ()
{
    int n, a, b, c, t, sum = 0;
    cin >> n;

    for (int i = 0; i < n; i++)
    {
        cin >> a >> b >> c;
        t = a * b + c;

        sum = 0;

        while (t != 0)
        {
            sum = sum + t % 10;
            t = t / 10;
        }

        cout << sum << " ";
    }

    return 0;
}

Input:
2
123 456 789
321 654 987

Output:
33 15


text:
Q: Push Notifications problems iOS TestFlight I'm trying to get a few friends of mine to test my app on TestFlight. This all is going fine except for the Push notifications. I do not seem to be able to extract their Push tokens. I've double checked and they've granted the app permission to take the Push token.

In my opinion this all looks fine:

Apple does however send the following e-mail after I upload the app to TestFlight:
Missing Push Notification Entitlement - Your app includes an API for Apple's Push Notification service, but the aps-environment entitlement is missing from the app's signature. To resolve this, make sure your App ID is enabled for push notification in the Provisioning Portal. Then, sign your app with a distribution provisioning profile that includes the aps-environment entitlement. This will create the correct signature, and you can resubmit your app. See "Provisioning and Development" in the Local and Push Notification Programming Guide for more information. If your app does not use the Apple Push Notification service, no action is required. You may remove the API from future submissions to stop this warning. If you use a third-party framework, you may need to contact the developer for information on removing the API.

I am able to extract my own device's Push token when downloading a fresh copy from TestFlight.

I've no idea what's going on and would really like to fix this. Can anyone help me out?

In case it helps. This is my code:
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

    for i in 0..<deviceToken.length {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }

    Constant.pushToken = tokenString

    if (KeychainWrapper.hasValueForKey("user_id")){
        let user = User()
        user.id = Int(KeychainWrapper.stringForKey("user_id")!)!
        ApiManager.sharedInstance.putPushToken(user){ (result, error) -> Void in
            if error != nil {
                //error
            } else {
                //success
            }
        }
    }
}

A: You need to add an entitlements file for this. In your case, somehow its not attached with your project when you have enabled push notifications from Capabilities. Please Turn off and turn on Push Notifications option. You may get the entitlements file added automatically in your project.

Update : Is server using the sandbox url or the disribution url ?

A: Make sure you are archiving with distribution profile for TestFlight beta testing.

A: *

*Check the service which you have been using for Push notification.

*Check if you have registered for the Notification service for Badge|Sound|Alert.

*Add a debugger at receivedRemoteNotification and check if you are being able to get the notification.


text:
Q: Custom Condition Formatting, how to work with a String amount based condition in a Cell I want to format cells with a custom function.
The cells have the content like so (without the ") :
Cell_1: "String1 String2 String3"
Cell_2: ""
Cell_3: "String1 String2 String3 String4 String5 String6"

if there is at least like 5 Strings in it, separated with a space it should be a true statement.
I tried to use a custom script like so, because im calling a function in this cell anyway, before returning the value i could set the format too:
var self = SpreadsheetApp.getActiveSheet().getActiveCell();
self.setFontWeight("normal");
if(returnValue.length>=5){
  self.setFontWeight("bold");
}
return returnValue.sort().join(" ");

But i got a "You do not have permission to call setFontWeight" Exeption. After a little research i found that cunstom scripts are not allowed to cange format at all. Fine ... but how can i do it with the custom formatting condition
is something like this possible?:
=If(Split(?inputRange?;" ").length>=5;True;False)

If Yes how do i get the Range in the right format and which function is needed to get the String amount?
i tried also to write a custom function for that purpose:
function customFormat(input){
if(input.length>=5)
   return true;
}
return false;

calling like so as custom condition:
=customFormat(range)

it seams like i cant use custom function there, i get no positiv result even than i return true always.
If you got some ideas how to accomplish this, i would be thankfull.

A: Assuming those three cells are in A1:A3
Apply conditional formatting to that range with the formula
=COUNTA(SPLIT(A1, " ")) >= 5


text:
Q: Two ribbon with same z, they covered each other I'm drawing map roads with THREE.Ribbon, every road has border with different color, so I use two ribbons, one is wider with the color of border, one is narrower, then I can achieve my purpose.
I also draw cap on two ends of ribbon with circles, certainly draw two circles, the smaller one covers bigger one, just like linecap in canvas2D.
I can't use THREE.Line as my alternative, because the maximum value of width of Line is 1 in my webgl.
My codes are just like this:
var circleShape = new THREE.Shape();
var circleRadius = lineWidth/2;
circleShape.moveTo( 0, circleRadius );
circleShape.quadraticCurveTo( circleRadius, circleRadius, circleRadius, 0 );
circleShape.quadraticCurveTo( circleRadius, -circleRadius, 0, -circleRadius );
circleShape.quadraticCurveTo( -circleRadius, -circleRadius, -circleRadius, 0 );
circleShape.quadraticCurveTo( -circleRadius, circleRadius, 0, circleRadius );
var circle = new THREE.ShapeGeometry( circleShape);
var material = new THREE.MeshBasicMaterial( { color: color, depthWrite: false} );
var mesh = new THREE.Mesh( circle, material );
this.parent.add( mesh );

var material = new THREE.MeshBasicMaterial( { color: widerColor, depthWrite: false} );
var widerRibbon = new THREE.Ribbon( widerGeometry, material );
this.parent.add( widerRibbon );

var material = new THREE.MeshBasicMaterial( { color: narrowerColor, depthWrite: false} );
var narrowerRibbon = new THREE.Ribbon( narrowerGeometry, material );
this.parent.add( narrowerRibbon );

My logic is the latter will cover the former. so narrower ribbon will cover wider ribbon, ribbon will cover half of circle.
My difficulty:
The consequence is they cover each other(without depthWrite:false).
I have found that THREE.MeshBasicMaterial can set depthWrite to false, I add it, then I find that narrower ribbon covered wider ribbon successfully, but what is weird is the cap on the ends of ribbon seems abnormal, when I look at the ribbon right on top, it works well, but when I look it with a angle, I find that the ribbon can't cover circle.
I don't know how to deal this issue, I just want the later drawing covers the former drawing when they all have same z coordinate.
Thanks for your guidance!

A: If you want to use "painter's algorith" (whatevr is painted last is always what you see), just turn Z off in the material(s). This is, set the "depthTest" attribute to false when declaring the material


text:
Q: How to find the Sizes of stash repositories I am trying to query my stash database to find out all repository ids',repository sizes and project names , but i am not sure which table can get me repository size .Could anyone please help ?

A: The information you have asked for is not available in the Stash database as the repositories are stored on the server in the form of binaries. Hope you are aware of the "Repository Size Details" linkbutton available inside the repository settings which will compute the size when we click on it. I presume that you have admin access to the server and database. There was a requirement to compute the sizes of the top 10 repositories in Stash as part of which I developed a shell script. However, I am only pasting the crux here and hope others can improvise on it to suit their needs.
In the Stash server run this command in your stash-home repositories path to fetch the top 10 repositories:
du -ksm /stash-home/.../.../repositories/* |  sort -n | tail -10

This will give the top 10 heaviest repositories in descending sort:
1031    /stash-home/.../.../repositories/1732
646     /stash-home/.../.../repositories/132
555     /stash-home/.../.../repositories/1221
449     /stash-home/.../.../repositories/785
324     /stash-home/.../.../repositories/234
320     /stash-home/.../.../repositories/354
292     /stash-home/.../.../repositories/282
282     /stash-home/.../.../repositories/1328
237     /stash-home/.../.../repositories/2810
221     /stash-home/.../.../repositories/263

In the above output the first column denotes the size in MB. The second column contains the repository path which also includes the repository id eg: 1732
Now that you have the repository ids, in the Stash database you can run the following query to get the associated project names and repo names:
select p.id as projectid, p.project_key, p.name projectname, r.id as repoid,
r.name as reponame from PROJECT p ,REPOSITORY r Where p.ID=r.PROJECT_ID
and r.id in (1732,132,1221,785,234,354,282,1328,2810,263)

The size displayed by the du command will give output identical to clicking on "Repository Size Details" in the front end. It will serve well if these two are linked into a shell script to generate a weekly report.
P.S. There is also a Stash Repo Size Plugin but not as flexible.


text:
Q: How to keep running through an R script on command line when there is an error I am trying to run an R script on the command line and I want it to keep running even when there is an error. Is there a flag I can add to tell R to keep running through the script even when it encounters an error?
Right now it just halts execution when there is an error.
I also don't want to use methods like "try()" to wrap around the error lines because I have way too many of them and it's not possible for me to go through thousands of lines of code to catch all the error lines. I just want R to skip through the error lines when encountering them. Is there a way to do so?
Thank you!


text:
Q: arm-none-eabi-g++: error: CreateProcess: No such file or directory I have a problem with arm-none-eabi-g++ compiler running on Windows.
When I run my makefile on Ubuntu, everything works fine.
Makefile target fails on Windows with error
arm-none-eabi-g++: error: CreateProcess: No such file or directory

I'm using MingGW on Windows. MinGW, make and G++ locations are added to Win PATH.
Compiler and make are the same versions on both OS.
Ubuntu
getconf ARG_MAX
2097152

arm-none-eabi-g++ --version
arm-none-eabi-g++ (GNU Tools for Arm Embedded Processors 7-2018-q3-update) 7.3.1 20180622 (release) [ARM/embedded-7-branch revision 261907]
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

make --version
GNU Make 4.1
Built for x86_64-pc-linux-gnu
Copyright (C) 1988-2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Windows 10 with MinGW
getconf ARG_MAX
32000

arm-none-eabi-g++ --version
arm-none-eabi-g++ (GNU Tools for Arm Embedded Processors 7-2018-q2-update) 7.3.1 20180622 (release) [ARM/embedded-7-branch revision 261907]
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

make --version
GNU Make 4.1
Built for i686-w64-mingw32
Copyright (C) 1988-2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

More information
This is how one of my makefile targets look like
$(PROJECT).o: $(PROJECT).cpp
    @echo start of $(@F)
    $(CPP) $(CC_FLAGS) @./.symbols.txt -std=gnu++11 -fno-rtti @./.includes.txt -o $@ $<
    @echo end of $(@F)

Interesting thing is, that Windows build works fine only if the size of .symbols.txt and .includes.txt combined is lower than 32k. So it might look like it depends on ARG_MAX size (which is on MINGW 32k), but it's probably not true. Because another target in the same makefile looks like
$(PROJECT).elf: $(SYS_OBJECTS)
    $(file > .sys_objects.txt, $(SYS_OBJECTS))
    $(LD) $(LD_FLAGS) -T$(LINKER_SCRIPT) $(LIBRARY_PATHS) -o $@ @./.sys_objects.txt $(LIBRARIES) $(LD_SYS_LIBS) $(LIBRARIES) $(LD_SYS_LIBS)

and it works well on Windows despite that sys_objects.txt size is about 90k.
Both $(LD) and variables $(CPP) variables are set to arm-none-eabi-g++.
Another thing I have noticed is that something on Windows adds a file like C:\Users\user\AppData\Local\Temp\ccQWU5K6.s to the end of g++ command (regardless if it fails or not). I have no clue where does this come from (maybe some MINGW support argument?).
Has anyone a clue why build fails on Windows with arguments bigger than 32k even if another target works fine with big arguments? Maybe it might be a coincidence.


text:
Q: Reading image(varBinary) from Sql Server Database using Native C++ How can i read varBinary(max) Image from sql server using native C++ code. Do you have any advice? What is the best way to do it? If possible could you please give an example?
**I tried to read image using COM(c#). It works perfect but i want to do using native c++ code. what is another way to do it.For example using ODBC or etc. I couldnt find any usefull article on internet.
Thanks in advance


text:
Q: Input NAME Tag With Quotation Marks? For an <input> html element - can quotation marks be omitted around the name, like this?
<input type="text" id="nameText" name=nameTextBox>

Or do I have to include the quotation marks, like this?
<input type="text" id="nameText" name="nameTextBox">

I am keeping in mind that when the form is processed the name value is sent along with the entered value.

A: The quotation marks are optional, but I would consider them "good practice"
EDIT: And, as deceze pointed out, conditions are met, such as no spaces, single or double quotes, or equal signs in your name (or other attribute).  I just use them, makes code easier to read, IMO.


text:
Q: Initializing constant variable based on constexpr condition How can I initialize constant variable based on constexpr condition?
I need initialization equivalent to this non-compilable code:
const int x;
if constexpr(cond)
    x = value1; // value1 may not be valid if cond is false
else
    x = value2; // value2 may not be valid if cond is true

A: constexpr int x = []{
    if constexpr (cond)
        return value1;
    else
        return value2;
}();


text:
Q: How to add inline reply button? How to append message with an inline button that will do the same action than
Right click → Reply?
Is it possible?

A: *

*Create an inline button

Pressing the button will send a callback query to your server.

*React to this CallbackQuery by calling sendMessage method with it's parameter reply_markup set to force_reply == true
Your result will look like this.


text:
Q: Authorization in Rails 4 app that has external data source I am building an app that uses Salesforce as a backend for data storage. This means I have no models in my database other than User. I can't use traditional authorization solutions for rails because they require me to access rails models.
The app I'm building requires certain permissions surrounding the user. The user has two states:
User:unactivated
User:activated
I will be triggering the change in the users' states from Salesforce.
I have views that need to be protected based on the state of the user. I'm not sure if the most scalable way to handle this is a simple state column in the user model and just have <%= current_user.state == "activated" %> in my views or if there is a better solution?
Thank you

A: You can use cancan (cancancan), there is an option which will let you make authorizations on the controller.
authorize_resource :class => false

You can read more about this on their wiki here is a start

A: A new feature of Active Record, Enum, introduced in Rails 4.1, is the simplest way to implement your requirement. You can implement a very basic form of role-based authorization, with a single role "activated" that has two states.
Create a migration:
$ rails generate migration AddRoleToUsers role:integer

The migration will look like this:
class AddRoleToUsers < ActiveRecord::Migration
  def change
    add_column :users, :role, :integer
  end
end

Add code to your User model to implement the Enum:
class User < ActiveRecord::Base
  enum role: [:activated, :unactivated]
  after_initialize :set_default_role, :if => :new_record?

  def set_default_role
    self.role ||= :unactivated
  end

end

You define the names of the roles, and if necessary, can change the names as needed (the integer values stored with each user record remain unchanged). Active Record will restrict the assignment of the attribute to a collection of predefined values, so you don't have to add any code to restrict the names of the roles to a defined set. Best of all, enums come with a set of convenience methods that allow you to directly query the role without any extra code. For an enum attribute named role, with the values activated, and unactivated, you can use these methods:
User.roles # => {"activated"=>0, "unactivated"=>1} # list all roles
user.activated! # make the user activated
user.activated? # => true # query if the user is activated
user.role # => "activated" # find out the user's role
@users = User.activated # obtain an array of all users who are activated
user.role = 'foo' # ArgumentError: 'foo' is not a valid, we can't set invalid roles

You can use the conditionals in a controller:
class UsersController < ApplicationController
  def index
    unless current_user.activated?
      redirect_to :back, :alert => "Access denied."
    end
    @users = User.all
  end
end

Or use it in a view:
<% if current_user.activated? %>

<%= link_to 'Special Reports', some_path %>

<% end %>

In general, if access control adds a lot of code to a controller, you're well-advised to use  CanCanCan or Pundit, because you can move the complex authorization logic into a central location segregated from the controllers ("skinny controllers"). However, if your needs are as simple as you describe, role-based authorization in the controller is optimal.
I've written a Rails Pundit tutorial that compares both approaches and provides greater detail on simple role-based authorization as well as role-based authorization with Pundit.


text:
Q: I accidentally remove the usb when live Can someone show me how to fix this please ?

Here some more information about kernel version and ram
Linux kali 6.0.0-kali3-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.0.7-1kali1 (2022-11-07) x86_64 GNU/Linux

total
used
free
shared
buff/cache
available

Mem
7867104
1197352
5094656
451168
1575096
5966072

Swap
0
0
0


text:
Q: Uncaught TypeError: Cannot read property 'SharedStylesHost' of undefined I'm having a really hard time updating an Angular 2 project to Angular 4. I'm following the steps in https://update.angular.io/. Things seems to work however when I run the APP I get Uncaught TypeError: Cannot read property 'SharedStylesHost' of undefined in vendor.js file.
when I run the following command npm install @angular/{animations,common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router}@^4.1.0 typescript@'>=2.1.0 <2.4.0'
I then run this command npx webpack --config webpack.config.vendor.js which builds the vendor.js file
I already tried, deleting the node_modules directory and package-lock files and then do npm install but does not work.
Here is my package.json file
  "name": "Angular2Spa",
  "version": "0.0.0",
  "scripts": {
    "test": "karma start ClientApp/test/karma.conf.js"
  },
  "dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/platform-server": "^4.0.0",
    "@angular/router": "^4.0.0",
    "@progress/kendo-angular-buttons": "^0.20.1",
    "@progress/kendo-angular-dateinputs": "^0.3.5",
    "@progress/kendo-angular-dialog": "^0.15.1",
    "@progress/kendo-angular-dropdowns": "^0.29.0",
    "@progress/kendo-angular-grid": "^0.16.2",
    "@progress/kendo-angular-inputs": "^0.18.7",
    "@progress/kendo-angular-intl": "^0.10.0",
    "@progress/kendo-angular-layout": "^0.21.5",
    "@progress/kendo-angular-popup": "^0.16.2",
    "@progress/kendo-data-query": "^0.3.6",
    "@progress/kendo-theme-default": "^2.12.11",
    "@types/node": "^6.14.6",
    "angular2-platform-node": "~2.0.11",
    "angular2-template-loader": "^0.6.2",
    "angular2-universal": "^2.1.0-rc.1",
    "angular2-universal-patch": "^0.2.1",
    "angular2-universal-polyfills": "^2.1.0-rc.1",
    "aspnet-prerendering": "^2.0.0",
    "aspnet-webpack": "^1.0.17",
    "awesome-typescript-loader": "3.0.0-beta.13 || ^3.0.0",
    "bootstrap": "^3.3.7",
    "css": "^2.2.1",
    "css-loader": "^2.1.1",
    "es6-shim": "^0.35.3",
    "event-source-polyfill": "^0.0.7",
    "expose-loader": "^0.7.1",
    "extract-text-webpack-plugin": "^2.0.0-rc",
    "file-loader": "^0.9.0",
    "html-loader": "^0.4.4",
    "isomorphic-fetch": "^2.2.1",
    "jquery": "^3.4.1",
    "json-loader": "^0.5.4",
    "preboot": "^4.5.2",
    "raw-loader": "^0.5.1",
    "rxjs": "^5.0.1",
    "style-loader": "^0.13.1",
    "to-string-loader": "^1.1.5",
    "typescript": "^2.3.4",
    "url-loader": "^1.1.2",
    "webpack": "^2.2.0",
    "webpack-hot-middleware": "^2.12.2",
    "webpack-merge": "^0.14.1",
    "zone.js": "^0.7.6"
  },
  "devDependencies": {
    "@types/chai": "^3.4.34",
    "@types/jasmine": "^2.5.37",
    "chai": "^3.5.0",
    "jasmine-core": "^2.5.2",
    "karma": "^4.1.0",
    "karma-chai": "^0.1.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-webpack": "^3.0.5"
  }
}

tsconfig.json file
  "compilerOptions": {
    "moduleResolution": "node",
    "target": "es5",
    "sourceMap": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipDefaultLibCheck": true,
    "skipLibCheck": true,
    "lib": [ "es6", "dom" ],
    "types": [ "node" ]
  },
  "exclude": [ "bin", "node_modules" ],
  "atom": { "rewriteTsconfig": false }
}

webpack.config.js file
const webpack = require('webpack');
const merge = require('webpack-merge');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = true; //!(env && env.prod);
    devtool: 'cheap-module-source-map';
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: [ '.js', '.ts' ] },
        output: {
            filename: '[name].js',
            publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /\.ts$/, include: /ClientApp/, use: ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: ['to-string-loader', 'css-loader'] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [new CheckerPlugin(), new webpack.ContextReplacementPlugin(
            /angular(\\|\/)core(\\|\/)@angular/,
            path.resolve(__dirname, '/dist/')
        )]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot-client.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                //filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
            // Plugins that apply in production builds only
            new webpack.optimize.UglifyJsPlugin()
        ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot-server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ],
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};

and my webpack.config.vendor.js file
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const merge = require('webpack-merge');

module.exports = (env) => {
    const extractCSS = new ExtractTextPlugin('vendor.css');
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        resolve: { extensions: [ '.js' ] },
        module: {
            rules: [
                { test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' }
            ]
        },
        entry: {
            vendor: [
                '@angular/common',
                '@angular/compiler',
                '@angular/core',
                '@angular/http',
                '@angular/platform-browser',
                '@angular/platform-browser-dynamic',
                '@angular/router',
                '@angular/platform-server',
                'angular2-universal',
                'angular2-universal-polyfills',
                'bootstrap',
                'bootstrap/dist/css/bootstrap.css',
                'es6-shim',
                'es6-promise',
                'event-source-polyfill',
                'jquery',
                'zone.js',
                '@progress/kendo-theme-default/dist/all.css'
            ]
        },
        output: {
            publicPath: '/dist/',
            filename: '[name].js',
            library: '[name]_[hash]'
        },
        plugins: [
            new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
            new webpack.ContextReplacementPlugin(/\@angular\b.*\b(bundles|linker)/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/11580
            new webpack.IgnorePlugin(/^vertx$/) // Workaround for https://github.com/stefanpenner/es6-promise/issues/100
        ]
    };

    const clientBundleConfig = merge(sharedConfig, {
        output: { path: path.join(__dirname, 'wwwroot', 'dist') },
        module: {
            rules: [
                { test: /\.css(\?|$)/, use: extractCSS.extract({ use: 'css-loader' }) }
                ]
        },
        plugins: [
            extractCSS,
            new webpack.DllPlugin({
                path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
                name: '[name]_[hash]'
            })
        ].concat(isDevBuild ? [] : [
            new webpack.optimize.UglifyJsPlugin()
        ])
    });

    const serverBundleConfig = merge(sharedConfig, {
        target: 'node',
        resolve: { mainFields: ['main'] },
        output: {
            path: path.join(__dirname, 'ClientApp', 'dist'),
            libraryTarget: 'commonjs2',
        },
        module: {
            rules: [{ test: /\.css(\?|$)/, use: ['to-string-loader', 'css-loader'] }],

        },
        entry: { vendor: ['aspnet-prerendering'] },
        plugins: [
            new webpack.DllPlugin({
                path: path.join(__dirname, 'ClientApp', 'dist', '[name]-manifest.json'),
                name: '[name]_[hash]'
            })
        ]
    });

    return [clientBundleConfig, serverBundleConfig];
}


text:
Q: Redirecting stdin throws ambigous redirect error I m trying to read in data either from a file or from the user's input to process it in a bash shell script. I m very new to it and I have this code working so far when the script accepts a file as an argument. When i try to create a new file that I can read the user's inputs and process it it throws an error : $datafilepath ambiguous redirect. I feel I m very close to it but I might be missing some good syntax. Can somebody push me in a right direction? Thanks!
#!/bin/bash
if [ "$#"  = "1" ]
then
    cat >>"$datafilepath"
elif  [ "$#" = "2" ]
then
    datafilepath=$2
fi

echo Average Median
while read myLine
do
    sum=0
    med=0
    for word in $myLine
        do
            sum=`expr $sum + $word`
            echo -e $word >> medfile
        done

sort < medfile >sorted
cat sorted | tr '\n' '\t' > rowfile
printf "%.0f\t%.0f\n" $(echo "scale=2; $sum/5" | bc ) $(cut -d' ' -f3 rowfile)
rm -f medfile
rm -f sorted
rm -f rowfile
done <$datafilepath

A: #!/bin/bash
if [ "$#"  = "1" ]
then
    cat >>"$datafilepath"
elif  [ "$#" = "2" ]
then
    datafilepath=$2
fi

$datafilepath first appears in line #4, but it hasn't been initialized, so it's blank.  The shell '>>' won't append unless there is a filename.  There needs to be a line before that that sets $datafilepath to a default filename.
Line #2: the '1' should be a '0'.
Line #5: the '2' should be a '1'
Line #7: the '$2' should be a '$1'
This block has a needless file "sorted":
sort < medfile >sorted
cat sorted | tr '\n' '\t' > rowfile
printf "%.0f\t%.0f\n" $(echo "scale=2; $sum/5" | bc ) $(cut -d' ' -f3 rowfile)
rm -f medfile
rm -f sorted
rm -f rowfile

Suggested reduction:
sort medfile | tr '\n' '\t' > rowfile
printf "%.0f\t%.0f\n" $(echo "scale=2; $sum/5" | bc ) $(cut -d' ' -f3 rowfile)
rm -f medfile rowfile


text:
Q: Why does this assembly code segfaults upon printf I'm trying to call a function from a .s file in a .c file, compiled with gcc, in the following way:
print.s
.section .data
  str1: .string "Print anything\n"
.section .text
.globl print
print:
  movq $0, %rax
  movq $str1, %rdi
  call printf

main.c
int main(void){
  print();

  return 0;
}

and compilling/ running like this:
run.sh
as print.s -o print.o
gcc -g -c main.c -o main.o
gcc -static main.o print.o -o print
./print

For some reason, the program prints the string "Print anything\n", then quickly segfaults. Why is this happening?


text:
Q: How to Display JSON data from another site I have a page where is some of JSON data stored like this
{
    "video": {
        "user": {
            "first_name": "Curtis",
            "last_name": "Shoch"
        },
        "name": "Darwin Digital",
        "location": "Kennesaw",
        "video_type": "c",
        "created": "2018-01-16T13:11:11.326636Z"
    }
}

I need to take this data and display it on another page, o I tried to do something like this
var getJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        callback(null, xhr.response);
      } else {
        callback(status);
      }
    };
    xhr.send();
};
getJSON('https://dev.truthify.com/api/deeplink/info/bf76b0bd-5210-4c55-af23-c9689ffec536/', function(err, data) {
  if (err != null) {
    alert('Something went wrong: ' + err);
  } else {
    result.innerText = video.name;
  }

But I got a message

No Access-Control-Allow-Origin

Header is present on the requested resource because I am using source from another website and it is blocked. So is there any why to bypass this, or some other way to take this data.

A: You are getting and json and try to send it in another url in a different origin domain.
In order to access a server on different origin domain  u have to make a cors request (Cross-Origin Resource Sharing) .
This  means you have to set an "Access-Control-Allow-Origin" header  in order for your client agent to gain permission  on the server.


text:
Q: Monotouch - Phone Will Not Vibrate I cant seem to get my phone to vibrate when calling the vibrate method.
SystemSound.Vibrate.PlaySystemSound();
It looks like there is a bug filed that show the same thing but I cant believe it would not be fixed yet.
https://bugzilla.xamarin.com/show_bug.cgi?id=7983
Any ideas?  Thanks.

A: Are you calling it from the UI thread?
I learned many problems with the APIs are solved when invoking them in the UI thread by using InvokeOnMainThread


text:
Q: Sort dict and save as dict So i have dictionary like this
   mydic={
    'a':3,
    'b':1,
    'c':2,}
    def sortedby():
        sort= (sorted(mydic.items(), key = lambda t : t[0]))

        return(sort)
    print(sortedby())

I would like to get it returned not as list or int but as dictionary

A: Python's dict are not ordered. In order to maintain the order in the dict, you should use collections.OrderedDict:
from collections import OrderedDict

mydic = {
    'a':3,
    'b':1,
    'c':2,}
ordered_dict = OrderedDict(sorted(mydic.items(), key=lambda t: t[0]))
# Store dict as: OrderedDict([('a', 3), ('b', 1), ('c', 2)])
#                 Sorted        ^         ^         ^


text:
Q: CSS - why does my JS script take the full height? I try to make the Gallery.js script appear above the header. I can only make it display next to it, because by default the script takes the whole height. How can I change it?
<div className="App">
    <Gallery images={this.state.IMAGES} />
    <header className="App-header">
        <Link to="/success">
            <button variant="outlined">
                back
            </button>
        </Link>
    </header>
</div>

A: .App-header {
   min-height: 100vh;
}

.App-header has as min height the full heigth


text:
Q: scatter plot over boxplot using Matlab I've plotted a simple boxplot of a vector y (1xN) using Matlab. I used multiple grouping variables: x1, x2, x3
x1 (1xN) represents length (0.5, 1 , 2 or 3)
x2 (1xN) represents gauge (26 or 30)
x3 (1xN cell array) represents the name of the vendor.
close all; clc;

N = 1000;

% measurements values: they represent some kind of an
% electrical characteristic of a cable.
y = randn(N,1);

% each cable being measured can be of length 1m, 2m, or 3m:
x1 = randi(3,N,1);

% each cable being measured have a gauge of  1awg or 2awg:
x2 = randi(2,N,1);

% each cable can be produced by a different vendor. for instance: 'SONY' or
% 'YAMAHA'

x3 = cell(N,1);

for ii = 1:N
   if mod(ii,3) == 0
       x3{ii} = 'SONY';
   else
       x3{ii} = 'YAMAHA';
   end
end

figure(1)
boxplot(y,{x1,x2,x3});

I would like to plot a scatter plot over this boxplot in order to show the relevant values of y that create the boxplot, but I could not find a function that groups the values as the boxplot function does.
the closest thing I've found is the following function but it only accepts a single grouping variable.
any help?

A: The box of the boxplot is determined by the IQR. The data between boxes and outliers is everything in a range of 1.5*IQR from the upper and lower quartile. You can filter the data manually.
For instance...
% data generation
data=randn(100,3);

%%
datas=sort(data);
datainbox=datas(ceil(end/4)+1:floor(end*3/4),:);

[n1 n2]=size(datainbox);

figure(1);clf
boxplot(data); hold on
plot(ones(n1,1)*[1 2 3],datainbox,'k.')

%%
% All datapoints coincide now horizontally. Consider adding a little random
% horizontal play to make them not coincide:

figure(2);clf
boxplot(data); hold on
plot(ones(n1,1)*[1 2 3]+.4*(rand(n1,n2)-.5),datainbox,'k.')

%%
% If you want to add all data between boxes and outliers too, do something like:

dataoutbox=datas([1:ceil(end/4) floor(end*3/4)+1:end],:);
n3=size(dataoutbox,1);
% calculate quartiles
dataq=quantile(data,[.25 .5 .75]);
% calculate range between box and outliers = between 1.5*IQR from quartiles
dataiqr=iqr(data);
datar=[dataq(1,:)-dataiqr*1.5;dataq(3,:)+dataiqr*1.5];
dataoutbox(dataoutbox<ones(n3,1)*datar(1,:)|dataoutbox>ones(n3,1)*datar(2,:))=nan;

figure(3);clf
boxplot(data); hold on
plot(ones(n1,1)*[1 2 3]+.4*(rand(n1,n2)-.5),datainbox,'k.')
plot(ones(n3,1)*[1 2 3]+.4*(rand(n3,n2)-.5),dataoutbox,'.','color',[1 1 1]*.5)

A: found a simple solution:
I edited the signature of the 'boxplot' function so it will return 'groupIndexByPoint' in addition to 'h':
function [h,groupIndexByPoint] = boxplot(varargin)
groupIndexByPoint is an internal variable used by 'boxplot'.
and now simply add 4 lines to the original code:
N = 1000;

% measurements values: they represent some kind of an
% electrical characteristic of a cable.
y = randn(N,1);

% each cable being measured can be of length 1m, 2m, or 3m:
x1 = randi(3,N,1);

% each cable being measured have a gauge of  1awg or 2awg:
x2 = randi(2,N,1);

% each cable can be produced by a different vendor. for instance: 'SONY' or
% 'YAMAHA'

x3 = cell(N,1);

for ii = 1:N
   if mod(ii,3) == 0
       x3{ii} = 'SONY';
   else
       x3{ii} = 'YAMAHA';
   end
end

figure(1);
hold on;
[h,groups] = boxplot(y,{x1,x2,x3});
scattering_factor = 0.3;
scaterring_vector = (rand(N,1)-0.5)*scattering_factor;
groups_scattered = groups + scaterring_vector;
plot(groups_scattered,y,'.g');


text:
Q: GROOVY - Parsing CSV: Ignore commas inside double quotes I'm looking for a groovy regex to be able to parse CSV file while ignoring commas insider double quotes.
The following regex works well in Java but not in Groovy:
it.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)")

Would you please help me to solve this issue.
I want to validate a CSv file format, for example for following example, the format is correct or not:
Header1, Header2, Header3
1, 2, 3
4, "5, 6", 7

But in this case, the format is not valid:
Header1, Header2, Header3
1, 2

I check Groovy Split CSV but it didn't solve my problem. Because the solution shown in that article, after parsing following csv:
Header1, Header2, Header3
1, "2, 3", 4, 5

will match:
Header1: 1
Header2: "2, 3"
Header3: 4

and it ignores 5! But me, I want to print out a message that format is not correct.
Thanks in advance.

A: try to change it like this:
it.split(",(?=(?:[^\"]\"[^\"]\")[^\"]\${1})")
Let me know.


text:
Q: How to read a variable declared in a html file inline script to another html inline script I have two html files e.g. abc.html & rst.html.
abc.html has inline script having a variable x declared inside it with some value.
Now I want to access the x value inside rst.html file's inline script.
Could you please let me know if this is possible.

A: You can't.
JavaScript does not let you access other tabs (to some extend, you may be able to access <iframes>s which could be in a separate window, but that's it and newer browsers generally prevent such accesses).
While in your browser, you have access to one set of global variables that are in that one window. Anything else is not accessible for security reasons.
The only way you would be able to do that is by using AJAX to read the second file and then search for the variable and grab the value. Good luck doing that...
The simplest for you will be to create a file, say x.js, and load that in both HTML pages. Now you will have access to all the data found in x.js.


text:
Q: (Incremental) Rebuild Debian/Ubuntu package I'm following the instructions at the how to build a Debian package from source question successfully.
However, I want to repeatedly rebuild the package after making modifications to the source (a "incremental build"), and the suggested commands do rebuild the package, but the modified source files are not recompiled.
How can I make dpkg-buildpackage (or debian/rules) rebuild modified source files? Is this possible to achieve generically, or does it depend on the package build file?
Specifically, I'm trying to do this for the chromium-browser package

A: The answer to your question was found on https://askubuntu.com/a/2879/164798
In short:

*

*dpkg-buildpackage -us -uc -nc uses the full toolchain

*fakeroot debian/rules binary just does the compile step

You need to execute it from the package source directory (where the debian/ directory lives).
Notes on how to get started with the Debian build system:

*

*For upstream packages download all 3 files: .dsc, .orig.tar.gz (or .xz etc.), .diff.gz (or .xz, etc.).

*For native packages download all 2 files: .dsc, .tar.gz (or .xz etc.)

*If it is in apt you can do apt-get source "$PACKAGE", this also includes the next step (it runs dpkg-source -x for you).

Unpack the source:

*

*dpkg-source -x "$FULLPACKAGE.dsc" where FULLPACKAGE is the full package name (including full version)

Compile the first time:

*

*cd "$ORIGPACKAGE" where ORIGPACKAGE is like FULLPACKAGE with the version only up to the first dash (-)

*Now run dpkg-buildpackage -us -uc -nc

*If you see Unmet build dependencies: (see also dpkg-checkbuilddeps):

*

*Either try apt-get build-dep $PACKAGE if you can use apt.  If not:

*Look into debian/control for the Build-Depends and install the dependencies.  If you want to automate this

*mk-build-deps -i "$FULLPACKAGE.dsc" -t sudo apt-get --no-install-recommends -y (found there: https://www.v13.gr/blog/?p=364).

*If you cannot use this (build for different architecture etc.) then try pbuilder (sorry, I do not know anything about this yet)

To quick compile changes afterwards:

*

*Use fakeroot debian/rules binary
If you are happy with it use dpkg-buildpackage -us -uc (and leave the options away if you use signing).

A: Depending on your source code, the build tool used should take care of compiling freshly modified source files. The debian packaging tools call the build tool, maybe a Makefile in your case, and build a package from the generated binary and other artefacts.
In general packaging should be a late step in your software development process. First write the code and then package it when ready for release.
I recommend using pbuilder to do the package building in a virtual container on your system, rather than on the system itself.

A: You can use git hooks with git-buildpackage on a fork of the debian git repository to help automate this.


text:
Q: How to add shadows to a popover that implements a UIPopoverBackgroundView According to Apple's documentation, a custom UIPopoverBackgroundView implementation should not contain shadows, but those don't seem to be provided elsewhere either.
http://developer.apple.com/library/IOs/#documentation/UIKit/Reference/UIPopoverBackgroundView_class/Reference/Reference.html

Note: The images you use for your popover background view should
  not contain any shadow effects. The popover controller adds a shadow
  to the popover for you.

The UIPopoverBackgroundView implementation: https://gist.github.com/1489041

A: I believe that the shadows should be part of your background image you are using when subclassing the UIPopoverBackgroundView. The shadows mentioned in Apple's documentation note seems to apply to the view contained in your popover. At least this is what i experimented.


text:
Q: Google Map not loading when running script (shows "map div") I am trying to place markers where the cities in a mySQL database are.  The page loads but it shows "map div" where the map should load.  I am not sure what is wrong.  Thank you for taking a look and trying to help!

When I open the html, I call initialize and make the canvas:

map div


text:
Q: How to ignore certificate verification while using openssl s_client connect? I am trying to connect to a server using the following command:
openssl s_client -connect xx.xx.xx.xx:443

Error:
CONNECTED(00000005)
depth=0 L = XXXXXXX
verify error:num=20:**unable to get local issuer certificate**
verify return:1
depth=0 L = XXXXXXXX
verify error:num=21:**unable to verify the first certificate
verify return:1**
---
Certificate chain
 0 s:/L=XXXX
   i:/C=XXXX
---
Server certificate
-----BEGIN CERTIFICATE-----
....
...
..
<removed cert>
..
...
....
-----END CERTIFICATE-----
subject=xxxxxxx CN=*xxx.xom
issuer=XXXX CA
---
No client certificate CA names sent
Server Temp Key: ECDH, P-256, 256 bits
---
SSL handshake has read 2281 bytes and written 326 bytes
---
New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES256-GCM-SHA384
    Session-ID: 52A27BC97001D52A7DA4A73FBA87C7DD2902A0C55B0AE9FAA87A3A8DBA94A7CE
    Session-ID-ctx:
    Master-Key: ECD435DCDD59B2BAD50A1BF8BAEA39E68058524A082DC219CEE290DB7A80A37AE4E763DF7FA
    TLS session ticket lifetime hint: 300 (seconds)
    TLS session ticket:
    0000 - 5d b4 5c fe ca 2d 54 2e-31 49 74 a6 18 a7 3a f5   ].\..-T.1It...:.
    XXXX
    0080 - ab 5c 0a bc 45 9c 10 01-9f 3b ce 6e ee 1a a6 99   .\..E....;.n....
    0090 - 04 81 ea e0 be a5 91 a2-18 09 d4 b8 90 b7 c7 50   ...............P
    00a0 - f7 7d 73 e5 b1 3d 0d 58-20 07 78 7b 57 c4 34 58   .}s..=.X .x{W.4X

    Start Time: 1566410644
    Timeout   : 7200 (sec)
    **Verify return code: 21 (unable to verify the first certificate)**
---

So it looks like the command is trying to verify the certificate which I don't want. How can I bypass the verification?
Is there something similar to curl -k flag?

A: OpenSSL's s_client is never terminating on wrong certificate unless you ask him too using
-verify_return_error argument (as already suggested by @bartonjs in comments).
You can read more about it in man page man 1 s_client or online. Look for  -verify argument or later in NOTES:

If there are problems verifying a server certificate then the -showcerts
option can be used to show all the certificates sent by the server.
The s_client utility is a test tool and is designed to continue the handshake
after any certificate verification errors. As a result it will accept any
certificate chain (trusted or not) sent by the peer. None test applications
should not do this as it makes them vulnerable to a MITM attack. This
behaviour can be changed by with the -verify_return_error option: any verify
errors are then returned aborting the handshake.

If the result you are seeing is last "error" you are seeing, it is probably something else on server which is terminating the connection at that moment. You should see reason in web server logs.


text:
Q: Creating LinearLayout in Java - Elements are not shown I am trying to create a LinearLayout with TextViews in Java, because the number of elements is dynamically specified so using XML won't work out for me.
Here is a little sample of my Code:
public class MyActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

    TextView titleView = new TextView(this);
    titleView.setWidth(LayoutParams.WRAP_CONTENT);
    titleView.setHeight(LayoutParams.WRAP_CONTENT);
    titleView.setTextAppearance(this, android.R.attr.textAppearanceLarge);
    titleView.setText("Hallo Welt!");
    layout.addView(titleView);

    setContentView(layout);

}
}

When i start this activity it does not show this TextView but it also does not show an error.
Does anyone have an advice?

A: TextView titleView = new TextView(this);
    titleView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    titleView.setTextAppearance(this, android.R.attr.textAppearanceLarge);
    titleView.setText("Hallo Welt!");
    layout.addView(titleView);
    setContentView(layout);

A: Use this code:
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

    TextView titleView = new TextView(this);
    titleView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    titleView.setTextAppearance(this, android.R.attr.textAppearanceLarge);
    titleView.setText("Hallo Welt!");
    layout.addView(titleView);

    setContentView(layout);

A: Try this,
  LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

        TextView titleView = new TextView(this);
        LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        titleView.setLayoutParams(lparams);
        titleView.setTextAppearance(this, android.R.attr.textAppearanceLarge);
        titleView.setText("Hallo Welt!");
        layout.addView(titleView);

        setContentView(layout);

A: try this
titleView.setWidth(100);
titleView.setHeight(40);

or
   titleView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));


text:
Q: (node:8196) [DEP0066] DeprecationWarning: OutgoingMessage.prototype._headers is deprecated I am facing this problem when switching from HTTP to spdy HTTP/2 and I got this warning! Any solution how to fix it?

A: https://github.com/spdy-http2/node-spdy/issues/382
not yet addressed. but spdy project is not updated for long time. expect this issue will be open for long time as contributors are not active.


text: Q: $S_n$ symmetric group of order n and elements of order n Let $S_n$ symmetric group of order n. I know that left rotation $\lambda$ and right rotation $\rho$ have order n. How can I find others elements of order n?


text:
Q: Is there a sample project in github that shows how to use the maven-shade-plugin? As the title says, I'm looking for a simple example in github that contains a code example that shows how to use the [the maven-shade-plugin] to rename classes when two versions of a library must be included in an application.
I found this answer on SO: https://stackoverflow.com/a/13620420/3281336 which shows exactly what I'm trying to do and I'm looking for a github repo that has that code example in it.

In the mean time, I'm starting to create my on version of this example and will post what I've created if no one points one out to me.
I have found several web pages that describe the plugin but nothing that has included a pointer to a repo with sample code.
Some useful writes up on the maven-shade-plugin

*

*The plugin documentation: https://maven.apache.org/plugins/maven-shade-plugin/examples/class-relocation.html

*What is the maven-shade-plugin used for, and why would you want to relocate Java packages? - the answer that included the diagram that shows how maven-shade-plugin allows two versions of a library to be included in an application.

*In the same question this answer was great because it gave several real-life examples of how and why the maven-shade-plugin is used:  https://stackoverflow.com/a/19386712/3281336

*What is the maven-shade-plugin used for, and why would you want to relocate Java packages?

*Difference between maven plugins ( assembly-plugins , jar-plugins , shaded-plugins) - differences between the different plugins to create a JAR executable.
Searching on google there were several articles I found that explained how to use the maven-shade-plugin.  Some were:

*

*https://howtodoinjava.com/maven/maven-shade-plugin-create-uberfat-jar-example/

*https://mkyong.com/maven/create-a-fat-jar-file-maven-shade-plugin/

A: I created a github repo so others can learn/benefit from this question and answer.
The github repo is public at: https://github.com/steranka/maven-shade-example
The Readme.md explains the solution.  Some if it is documented here in the event that goes away (some day).
Overview of the application
This is an example that illustrates the problem that occurs in most large projects and how the
maven-shade-plugin works to fix the problem.
This code example was developed in order to allow me to understand how the maven-shade-plugin works
with a real code but very simplified.
The idea of the simplicity was inspired by the StackOverflow answer: What is the maven-shade-plugin used for, and why would you want to relocate Java packages?
which explains why the maven-shade-plugin is needed and the problem it solves.
In this code the following JAR files exist

*

*helloworld.jar - A Java executable jar that is the main program.

*loglib.jar - There are two versions of this jar file (in different directories).

*goodlib.jar - This is another JAR file that uses version 1 of loglib.jar (dir loglibv1).
Overview of the Dependency Tree
The following diagram shows the dependency tree for the helloworld application.

Each of the pom files create a JAR file so there are 4 (four) jar files created by this code example.
Summary of the Problem
The next diagram shows the loglib.jar file being used in both the main application (helloworld)

It shows the class LogIt contains a method sayHello which takes one argument String name in version 1.0.0 of the package (liblog.jar)
and sayHello takes two arguments in the 2nd version of the package.
While this example is contrived to demonstrate the general problem
that faces Java developers on more complex code bases, this simplified version of the problem is intended to make the problem
easy to understand and to fix.
So by default, when a FAT jar is created for the HelloWorld application, the Fat jar only contains one copy of the class file com.steranka.play.LogIt.
The result is that either the HelloWorld class will crash or the GoodFeature class will crash. Where crash means throw an exception
Below is an example of the exception I saw when I first ran the application.
Hello World!
What's up, Sam
Exception in thread "main" java.lang.NoSuchMethodError: 'java.lang.String com.steranka.play.LogIt.sayHello(java.lang.String)'
at com.steranka.play.GoodFeature.sayGoodbye(GoodFeature.java:6)
at com.steranka.play.HelloWorldApp.main(HelloWorldApp.java:15)

This problem occurs because version 2.0.0 of the loglib.jar was used which contained the signature:
sayHello(String name, String greeting)

and the code in GoodFeature.sayGoodbye had bytecode which called the version 1.0.0 of the signature which was:
sayHello(String name)

Since that signature did not exist, the exception occured.
The Solution
The solution is to include both versions of the loglib jar file as shown in the next diagram.

Next Steps
If you want to follow along with what I did, and learn how I solved this problem
continue here with the doc/01-Starting.md file.


text:
Q: How create an Global Variable for all the project type NSArray I would like to know how can I create a global variable type NSArray that i can use (write in/read data) from any class from y app.
At the moment i'm using NSUserDefaults, but I don't think this is the best option, because i'm saving one NSArray quite big.
Thanks.

A: You can either just put it in a global variable (works the same as in C, just declare it at global scope) or, better, put it in a singleton object. Each class that wants to access it would first get the shared instance of the singleton object, which has a reference to your array. If you want the data to be persistent between runs of the application, you can still make sure to save it before quitting the app.


text:
Q: c# capture Ctrl+PageUp keystroke I am having trouble capturing Ctrl+PageUp keystroke in a ListView control in WinForms application.
I am using this code to capture keystrokes -
private void ListViewEx_KeyDown(object sender, KeyEventArgs e)
{
...
if(e.Control){
if((e.KeyCode ^ Keys.Left) == 0)
    MessageBox.Show("Left"); //shows messagebox
else if((e.KeyCode ^ Keys.PageUp) == 0)
    MessageBox.Show("PageUp"); //does not
...
}

Do I need to dive into WndProc to process this key? Thanks.

Edit: I've found out that this works, the problem was in enclosing TabControl handling these keys before ListControl got to them.

A: No need for WndProc:
if ((e.Modifiers & ModifierKeys) == Keys.Control && e.KeyCode == Keys.PageUp)
{
    // ctrl + page up was pressed
}

A: The e.KeyData argument includes the modifier keys.  Make it look like this:
  if (e.KeyData == (Keys.Control | Keys.PageDown)) {
    // Do your stuff
    Console.WriteLine("Ctrl+PgDn");
  }

A: check for
Keys.Control | Keys.PageUp


text:
Q: What's the meaning of "on notice" and "under advisement"? Can someone please give a clear definition and distinction of these terms, as when a public figure is asked a difficult question and says: "I'll take that on notice" or "I'll take that under advisement."

A: Let me answer your second question first

take something under advisement reserve judgment while considering something.

It's usually used by a judge when he announces he is going to consider what counsel has said and rule on it later.
As for "I'll take that on notice," I haven't heard that used. Usually the term is to "put someone on notice" meaning to alert someone to a fact and to the fact that you have given them some kind of ultimatum:

The police put Niko Bellic on notice that no further racketeering would be tolerated in Liberty City.

It's a way of telling someone "You have been warned."

A: In Parliament there is a session called Question time where members can ask ministers questions relating to anything.  Generally these questions are without notice.  That is to say the recipient has been asked a question without the benefit of receiving it earlier and being able to research the answer first.  If the answer is not known the Minster can answer by saying that they are taking the question "on notice".  In other words, let me find out and get back to you.  The reason they word it this way is because the opposite of a question without notice is a question with notice or "on notice".


text:
Q: How to create ontology specifically .owl file using Jena Hi I am new to Ontology.
How can I create .owl file using Apache Jena. Actually I have some data which I want to place in ontology .owl file but I am not sure how to create .owl file.
Can someone please point to example/url to create the ontology file using Apache Jena
Thanks in advance.

A: Information on RDBMS to RDF conversion:

*

*W3C Direct Mapping

*W3C R2RML

*Survey
Some potential tools that can achieve this are:

*

*Antidot.

*D2RQ