text:
Q: magento custom url for shopping cart Is there any way i can have a custom URL for the shopping cart of magento ?
ex: when you add a product to the cart, you get the link as
you will go to http://www.domain.com/magento/checkout/cart/
I want to change this to
http://www.domain.com/magento/checkout/CUSTOM_NAME_GOES_HERE/
i tried to edit
class Mage_Checkout_Helper_Url extends Mage_Core_Helper_Url
public function getCartUrl()
{
return $this->_getUrl('checkout/cart');
}

but it dosent works

A: easy as pie: go to catalog > URL rewrite management and add your rewrite condition and rewrite this whatever you like. and change the checkout/cart to indicate new route


text:
Q: Python: How to plot Pabon Lasso chart using matplotlib? I'm trying to plot a Pabon-Lasso chart using python's matplotlib library.
Pabon-Lasso is a healthcare services efficiency/performance plot.
I only found the R code library for the plotting at:
https://cran.r-project.org/web/packages/PabonLasso/index.html through searching but I have zero R knowledge.
Examples of a Pabon-Lasso chart is as follows:

The X-axis refers to BOR (Bed Occupancy Rate).
The Y-axis refers to BTR (Bed Turnover Rate).
The top and right-hand side axis represent the ALOS (Average Length of Stay).
The chart is divided into four quadrants with each representing different efficiencies/performance level.
The horizontal line on the middle of the chart is the mean BTR.
The vertical line on the middle of the chart is the mean BOR.
The diagonal lines on the chart are at gradients of y/x = BTR/BOR.
Each diagonal lines starts from origin.
The intersection on the right(or top) axis represents the ALOS.
I have tried using the code below but stuck on the labelling for the top and right axis for ALOS parameter.
My code:
import matplotlib.pyplot as plt
import numpy as np

#[2016, 2017]
BOR=[57.6, 52.03]
BTR=[69.81, 20.08]
ALOS = [4.04, 12.68]

mean_BTR = np.mean(BTR)
mean_BOR = np.mean(BOR)

fig=plt.figure()
ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)

#scatter points
ax.scatter([0, 57.6], [0, 52.03], color="C0")
ax.annotate('2016', (57.6 + 2, 52.03))
ax.scatter([0, 69.81], [0, 20.08], color="C0")
ax.annotate('2017', (69.81 - 5, 20.08+2))

#draw diagonals
ax.axline((0, 0), (57.6, 52.03))
ax.axline((0, 0), (69.81, 20.08))

#draw quadrants/ mean BOR & BTR
ax.vlines(x=mean_BOR, ymin=0, ymax=np.max(BOR) + 20, color='b')
ax.hlines(y=mean_BTR, xmin=0, xmax=np.max(BTR) + 20, color='b')

ax.set_xlabel("BOR", color="C0")
ax.set_ylabel("BTR", color="C0")
ax.tick_params(axis='x', colors="C0")
ax.tick_params(axis='y', colors="C0")
ax.set_xlim(xmin=0, xmax=np.max(BTR) + 20)
ax.set_ylim(ymin=0, ymax=np.max(BOR) + 20)

ax2.xaxis.tick_top()
ax2.yaxis.tick_right()
ax2.set_xlabel('ALOS', color="C1")
ax2.set_ylabel('ALOS', color="C1")
ax2.xaxis.set_label_position('top')
ax2.yaxis.set_label_position('right')
ax2.tick_params(axis='x', colors="C1")
ax2.tick_params(axis='y', colors="C1")
ax2.axes.xaxis.set_ticks([])
ax2.axes.yaxis.set_ticks([])

plt.show()

Any help, please? Or are there any libraries already for this purpose. Thank you.

A: You are on the right track. The matplotlib.axes object has twinning methods that adds additional single axes.
For example:
import numpy as np
import matplotlib.pyplot as plt

#2016/2017
xmax, ymax = 100, 100
ALS = np.array([4.04, 12.68, 2])
BOR = [57.6, 69.81, 40]
BTR = [52.03, 20.08, 80]
annotations = [2016, 2017, 2018]
mean_BTR = np.mean(BTR)
mean_BOR = np.mean(BOR)

fig = plt.figure()
plot = fig.add_subplot()
plot.set_xlim(0, xmax)
plot.set_ylim(0, ymax)

# add lines
for x, y, label in zip(BOR, BTR, annotations):
    plot.axline((0, 0), (x, y))
    plot.scatter((0, x), (0, y))
    plot.annotate(label, (x - 10, y))
plot.vlines(x=mean_BOR, ymin=0, ymax=ymax, color='b')
plot.hlines(y=mean_BTR, xmin=0, xmax=xmax, color='b')

# add right axis ticks
right_axis = plot.twinx()
right_axis.set_ylim(0, ymax)
right_ticks = np.array([ymax * y / x for x, y in zip(BOR, BTR)])
right_axis.set_yticks(right_ticks[right_ticks <= ymax])
right_axis.set_yticklabels(ALS[right_ticks <= ymax])

# add top axis ticks
top_axis = plot.twiny()
top_axis.set_xlim(0, xmax)
top_ticks = np.array([xmax * x / y for x, y in zip(BOR, BTR)])
top_axis.set_xticks(top_ticks[top_ticks < xmax])
top_axis.set_xticklabels(ALS[top_ticks < xmax])

# add labels
plot.set_xlabel('BOR')
plot.set_ylabel('BTR', color='g')
right_axis.set_ylabel("ALOS")
top_axis.set_xlabel("ALOS")

plt.show()

redpajama_set_name: RedPajamaStackExchange


text:
Q: what is Key parameter in the constructor I'm doing the Udacity flutter course.
There's this constructor call.
  child: Category(
    name: _categoryName,
    color: _categoryColor,
    iconLocation: _categoryIcon,
  ),

When I did this on my own, I naturally wrote the constructor as follows:
 const Category({
    @required this.name,
    @required this.icon,
    @required this.color
  }) : assert(name != null),
      assert(icon != null),
      assert(color != null);

Disregard the asserts and @requireds. You call using three parameters, so the constructor must have three parameters.
However, in the solution file of this exercise, the instructors did it like this.
  const Category({
    Key key,
    @required this.name,
    @required this.color,
    @required this.iconLocation,
  })  : assert(name != null),
        assert(color != null),
        assert(iconLocation != null),
        super(key: key);

What is this key parameter and why is the parent of the category widget class (StatelessWidget I presume) is being passed it?
I have looked at Key class, but I did not understand anything. There's no context in this page or an example I can use.

A: What are keys?
Let's go through the key documentation you linked..

A Key is an identifier for Widgets, Elements and SemanticsNodes.

Cool, widgets have an identifier, and that's the Key. Easy.
What are keys for?

A new widget will only be used to update an existing element if its
  key is the same as the key of the current widget associated with the
  element.

Now this is a bit more cryptic, let's break it down.
What's happening here is when there's a change in state and your widget tree is being rebuilt, flutter needs a way to know:

*

*Which widgets are completely new, and need to have a new state created for them;

*Or most interestingly, which widgets aren't really new, such that flutter already has a state object that should be associated with it. After all this is the reason why widget/state are separate in flutter, so that state survives while views change, animate, rotate, etc.

The key identifies a widget, and this tells flutter whether a widget should be inflated new, or whether it should replace an existing widget in the tree during a build.

Keys must be unique amongst the Elements with the same parent.

Now this becomes obvious, since we can't know which state belongs to this widget if it's key is not unique. Try it yourself! Create a column with two widgets and give them the same key. Spoiler alert: flutter will complain, and you now know why :)
Gotcha, anything else I should know?
For completeness one last point to be made here is about local and global keys. A regular Key is most probably a LocalKey, this one just needs be unique among its siblings. If you want to retain state for a widget that moves around the tree changing parents, then you're looking for a GlobalKey.
Also, flutter uses the type of the object (as in Object.runtimeType) along with the key to identify widgets during a build. This is why you often don't specify a key at all and things still work, because these are likely LocalKeys and you likely don't have two widgets of the same runtimeType under the same parent, so even if they happen to have the same default key they still don't clash.


text:
Q: How can I get AngularJS ui router to work with fullPage.js? I am creating a full page scrolling web app. I have something like this for a view

Section 1

Section 2

Section 3

And my route looks like this:
.state('home', {
            url: '/',

            templateProvider: function($templateCache) {
              return $templateCache.get('partials/home.html');
            }
        });

I want my routes to look like this:
.state('home', {
            url: '/',

            templateProvider: function($templateCache) {
              return $templateCache.get('partials/home.html');
            }
        })
        .state('section1', {//code}),
        .state('section2', {//code}),
        .state('section3', {//code});

My URL are formatted: www.example.com#section1, www.example.com#section2, etc.
How do I get the route to change each time a user scrolls to a different section?


text:
Q: Compilation hangs when using packages silence and hyperref As I was working on a document, I temporarily put some mathematical formulae with \mathscr in a section title. That didn't pose me any problem until the moment I tried to use both packages silence and hyperref, at which point compilation simply hung up. I've since found a way around the problem that fits my need, but I'm still curious as to why having silence or hyperref alone works fine, while having both interupts the compilation?
\documentclass{article}

\usepackage{mathrsfs}

%%%% this alone works
%\usepackage{silence}
%%%% this alone also works
%\usepackage{hyperref}

%%%% this hangs compilation
\usepackage{silence}
\usepackage{hyperref}

\begin{document}
\section{Testing $\mathscr A$}
lorem

\end{document}

I'm currently using pdflatex to produce a PDF output.
Note: if anyone has a similar problem, I'm told you should avoid mathematical formulae in section titles, and if you really have to, try using \texorpdfstring{math}{replacement text}.
EDIT: As Heiko Oberdiek commented, a better workaround is "to disable \mathscr when generating bookmark strings" with
\pdfstringdefDisableCommands{\let\mathscr\relax}.
That way, whenever \mathscr was used in a section title, it will be ignored, whereas \texorpdfstring{}{} requires you to specify replacement text every single time.


text:
Q: Scope -- how to evaluate an object in parent environment if local var with same name exists? If I have two nested environments using the same variable name, how would I grab the value of the outer environment?
I am having difficulty figuring out the correct way to implement this.  I have tried a few variations of parent.frame(x) and sys.frame(x) inside eval. Any suggestions would be appreciated.

EXAMPLE:
outerFunc <- function() {
  obj <- "Outer Object"
  innerFunc()
}

innerFunc <- function() {
  # A local variable with same name is created
  obj <- "Inner Object"

  # would like to grab the value of obj from the outer environment
  obj.callingFunc <- eval(obj, envir=sys.frame(-1))

  cat(obj.callingFunc)  # gives "Inner Object" instead of "Outer Object"
}

> outerFunc()
Inner Object

The obvious solutions (Pass obj explicitly. Use a different variable name, etc) are not available to me in this specific case.

EDIT
examining @GregSnow's and @Dwin's answers below
  # THESE WORK
  eval(quote(obj), envir=parent.frame()) # equivalent to evalq(obj, envir=parent.frame())
  get("obj", envir=parent.frame())

  # THESE DO *NOT* WORK
  eval("obj", envir=parent.frame())
  get(quote(obj), envir=parent.frame())

Any thoughts as to the effects of quoting in get() vs eval()?

A: Change your eval to evalq or otherwise quote obj in the call to eval.  As is obj is being evaluated before it is given to eval so it has the inner value, quoting it says pass the expression (not the value) to eval to be evaluated.

A: outerFunc <- function() {
  obj <- "Outer Object"
  innerFunc()
}

innerFunc <- function() {
  # A local variable with same name is created
  obj <- "Inner Object"

  # would like to grab the value of obj from the outer environment
  cat( get('obj', envir=parent.frame()) )

   }

 outerFunc()
#Outer Object

Could have also used: eval(quote(obj), envir=sys.frame(-1)). It becomes clear that the meaning of quote(expr) is different than than of "expr".  The get function is "expecting" (or perhaps more accurately is designed) to receive character values, whereas eval is expecting calls and expressions, i.e "language" objects. There is sort of a semi-permeable membrane between data and language in R and get is one of the membrane channels through which you can pass character valued objects to language domain.


text:
Q: What is the SuiteScript 2.0 equivalent to nlapiRequestURL()? Does anyone know the SuiteScript 2.0 equivalent?
nlapiRequestURL(url, postdata, headers, httpMethod)

A: http and https modules are equivalent of nlapiRequestURL()
HTTP SIMPLE EXAMPLE
var response = http.get({
    url: 'http://www.google.com',
    headers: headers
});

var response = https.post({
    url: 'http://www.google.com',
    body: myPostDataObj,
    headers: headers
});

HTTPS EXAMPLE
 var response = https.get({
     url: url,
     headers: headers
 });


text:
Q: How to center an image using Showdown Is there a way to center an image using ShowDown.
I am trying something like this:
## Next line has an image

![image](http://i.imgur.com/wYTCtRu.jpg =50%x50% )

A: To style a specific image in shodown, you can use the title attribute.
The problem is that "centering" requires a parent element to "center" against. So you will always need to add a "wrapper".
To accomplish that, you have a couple of options:

*

*use HTML and CSS (click the 3 bar symbol in the upper-left corner to close the options menu)
## Next line has an image

or
## Next line has an image

![image](http://i.imgur.com/wYTCtRu.jpg =50%x50%)

*use the  html tag (deprecated in HTML5)
## Next line has an image

![image](http://i.imgur.com/wYTCtRu.jpg =50%x50%)

*wrap the image tag in a  tag and style with CSS

## Next line has an image

[![image](http://i.imgur.com/wYTCtRu.jpg =50%x50%)](# "myImageWrapper")


text:
Q: linearmodels panelOLS: Regression output with stars I'm using the linearmodels package to estimate a Panel-OLS. As an example see:
import numpy as np
from statsmodels.datasets import grunfeld
data = grunfeld.load_pandas().data
data.year = data.year.astype(np.int64)
# MultiIndex, entity - time
data = data.set_index(['firm','year'])
from linearmodels import PanelOLS
mod = PanelOLS(data.invest, data[['value','capital']], entity_effect=True)
res = mod.fit(cov_type='clustered', cluster_entity=True)

I want to export the regression's output in a .tex file. Is there a convenient way of formatting the output with confidence stars and without the other information like the CIs? The question has been asked in the context of a standard OLS in here but this does not apply for a 'PanelEffectsResults' object, since I get the following error:
'PanelEffectsResults' object has no attribute 'bse'

Thanks in advance.

A: A bit late but here is what I use. In the example above I calculated two fixed effects regressions with their results stored in fe_res_VS and fe_res_CVS:
pd.set_option('precision', 4)
pd.options.display.float_format = '{:,.4f}'.format
Reg_Output_FAmount= pd.DataFrame()

#1)
Table1 = pd.DataFrame(fe_res_VS.params)
Table1['id'] = np.arange(len(Table1))#create numerical index for pd.DataFrame
Table1 = Table1.reset_index().set_index(keys = 'id')#set numercial index as new index
Table1 = Table1.rename(columns={"index":"parameter", "parameter":"coefficient 1"})

P1 = pd.DataFrame(fe_res_VS.pvalues)
P1['id'] = np.arange(len(P1))#create numerical index for pd.DataFrame
P1 = P1.reset_index().set_index(keys = 'id')#set numercial index as new index
P1 = P1.rename(columns={"index":"parameter"})

Table1 = pd.merge(Table1, P1, on='parameter')
Table1['significance 1'] = np.where(Table1['pvalue'] <= 0.01, '***',\
       np.where(Table1['pvalue'] <= 0.05, '**',\
       np.where(Table1['pvalue'] <= 0.1, '*', '')))
Table1.rename(columns={"pvalue": "pvalue 1"}, inplace=True)

SE1 = pd.DataFrame(fe_res_VS.std_errors)
SE1['id'] = np.arange(len(SE1))#create numerical index for pd.DataFrame
SE1 = SE1.reset_index().set_index(keys = 'id')#set numercial index as new index
SE1 = SE1.rename(columns={"index":"parameter", "std_error":"coefficient 1"})
SE1['parameter'] =  SE1['parameter'].astype(str) + '_SE'
SE1['significance 1'] = ''
SE1 = SE1.round(4)

SE1['coefficient 1'] = '(' + SE1['coefficient 1'].astype(str) + ')'
Table1 = Table1.append(SE1)
Table1 = Table1.sort_values('parameter')
Table1.replace(np.nan,'', inplace=True)
del P1
del SE1

#2)
Table2 = pd.DataFrame(fe_res_CVS.params)
Table2['id'] = np.arange(len(Table2))#create numerical index for pd.DataFrame
Table2 = Table2.reset_index().set_index(keys = 'id')#set numercial index as new index
Table2 = Table2.rename(columns={"index":"parameter", "parameter":"coefficient 2"})

P2 = pd.DataFrame(fe_res_CVS.pvalues)
P2['id'] = np.arange(len(P2))#create numerical index for pd.DataFrame
P2 = P2.reset_index().set_index(keys = 'id')#set numercial index as new index
P2 = P2.rename(columns={"index":"parameter"})

Table2 = pd.merge(Table2, P2, on='parameter')
Table2['significance 2'] = np.where(Table2['pvalue'] <= 0.01, '***',\
       np.where(Table2['pvalue'] <= 0.05, '**',\
       np.where(Table2['pvalue'] <= 0.1, '*', '')))
Table2.rename(columns={"pvalue": "pvalue 2"}, inplace=True)

SE2 = pd.DataFrame(fe_res_CVS.std_errors)
SE2['id'] = np.arange(len(SE2))#create numerical index for pd.DataFrame
SE2 = SE2.reset_index().set_index(keys = 'id')#set numercial index as new index
SE2 = SE2.rename(columns={"index":"parameter", "std_error":"coefficient 2"})
SE2['parameter'] =  SE2['parameter'].astype(str) + '_SE'
SE2['significance 2'] = ''
SE2 = SE2.round(4)

SE2['coefficient 2'] = '(' + SE2['coefficient 2'].astype(str) + ')'
Table2 = Table2.append(SE2)
Table2 = Table2.sort_values('parameter')
Table2.replace(np.nan,'', inplace=True)
del P2
del SE2

#Merging Tables and adding Stats
Reg_Output_FAmount= pd.merge(Table1, Table2, on='parameter', how='outer')

Reg_Output_FAmount = Reg_Output_FAmount.append(pd.DataFrame(np.array([["observ.", fe_res_VS.nobs, '', fe_res_CVS.nobs, '']]), columns=['parameter', 'pvalue 1', 'significance 1', 'pvalue 2', 'significance 2']), ignore_index=True)
Reg_Output_FAmount = Reg_Output_FAmount.append(pd.DataFrame(np.array([["Rsquared", "{:.4f}".format(fe_res_VS.rsquared), '',  "{:.4f}".format(fe_res_CVS.rsquared), '']]), columns=['parameter', 'pvalue 1', 'significance 1', 'pvalue 2', 'significance 2']), ignore_index=True)
Reg_Output_FAmount= Reg_Output_FAmount.append(pd.DataFrame(np.array([["Model type", fe_res_VS.name, '', fe_res_CVS.name, '']]), columns=['parameter', 'pvalue 1', 'significance 1', 'pvalue 2', 'significance 2']), ignore_index=True)
Reg_Output_FAmount = Reg_Output_FAmount.append(pd.DataFrame(np.array([["DV", fe_res_VS.model.dependent.vars[0], '', fe_res_CVS.model.dependent.vars[0], '']]), columns=['parameter', 'pvalue 1', 'significance 1', 'pvalue 2', 'significance 2']), ignore_index=True)

Reg_Output_FAmount.fillna('', inplace=True)

resulting in a nice regression output looking like that:
    parameter   coefficient 1   pvalue 1    significance 1  coefficient 2   pvalue 2   significance 2
0   IV          0.0676          0.2269                      0.0732          0.1835
1   IV_SE       (0.0559)                                    (0.055)
2   Control     0.3406          0.0125      **              0.3482          0.0118      **
3   Control_SE  (0.1363)        0.1383)
4   const       0.2772          0.0000      ***             0.2769          0.0000      ***
5   const_SE    (0.012)         (0.012)
6   observ.                     99003                                       99003
7   Rsquared                    0.12                                        0.14
8   Model type                  PanelOLS                                    PanelOLS
9   DV                          FAmount                                     FAmount

A: Have been struggling with the same problem for a few days. Very excited to share with my peers a very easy way to do it: include the significance stars, remove CIs.
Here it is:
Step 1: install linearmodels package.
Step 2: import compare function from linearmodels.panel
from linearmodels.panel import compare

Step3: Use compare function and specify the arguments as you want in compare. For instance, specifying stars = True will give you significance stars. Very convenient!
compare({'model_A_name': results of model_A, 'model_B_name': results of model_B, }, stars = True)

This small function saved my life! Enjoy it.
One more thing, please know that the stars are based on the p-value of the coefficient where 1, 2 and 3-stars correspond to p-values of 10%, 5% and 1%, respectively. I am not sure whether there is a way to make a customized stars measurement, like 1, 2 and 3-stars correspond to p-values of 5%, 1% and 0.1%.
The credit goes to the fantastic package developer and maintainer. Thank you all! Please see the file and get more information at:
~/opt/anaconda3/lib/python3.7/site-packages/linearmodels/panel/results.py


text:
Q: How to include pip packages in an rpm build I want to include a Python package dependency (installed using pip3 install) in an rpm package. I cannot install using dnf because its version is out of date. rpm returns the following error if I install the dependency using pip3 install:
error: Failed dependencies python3.6dist(dependency-package)

Any suggestions on how to include a Python package inside of an rpm?

A: OK. Some of your package require python3-somepackage or python3dist(somepackage). For rpm, it is just a string. Rpm does not care that the python module has been installed using pip. There must be some package which provides that string.
You have two options.
Prefered is use of pyp2rpm --srpm somepackage. That will download the latest version of the module from PyPI and produce the src.rpm. You can then build it using mock -r epel-8-x86_64 somepackage.src.rpm
The other option is to fake the provides. You can install the module using pip and then run: create-fake-rpm --build python3-somepackage 'python3dist(somepackage)'. This will generate the file fake-python3-somepackage-0-0.noarch.rpm which you can install using rpm. Then you can proceed with the install of your application. Be warned, that this is cheating. Future dnf upgrade will not update this module, you will have to take care of that yourself.


text:
Q: How to write Pandas DataFrame filter condition from parameters in a function Let say I have pandas DataFrame like this:
  NO_DOC | NO_SEQ | DESC
  A1     | 1      | A
  B1     | 2      | B
  C1     | 3      | C

I want to search row index from data above on a certain filter:
I am able to find it using statement:
idx = data.index[data["NO_DOC"] == "A1" && data["NO_SEQ"] == 1]

but what I want to ask is how to make the "condition" is variable because I want to make it in a function.
Example:
def find(self, data, columns, value):
  return data.index[data[...] == value[...] && ....].tolist()

columns parameters is ["NO_DOC","NO_SEQ"]
value is ["A1", 1]
the filter condition above is: data["NO_DOC"] == "A1" && data["NO_SEQ"] == 1
How do I make a function to find row index on pandas DataFrame with a certain filter condition?

A: We can use zip with a list comprehension to build a DataFrame from each Series of boolean values:
mask_df = pd.DataFrame([
    data[col] == val for col, val in zip(columns, values)
])

           0      1      2
NO_DOC  True  False  False
NO_SEQ  True  False  False

Then we can reduce this DataFrame of booleans with all to check which columns (indexes) have only True values (logical AND):
mask = mask_df.all()

0     True
1    False
2    False
dtype: bool

Note: logical OR can be achieved with any instead of all
Now we can use the mask to filter the indexes:
data.index[mask].tolist()

[0]

Together find can look something like:
def find(data, columns, values):
    # Create a DataFrame of boolean conditions
    # Take logical AND using DataFrame.all
    mask = pd.DataFrame([
        data[col] == val for col, val in zip(columns, values)
    ]).all()
    # Filter and convert to list
    return data.index[mask].tolist()

Or with np.logical_and and .reduce which behaves in with the same logic as the DataFrame but can be much faster as it does not need to maintain pandas objects:
def find(data, columns, values):
    mask = np.logical_and.reduce(
        [data[col] == val for col, val in zip(columns, values)]
    )
    return data.index[mask].tolist()

Some timing via timeit.
Setup:
import numpy as np
import pandas as pd

def find_with_df_mask(data, columns, values):
    mask = pd.DataFrame([
        data[col] == val for col, val in zip(columns, values)
    ]).all()
    return data.index[mask].tolist()

def find_with_np_mask(data, columns, values):
    mask = np.logical_and.reduce(
        [data[col] == val for col, val in zip(columns, values)]
    )
    return data.index[mask].tolist()

df = pd.concat([pd.DataFrame({
    'NO_DOC': ['A1', 'B1', 'C1'],
    'NO_SEQ': [1, 2, 3],
    'DESC': ['A', 'B', 'C']
})] * 1000, ignore_index=True)
cols = ["NO_DOC", "NO_SEQ"]
vals = ["A1", 1]

Timings:
%timeit find_with_df_mask(df, cols, vals)
21.9 ms ± 65.5 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit find_with_np_mask(df, cols, vals)
319 µs ± 253 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)

A: To write Pandas dataframe filter condition from parameters in a function:
import pandas as pd

raw_data = {'NO_DOC':['A1','B1','C1'],'NO_SEQ':[1,2,3],'DESC':['A','B','C']}
data = pd.DataFrame(raw_data)

columns = ["NO_DOC", "NO_SEQ"]
value = ["A1", 1]

Create masks and send them to functions instead of columns and values:
mask1 = data[columns[0]] == value[0]
mask2 = data[columns[1]] == value[1]

def find(data, mask1,mask2):
    return data.index[mask1 & mask2].tolist()

Call your function as follows:
find(data, mask1, mask2)


text:
Q: How to lock the form from further resizing with aspect ratio resizing I currently use this code and it works flawlessly
My question is how do I modify the WndProc to stop at my preferred limit of Width and Height. Okay I solved that by setting the MinimumSize, but a new problem arises when the aspect ratio of the form reaches the limit of the windows desktop maximum right size it starts to mess up the aspect ratio starts streching instead of locking up.
Need to somehow fix the WndProc with SystemInformation.VirtualScreen.Width to stop increasing both sizes when the limit Width is hit.
I added this which works but it's still only for my resolution how do I make it universal to support all resolutions.
        If r.right - r.left > SystemInformation.VirtualScreen.Width Then
            r.bottom = 900 'quick fix (not good) how to calculate this value?
        End If

source of code:
http://www.vb-helper.com/howto_net_form_fixed_aspect.html
Imports System.Runtime.InteropServices
...
Public Structure Rect
    Public left As Integer
    Public top As Integer
    Public right As Integer
    Public bottom As Integer
End Structure

Protected Overrides Sub WndProc(ByRef m As _
    System.Windows.Forms.Message)
    Static first_time As Boolean = True
    Static aspect_ratio As Double
    Const WM_SIZING As Long = &H214
    Const WMSZ_LEFT As Integer = 1
    Const WMSZ_RIGHT As Integer = 2
    Const WMSZ_TOP As Integer = 3
    Const WMSZ_TOPLEFT As Integer = 4
    Const WMSZ_TOPRIGHT As Integer = 5
    Const WMSZ_BOTTOM As Integer = 6
    Const WMSZ_BOTTOMLEFT As Integer = 7
    Const WMSZ_BOTTOMRIGHT As Integer = 8

    If m.Msg = WM_SIZING And m.HWnd.Equals(Me.Handle) Then
        ' Turn the message's lParam into a Rect.
        Dim r As Rect
        r = DirectCast( _
            Marshal.PtrToStructure(m.LParam, _
                GetType(Rect)), _
            Rect)

        ' The first time, save the form's aspect ratio.
        If first_time Then
            first_time = False
            aspect_ratio = (r.bottom - r.top) / (r.right - _
                r.left)
        End If

        ' Get the current dimensions.
        Dim wid As Double = r.right - r.left
        Dim hgt As Double = r.bottom - r.top

        ' Enlarge if necessary to preserve the aspect ratio.
        If hgt / wid > aspect_ratio Then
            ' It's too tall and thin. Make it wider.
            wid = hgt / aspect_ratio
        Else
            ' It's too short and wide. Make it taller.
            hgt = wid * aspect_ratio
        End If

        ' See if the user is dragging the top edge.
        If m.WParam.ToInt32 = WMSZ_TOP Or _
           m.WParam.ToInt32 = WMSZ_TOPLEFT Or _
           m.WParam.ToInt32 = WMSZ_TOPRIGHT _
        Then
            ' Reset the top.
            r.top = r.bottom - CInt(hgt)
        Else
            ' Reset the height to the saved value.
            r.bottom = r.top + CInt(hgt)
        End If

        ' See if the user is dragging the left edge.
        If m.WParam.ToInt32 = WMSZ_LEFT Or _
           m.WParam.ToInt32 = WMSZ_TOPLEFT Or _
           m.WParam.ToInt32 = WMSZ_BOTTOMLEFT _
        Then
            ' Reset the left.
            r.left = r.right - CInt(wid)
        Else
            ' Reset the width to the saved value.
            r.right = r.left + CInt(wid)
        End If

        ' Update the Message object's LParam field.
        Marshal.StructureToPtr(r, m.LParam, True)
    End If

    MyBase.WndProc(m)
End Sub

A: You can find out user's desktop resolution with Screen.PrimaryScreen.Bounds.Bottom and Screen.PrimaryScreen.Bounds.Right


text:
Q: How to find index of a given Fibonacci number I tried to use the following formula

to find the index of a fibonacci number() in a programming question and all the smaller test cases passed but some cases in which F was close to 10^18 failed. I did some dry-run and found out that if F = 99194853094755497 (82nd Fibonacci number) the value of n according to the above formula is 81. I coded this in Python and C++ which can be found here and here respectively. I want to know whether the formula works for every value of F or has some limitations?
Note: After doing some more tests, I found out that the code is giving correct answers till 52nd fibonacci number.
Update: The question has t test cases that's why I used a for loop. The given number F might not necessarily be a Fibonacci number. For ex- If F = 6, then it lies between two fibonacci numbers 5 and 8. Now the index of '5' in the fibonacci sequence is 4 so the answer is 4.

A: The formula works just fine:
import math
n = 99194853094755497
print math.log(n * math.sqrt(5) + 0.5) / math.log(1.61803398875) - 1

Output:
82.0

A remark on your code:

*

*Using int(...) for rounding off to an integer might cause trouble if the floating point result is very close to 82.0. Numerical issues might cause it to be slightly larger, even though mathematically it would be smaller.

A: F = 99194853094755497 is 84 Fibonacci number and hence the index for it is 83. Use the below script to get the correct index (integer instead of float).
eps = 10**-10
phi = (1+math.sqrt(5))/2  # golden search ratio
fibonacci_index = int(round(math.log(n * math.sqrt(5)+eps)/math.log(phi)))

Additional Info, code
See this https://github.com/gvavvari/Python/tree/master/Fibonacci_index for more detailed documentation on the implementation

A: I think your formula is causing a stack overflow because the number is too large to hold in int.


text:
Q: DateTime Field shows invalid format error while passing empty value through form I trying to submit form while keeping field for datetime as empty which results in an error showing invalid format for datetime.
my modal
class lead(models.Model):
    assigned_to=models.CharField(max_length=15)
    ref=models.CharField(max_length=10,blank=True)
    lead_type=models.CharField(max_length=20)
    priority=models.CharField(max_length=20)
    hot=models.CharField(max_length=20,blank=True)
    source=models.CharField(max_length=20,blank=True)
    mls_lead=models.CharField(max_length=20,blank=True)
    auto_imported=models.CharField(max_length=20,blank=True)
    inquiry_date=models.DateTimeField(blank=True,null=True)
    lead_closed_date=models.DateTimeField(blank=True,null=True)
    created_by=models.CharField(max_length=20,blank=True)
    property_id=models.IntegerField(blank=True,null=True)
    contact_id=models.IntegerField(blank=True,null=True)

its clear that i have  given null true for the datetime field and the form
i have is
 my form
class leads_form(forms.Form):
    assigned_to = forms.ChoiceField(choices=[(o.id, str(o.username)) for o in CustomUser.objects.all()],required=True,widget=forms.Select(attrs={'class':'form-control'}))
    ref = forms.CharField(max_length=50,required=False,widget=forms.TextInput(attrs={'class':'form-control'}))
    lead_type = forms.ChoiceField(choices=dicto.lead_type_dict.items(),required=True,widget=forms.Select(attrs={'class':'form-control slct'}))
    priority = forms.ChoiceField(choices=dicto.priority_dict.items(),required=True,widget=forms.Select(attrs={'class':'form-control slct'}))
    hot = forms.ChoiceField(choices=dicto.hot_dict.items(),required=True,widget=forms.Select(attrs={'class':'form-control slct'}))
    source = forms.ChoiceField(choices=dicto.source_dict.items(),required=True,widget=forms.Select(attrs={'class':'form-control slct'}))
    mls_lead = forms.ChoiceField(choices=dicto.true_false_dict.items(),required=True,widget=forms.Select(attrs={'class':'form-control slct'}))
    auto_imported = forms.ChoiceField(choices=dicto.true_false_dict.items(),required=False,widget=forms.Select(attrs={'class':'form-control slct'}))
    inquiry_date = forms.CharField(max_length=50,required=False,widget=forms.TextInput(attrs={'class':'form-control'}))
    lead_closed_date = forms.CharField(max_length=50,required=False,widget=forms.TextInput(attrs={'class':'form-control'}))
    created_by = forms.CharField(max_length=50,required=False,widget=forms.TextInput(attrs={'class':'form-control'}))
    property_id =  forms.IntegerField(required=False,widget=forms.HiddenInput())
    set_status = forms.ChoiceField(choices=dicto.set_status_dict.items(),required=True,widget=forms.Select(attrs={'class':'form-control slct','placeholder':'set status','required':'true'}))
    contact=forms.IntegerField(required=True,widget=forms.HiddenInput(attrs={'required':'true'}))

and when i try to create object of model with validate form data it shows
django.core.exceptions.ValidationError: ["'' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]

the way i create object is as follows
if form.is_valid():
            lead.objects.create(
                assigned_to=form.cleaned_data['assigned_to'],
                ref=form.cleaned_data['ref'],
                lead_type=form.cleaned_data['lead_type'],
                priority=form.cleaned_data['priority'],
                hot=form.cleaned_data['hot'],
                source=form.cleaned_data['source'],
                mls_lead=form.cleaned_data['mls_lead'],
                auto_imported=form.cleaned_data['auto_imported'],
                inquiry_date=form.cleaned_data['inquiry_date'],
                lead_closed_date=form.cleaned_data['lead_closed_date'],
                created_by=form.cleaned_data['created_by'],
                property_id=form.cleaned_data['property_id'],
                contact_id=form.cleaned_data['contact'])

A: To Django's DateTimeField, a blank string is not the same as None (or null). I believe this confusion comes from the similar evaluation of truth values for a blank string and None.
To assert no error is raised and the field is populated with a null value when wanted, rework DateTimeField populating lines like this one (from the lead.objects.create call):
lead_closed_date=form.cleaned_data['lead_closed_date']

to this:
lead_closed_date=(
    form.cleaned_data['lead_closed_date']
    if form.cleaned_data['lead_closed_date']
    else None
)

With this correction, it will populate the value of lead_closed_date with form.cleaned_date['lead_closed_date'] if the truth value of form.cleaned_data['lead_closed_date'] is True.


text:
Q: Why are we able to take the union here?, also axiom of countable choice. In theorem 8.3 in Munkres Topology, he takes the union over some functions, and the functions are regarded as collection of ordered pairs. But in order to do this, must we not first prove that $\{f_1,f_2,.\dots \}$ is a set? How is he sure that it is a set?
First he has sopme relevant lemmas:

Then he proves the theorem I am talking about:

But he has not proved that $\{f_1,f_2,\ldots\}$ is a set?
For instance if $\{A_n\}$ is a countable collection of nonempty set. For each n we know that there exists an ordered pair $(A_n,a_n), a_n \in A_n$ since $A_n$ is nonempty. But if we also have that $\{(A_1,a_1),(A_2,a_2),\ldots\}$ is a set, we have proved the axiom of countable choice?

A: Note that $f_n$ is unique (Munkres mentions this in his proof). So, we have a formula $\varphi$ assigning, to each natural number $n$, a unique set $f_n$. Then $\{f_n: n\in\mathbb{N}\}$ exists by Replacement.
Were the $f_n$s not uniquely determined by $n$, then this would indeed need some amount of the axiom of choice (or a clever argument explaining how to pick out a specific $f_n$ for each $n$, without choice).

Actually, we would never need the axiom of choice here! Specifically, suppose for each $n$ we have a nonempty set of functions $F_n$. Then let $f_n$ be the lexicographically least element of $F_n$. This relies on two properties: that the domain be finite, and that the range be well-orderable.

*

*Note that a set of functions $G$ from an infinite set $A$ to $\mathbb{N}$ need not have a lexicographically least element, even if $A$ is well-ordered; consider the set $$G=\{f:\mathbb{N}\rightarrow\mathbb{N}: \exists n(f(n)\not=0)\}.$$ The lexicographically least element of $G$ would be the constantly-zero map, but that's not an element of $G$!

*Note also that a set $G$ of functions from a singleton $\{a\}$ to a non-well-orderable set $B$ (such exist without the Axiom of Choice) need not have a lexicographically least element.


text:
Q: Can a file be retrieved by its inode? I ran following commands in the order specified:
$ln a b
$ls -i a b
523669 a 523669 b
$rm -f a
$ls -i b
523669 b

I concluded from this test that the command rm actually removes only the filename (a in this test) instead of the file, as the inode still exists and could be retrieved through another filename (b).
My question is, if a file is hard linked to only one filename, when rm is executed to the file, is the real file (i.e., the inode) removed completely? And if not, can a file inode be retrieved without a filename and only through the inode?

A: The question can be taken theoretically (which can be achieved with debugfs) or pragmatically (emergency situation). In the latter case, I assume the intent is saving the day and restoring the file's content, possibly urgently (which is how I landed on this question, so I think it is still relevant and useful).
Since there's no kernel API, debugfs should not be run on a live file system because it manipulates the FS structure directly. Therefore to do it live, you have to get hold of another filename. Assuming the file is still open by some process (any process), one can reach for the ever convenient file descriptors in /proc:
$ lsof -F pf "$PWD/a" | sed 's/^p//' # find pid and file descriptor number of any process having the file open
$ pid=1234
$ ls -l /proc/$pid/fd/* | grep "$PWD/a" # find file descriptor number
$ fd=42
$ cat /proc/$pid/fd/$fd > "$PWD/a.restored" # read contents to a new filename

Tips:

*

*if you have a doubt about the right fd, you can run commands such as file on it

*if there's a process writing to the file, be sure to stop that process ASAP or you won't get the latest data. An (untested) trick might be to open the file read only through the fd with some other process (try tail -f < /proc/$pid/fd/$fd > /dev/null, exit the writing process so that it exits cleanly, and use the new process's fd.

A: If you try to open a file via its inode, this bypasses any directory traversal. The directory traversal is necessary to determine the permissions of the file and directories leading to it. Without a directory traversal, the kernel has no way to determine whether the calling process is allowed to access the file.
There was a proposed patch to the Linux kernel to allow creating a link to a file from a file descriptor. It was rejected because implementing this securely would have been extremely hard.
Under Linux (and probably on other unix variants for the same reason), you cannot create a link to a deleted file, so if a file no longer has a name, you can't re-add one.¹ You can open a deleted file by opening the magic links under /proc/$pid/fd/.
If a file no longer has any link and is no longer open, it no longer exists and the space formerly used by its data may be reclaimed at any time.
¹  You may be able to do this by twiddling the bytes directly in the filesystem in a filesystem-dependent way, for example with debugfs for ext2/ext3/ext4. This requires access to the device on which the filesystem is mounted (i.e. typically only root can attempt it). However, while debugfs can access a file by inode, this doesn't help if the file is deleted: the file will be truly deleted if the application closes it, and running debugfs in read-write mode on a mounted filesystem is a recipe for disaster.

A: debugfs has a cat command that takes an inode number and prints the data where the inode's addresses point to.
For example:
sudo debugfs -D -R 'cat <8>' /dev/sda3 > ext4_journal

writes the contents of the ext4 journal (which commonly has inode number 8 but no file name) to a file.
The angle brackets around the inode number are not a placeholder, cat expects them to be there.
The -D causes debugfs to bypass the buffer cache. Without this option, you might read stale data.

A: The 'ln' and 'rm' commands have worked exactly like this in every UNIX filesystem since the early 1970s. Mac OSX, BSD and Linux all inherit this original design.
By itself, a UNIX file has no name, only an inode number or inum. But you can only access it through an entry in a special "directory" file that associates a name with the inum in question; you can't specify the inum directly.
A directory is itself a file, so you must also access it through (another) directory and so on, through a series of directory names delimited by forward slashes (/) known as a "path name". A path starts in the "current working directory" of the process unless the name begins with a "/", in which case it starts with the file system root directory. E.g., if the path name contains no "/" characters, then it is expected to be an entry in the current directory.
A non-directory file can have any number of path names, known as "hard links", and it will continue to exist until all of its path names have been removed and the last process has closed the file. Then the file is actually deleted and its space marked as available for reuse. That is, you can creat() or open() a singly-linked file and then unlink() it so it no longer appears in the file system name space, but the file will continue to exist until you close it. This is useful for temporary scratch files that won't be read by any other program.
Although directories have inode numbers, most file systems disallow hard links to them; they can appear in only one other directory. (One unusual exception is the Mac OSX HFS+ file system; this lets Time Machine backups work.) You can still create "soft links" to directories (or any other file). A soft link resembles a directory entry except that it contains another path name rather than an inum.
Every UNIX file has an owner, group and access permissions. It is necessary but not sufficient that they let you open the file; you must also have at least execute permission for every directory in the pathname you use to refer to it. That's why there's no standard way to open a UNIX file by its inode number; that would bypass an important, widely used security mechanism.
But this doesn't explain why there can't be a standard way for a root (privileged) user to open a file by inode number, since permissions checking is bypassed anyway. This would be very useful for certain system management functions such as backups. To my knowledge, such mechanisms do exist, but they're all filesystem-specific; there is no general way to do it for any UNIX filesystem.

A: On Linux, debugfs, the interactive ext2/ext3/ext4 file system debugger provides a ln command which can take an inode number as filespec and create a new hard link to the corresponding file. In practice though, this requires that the unlinked file is kept open by a process, maintaining an open file descriptor in /proc/[pid]/fd/[n]. Attempting this is on a deleted file will most likely lead to file system corruption.
This is because in order to ensure that ext3 (and in extension ext4) can safely resume an unlink after a crash, it actually zeros out the block pointers in the inode, whereas ext2 just marks these blocks as unused in the block bitmaps and marks the inode as "deleted" and leaves the block pointers alone. Even so, as the file system needs to be mounted read-write in order to create the hard link, the blocks reserved for the deleted file might already have been reallocated.
Prior to kernel version 2.6.39 it used to be that the ln -L|--logical option introduced in GNU coreutils v8.0 could be used to recover an unlinked file via an open file descriptor in /proc/[pid]/fd/[n] if both the unlinked file and new hardlink resided on a tmpfs file system . This capability has since been disabled, due to, as Gilles pointed out, the security considerations involved in allowing hard link creation directly from a file descriptor.


text:
Q: WebStorm 2018.1 sub-folder collapse feature gone Recently updated my WebStorm to version 2018.1 and a feature I liked is missing from what I can see. It's the collapse subfolders when collapsing a folder on the project panel.
I've been able to collapse all sub folders without the need to collapse the whole project. Once I reopened that folder, all the subfolders were closed. Now this feature is gone or I must change my settings.
Does anyone know how to get it back?

A: Please vote for IDEA-186081 to be notified on any progress with it. See https://intellij-support.jetbrains.com/hc/articles/207241135 if you are not familiar with YouTrack.


text:
Q: My audio files won't play anymore? how to fix? <embed name="audioforwebsite" src="audiofile1.mp3" type="audio/mp3"
 autostart="false" Hidden="true" ></embed>
<audio loop autoplay>
  <source src="audiofile1.mp3" type="audio/mp3">

I use this code and it used to work on my website. However for some reason, it doesn't work anymore.
(i use chrome to play it)
i'm very new to coding and i've looked around the internet for the past hour, but none of the advice seem to work.
my objective is to create an audio file that auto plays when you get into the website, it loops, and it cant be seen in the form of a play/pause button thingy.
help me please.
if you dont know how to fix it, please tell me how to make a new one that you know works using HTML chrome. Thanks.

A: Auto Play in Chrome ist disabled for security reasons. The user has to click in your page or do anything.


text:
Q: Clone an existing ApplicationContext in Spring I have a multi-threaded application I am trying to write with Spring, right now I am using the new thread scope declaration on my beans and passing the same context into the Runnable class. The threading works fine and I get a new copy of the DAO/Services for each thread so exactly how I want it.
Though I think I'll have memory issues in this case since these threads can spawn indefinitely, but creating a brand new ApplicationContext with ClassPathXmlApplicationContext is slow, is there a way to make a deep copy of the context so it doesn't need to be reloaded from scratch?

A: Instead of using thread scope beans, use singleton scope beans. This is the default behavior, so you shouldn't have to do anything special -- i.e. don't specify a scope. If you've already added a custom thread scope, then simply remove that part of your config.
There should be no need to close a context containing singleton scope beans until application shutdown. Here is how to do a clean shutdown.
The whole ideal of cloning an ApplicationContext is a step in the wrong direction. You really ought to think only in terms of the lifecycle of the Spring-managed beans. In other words, generally your application should not know or care about the ApplicationContext, but rather should just rely on the Spring IoC working properly. So, your original question changes from "how do I create a new ApplicationContext?" to "how do I get references to the right Spring-managed beans"? Further, if you clone the ApplicationContext, then you probably break the contract of Spring's IoC container (e.g. create multiple instances of a database connection pool which ought to be a singleton), and nobody else will be able to figure out what's going on!


text:
Q: WANTED : All operative systems OS which run on the Raspberry Pi? I bought one of those 512MB Ram supported models, I downloaded a common image with 7 different modes to boot the system and installed the most common one.
I wondered whats possible to manage on this  ARMv6 Chip. Sincu Ubuntu needs  ARMv7 it will not run under this. But is there a list of many or even all ? operating systems or similiar workplatforms which are supported by this super small super computer?
I start here :

*

*RiscOS

*DEBIAN

*Pidora

*Raspbian

*OpenELEC

*Archlinux

A: There's a list that seems to be maintained on the RPi Distributions page on the eLinux wiki.


text:
Q: Session invalidation in FF , Tomcat I am using Tomcat web container. I have an admin console app implemented. When I click on logout a session attribute is made null and invalidated see the below code in my logout.jsp file.
After logout the user is taken to the login page. In fireFox I click back button I have the below issues.
First I do not get page expired page like in IE
Second when I click on any of the link in the page , I check for the sessioon attribute which I made null in logout. The value of that is "success".
I am totally confused with this behaviour. Is it issue with firefox or tomcat session management.
I am sure I need more knowledge to understand this behaviour. Appreciate your help in letting me know what happens here...
<%@ page session="false" %>
<%
response.setHeader("cache-control","no-cache");
response.setHeader("Pragma","no-cache");
response.setDateHeader("Expires",-1);

%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%
    HttpSession session = request.getSession(false);
    System.out.println("session"+session);
    session.setAttribute("loginStatus",null);
    session.invalidate();
  %>

A: The headers are incomplete. You need the following set of headers:
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.

Escpecially the must-revalidate entry fixes this particular FF issue.
See also

*

*Making sure a webpage is not cached across all browsers

*Caching tutorial

Unrelated to the actual problem, I've a few comments about this piece of code:

*

*You should prefer UTF-8 over ISO-8859-1 to gain world domination.

*Raw Java code in a JSP page is poor practice. The response headers needs to be set in a Filter and the logout needs to happen (indirectly) in a Servlet.

*Calling getSession(false) with false may return a null session which in turn can lead to a NullPointerException in certain circumstances. Get rid of false or at least add a nullcheck.

*Setting attribute to null right before calling invalidate() is unnecessary. The invalidate() call already trashes all the attribtues.

Hope you learn something from this.


text:
Q: laravel 5.5 login via google gives Client error I was trying to add the google login to my laravel project. but it gives a Client error. Given below is the error i got. I successfully installed the socialite as well.
 Client error: `GET https://www.googleapis.com/plus/v1/people/me?prettyPrint=false` resulted in a `403 Forbidden` response: {"error":{"errors":[{"domain":"usageLimits","reason":"accessNotConfigured","message":"Project 983930379932 is not found (truncated...)

A: Remember you have to register your google app within googles service as well. That error if I remember correctly is simply telling you that you aren't allowed to use google services.
I am not super sure if this steps are up to date, but it shouldn't be that different: https://itsolutionstuff.com/post/laravel-5-google-oauth-authentication-using-socialite-packageexample.html

A: Go to https://console.cloud.google.com/apis and enable Google+ api.
Took me 3 hours to find out that Google Cloud does not automatically enable the api for you when you create OAuth service.

A: First Open your Google Console Account from Here : console.developers.google.com
Select your project.
After this you have to click on google+ API detail page.
Now we can enable API.


text:
Q: How to display information and numbers from an unstructured text in a table with Spacy I am trying, and so far failing to find a way to extract textual information via Spacy and present it in a table.
An example text would  be:
lines = 'From June 2020 to November 2020 the total rent was 800 Euro. It was composed of a basic rent of 600 Euro, a premium for the Heating of 100 Euro and another premium for the Garage of 100 Euro. From Dezember 2020 to January 2021 the total rent was 1000 Euro, then composed of a basic rent of 800 Euro, a premium for the Heating of 100 Euro and another premium for the Garage of 100 Euro.'

The output I would like to achieve is as follows:
| Period                | Total Rent | Basic Rent | Heating Premium | Garage Premium |
|------------------------|------------|------------|-----------------|----------------|
| June 2020-November 2020 | 800 Euro   | 600 Euro   | 100 Euro         | 100 Euro       |
| Dezember 2020-January 2021 | 1000 Euro | 800 Euro   | 100 Euro         | 100 Euro       |

So far I have tokenized the text and which seems useful. Then I have iterated over the tokens and only displayed Nouns and Numbers:
print("Iteriere über die Tokens und sage wortart vorher:")
for token in doc:
    # Drucke den Text und die vorhergesagte Wortart
    if token.pos_ == "NOUN" or token.pos_ == "NUM" or token.pos_ == "PROPN":
        print(token.text, token.pos_)

The result ist:
June PROPN
2020 NUM
November PROPN
2020 NUM
rent NOUN
800 NUM
Euro PROPN
rent NOUN
600 NUM
Euro PROPN
premium NOUN
Heating PROPN
100 NUM
Euro PROPN
premium NOUN
Garage PROPN
100 NUM
Euro PROPN
Dezember PROPN
2020 NUM
January PROPN
2021 NUM
rent NOUN
1000 NUM
Euro PROPN
rent NOUN
800 NUM
Euro PROPN
premium NOUN
Heating PROPN
100 NUM
Euro PROPN
premium NOUN
Garage PROPN
100 NUM
Euro PROPN

This seems helpful, because it contains the main parts that shall be displayed in the table.
However, there may not be a way to automatically get the table done.
Does anybody have an idea?
Thanks in advance.


text:
Q: grails 3 oracle datasource for russian text I am working on a grails application which connects to oracle database. It works fine except when there are any russian text in the db. For russian text, I get inverted ?. There are some approach in other questions for mysql but I could not find datasource configuration for oracle. Any help here will be great.
EDIT -
The russian text is stored in varchar2 datatype.
and here is the query -
SELECT * FROM NLS_DATABASE_PARAMETERS WHERE PARAMETER LIKE '%SET';
NLS_CHARACTERSET    WE8MSWIN1252
NLS_NCHAR_CHARACTERSET    AL16UTF16

A: What does a result of the below query mean ?
SELECT * FROM NLS_DATABASE_PARAMETERS
WHERE PARAMETER LIKE '%SET';
PARAMETER                      VALUE
------------------------------ ------------------------------
NLS_NCHAR_CHARACTERSET         AL16UTF16
NLS_CHARACTERSET               WE8MSWIN1252

This means that:

*

*AL16UTF16 encoding (a 16-bit encoding of Unicode) is used to encode data in NVARCHAR2 variables, table columns and literals

*WE8MSWIN1252 (an 8-bit ASCII based Oracle Database character set) is used to encode data in VARCHAR2 variables, table columns and literals

Unfortunately WE8MSWIN1252 is CP-1252 code page, which does not support Russian cyrillic characters (like консэквюат etc).
See this link to know supported characters by this code page: en.wikipedia.org/wiki/Windows-1252.

Someone during installation has not considered Russian characters and probably choosen a bad code page. The documentation lists code pages that support Russian language (see Table A-13 Languages and Character Sets Supported by LCSSCAN and GDK):
https://docs.oracle.com/database/121/NLSPG/applocaledata.htm#NLSPG585

Russian
AL16UTF16, AL32UTF8, CL8ISO8859P5, CL8KOI8R, CL8MSWIN1251, RU8PC866,
  UTF8

You can observe an effect of using this code page in the following examples:
SELECT * FROM NLS_DATABASE_PARAMETERS
WHERE PARAMETER LIKE '%SET';
PARAMETER                      VALUE
------------------------------ ------------------------------
NLS_NCHAR_CHARACTERSET         AL16UTF16
NLS_CHARACTERSET               WE8MSWIN1252

select 'консэквюат' x, n'консэквюат' y from dual;
X          Y
---------- ----------
¿¿¿¿¿¿¿¿¿¿ консэквюат

and also:
create table test(
  v1 varchar2(100),
  v2 nvarchar2(100)
);

insert into test( v1, v2 ) values ('консэквюат', 'консэквюат' );
insert into test( v1, v2 ) values (n'консэквюат', n'консэквюат' );

select * from test;
V1              V2
--------------- ---------------
¿¿¿¿¿¿¿¿¿¿      ¿¿¿¿¿¿¿¿¿¿
¿¿¿¿¿¿¿¿¿¿      консэквюат

and also:
create FUNCTION function1( par varchar2 ) return varchar2
IS
BEGIN
  return par;
END;
/
create FUNCTION function2( par nvarchar2 ) return varchar2
IS
BEGIN
  return par;
END;
/
create FUNCTION function3( par varchar2 ) return nvarchar2
IS
BEGIN
  return par;
END;
/
create FUNCTION function4( par nvarchar2 ) return nvarchar2
IS
BEGIN
  return par;
END;
/

select function1( n'консэквюат' ) x1,
       function2( n'консэквюат' ) x2,
       function3( n'консэквюат' ) x3,
       function4( n'консэквюат' ) x4
from dual;

X1              X2              X3              X4
--------------- --------------- --------------- ---------------
¿¿¿¿¿¿¿¿¿¿      ¿¿¿¿¿¿¿¿¿¿      ¿¿¿¿¿¿¿¿¿¿      консэквюат

As you see from the above examples, only NVARCHAR2 values are properly stored and converted, any use of VARCHAR2 value causes a conversion to WE8MSWIN1252 code page and all Russian characters are lost.

What you can do in the current situation:

*

*Use NVARCHAR2 instead of VARCHAR2 datatype in all tables and stored procedures - you need to rewrite all database procedures, functions, triggers etc.

*Migrate your database to another character set that supports Russian language. This is not easy task and it's beyound this question, for details refer to the documentation: https://docs.oracle.com/database/121/NLSPG/ch11charsetmig.htm#NLSPG011 and disscuss this topic with your DBA


text:
Q: Images from network drive wont show when python script converted to exe I wrote small program to display images from network drive. It works perfectly when is launched as .py,
but when converted to .exe file (using auto-py-to-exe as one directory) program starts but not displays images and returns error "QPixmap::scaled: Pixmap is a null pixmap".
I have already tried:
path = "\\\\ow-sql\\Users\\file scanner\\Documents\\job_scans_copy\\20206\\012252988_30-06-2020-
    151531.jpg"

path = r"\\" + os.path.join("ow-sql", "Users", "file scanner", "Documents", "job_scans_copy","20206","012252988_30-06-2020-151531.jpg")

I also tried both \ and /.
I can't simply include file into the build as the files will change and new files will be added.
There is no problem with images from img. folder.
for example:
img = QPixmap("img\\image.jpg")

works perfect as an exe.
Would you advise me how to fix this problem?
Please find simplified code below:
import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton, QLabel, QScrollArea
from PyQt5.QtGui import QPixmap

class ApplicationWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        main_widget = QWidget(self)

        btn = QPushButton("Close", self)
        btn.clicked.connect(self.close)

        img = QPixmap("\\\\ow-sql\\Users\\file scanner\\Documents\\job_scans_copy\\20206\\012252988_30-06-2020-151531.jpg")
        label = QLabel(main_widget)
        pixmap_resized = img.scaled(200, 200)
        label.setPixmap(pixmap_resized)

        scrollArea = QScrollArea(main_widget)
        scrollArea.setWidgetResizable(True)
        scrollArea.setWidget(label)

        l = QVBoxLayout(main_widget)
        l.addWidget(scrollArea)
        l.addWidget(btn)

        self.setCentralWidget(main_widget)

    def closeEvent(self, ce):
        self.close()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    aw = ApplicationWindow()
    aw.show()
    app.exec_()

A: I resolved my problem simply by using cx_Freeze to create an executable and everything works perfect.
For some reason pyInstaller does not want to load the image into QLabel if it's not included in build. It doesn't matter if it's a path to the file or the file is loaded as a BLOB from the database. None of them works.
cx_Freeze solved the problem without any additional code changes.


text:
Q: Primary key for multiple columns? I have this MySQL Table, the PRIMARY KEY (ID).
ID  | COLOR   | SIZE
====================
| 1 |   RED   | 1  |
| 2 |   RED   | 2  |
| 3 |   RED   | 3  |
| 4 |   GREEN | 1  |
| 5 |   GREEN | 2  |
| 6 |   BLUE  | 1  |
===================

When i insert this row for example
INSERT INTO `test`(`COLOR`, `SIZE`) VALUES (RED',1);

i have a duplicate row
1, RED, 1
and
7, RED, 1
how to avoid this problem?
Thanks

A: You can use alter table
ALTER TABLE `test`
ADD UNIQUE (color, size)

A: Before you run this empty your table first or remove the duplicate row from your table than run it.
ALTER TABLE  `test` ADD UNIQUE (color, size)


text:
Q: Text box next to image and another image i'm having trouble with some css/html again, i want text, then two images next to it, the first (most outside) div is the width of the page as it just works as a 'background color strip' and then within this div i want another div 950px X 250px and within that div 480px x 250px for the images on the right (which i have managed kind of) but when i add text it pushes them down.
i need the text to be on the left, the images to be on the right (just two seperate divs) containted within the content div, which is centered in the background div.
all divs need to be the same height.
the code is below
CSS
.greybackground {
background-color: #eee;
height: 230px;
width: 1920px;
margin-right: auto;
margin-left: auto;
margin-top: 10px;

}

.greybackgroundcontent {
height: 250px;
width: 950px;
margin-right: auto;
margin-left: auto;

}

.greybackgroundimage {
height: 250px;
width: 480px;
margin-left: 490px;
display:inline-block;

vertical-align:middle;

}

HTML

KLEENZONE KLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE

A: Try this,

Kleenzone can cater to cleaning of all applications and sizes.

A: Hope this helps.
FIDDLE
CSS
.greybackground {
    background-color: #eee;
    height: 230px;
    width: 1920px;
    margin-right: auto;
    margin-left: auto;
    margin-top: 10px;

    }

    .greybackgroundcontent {
    height: 250px;
    width: 950px;
    margin-right: auto;
    margin-left: auto;

    }

    .greybackgroundimage {
    height: 250px;
    width: 480px;
    /*margin-left: 490px;*/
    display:inline-block;
    float:right;
    vertical-align:middle;
    display: inline;

    }

UPDATED QUERY:
Updated Fiddle
Css issue,Now solved working fine in IE7 onwards.. Check this updated code,if you have any doubt let me know.
CSS
.greybackgroundimage {
    width: 480px;
    /*margin-left: 490px;*/
    height:100%;
    vertical-align:top;
    display: inline;

    }

LAST UPDATED
Now div is seperated with 2 sides horizontally with same height which you asked.
Just put this code in your browser then check it...
HTML

KLEENZONE KLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE
KLEENZONEKLEENZONEKLEENZONEKLEENZONEKLEENZONE

CSS
.greybackground {
background-color: #eee;
width: 100%;
margin-right: auto;
margin-left: auto;
margin-top: 10px;
}
.greybackgroundcontent {
background-color: #eee;
height: 250px;
width: 950px;
margin-right: auto;
margin-left: auto;
}
#greybackgroundtext,#greybackgroundimage {
height: 250px;
 width:50%;
float:left;
display:inline-block;
vertical-align:middle;
}

A: You can use table format to display the text and images side by side.
Apply the css to tr elements instead of div elements.


text:
Q: Touchpad stops working at reboot. Module missing I have Dell Inspiron 7591 installed with dual boot Ubuntu 18.04.5 LTS and Windows 10.
On installation touchpad was not working. The module i2c_hid seemed missing. When the module was loaded, touchpad started working fine. Although the module needs to be re-loaded every time after the reboot. Is there any way that the touchpad stays functioning without manually loading the module?
I tried Myx's answer. It didn't work.
Feel free to ask for any required details.

A: Try this solution. This will fix touchpad issue on dell

A: You may try "modprobe i2c_hid_acpi". This Tip comes from the Fujitsu Laptop community. Make it a systemd service !
Actually my Fujitsu E 5511 Lifebook E5511MF5BMDE needs this help only for touchpad. Works fine now. Tested with Ubuntu 22.04beta and 20.04.4LTS.
My older E5510 needed "modprobe i2c_hid" to do anything with input. Make it a systemd service ! Fujitsu E Laptops rock. ELAN does not always ...


text:
Q: crash in a Qt app in my reimplementation of QApplication::notify() I have a crash which occur seldom  (one times or two times per day).
I develop under MSVC2010 and in order to understand what's in going on, I debug using the "attach to process" feature provided by MSVC.
Each times the application crash the debugger break inside my reimplementation of QApplication::notify() which is very simple  :
bool AutomateQtApplication::notify(QObject *rec, QEvent *ev)
{
        return QApplication::notify(rec, ev);
}

the call stack is just about QtGui.dll (not the line of source code juste QtGui.dll) so no help..
Any ideas of what I can do to discover where is the bug or what's going wrong ?
Many thanks.


text:
Q: What is that thing that keeps showing in papers on different fields? A few months ago, when I was studying strategies for the evaluation of functional programs, I found that the optimal algorithm uses something called Interaction Combinators, a graph system based on a few nodes and rewrite rules.

I've implemented and got some surprising results with it. I tried learning more, only to realize there are very few papers and almost nobody talking about it. Another day, by sheer luck, I stumble with this paper about chemical computers that would be "the future of computation". Midway through my read, I see this:

The similarity to Interaction Nets in striking. The nodes, the rules, the principal ports - on its core, the system is mostly the same. I tried looking at references to find more about "it", but didn't find anything very relevant, so I gave up. Another day, by sheer luck once again, I sumble with this blog post about some kind of graphical linear algebra that "can divide by zero". Midway through the read, I see this:

Once again, the same "thing" can be seen. There are some minor differences but, on its core, it is the same. What is that thing in common with those systems? How is it called, what is its importance, where is it studied and, most importantly, why it keeps showing in completely different fields?

A: First, this is not the only spot where bizarre squiggly lines are used to represent deep concepts. There are things such as Feynmann diagrams,

circuit diagrams,

Petri nets,

and others. So this isn't the only spot where this type of thing is used. These things are called string diagrams and were first used by Roger Penrose in Combinatorial Mathematics and its Applications and Spinors and Spacetime for calculating with tensors.
The concept uses Poincaré duality to represent structures of dimension $d$ by structures of dimension 2-$d$. Objects are represented by portions of a plane, a 1-cell is represented by a vertical segment (or string) separating the plane into two, and a 2-cell is represented by an intersection of strings. Monoidal categories can be pictured this way, and the graphical language may be extended to represent expressions in categories with other structures, such as symmetric monoidal categories, and dagger categories.
Hope this helps!
References:
These are a few sites/papers that have good information (and good citations) about this topic; I'll be adding more as I find them:

*

*Wikipedia article

*The Geometry of Tensor Calculus, I by André Joyal

A: The whole field of operad theory (and properads, and props) studies this kind of things. I think you could take a look at the theory of algebraic operads. If you are interested in learning more, here are some references:

*

*A very gentle introduction is the paper Algebra + Homotopy = Operad by B. Vallette.

*More technical, but a lot more complete, almost up to date with current research is the book by Loday-Vallette, which you can find here in pdf version.

Let me know if you want some details on specific topics, and I'll see if I'm able to answer.
PS: The last diagrams you wrote down remind me a lot of Hopf algebras. (Of course, there is a prop - if I'm not wrong, could be a properad; I'm not really sure of the difference between the two, I only know operads decently enough - coding them.)


text:
Q: how to insert multiple records from text to mysql db with php how to insert many records to database from text area at one time instead of inserting them one after the other because it takes a long time if you have alot of records
1 - writing data to text area in this way
#fname-1980-74
#sname-1994-84
#lname-1990-54

2 - every line will be inserted to database as an Independent record
3 - this is the Best code And The Must Shortcuted Code that you have to use :
$txt = "#fname-1980-74#sname-1994-84#lname-1990-54";
foreach (explode('#' , $txt) as $line) {
    echo $line = str_replace('-' , ',' , $line);
}
My greetings for all .

A: <?php

$txt = "@fname-1980-74#@sname-1994-84#@lname-1990-54#";

// strip first @ and last #
$txt = substr($txt, 1);
$txt = substr($txt, 0, strlen($txt) - 1);

$values = array();
$parts = explode('#@', $txt);
foreach ($parts as $part) {
    list($name, $year, $number) = explode('-', $part);
    $values[] = "($name, $year, $number)";
}

$query = "
INSERT INTO mytable(name, year, number) VALUES
" . implode(',', $values) . ";";

echo $query;

A: code:
$txt = "@fname-1980-74#@sname-1994-84#@lname-1990-54#";
foreach ( explode( '#', $txt )  as $line ) {
    $line = str_replace( '@' , '' , $line );
    if ( empty( $line ) ) continue;
    echo '(' . implode( ',', explode( '-', $line ) ) . ')'.PHP_EOL;
}

output:
(fname,1980,74)
(sname,1994,84)
(lname,1990,54)


text:
Q: Refresh token in Gmail API? After successful login, I am getting access token, expire token type, and this stuff in my console by "console.log("my response ",response)". But there is no refresh token. how to get a refresh token.
And 2nd question is, How to get an access token using a refresh token?
I am using JavaScript.
And guide me is this a best way way to get an access token?
Successful login is not giving refresh token, without refresh token how can I refresh my access token?
Here is my code
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>FIFV Dashboard</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
  <link rel="stylesheet" href="home.css">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css">

      <form>

 Welcome to
      FIFV authentication

Please authenticate yourself to get access to the dashboard.

      <button onclick="authenticate().then(loadClient)" type="button" class="btn">Authorise</button>

      </form>

A: I was reviewing the Google Documentation for JavaScript, and I found the following sample that might help you:
 if (gapi.client.getToken() === null) {
          // Prompt the user to select a Google Account and ask for consent to share their data
          // when establishing a new session.
          tokenClient.requestAccessToken({prompt: 'consent'});
        } else {
          // Skip display of account chooser and consent dialog for an existing session.
          tokenClient.requestAccessToken({prompt: ''});
        }
      }

You can read more information about this here, and information about the refresh token can be found here.
Lastly, you can read the information in this question. It has a lot of information about the refresh token.


text:
Q: keep track of user progress without requiring login asp.net mvc I created a website which loads an a question pool from an XML file and generates random tests for my users to practice for an exam.  Some of the tests take a while for the user complete, and they may not finish it all in one sitting, so I would like for people to be able to come back later and finish up their tests during multiple sessions.  The catch is, I would like to do this without requiring the user to go through a signup/login process.  I just want to store the current state of the randomized practice test somewhere and then somehow they come back to it and pick up right where they left off.  It is also important that other people cannot modify other peoples tests if that is avoidable.
My current plan is to generate a GUID for each test, store serialized XML of the current state in a database, give the user a unique URL to return to and ask the user to input a password when they start/return to a test.  Once they finish the test, or a set time passes with no activity, I would destroy the test to keep the database clean.
Am I overlooking any problems with accomplishing my goal?  What other ways would you accomplish this task in ASP.NET MVC (2)?

A: Persistent cookies on users computers comes to mind. You might store the user state in a database and sore the primary key in a cookie which will allow you to later identify users. Of course this approach has limitations and might not be applicable in your scenario.

A: The scenario you describe is comparable to an anonymous user when you use the built in Membershipsystem/Profilesystem of ASP.NET. You could try to start with that.


text:
Q: Node.js: zlib.gzipSync() I have a few questions on zlib module, to be used with files under 40MB:

*

*What kind of options should be used in zlib.gzipSync() for fastest zipping (compression level does not matter)?

*Which default values is used, if options is not passed to the method?

*Is this method returns Buffer?

*What kind of extension and mime type should be used for final result?

*Update: How to pass a file name? (So after unzipping file has name and extension)

Asked because reference is not expressive.

A: Yeah, not much to go on in that documentation.
I recommend that you look at the zlib manual (the zlib.h source file) for information on the noted parameters and operations.
The fastest compression would be level 1.
The default compression level is 6.  Other defaults can be found in zlib.h.
There does not appear to be an interface to deflateSetHeader(), which would be required to insert a file name in a gzip header.

A: The docs describe the options object used for every zlib call.  They also point you to the zlib manual which describes those options in great detail.
The fastest level is 0, which means no compression.  However, this would be silly, since you may as well skip gzipping altogether.  1 means "some compression with best speed."
That said, don't use gzipSync.  We don't do things synchronously in node.  If you're looking to write the compressed data to a file, do:
var compressor = zlib.createGzip({level: 1});
compressor.pipe(fs.createWriteStream('output.gz'));

compressor.end(inputData);


text:
Q: hasClass Dynamic variable not working I wrote the below code but it won't work. Kindly advice

DANCE

ABOUT

Preview

$('a[data-toggle="tab"]').on('click', function (e) {
  if($('.globalPreview').hasClass($(this).text())){
     $('.globalPreview').show();
  }
});

here is the jsfiddle of this working code
Demo Working Code

A: Jsfiddle
$('a[data-toggle="tab"]')

change to
$('a[href^="#tab"]')


text:
Q: Lazy initialization inside willSet issue I'm trying to create optional array, but I want the initialization to be only before appending element into.
So I wrote:
    var names: [String]? {
        willSet {
            if names == nil {
                names = []
            }
        }
    }

But I get this error:

Attempting to store to property 'names' within its own willSet, which
  is about to be overwritten by the new value

A: If you want a lazy bar then you should do it like...
lazy var names: [String] = []


text:
Q: What are the strategies to send and retry a delayed API call? I have a customer-facing website that runs a Ruby on Rails app. Users place orders and they are synced using a series of background rake tasks to the internal ERP system. Every 30 minutes.
We are rebuilding internal systems, as RoR API style app, so web application would basically just send api calls to the internal application when an order is saved . Using something like ActiveResource or ROAR & Delayed Job or something else.
However if internal API goes down for some reason - what are a good strategies to save that customer order on the web server, and then sync it to API when it becomes available? It's kind of similar to what happens on the iPhone / Android - where it can save info locally and sync it later to the cloud API. Except client is a RoR server application. Are there ready made solutions for this? Or should I implement my own "Save to local DB -> sync to API asynchronously when it comes back" type solution?

*

*Web Application: RoR + jQuery basic CRUD type app, nothing fancy.
Sits in a public cloud.

*Internal API: - RoR + Trailblazer API, using MariaDB
cluster sits in in-house Data Center, behind firewall.

A:
Are there ready made solutions for this?

No.

Or should I implement my own "Save to local DB -> sync to API asynchronously when it comes back" type solution?

Yes. It's a relatively straight-forward mini-project. I did it yesterday, in fact. Took only a few hours.
For local storage, I use postgresql (I host on Heroku).
I use an NfpAdmin::ServiceRequest record to keep track of the results of each transaction attempt. It looks something like this:
  # == Schema Information
  #
  # Table name: nfp_admin_service_requests
  #
  #  id               :integer          not null, primary key
  #  service_name     :string
  #  status           :string           default("created")
  #  percent_complete :integer          default(0)
  #  details          :jsonb            not null
  #  created_at       :datetime         not null
  #  updated_at       :datetime         not null
  #

  class NfpAdmin::ServiceRequest < ActiveRecord::Base
    serialize :details, HashSerializer
    validates :service_name,
              :details,
              presence: true
  end

I run a nightly job using CloudAMQP and pull (using my real service_name, naturally):
  NfpAdmin::ServiceRequest.where(service_name: 'foo').where.not(status: 'complete')

In the jsonb column (details), I keep track of every attempted transaction for that service request, outcomes, error messages, etc.
Currently, I receive push messages from the remote API (a third party) and do pull requests. The API allows for updates from my system, but my use cases don't call for that yet.
I run a series of my own API web services in which I do 2-way data exchange.


text:
Q: The kinematic region for the operator product expansion In Ch.18 of the textbook An Introduction to Quantum Field Theory by Peskin and Schroeder, on P.613 the operator product expansion (OPE) is introduced
$$\mathcal{O}_1(x)\mathcal{O}_2(0)\to \sum_n C_{12}^n \mathcal{O}_n(0)\ .\tag{18.64}$$
The expansion is carried out for small $x$, and therefore for large momentum transfer. Subsequently, in section 18.4, the OPE is illustrated by the $e^+e^-$ annihilation process, where the r.h.s. of the above equation corresponds the vacuum polarization:
$$i\Pi_h^{\mu\nu}(q)=-e^2\int d^4 e^{iq\cdot x}<0|T\{J^\mu(x)J^\nu(0)\}|0>\ ,\tag{18.88}$$
where $q$ is the sum of the four momenta of electron and positron, $q=k+k_+$.
The OPE is specified in (18.89). Above (18.94), the text reads

Still assuming the Fourier transform of the product of currents can be computed from the OPE for the region of large time-like $q^2$, we can complete our evaluation of the cross section for $e^+e^-\to$hadrons by the vacuum expectation value ... We find

$$\sigma(e^+e^-\to\mathrm{hadrons})\\=\frac{4\pi\alpha}{s}[\mathrm{Im}\  c^1(q^2)+\mathrm{Im}\ c^{\bar q q}(q^2)<0|m\bar qq|0>+\mathrm{Im}\ c^{F^2}(q^2)<0|(F_{\alpha\beta}^2)|0>].\tag{18.94}$$
Shortly after that, it is stated that in order to calculate $\Pi_h(q^2)$ by using the leading perturbative QCD contributions shown in Fig.18.5. One should

... choose kinematic conditions such that the intermediate states that enter the computation of the product of currents are far off-shell, so that they cannot propagate far from the converging points $x$ and $0$.

I understand the following: the physical problem requires that $q^2$ is large and time-like (in the CM frame of reference and thus in any frame of reference). However, in order to evaluate the perturbative QCD contributions relatively easily, it requires that $q^2$ is large and to stay away from physical region, so that no hadron is formed, or otherwise one has to deal with soft process (to form hadron) and the problem becomes more difficult to proceed. This is the reason why the ITEP sum rule is utilized subsequently. Is it correct?
Please point me toward correct direction if I am wrong, and if my understanding is correct, are the discussions provided in the textbook a general argument? In other words, if one want to use perturbative QCD, one should always avoid the region of physical momentum to avoid significant contribution from the soft process to form intermediate hadron states. The arguments seem somewhat hand-waving, is there any alternative explanation?

A: Maybe I understand a little better now.
For a real physical process, one requires that $q^2$ is large and time-like (by evaluating $q^2$ in the CM frame of reference and thus in any frame of reference). However, in order to evaluate the perturbative QCD contributions relatively easily, it requires that $q^2$ is large. In principle, if one only considers that $x$ has to be small enough for the OPE to work reasonably well, $q$ can be time-like or space-like. But in order to stay away from singularities or cuts which might invalidate the perturbative treatment, which is also associated with the physical region, one usually goes to the space-like region of $q$ where no hadron is formed and subsequently employs perturbative QCD to evaluate things and then expands the results in terms of $1/q^2$. As one attempts to connect these two calculations, one assumes that the singularities or cuts are only related to physical states, and employ the contour integration to obtain the so-called QCD sum rule.


text:
Q: AspNet Core 2.1 Identity - External login user log out not persisting I just implemented AspNetCore Identity into my AspNetCore 2.1 MVC Web app. I am have not made any "custom" changes to the Identity code. I have local logins enabled with AspNetUsers table in my DB. I have enabled Google and Twitter logins in my app. They both work perfectly, users are getting redirected to the respective social platform login pages and then getting sent back to app page. This all works perfectly!
The issue comes in when the Google or Twitter user logs out. The app directs the user to the Log out.cshtml page and executes the below method.
public async Task<IActionResult> OnPost(string returnUrl = null)
{
    await _signInManager.SignOutAsync();
    _logger.LogInformation("User logged out.");
    if (returnUrl != null)
    {
        return LocalRedirect(returnUrl);
    }
    else
    {
        return Page();
    }
}

After the logout is executed the user is redirected to the home page of my app. Then when that same users decides to log back into the app, they are taken to the login page. On the login page, when the user clicks the Google or Twitter button to login, they are seamlessly logged into the app without getting prompted for user Id/password anywhere. I ran this code in debug and it all works without any errors. I can even see the authentication cookie getting removed from Chrome console.
Here is how I have Identity setup in my Startup.cs.
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
    //lockout settings
    options.Lockout.AllowedForNewUsers = true;
    options.Lockout.MaxFailedAccessAttempts = 3;
    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
    // Password settings
    options.Password.RequireDigit = true;
    options.Password.RequiredLength = 8;
    options.Password.RequiredUniqueChars = 2;
    options.Password.RequireLowercase = true;
    options.Password.RequireNonAlphanumeric = true;
    options.Password.RequireUppercase = true;
    // Signin settings
    options.SignIn.RequireConfirmedEmail = true;
    options.SignIn.RequireConfirmedPhoneNumber = false;
    // User settings
    options.User.RequireUniqueEmail = true;
})
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddUserManager<EXLNTUserManager>()
    .AddDefaultTokenProviders();

//Google authentication
services.AddAuthentication().AddGoogle(googleOptions =>
{
    googleOptions.ClientId = Configuration["GooglePlusApi:client_id"];
    googleOptions.ClientSecret = Configuration["GooglePlusApi:client_secret"];
});

//Twitter authentication
services.AddAuthentication().AddTwitter(twitterOptions =>
{
    twitterOptions.ConsumerKey = Configuration["TwitterApi:ConsumerKey"];
    twitterOptions.ConsumerSecret = Configuration["TwitterApi:ConsumerSecret"];
});

I have read the MS Docs multiple times and followed them step by step to implement these social logins. Not sure what I am missing here. I hope someone can help me out here!


text:
Q: Prove that for the primitive root $[g]$ modulo p we have $[g]^m=[g]^n \iff p-1\mid m-n$ Prove that for the primitive root $[g]$ modulo $p$ we have $[g]^m=[g]^n \iff p-1\mid m-n$.
Proof: We know
If $g$ is a primitive $p$-root of unity, then $g^n\equiv 1 \pmod p \iff (p-1)\mid n$. Hence if $n$ is not divisible by $(p-1)$ we have $s_n(p)\equiv 0 \pmod p$. Similarly, If $g$ is a primitive $p$-root of unity, then $g^m\equiv 1 \pmod p \iff (p-1)\mid m$. Hence if $m$ is not divisible by $(p-1)$ we have $s_m(p)\equiv 0 \pmod p$.
Can I use these statements to prove the statement above?

A: We have $g^m = g^n$, so multiply through by $(g^n)^{-1} = g^{-n}$:
$$g^{m-n} \equiv 1 \pmod{p}$$
Since $g$ is a generator of the multiplicative group $\mathbb{Z}_p^\times$, then the above holds $\iff$ $m-n$ is a multiple of $|g| = |\mathbb{Z}_p^\times|= p-1$.

A: Hint: $\mathbb{Z}_p^{\times}$ is a group and  the order of $g$ is $p-1$


text:
Q: Setup for evaluating $\iint_R y^2dA$ $\iint_R y^2dA$, where D is the triangular region with vertices $(0,1)$, $(1,2)$, $(4,1)$.
I was trying to do this problem, and ended up with the wrong answer, $\frac{28}{13}$, instead of the correct answer of $\frac{11}{3}$. I checked my integrations on symbolab and those where coming out right, so it seems like maybe my bounds for the integrals were wrong. I got $D={(x,y)| 0<=x<=4,1<=y<=2}$ And integrated with respect to $x$, and then $y$. Is that correct? I did I figure those wrong?

A: Let's convert the double integral to an iterated integral with integration order $dxdy$, since the region is horizontally simple.
$R$ is bounded above by the line $x=7-3y$ and below by $x=y-1$ from $y=1$ to $y=2$. Thus the integral becomes:
$$\iint_R y^2dA=\int_1^2 \int_{y-1}^{7-3y}y^2dxdy=\int_1^2y^2x\Big{|}_{y-1}^{7-3y}dy=\int_1^28y^2-4y^3dy.$$
I trust that you can take it from here? If not, please tell me.


text:
Q: Do while loop won't break? I'm working on this as a function for a class project, but I can't figure out why the loop won't break when the user enters "N". It just keeps looping no matter what the user enters when asked if they want to continue.
Can someone help me get the loop to break properly? That's the only part of the code that isn't working.

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

const string ADDRESS_FILE_NAME = "Address.csv";

int main()
{
    string name;
    string street;
    string city;
    string state;
    string zip;
    char input;
    //TODO: Declare variables for name and address fields

    ofstream inputAddress(ADDRESS_FILE_NAME);

    //TODO: Open address file for output using ofstream()

    do{
    cout << "Enter name: " << endl;
        getline(cin, name);
        cin.ignore();
    cout << "Enter street name: " << endl;
        getline(cin, street);
        cin.ignore();
    cout << "Enter city: " << endl;
        getline(cin, city);
        cin.ignore();
    cout << "Enter state: " << endl;
        getline(cin, state);
        cin.ignore();
    cout << "Enter zip code: " << endl;
        getline(cin, zip);
        cin.ignore();
    cout << "Enter another address? (Y/N)" << endl;
        cin >> input;
        cin.ignore();
    }while(input != 'N' && 'n');
    return 0;

    //TODO: Loop to accept and write addresses
    //    Prompt user to enter name and address fields
    //    Write entered data to address file separated by commas
    //    Ask user if more addresses to enter
    //    Repeat loop while user responds 'Y' or 'y'

    inputAddress.close();
    //TODO: Close address file

}