text:
Q: Generics error: more specific type does not coform to more generic type I have the following snippet of code:
private class SectionConversionMap
  extends HashMap[SectionSchema[_], ( Iterable[HtmlRow] ) => Option[Iterable[_]]] {
private type Value[Vt] = ( Iterable[HtmlRow] ) => Option[Iterable[Vt]]
private type SuperKV = (SectionSchema[_], Value[_])

def +[T](kv: (SectionSchema[T], Value[T])):
HashMap[SectionSchema[_], ( Iterable[HtmlRow] ) => Option[Iterable[_]]] = {
  super.+(kv: SuperKV)
}
def get[T](key: SectionSchema[T]): Option[Value[T]] = {
  super.get(key) match {
    case v: Some[Value[T]] => v
    case _ => None
  }
}
}

The issues is that my IDE says (in the + method's body, kv: SuperKV) that
Expression of type (SectionSchema[T], SectionConversionMap.this.Value[T]) does not conform to expected type  (SectionSchema[_], SectionConversionMap.this.Value[_])
How is that possible? The second one is more generic.

A: The underscore isn't the equivalent of "?" in Java, although much of the time it can be used in the same way. "_" is for specifying higher-kinded types and that does seem to be, more or less, what you're trying to do here, though I think your code could do with some cleanup of the way types are defined.
Nevertheless, you can make your code compile with the simple expedient of replacing HashMap with Map. Was this an oversight on your part? I can't see any reason why you would want to try to extend HashMap instead of Map (my compiler actually gives a warning about that too).


text:
Q: How to use SWIG %pointer_class with typedef types? If I have these two C++ files:
foo.cpp:
#include "foo.h"

void foo(Foo* p) {};

foo.h:
class Foo {};

void foo(Foo*);

I can write this SWIG interface
%{
    #include "foo.h"
%}

%include <cpointer.i>
%pointer_class(Foo, Foop)

%include "foo.h"

compile, and call
>>>p = Foop()
>>>foo(p)

How do I write the interface if Foo is typedef instead
typedef int Foo;

so that I can do the same Python calls as above?

A: I don't think %pointer_class is meant to be used with a typedef.  SWIG considers a typedef the same as the original type and doesn't generate a wrapper for the typedef-ed name.  For example, SWIG only generates Bar for Python:
%module x

%inline %{
class Bar {};
typedef Bar Foo;
void foo(Foo* p) {};
%}

Output:
>>> import x
>>> x.Foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Foo'
>>> p=x.Bar()
>>> x.foo(p)
>>>

So I believe your case with typedef int Foo; and %pointer_class(Foo, Foop) doesn't work because the Foo wrapper doesn't exist.  I found that the below "trick" works for a class and an int if you use a typedef in both cases and use the same value for both parameters of %pointer_class:
%module x

%inline %{
  class Bar {};
  typedef Bar Foo;
  void foo(Foo* p) {};
%}

%include <cpointer.i>
%pointer_class(Foo, Foo)  // doesn't work if 2nd param doesn't match 1st.

And:
%module x

%inline %{
  typedef int Foo;
  void foo(Foo* p) {};
%}

%include <cpointer.i>
%pointer_class(Foo, Foo)  // doesn't work if 2nd param doesn't match 1st.

But if you really want an opaque type, don't let SWIG see the definition at all by only forward declaring the class and hiding the definition:
%module x

%inline %{
class Foo;
void foo(Foo* p);
%}

%include <cpointer.i>
%pointer_class(Foo, Foop)

redpajama_set_name: RedPajamaStackExchange


text:
Q: page 140 quiz questions I'm working right now at present to make a quiz page to my friends about firefighter training. and I'm thinking about whether I can do it with javascript or should I do it with php?. where there are about 140 questions but I will start to build so there are only 10 questions to start with :)
I never try to do anything like that before so hope you can help me to the right and explain to me how to do it and help me further.
I think such a little like this:
<?php
if(isset($_POST["ok"] == 1)
{
    echo "TRUE!";
}
elseif(isset($_POST["ok"] >= 1)
{
    echo "FALSE!";
}
?>
<form action="#" method="post">
<input type="checkbox" name="1" />
Bla bla bla

<input type="checkbox" name="2" />
Bla bla bla

<input type="checkbox" name="3" />
Bla bla bla

<input type="submit" name="ok" value="Ok" />
</form>

It's probably not such but it must be such clicks on Mon such as it is true then it must be in it or look like in the still hope you can follow me in what I would like to have built?

A: Be a little clearer with your question. What exactly are you trying to accomplish?
If you write the quiz in PHP, then you will have to have the answers revealed after a form submission. This can be accomplished either with redirection, or AJAX through JavaScript.
If you write the answer checking in JavaScript, then all of the logic will be done client side, rather than server-side. This is the method I would recommend, as it will accomplish the same thing, and would really be much more simple for this task, as it doesn't seem you are really looking for security in this quiz.
Pretty much, go with PHP if you are looking for some something secure, JavaScript if you are doing it for fun.


text:
Q: Value Error: Incompatible layer in prediction method During my training steps, I am using predict method to keep track of the test error at each iteration. For instance, when I call the method at a given step with the array shown below.
 [[ 85.  99.   1.  39.  97.  45.  73.  26.  11.  93.]
 [ 85.  99.   1.  39.  97.  39.  73.  22.  16.  93.]
 [ 31.   5.   5. 100.  86.   5.  61.  38.  12.  65.]
 [ 31.   7.  15. 100.  86.  16.  61.  38.  57.  65.]
 [ 73.   4.  22.  21.  14.  49.  27.  54.  94.  87.]
 [ 73.   1.   6.   2.   2.  49.  27.  54.  94.  87.]]

I am getting my prediction result properly as
[[288.843  ]
 [297.50165]
 [214.63228]
 [234.74095]
 [240.8646 ]
 [238.9101 ]]

where the function that I call is
print(model.predict(my_data_set))

For some reason, I am receiving an incompatible layer error, when I call print(model.predict(my_data_set[0])) which corresponds to the first row of my data set.
ValueError: Input 0 of layer dense_22 is incompatible with the layer: expected axis -1 of input shape to have value 10 but received input with shape (None, 1)

When I print my_data_set[0], what I obtain is [ 85.  99.   1.  39.  97.  45.  73.  26.  11.  93.]
I just don't know what potentially I am doing wrong.

A: You should consider the batch dimension for your input data. Your input data shape should be like (number_of_samples, number_of_features) (a 2D array).
When you pass my_data_set it is a 2D array, and its shape represents (6 samples, 10 features), but when you pass my_data_set[0] it is a 1D array and its shape is like (10 features), while it should be 2D like (1 sample, 10 features).
Check it like this:
print(np.array(my_data_set[0]).shape)
# (10,)
print(np.array(my_data_set[0]).reshape(1,-1).shape)
# (1, 10)

So, try to pass it like this to add the first dimension as 1:
model.predict(np.array(my_data_set[0]).reshape(1,-1))


text:
Q: I want to hide my main window and then open new window(tkinter) Could you help me? I'm trying to close my main window and then create a new window. I'm using withdraw() instead of destroy() since I'm planning to use that widget later.
Here is my code, but I just get:  tkinter.TclError: image "pyimage10" doesn't exist
I separated the codes of the main window and a new window into two python file, which are "Page1" and "Page2".
Sorry for my rough English.
Any help to fix this would be much appreciated:)
tkinter.TclError: image "pyimage10" doesn't existseems to occur at image_2 = canvas.create_image(
Page1
    from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage

   OUTPUT_PATH = Path(__file__).parent
   ASSETS_PATH = OUTPUT_PATH / Path("./assets")

   def relative_to_assets(path: str) -> Path:
       return ASSETS_PATH / Path(path)

   window = Tk()

   window.geometry("703x981")
   window.configure(bg = "#FFFFFF")

     button_image_6 = PhotoImage(
         file=relative_to_assets("button_6.png"))
     button_6 = Button(
         image=button_image_6,
         borderwidth=0,
         highlightthickness=0,
         command=lambda: ("WM_DELETE_WINDOW", nextPage()),
         relief="flat"
     )
     button_6.place(
         x=415.0,
         y=793.0,
         width=86.0,
         height=78.0
     )

    def nextPage():
        window.withdraw()
        import Page2

Page2

from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage

window = Tk()

def relative_to_assets(path: str) -> Path:
    return ASSETS_PATH / Path(path)

window.geometry("545x470")
window.configure(bg = "#FFFFFF")

window.title('PythonGuides')
canvas = Canvas(
    window,
    bg = "#FFFFFF",
    height = 470,
    width = 545,
    bd = 0,
    highlightthickness = 0,
    relief = "ridge"
)

canvas.place(x = 0, y = 0)
image_image_2 = PhotoImage(
    file=relative_to_assets("image_2.png"))
image_2 = canvas.create_image(
    272.0,
    175.0,
    image=image_image_2
)

A: Maybe it's happening because the image you are trying to add on the button is not present where you are trying to access it from.
And seems you have missed this:

*

*You didn't pack the button

*You didn't run the .mainloop() i.e window.mainloop()

*and what does the :
[enter the image description here][1]
is meant to do ?
I didn't use this and the code ran perfectly fine.

A: This error is caused by having multiple instances of Tk. Having multiple instances of Tk can cause errors. Use Toplevel instead for additional windows.
Change window = Tk() to window = Toplevel() in Page2. You will also need to add Toplevel to your import list.


text:
Q: Ошибка не отображается в списке ошибок Visual Studio 2015 Ошибки в коде перестали отображаться в списке ошибок. Проект давно не запускал, переустановил винду на вин 10 и заново установил визуалку с момента последнего запуска проекта.

После того как очистил и пересобрал.

Подозрительная ошибка сообщающая о невозможности проанализировать весь проект.


text:
Q: Prove that if $X$ is a Hilbert space, then $B(X)$ is not a Hilbert space I`m having a homework question that goes like this: X is a Hilbert space, a complete inner product space, show that B(X) is not a Hilbert space.
I`m quite stuck and I would love to understand this problem!
My attempt so far:
Let $T \in B(X)$ be a linear operator, $\exists M > 0$ such that $||Tx|| \leq M||x||$, $\forall x \in X$. ( $T: X \rightarrow X$)
$T_n$ is a Cauchy sequence in $B(X)$ such that $T_n \rightarrow T$.
I think I have to show that $B(X)$ is not complete under the norm $||x||=\sqrt{(x,x)}$, so show that $B(X)$ is open. I can also show that the parallelogram law isnt satisfied, but I dont see how.
Proof:
$\forall \epsilon > 0 $, $\exists N \in \mathbb{N}$ such that $||T_n-T|| < \epsilon $.
Also we have $||T_nx-Tx|| \leq ||T_n-T||||x|| < \epsilon||x||$ $\forall, x \in X$.
I dont know how to get further, please help!


text:
Q: How to use Basemap (Python) to plot US with 50 states? I am aware that the powerful package Basemap can be utilized to plot US map with state boundaries. I have adapted this example from Basemap GitHub repository to plot 48 states colored by their respective population density:

Now my question is: Is there a simple way to add Alaska and Hawaii to this map and place those at a custom location, e.g. bottom left corner? Something like this:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap as Basemap
from matplotlib.colors import rgb2hex
from matplotlib.patches import Polygon
# Lambert Conformal map of lower 48 states.
m = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
        projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
# draw state boundaries.
# data from U.S Census Bureau
# http://www.census.gov/geo/www/cob/st2000.html
shp_info = m.readshapefile('st99_d00','states',drawbounds=True)
# population density by state from
# http://en.wikipedia.org/wiki/List_of_U.S._states_by_population_density
popdensity = {
'New Jersey':  438.00,
'Rhode Island':   387.35,
'Massachusetts':   312.68,
'Connecticut':    271.40,
'Maryland':   209.23,
'New York':    155.18,
'Delaware':    154.87,
'Florida':     114.43,
'Ohio':  107.05,
'Pennsylvania':  105.80,
'Illinois':    86.27,
'California':  83.85,
'Hawaii':  72.83,
'Virginia':    69.03,
'Michigan':    67.55,
'Indiana':    65.46,
'North Carolina':  63.80,
'Georgia':     54.59,
'Tennessee':   53.29,
'New Hampshire':   53.20,
'South Carolina':  51.45,
'Louisiana':   39.61,
'Kentucky':   39.28,
'Wisconsin':  38.13,
'Washington':  34.20,
'Alabama':     33.84,
'Missouri':    31.36,
'Texas':   30.75,
'West Virginia':   29.00,
'Vermont':     25.41,
'Minnesota':  23.86,
'Mississippi':   23.42,
'Iowa':  20.22,
'Arkansas':    19.82,
'Oklahoma':    19.40,
'Arizona':     17.43,
'Colorado':    16.01,
'Maine':  15.95,
'Oregon':  13.76,
'Kansas':  12.69,
'Utah':  10.50,
'Nebraska':    8.60,
'Nevada':  7.03,
'Idaho':   6.04,
'New Mexico':  5.79,
'South Dakota':  3.84,
'North Dakota':  3.59,
'Montana':     2.39,
'Wyoming':      1.96,
'Alaska':     0.42}
# choose a color for each state based on population density.
colors={}
statenames=[]
cmap = plt.cm.hot # use 'hot' colormap
vmin = 0; vmax = 450 # set range.
for shapedict in m.states_info:
    statename = shapedict['NAME']
    # skip DC and Puerto Rico.
    if statename not in ['District of Columbia','Puerto Rico']:
        pop = popdensity[statename]
        # calling colormap with value between 0 and 1 returns
        # rgba value.  Invert color range (hot colors are high
        # population), take sqrt root to spread out colors more.
        colors[statename] = cmap(1.-np.sqrt((pop-vmin)/(vmax-vmin)))[:3]
    statenames.append(statename)
# cycle through state names, color each one.
ax = plt.gca() # get current axes instance
for nshape,seg in enumerate(m.states):
    # skip DC and Puerto Rico.
    if statenames[nshape] not in ['District of Columbia','Puerto Rico']:
        color = rgb2hex(colors[statenames[nshape]])
        poly = Polygon(seg,facecolor=color,edgecolor=color)
        ax.add_patch(poly)
plt.title('Filling State Polygons by Population Density')
plt.show()

A: For anyone interested, I was able to fix it myself. The (x,y) coordinates of each segment (for Alaska and Hawaii) should be translated. I also scale down Alaska to 35% before translating it.
The second for-loop should be modified as following:
for nshape,seg in enumerate(m.states):
    # skip DC and Puerto Rico.
    if statenames[nshape] not in ['Puerto Rico', 'District of Columbia']:
    # Offset Alaska and Hawaii to the lower-left corner.
        if statenames[nshape] == 'Alaska':
        # Alaska is too big. Scale it down to 35% first, then transate it.
            seg = list(map(lambda (x,y): (0.35*x + 1100000, 0.35*y-1300000), seg))
        if statenames[nshape] == 'Hawaii':
            seg = list(map(lambda (x,y): (x + 5100000, y-900000), seg))

        color = rgb2hex(colors[statenames[nshape]])
        poly = Polygon(seg,facecolor=color,edgecolor=color)
        ax.add_patch(poly)

Here is the new US map (using the 'Greens' colormap).

A: (The "solution" uses only the shapefile downloaded from the Census.gov website),
My knowledge in spatial mapping is limited as well, hope this solution works for someone..
I had to undergo this specific task for one of my project and my supervisor needed a mapping code, highly editable and intuitive for other members. So this is how I managed to get all the polygons in one plot.
CORE IDEA: Create 3 different axis (one for the inland states, one for Alaska and one for Hawaii) in the figure and manipulate the axis limits and axis coordinates
NOTE: The axis limits depends on the CRS information of the shapefile used (CRS:4269 used here)
import matplotlib.pyplot as plt
import geopandas as gpd

shp_path="<add your shapefile path here>"
usa_state_shp= gpd.read_file(shp_path)
usa_state_shp= usa_state_shp.to_crs("EPSG:4269") # to replicate the plot shown below

fig = plt.figure(figsize=(20,10))
plt.rcParams["font.family"]="Times New Roman"
plt.rcParams["font.size"]=12
ax1.set_title("USA")
ax1 = plt.axes()  # for the inland states
ax3 = plt.axes([0.27, 0.35, 0.12, 0.12]) # for Alaska
ax2 = plt.axes([0.35, 0.17, 0.14, 0.14]) # For Hawaii

usa_state_shp.boundary.plot(ax=ax1, linewidth=.4, edgecolor='black')
usa_state_shp.boundary.plot(ax=ax2, linewidth=.4, edgecolor='black')
usa_state_shp.boundary.plot(ax=ax3, linewidth=.4, edgecolor='black')

ax1.set_xlim(-128,-65)
ax1.set_ylim(15,50)
ax1.grid(alpha=0.3)
ax1.spines['bottom'].set_color('red')
ax1.spines['top'].set_color('red')
ax1.spines['left'].set_color('red')
ax1.spines['right'].set_color('red')
ax1.xaxis.label.set_color('red')
ax1.yaxis.label.set_color('red')
ax1.tick_params(axis='both', colors='red')
#ax1.legend()
#ax1.set_axis_off();

ax2.set_xlim(-162,-154)
ax2.set_ylim(18,22.5)
ax2.grid(alpha=0.4)
ax2.set_title("Hawaii")
ax2.set_xlabel("")
ax2.set_ylabel("")
#ax2.set_axis_off();
ax2.spines['bottom'].set_color('red')
ax2.spines['top'].set_color('red')
ax2.spines['left'].set_color('red')
ax2.spines['right'].set_color('red')
ax2.xaxis.label.set_color('red')
ax2.yaxis.label.set_color('red')
ax2.tick_params(axis='both', colors='red')

ax3.set_ylim(50,75)
ax3.set_title("Alaska")
ax3.set_xlim(-180,-125)
ax3.grid(alpha=0.4)
ax3.set_xlabel("")
ax3.set_ylabel("")
#ax3.set_axis_off();
ax3.spines['bottom'].set_color('red')
ax3.spines['top'].set_color('red')
ax3.spines['left'].set_color('red')
ax3.spines['right'].set_color('red')
ax3.xaxis.label.set_color('red')
ax3.yaxis.label.set_color('red')
ax3.tick_params(axis='both', colors='red')

The resulting Map will look similar to this: https://i.stack.imgur.com/O1jco.png

A: The above answer is great and was very helpful for me.
I noticed that there are many tiny islands that extend for many miles beyond the 8 main islands of Hawaii. These create little dots in Arizona, California, and Oregon, (or Nevada and Idaho) depending on how you translated Hawaii. To remove these, you need a condition on the area of the polygon. It's helpful to do one loop through the states_info object to do this:
# Hawaii has 8 main islands but several tiny atolls that extend for many miles.
# This is the area cutoff between the 8 main islands and the tiny atolls.
ATOLL_CUTOFF = 0.005

m = Basemap(llcrnrlon=-121,llcrnrlat=20,urcrnrlon=-62,urcrnrlat=51,
    projection='lcc',lat_1=32,lat_2=45,lon_0=-95)

# load the shapefile, use the name 'states'
m.readshapefile('st99_d00', name='states', drawbounds=True)

ax = plt.gca()

for i, shapedict in enumerate(m.states_info):
    # Translate the noncontiguous states:
    if shapedict['NAME'] in ['Alaska', 'Hawaii']:
        seg = m.states[int(shapedict['SHAPENUM'] - 1)]
        # Only include the 8 main islands of Hawaii so that we don't put dots in the western states.
        if shapedict['NAME'] == 'Hawaii' and float(shapedict['AREA']) > ATOLL_CUTOFF:
            seg = list(map(lambda (x,y): (x + 5200000, y-1400000), seg))
        # Alaska is large. Rescale it.
        elif shapedict['NAME'] == 'Alaska':
            seg = list(map(lambda (x,y): (0.35*x + 1100000, 0.35*y-1300000), seg))
        poly = Polygon(seg, facecolor='white', edgecolor='black', linewidth=.5)
        ax.add_patch(poly)


text:
Q: SELECT FOR UPDATE with SQL Server I'm using a Microsoft SQL Server 2005 database with isolation level READ_COMMITTED and READ_COMMITTED_SNAPSHOT=ON.
Now I want to use:
SELECT * FROM <tablename> FOR UPDATE

...so that other database connections block when trying to access the same row "FOR UPDATE".
I tried:
SELECT * FROM <tablename> WITH (updlock) WHERE id=1

...but this blocks all other connections even for selecting an id other than "1".
Which is the correct hint to do a SELECT FOR UPDATE as known for Oracle, DB2, MySql?
EDIT 2009-10-03:
These are the statements to create the table and the index:
CREATE TABLE example ( Id BIGINT NOT NULL, TransactionId BIGINT,
    Terminal BIGINT, Status SMALLINT );
ALTER TABLE example ADD CONSTRAINT index108 PRIMARY KEY ( Id )
CREATE INDEX I108_FkTerminal ON example ( Terminal )
CREATE INDEX I108_Key ON example ( TransactionId )

A lot of parallel processes do this SELECT:
SELECT * FROM example o WITH (updlock) WHERE o.TransactionId = ?

EDIT 2009-10-05:
For a better overview I've written down all tried solutions in the following table:

mechanism              | SELECT on different row blocks | SELECT on same row blocks
-----------------------+--------------------------------+--------------------------
ROWLOCK                | no                             | no
updlock, rowlock       | yes                            | yes
xlock,rowlock          | yes                            | yes
repeatableread         | no                             | no
DBCC TRACEON (1211,-1) | yes                            | yes
rowlock,xlock,holdlock | yes                            | yes
updlock,holdlock       | yes                            | yes
UPDLOCK,READPAST       | no                             | no

I'm looking for        | no                             | yes

A: You cannot have snapshot isolation and blocking reads at the same time. The purpose of snapshot isolation is to prevent blocking reads.

A: perhaps making mvcc permanent could solve it (as opposed to specific batch only: SET TRANSACTION ISOLATION LEVEL SNAPSHOT):
ALTER DATABASE yourDbNameHere SET READ_COMMITTED_SNAPSHOT ON;

[EDIT: October 14]
After reading this: Better concurrency in Oracle than SQL Server? and this: http://msdn.microsoft.com/en-us/library/ms175095.aspx

When the READ_COMMITTED_SNAPSHOT
  database option is set ON, the
  mechanisms used to support the option
  are activated immediately. When
  setting the READ_COMMITTED_SNAPSHOT
  option, only the connection executing
  the ALTER DATABASE command is allowed
  in the database. There must be no
  other open connection in the database
  until ALTER DATABASE is complete. The
  database does not have to be in
  single-user mode.

i've come to conclusion that you need to set two flags in order to activate mssql's MVCC permanently on a given database:
ALTER DATABASE yourDbNameHere SET ALLOW_SNAPSHOT_ISOLATION ON;
ALTER DATABASE yourDbNameHere SET READ_COMMITTED_SNAPSHOT ON;

A: Try (updlock, rowlock)

A: The full answer could delve into the internals of the DBMS.  It depends on how the query engine (which executes the query plan generated by the SQL optimizer) operates.
However, one possible explanation (applicable to at least some versions of some DBMS - not necessarily to MS SQL Server) is that there is no index on the ID column, so any process trying to work a query with 'WHERE id = ?' in it ends up doing a sequential scan of the table, and that sequential scan hits the lock which your process applied.  You can also run into problems if the DBMS applies page-level locking by default; locking one row locks the entire page and all the rows on that page.
There are some ways you could debunk this as the source of trouble.  Look at the query plan; study the indexes; try your SELECT with ID of 1000000 instead of 1 and see whether other processes are still blocked.

A: Recently I had a deadlock problem because Sql Server locks more then necessary (page). You can't really do anything against it. Now we are catching deadlock exceptions... and I wish I had Oracle instead.
Edit:
We are using snapshot isolation meanwhile, which solves many, but not all of the problems. Unfortunately, to be able to use snapshot isolation it must be allowed by the database server, which may cause unnecessary problems at customers site. Now we are not only catching deadlock exceptions (which still can occur, of course) but also snapshot concurrency problems to repeat transactions from background processes (which cannot be repeated by the user). But this still performs much better than before.

A: I have a similar problem, I want to lock only 1 row.
As far as I know, with UPDLOCK option, SQLSERVER locks all the rows that it needs to read in order to get the row. So, if you don't define a index to direct access to the row, all the preceded rows will be locked.
In your example:
Asume that you have a table named TBL with an id field.
You want to lock the row with id=10.
You need to define a index for the field id (or any other fields that are involved in you select):
CREATE INDEX TBLINDEX ON TBL ( id )

And then, your query to lock ONLY the rows that you read is:
SELECT * FROM TBL WITH (UPDLOCK, INDEX(TBLINDEX)) WHERE id=10.

If you don't use the INDEX(TBLINDEX) option, SQLSERVER needs to read all rows from the beginning of the table to find your row with id=10, so those rows will be locked.

A: OK, a single select wil by default use "Read Committed" transaction isolation which locks and therefore stops writes to that set. You can change the transaction isolation level with
Set Transaction Isolation Level { Read Uncommitted | Read Committed | Repeatable Read | Serializable }
Begin Tran
  Select ...
Commit Tran

These are explained in detail in SQL Server BOL
Your next problem is that by default SQL Server 2K5 will escalate the locks if you have more than ~2500 locks or use more than 40% of 'normal' memory in the lock transaction. The escalation goes to page, then table lock
You can switch this escalation off by setting "trace flag"  1211t, see BOL for more information

A: Create a fake update to enforce the rowlock.
UPDATE <tablename> (ROWLOCK) SET <somecolumn> = <somecolumn> WHERE id=1

If that's not locking your row, god knows what will.
After this "UPDATE" you can do your SELECT (ROWLOCK) and subsequent updates.

A: I'm assuming you don't want any other session to be able to read the row while this specific query is running...
Wrapping your SELECT in a transaction while using WITH (XLOCK,READPAST) locking hint will get the results you want. Just make sure those other concurrent reads are NOT using WITH (NOLOCK). READPAST allows other sessions to perform the same SELECT but on other rows.
BEGIN TRAN
  SELECT *
  FROM <tablename> WITH (XLOCK,READPAST)
  WHERE RowId = @SomeId

  -- Do SOMETHING

  UPDATE <tablename>
  SET <column>=@somevalue
  WHERE RowId=@SomeId
COMMIT

A: Question - is this case proven to be the result of lock escalation (i.e. if you trace with profiler for lock escalation events, is that definitely what is happening to cause the blocking)? If so, there is a full explanation and a (rather extreme) workaround by enabling a trace flag at the instance level to prevent lock escalation. See http://support.microsoft.com/kb/323630 trace flag 1211
But, that will likely have unintended side effects.
If you are deliberately locking a row and keeping it locked for an extended period, then using the internal locking mechanism for transactions isn't the best method (in SQL Server at least). All the optimization in SQL Server is geared toward short transactions - get in, make an update, get out. That's the reason for lock escalation in the first place.
So if the intent is to "check out" a row for a prolonged period, instead of transactional locking it's best to use a column with values and a plain ol' update statement to flag the rows as locked or not.

A: Application locks are one way to roll your own locking with custom granularity while avoiding "helpful" lock escalation. See sp_getapplock.

A: Try using:
SELECT * FROM <tablename> WITH ROWLOCK XLOCK HOLDLOCK

This should make the lock exclusive and hold it for the duration of the transaction.

A: According to this article, the solution is to use the WITH(REPEATABLEREAD) hint.

A: Revisit all your queries, maybe you have some query that select without ROWLOCK/FOR UPDATE hint from the same table you have SELECT FOR UPDATE.

MSSQL often escalates those row locks to page-level locks (even table-level locks, if you don't have index on field you are querying), see this explanation.  Since you ask for FOR UPDATE, i could assume that you need transacion-level(e.g. financial, inventory, etc) robustness.  So the advice on that site is not applicable to your problem.  It's just an insight why MSSQL escalates locks.

If you are already using MSSQL 2005(and up), they are MVCC-based, i think you should have no problem with row-level lock using ROWLOCK/UPDLOCK hint.  But if you are already using MSSQL 2005 and up, try to check some of your queries which query the same table you want to FOR UPDATE if they escalate locks by checking the fields on their WHERE clause if they have index.

P.S.
I'm using PostgreSQL, it also uses MVCC have FOR UPDATE, i don't encounter same problem.  Lock escalations is what MVCC solves, so i would be surprised if MSSQL 2005 still escalate locks on table with WHERE clauses that doesn't have index on its fields.  If that(lock escalation) is still the case for MSSQL 2005, try to check the fields on WHERE clauses if they have index.
Disclaimer: my last use of MSSQL is version 2000 only.

A: You have to deal with the exception at commit time and repeat the transaction.

A: I solved the rowlock problem in a completely different way. I realized that sql server was not able to manage such a lock in a satisfying way. I choosed to solve this from a programatically point of view by the use of a mutex... waitForLock... releaseLock...

A: Have you tried READPAST?
I've used UPDLOCK and READPAST together when treating a table like a queue.

A: How about trying to do a simple update on this row first (without really changing any data)? After that you can proceed with the row like in was selected for update.
UPDATE dbo.Customer SET FieldForLock = FieldForLock WHERE CustomerID = @CustomerID
/* do whatever you want */

Edit: you should wrap it in a transaction of course
Edit 2: another solution is to use SERIALIZABLE isolation level


text:
Q: NiFi: Converting a Nested JSON File into CSV I'm new to Nifi and in my case have to consume a JSON topic from Kafka
and would like to convert it into a CSV file where I need to select only few scalar and some nested fields.
I need to do the following things:
 Consume topic - Done
 Json to CSV
 Include header in the CSV file
 Merge into single file (if its split)
 Give a proper filename with date

Following the below link:
     https://community.hortonworks.com/articles/64069/converting-a-large-json-file-into-csv.html
But not sure if this is the right approach and also don't know how to make a single file.
Im using NiFi (1.8) and schema is stored in Confluent Schema Registry
Json Sample:
{
  "type" : "record",
  "name" : "Customer",
  "namespace" : "namespace1"
  "fields" : [ {
    "name" : "header",
    "type" : {
      "type" : "record",
      "name" : "CustomerDetails",
      "namespace" : "namespace1"
      "fields" : [ {
        "name" : "Id",
        "type" : "string"
      }, {
        "name" : "name",
        "type" : "string"
      }, {
        "name" : "age",
        "type" : [ "null", "int" ],
        "default" : null
      }, {
        "name" : "comm",
        "type" : [ "null", "int" ],
        "default" : null
      } ]
    },
    "doc" : ""
  }, {
    "name" : "data",
    "type" : {
      "type" : "record",
      "name" : "CustomerData"
      "fields" : [ {
        "name" : "tags",
        "type" : {
          "type" : "map",
          "values" : "string"
        }
      }, {
        "name" : "data",
        "type" : [ "null", "bytes" ]
        "default" : null
      } ]
    },
    "doc" : ""
  } ]
}

Please guide me.

A: Try ConvertRecord with a JsonTreeReader and CSVRecordSetWriter. The writer can be configured to include the header line, and you won't need to split/merge. UpdateAttribute can be used to set the filename attribute which is the associated filename for the flow file (used by PutFile, e.g.).
If ConvertRecord doesn't give you the output you want, can you please elaborate on the difference between what it gives you and what you expect?


text:
Q: How to pass dependency to test class in dotnet core? [TestClass]
public class HomeControllerTests
{
    public HomeControllerTests(IStringLocalizer<HomeController> localizer)
    {

    }
}

In the above class to test HomeController, I want to get StringLocalizer thorugh DI, which is used to create instance of HomeController. How to get it through DI?


text:
Q: Question Regarding Zero Conditional Mean Hi I am a beginner to econometrics!
I have been dealing with bivariate regression. We use the formula $y = \beta_0 + \beta_1 x$.
I am told that if $E(u\mid x) \ne 0$ then the estimate of the slope parameter $\beta_1$ will be biased.
My question is: if $E(u\mid x) = 1$ for all $x$'s, then why would the estimate of the slope parameter be biased? I thought this would mean that only the intercept estimate will be biased.
I thought that the slope parameter will only be biased if the expected value of the errors is different for each $x$. For example if $E(u\mid x_1) = 1$ and the $E(u\mid x_2) = 3$, etc. etc.
Any help will be immensely appreciated! Thank you!

A: You are correct that the condition for unbiasedness of the slope coefficient is that
$$E(u \mid X) = const.$$
However, if it is different than zero, we will have bias in the estimation of the constant term.
If you want to go deeper, this thread may be useful, Conditional mean independence implies unbiasedness and consistency of the OLS estimator

A: This is my attempt. I think you are confusing $X_s$ to observations $n$. There is no reason for $\beta_1$ to be biased if for all observation the $E(u|X)=1$, as that would mean you simply subtract the constant term, 1 in this case from the error term and the constant, and your equation becomes $y=\beta_0 -1 +\beta_1x + u-1$. So, your $\beta_0$ is biased but not $\beta_1$.

A: Let's see what's going on:
$$\begin{align}E[\hat{\beta_1}|x] &=E\left[\frac{\sum(x_i-\bar{x})(y_i-\bar{y})}{S_{xx}}\bigg|\ x\right]=\frac{1}{S_{xx}}\sum E[(x_i-\bar{x})(\beta_1(x_i-\bar{x})+(u_i-\bar{u}))]\\ &=\frac{1}{S_{xx}}\beta_1 S_{xx}+\sum(x_i-\bar{x})E[u_i|x]-E[\bar{u}|x]\sum(x_i-\bar{x}) \\ &= \beta_1+\sum(x_i-\bar{x})E[u_i|x]\end{align}$$
The second term won't go off when $E[u_i|x]\neq c$ (thanks to the correction by @Laconic), and introduce a bias to the expected value. So, it seems you're right.


text:
Q: How to intercept 401 unauthorized and add the new Authorization code? I want to detect a 401 response code for my HTTP request in one component:
@Injectable()
export class InterceptorProvider implements HttpInterceptor {

  constructor(private authService: AuthenticationService) { }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      console.log(request);
      return next.handle(request);
  }

How can I catch the error, do a refresh token request and let the other component continue if the response code is ok?
UPDATE
@Injectable()

export class InterceptorProvider implements HttpInterceptor {
constructor(private authService: AuthenticationService, private storage: Storage) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  console.log(request);
  return next.handle(request)
    .pipe(tap(event => {
        if (event instanceof HttpResponse) {
        }
      }, err => {
        if (err instanceof HttpErrorResponse) {
          if (err.status === 401) {

            console.log(err);
            console.log("Retriving user....");
           let user = new User();
this.storage.get('username').then((result)=>{
  console.log(result);
  user.username = result;
  let pass = this.storage.get('password').then((result)=>{
    console.log(result);
    user.password = result;
    console.log(user.username);
console.log(user.password);

  console.log("user ok");
  this.authService.login(user.username, user.password).toPromise().then(response=>{
    let token = response['message'];
    this.storage.set('token', token);
    this.addToken(request, token);
    return next.handle(this.addToken(request, token));
  });

  });
});
          }
        }
      })
    )
}

// Adds the token to your headers if it exists
private addToken(request: HttpRequest<any>, token: any) {
    if (token) {
        let clone: HttpRequest<any>;
        clone = request.clone({
            setHeaders: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                Authorization: token
            }
        });
        return clone;
    }

    return request;
}

}
This new version does the re-login operation, but it doesn't go further, it seems some problem with the re do of the original request, added with the new access token; where am I wrong?
UPDATE
This is the console error:
core.js:9110 ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":401,"statusText":"Unauthorized","url":"https://www.fantacalciopizza.it/php/formazioniinviatejson2.php","ok":false,"name":"HttpErrorResponse","message":"Http failure response for https://www.fantacalciopizza.it/php/formazioniinviatejson2.php: 401 Unauthorized","error":"\n\n"}
at resolvePromise (zone-evergreen.js:797)
at resolvePromise (zone-evergreen.js:754)
at zone-evergreen.js:858
at ZoneDelegate.invokeTask (zone-evergreen.js:391)
at Object.onInvokeTask (core.js:34182)
at ZoneDelegate.invokeTask (zone-evergreen.js:390)
at Zone.runTask (zone-evergreen.js:168)
at drainMicroTaskQueue (zone-evergreen.js:559)
at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:469)
at invokeTask (zone-evergreen.js:1603)

Then there is the try to Login, I got the response, but the cloned request doesn't seem to be executed; where am I wrong?

A: Try like this:
 return next.handle(authRquest)
        .pipe(
          tap(event => {
            if (event instanceof HttpResponse) {
            }
          }, err => {
            if (err instanceof HttpErrorResponse) {
              if (err.status === 401) {
                // handle error
              }
            }
          })
        )

A: I usually do this on the interceptor:
return next.handle(req).pipe(
    tap<HttpResponse<any>>(
        res => {
            // Logic if response is ok
        },

        err => {
            // Logic if response is not ok

            if(err.status === 401) {
                // Handle the error
            }
        }
    )
)

A: After registering the UnauthorizedInterceptor in providers of Root module , it will automatically detect the 401,403 errors
In unauthorized.interceptor.ts
@Injectable()
export class UnauthorizedInterceptor implements HttpInterceptor {
    constructor() { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if ([401, 403].indexOf(err.status) !== -1) {
                // YOUR  MESSAGE
            }

            const error = err || err.statusText;
            return throwError(error);
        }))
    }
}

In AppModule.ts
@NgModule({
    ...,
   providers: [{
      provide: HTTP_INTERCEPTORS,
      useClass: UnauthorizedInterceptor,
      multi: true
    }]
})


text:
Q: How to prove that every weak solution is classic for a simple parabolic equation Consider equation
$$
Lu=u_t-a(x)u_{xx}=0, \tag 1
$$
where coefficient $a$ is bounded and $a(x)\ge \delta>0$ for all $x\in \mathbb R$.
If $a$ is not smooth the conjugate operator $L^*$ can not be defined. But equation (1) can be rewritten as
$$
L_1u=a^{-1}(x)u_t-u_{xx}=0,
$$
which has divergence form.
So we'll define a weak solution of (1) in domain $Q\subset R^2$ as a continuous function $u$ s.t. for any trial function $\varphi\in C^\infty(Q)$ with compact support in $Q$ the equality
$$
\int_Q u L_1^*\varphi\,dx\,dt=0
$$
holds, where $L_1^*u=-a^{-1}(x)u_t-u_{xx}$ is the conjugate operator to $L_1$.
Suppose that the coefficient $a$ is regular enough to guarantee that solutions of (1) be classic (i.e. derivatives $u_t$, $u_{xx}$ are continuous), say, let $a$ be from Holder space $C^\alpha(\mathbb R)$, $0<\alpha<1$.
Q: Can it be proved that every weak solution of $(1)$ is a classic solution? Or may be  a question of this sort was considered somewhere?


text:
Q: Tree grid component with cellTemplate in AngularJS I am using tree-grid component in AngularJS: http://khan4019.github.io/tree-grid-directive/test/treeGrid.html
here is above example in plunker:
http://plnkr.co/edit/CQwY0sNh3jcLLc0vMP5D?p=preview

in comparison with ng-grid, I can't define cellTemplate, but I really need cell formatting possibility. How can I implement example rules for each row:

*

*if TimeZone is equal to EST color Description content on green

*if TimeZone is equal to PST color Description content on red

*if Population as an odd number replace Area content  by image good.jpg

*if Population as a even number replace Area content by image bad.jpg
with tree-grid-directive?
Maybe you can propose me some other AngularJS component (with tree expand functionality)?

A: adapt-strap has a component called tree-browser. That is what you are looking for.
It is highly customizable and you can specify template for the whole row. You can also submit a feature request if something is missing.
Project homepage and examples: http://adaptv.github.io/adapt-strap/


text:
Q: Applications launch on leftmost monitor in multi-monitor setup For some reason applications decide to launch on my leftmost monitor(which is my TV) instead of my primary(which is the monitor the the far right). It's not all applications that have this behavior but a good portion of them. VLC and BlueJ for instance are applications that won't launch on my preferred monitor, they always launch on my leftmost monitor. I won't matter if I close them on the monitor I wishes to open them on.
It also doesn't matter if I run Unity or Gnome Shell 3.10, the problem persist on both.
Here is my xrandr output to give you an idea on how my monitors are positioned. I run an Nvidia Gefore 670 with the proprietary and tested version of the drivers, 331.38.
xrandr
Screen 0: minimum 8 x 8, current 4480 x 1447, maximum 16384 x 16384
DVI-I-0 connected 1280x1024+1280+423 (normal left inverted right x axis y axis) 340mm x 270mm
   1280x1024      75.0*+   60.0
   1024x768       75.0     70.1     60.0
   800x600        75.0     72.2     60.3     56.2
   640x480        75.0     72.8     59.9
DVI-I-1 disconnected (normal left inverted right x axis y axis)
HDMI-0 connected 1280x720+0+423 (normal left inverted right x axis y axis) 1434mm x 806mm
   1280x720       50.0*+   60.0     59.9
   1920x1080      60.1     60.0     50.0
   720x576        50.0     50.1
   720x480        59.9     60.1
   640x480        59.9
DP-0 connected primary 1920x1080+2560+0 (normal left inverted right x axis y axis) 531mm x 299mm
   1920x1080      60.0*+   59.9     50.0     60.1     60.0     50.0
   1680x1050      60.0
   1600x1200      60.0
   1440x900       75.0     59.9
   1280x1024      75.0     60.0
   1280x960       60.0
   1280x800       59.8
   1280x720       60.0     59.9     50.0
   1152x864       75.0
   1024x768       75.0     70.1     60.0
   800x600        75.0     72.2     60.3     56.2
   720x576        50.0
   720x480        59.9
   640x480        75.0     72.8     59.9
DVI-D-0 disconnected (normal left inverted right x axis y axis)
DP-1 disconnected (normal left inverted right x axis y axis)

Anyone who got an idea?
Edit. I've made a video to show the problem with the latest nvidia drivers 334.21.  Still the same problem.
Youtube video


text:
Q: How to change the bin separate for histogram in ggplot2? I am using ggplot 2 to do plot a histogram. I set the binwidth = 6 because I hope the histogram can get the count for groups(x-axis): (0,6],(6,12],(12,18]..... However, with my code ,I finally got the count for groups: (0,3],(3,9].... as the graph shown below. I hope to know if there is anyway to let the histogram show (0,6],(6,12],(12,18]..... and get the count for each group?
    ggplot(aes(x = customer_age), data = data_churn_1) +
geom_histogram( aes(fill = churn), binwidth=6, colour="white") +
stat_bin(binwidth=6, geom="text", colour="black", size=3,
   aes(label=..count..)) +
scale_x_continuous(breaks=seq(0,max(data_churn_1$customer_age), 6))+ facet_grid(.~ churn)


text:
Q: js modal popup value get stacked I want to show a modal popup when the user clicked a button, but it keeps adding to the innerHTML

                        <button class="minusBtn"></button>

1

                        <button class="plusBtn"></button>

                    <button class="orderBtn">Add To Cart</button>

Here I create a new div and insert it into the parent, and showing the clicked data with literal template
            let content = document.createElement('div');
                content.classList.add('popup-content');
                content.innerHTML = `

                        ${item.name}

                        ${item.price}

                `;
                let wrapper = document.querySelector('.popup-wrapper');
                let orderContainer = document.querySelector('.order-container');
                wrapper.insertBefore(content, orderContainer);

A: You need to remove all existing .popup-content elements before you insert a new one if you want only one to appear.
document.querySelectorAll('.popup-content').forEach(el => el.remove());

let content = document.createElement('div');
...


text:
Q: How to derive the determinant of quaternion? It is true that
$$ \begin{bmatrix}
a & -b & -c & -d \\
b & a & -d & c \\
c & d & a & -b \\
d & -c & b & a
\end{bmatrix}  $$
has a determinant $(a^2+b^2+c^2+d^2)^2$
However, I find it very difficult to derive it manually, I have tried to do row operations but it seems very complicated. Is there a more speedy way?


text:
Q: KRFB doesn't save settings I use KRFB 4.14.12 on KUbuntu 15.10 x64. Each time I open it (using krfb from terminal) and change the settings, if I close it, the settings are not saved. Why?

A: It looks like it is a one-year old bug that still hasn't been fixed:  https://bugs.kde.org/show_bug.cgi?id=340411

A: Either you are on Vivid 15.04 or you are using an outdated version?
see -> http://packages.ubuntu.com/search?keywords=KRFB&searchon=names&suite=all&section=all
current version in Wily 15.10 is: krfb (4:15.08.2-0ubuntu1)
This should fix it!

A: You could place a bug-report @Debian & Launchpad-bugs against that package (haven't found anything likely there). Reference the KDE-bug. Sometimes this speeds up things, to poke the devs from more sides ;-).


text:
Q: Anchored links in Outlook(Mac) HTML mail not working I have a problem with internal links in outlook for Mac  (Ver. 15.12.3).
This is the markup i am using:
english version below
....

This is working fine in GMail or Roundcube, but not in outlook.
When i click the link i get the following error/message.

I found this issue, but including "name" did not help.
Did anyone succeed in using internal links?


text:
Q: Django 2 Sendmail with timeweb.ru I checked Django app in Ubuntu 18.04 without ufw
When added to settings.py these:
EMAIL_HOST = 'smtp.timeweb.ru'
EMAIL_PORT = 465
EMAIL_HOST_USER = 'myemail@timeweb.ru'
DEFAULT_FROM_EMAIL = 'myemail@timeweb.ru'
SERVER_EMAIL = 'myemail@timeweb.ru'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

Run in the console
python manage.py shell
>>> from django.core.mail import send_mail
>>> send_mail('ddd','fffffffffff', 'myemail@timeweb.ru',['test@gmail.com'],fail_silently=False)

After 7 minutes I get this error.
Traceback (most recent call last):
      File "<console>", line 1, in <module>
      File "/home/mikhail/Django/Chapter01/mysite/env/lib/python3.7/site-packages/django/core/mail/__init__.py", line 60, in send_mail
        return mail.send()
      File "/home/mikhail/Django/Chapter01/mysite/env/lib/python3.7/site-packages/django/core/mail/message.py", line 291, in send
        return self.get_connection(fail_silently).send_messages([self])
      File "/home/mikhail/Django/Chapter01/mysite/env/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 103, in send_messages
        new_conn_created = self.open()
      File "/home/mikhail/Django/Chapter01/mysite/env/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 63, in open
        self.connection = self.connection_class(self.host, self.port, **connection_params)
      File "/usr/lib/python3.7/smtplib.py", line 251, in __init__
        (code, msg) = self.connect(host, port)
      File "/usr/lib/python3.7/smtplib.py", line 338, in connect
        (code, msg) = self.getreply()
      File "/usr/lib/python3.7/smtplib.py", line 394, in getreply
        raise SMTPServerDisconnected("Connection unexpectedly closed")
    smtplib.SMTPServerDisconnected: Connection unexpectedly closed

What am I doing wrong?


text:
Q: SwiftUI using NavigationLink and NavigationView I am trying to use NavigationView and NavigationLink in my code below.
I heard that NavigationLink only works inside NavigationView.
However, whenever I embed my ScrollView into a NavigationView, the scrollView stop showing up and I get a blank space. I am not sure what is the reason behind it.
var body: some View {
        // I tried to embed the entire VStack into NaviationView. However, it ends up showing nothing as well
            VStack(alignment: .leading) {
                Text(self.categoryName)
                    .font(.title)
                NavigationView {
                    ScrollView(.horizontal, showsIndicators: false) {
                        HStack(alignment: .top) {
                            ForEach (self.drummers) { drummer in
                                NavigationLink("Moreinfo", destination: drummerDetail(drummer: drummer))
                                aDrummer(drummer: drummer)
                                .frame(width: 300)
                                .padding(.trailing, 30)
                            }
                        }
                    }
                    .padding()
                }
            }

    }

A: If aDrummer is-a View (as I assume) then see below possible fix - ForEach content should be single view
ForEach (self.drummers) { drummer in
  VStack {
    NavigationLink("Moreinfo", destination: drummerDetail(drummer: drummer))
       aDrummer(drummer: drummer)
         .frame(width: 300)
         .padding(.trailing, 30)
  }
}


text:
Q: Destroying activity and calling it again by clicking notification I issue the a notification with an action that opens mainactivity. This is the first time the activity is called, created and everything works perfectly. After I pause the activity I automatically call onDestroy() of the activity and it is destroyed with success. When I click the notification for the second time, however, there is an error that says FATAL EXCEPTION: main can't resume activity. If the activity was destroyed I wasn't expecting it to be resumed but recreated again... why is this happening and how can I force the recreation of the activity by these methods?

A: Do not call onDestroy() directly!
These are lifecycle methods that the system should call. The problem you are having is that the system still believes the activity is paused (rather than destroyed as you would have liked) since it was never notified. You undoubtedly invoked super.onDestroy() within your onDestroy() method (the right thing) which caused part of the activity to clean itself up, making it non-resumable. When the system comes around the resume the activity in which it thought was paused, it throws that error.
Fortunately, there are ways to tell the system to kill your activity when you want it, through a method called finish().
Android documentation:

Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via onActivityResult().

Replace your call to onDestroy() with this call should resolve your issue.
Never call lifecycle methods directly!


text:
Q: How to perform group by, count and sum from list of object in single stream and store in another list of object? I am trying to get the group by, count and sum from list of the object using java stream and collection. I am not sure how do I achieve the desired result.
InputModel
String month;
BigDecimal salary;
String department;
String noOfEmp;

InputModel[(May,100,IT,10), (June,300,IT,7),(July,300,IT,7),(May,1000,HR,5), (June,300,HR,7),(July,600,HR,5)]
OutputModel
String month
BigDecimal salary
String noOfEmp

Expected Output
OutputModel[(May,1100,15),(June,600,14),(July,900,12)]
I tried below code but it returned group by and Count.
Map<String, Integer> result= inputModels.parallelStream().collect(Collectors.groupingBy(InputModel::getMonth,
            LinkedHashMap::new, Collectors.summingInt(InputModel::getNoOfEmp)));

Thanks in Advance!!!

A: Given that you have OutputModel class in place, this will solve your problem.
Collection<OutputModel> outputModels = inputModel.stream()
    .map(im -> new OutputModel(im.getMonth(), im.getSalary(), im.getNoOfEmp()))
    .collect(Collectors.toMap(OutputModel::getMonth, Function.identity(),
        (m1, m2) -> new OutputModel(m1.getMonth(), m1.getSalary().add(m2.getSalary()),
            String.valueOf(Integer.valueOf(m1.getNoOfEmp()) + Integer.valueOf(m2.getNoOfEmp()))),
        LinkedHashMap::new))
    .values();

Word of caution: Better NOT to use Strings where other types are more appropriate. For an instance you should have used int to represent noOfEmp instead of a String. That would simplify the code while reducing the possibility of runtime errors due to spurious data. Moreover consider using java.time.Month enum to represent month of the year contrary to using String literals.
Here's the output,

[{month=May, salary=1100, noOfEmp=15}, {month=June, salary=600,
  noOfEmp=14}, {month=July, salary=900, noOfEmp=12}]

A: you can combine groupingBy and reducing
Map<String, Optional<OutputModel>> outputModels = inputModel.stream()
            .map(ip -> new OutputModel(ip.getMonth(), ip.getSalary(), ip.getNoOfEmp()))
            .collect(Collectors.groupingBy(OutputModel::getMonth,
                           LinkedHashMap::new,
                           Collectors.reducing(OutputModel::merge)));

//the following method goes into OutputModel
public static OutputModel merge(OutputModel o1, OutputModel o2) {
        return new OutputModel(o1.month, o1.salary.add(o1.salary), o1.noOfEmp + o2.noOfEmp);
}

I used LinkedHashMap so insert order will be preserved, also I've changed noOfEmp to Integer


text:
Q: SQL continuous database blocking for EJB timers scheduler We have a Java enterprise based application which is running on IBM WebSphere servers ( running on cluster environment). Our application uses EJB timers scheduler (Timers in WebSphere are used to schedule tasks and events, such as a business process, at certain times throughout the day. Timers and their associated events are stored in the EJB container.) functionality.
EJB creates its own table based on scheduler configuration.
From past few days we are getting continuous blocking alert for our timer services -
Below queries are continuously blocked -
SELECT ME_UUID,INC_UUID,VERSION,MIGRATION_VERSION FROM SIBOWNER WHERE NOT ME_UUID='LOCK'
SELECT 1 FROM SIBOWNER (TABLOCKX)
We have restarted our websphere, JVM nodes to make sure fresh timers are created, but after 4-5 hrs of restart DB blocking starts reappearing.
Need your help, if any of you have faced similar situation and found remedy of it.

A: You mentioned that your servers are clustered.  Are you scheduling persistent EJB timers at the cluster level as well (one timer for the cluster, where all servers are pointing at the same database tables), or at the server level (each server uses different database tables for storing the EJB persistent timer data)?  If the latter, you may be ending up with the same timer logic running on all the servers at once, which could be a source of lock contention.  Also, I should point out that persistent EJB timers (persistent is the default) do not disappear when the server shuts down, because the record of them persists in the database, and so if you have initialization logic to "make sure fresh timers are created", you could be ending up with duplicates that compete with each other for the database.  There are a lot of ways that EJB timers can be used, and more detail about your configuration, the types of timers, how you schedule them, and all of the transactional operations that you perform within them (and outside of them upon the same data) would be needed to properly diagnose this.  This is the best guess I can offer lacking that level of detail.


text:
Q: Setting connection Apache Derby in IntelliJ I'm using IntelliJ as IDE.
My teacher gave me some code already.
I have a Java class AnimalSurvey (pojo) that creates a  database animalsurvey.
Below is its constructor.
    public AnimalSurvey() {

    System.out.println("AnimalSurvey starting in " + framework + " mode.");

    try {
        /*
         * The driver is installed by loading its class. In an embedded
         * environment, this will start up Derby, since it is not already
         * running.
         */
        Class.forName(driver).newInstance();
        System.out.println("Loaded the appropriate driver.");

        props = new Properties();
        props.put("user", "app");
        props.put("password", "app");

        /*
         * The connection specifies create=true to cause the database to be
         * created. To remove the database, remove the directory
         * animalsurvey and its contents. The directory animalsurvey will be
         * created under the directory that the system property
         * derby.system.home points to, or the current directory if
         * derby.system.home is not set.
         */

        String dataPath =System.getProperty("user.home");
        dataPath += "/DerbyDB/";

        conn = DriverManager.getConnection(protocol
            //  + "c:\\cloudscape_db\\animalsurvey;create=true", props); //windows
        + dataPath+"animalsurvey;create=false", props);                  //Macos

        System.out
                .println("Connected to and created database animalsurvey");

        conn.setAutoCommit(false);

    } catch (Throwable e) {
        System.out.println("exception thrown:");

        if (e instanceof SQLException) {
            printSQLError((SQLException) e);
        } else {
            e.printStackTrace();
        }
    }

And an initialize() method in this class AnimalSurvey:
public void initialize()throws SQLException{

    /*
     * Creating a statement lets us issue commands against the
     * connection.
     */
    s = conn.createStatement();

    s.execute("drop table surveyresults");

    /*
     * We create a table, add a few rows, and update one.
     */
    s.execute("create table surveyresults (id int NOT NULL , surveyoption varchar (20) NOT NULL , votes int NOT NULL , constraint surveyresults_id primary key (id)) ");
    s.execute("insert into surveyresults (id,surveyoption,votes) values (1, 'Dog', 0)");
    s.execute("insert into surveyresults (id,surveyoption,votes) values (2, 'Cat', 0)");
    s.execute("insert into surveyresults (id,surveyoption,votes) values (3, 'Bird', 0)");
    s.execute("insert into surveyresults (id,surveyoption,votes) values (4, 'Snake', 0)");
    s.execute("insert into surveyresults (id,surveyoption,votes) values (5, 'None', 0)");
    /*
     * We select the rows and verify the results.
     */
    rs = s.executeQuery("SELECT * FROM surveyresults ORDER BY surveyoption");
    rmd = rs.getMetaData();
}

Now I have Java servlet that contains the following code, a AnimalSurvey object is initialized and then the initialize() method on this object is defined:
    AnimalSurvey dataObject = new AnimalSurvey();
    dataObject.initialize();

When I run my web program and end up in that java servlet, I always get a HTTP Status 500 ? Internal Server Error and it gives me the next exception:
java.lang.NullPointerException
data.AnimalSurvey.initialize(AnimalSurvey.java:184)
be.SurveyServlet.doPost(SurveyServlet.java:25)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

So it looks like in the AnimalSurvey class, in the initialize method, the following code (private Connection conn was set on null in that class), is still null when I execute the code.
s = conn.createStatement();

It's a lot of code, I know and I hope it makes sense.
My teacher also gave me the next info in order to have access to the database:
'jdbc:derby://localhost:1527/surveyresults;user=app;password=app;
But how do I get Apache Derby working? Do I need to download the drivers? And where in IntelliJ do I set a connection to this database?


text:
Q: Launch a program at login without permissions (fedora 20) I'm currently developing an application with QT 4.8 with a "Launch on login" option. My main problem currently is that I can't seem to find a proper way to make the program launch itself after login on Linux (Fedora 20 in my case).
My program should be able to run in the background without stopping fedora to launch.
I would also like to avoid having to ask for any sort of admin privilege since my application doesn't require any (except maybe for this option).

A: Finally found out about "home/.config/autostart/.desktop".
I'll have to create autostart if it's not created but from there I can chose to make or delete the file depending on what my user decided to do.
The .desktop file have to follow a particular syntax (which is not a problem for me)
[Desktop Entry]
Type=Application
Exec=</path/to/binary or command to execute>
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name=<Name_to_be_displayed>
Comment=<optional comment>

In my case, I can just remove the "comment" line since just the name of the application should be enough for the user to recognize it.

A: You can Either keep your executable in side /etc/rc.d/rs or inside /etc/init.d folder, so that it can automatically start once device is up.
Hope this Helps.

A: Each user has a .bashrc file located in their home directory, you could append a command to run your application to the end of that.
That will run when only that user logs in (I think either with graphical or terminal session)
To run for all users, look at creating a systemd service if you dare, or append a line to the end of /etc/rc.local. You'll need to be root for that though.
EDIT: Don't forget to put an ampersand at the end of the command to run in background.


text:
Q: Running RSpec With Existing TestUnit tests and coverage with Simplecov I'm new to ROR and wondering if Simplecov provides tests coverage for both TestUnit and RSpec tests in the same project?
I am in the process of migrating some tests we wrote in RSpec from a standalone webapp to an existing webapp that currently uses TestUnit.
I know that both RSpec and TestUnit can live in the same project, but I haven't been able to see how Simplecov will generate coverage for both test frameworks.
When I run on the command line bundle exec rake spec I get:
Coverage report generated for RSpec to /.../coverage. 0 / 0 LOC (0.0%) covered.
when I run bundle exec rake test I get test coverage generated.
The plan is to migrate everything from TestUnit to rspec but with 400+ tests we want to have both TestUnit and RSpec tests covered by Simplecov whilst we migrate to TestUnit.
I'm sure there must be something incorrect in my configuration
Any help would be much appreciated!
I have the following set up:
--- Rakefile ---
require File.expand_path('../config/application', __FILE__)
require 'rake'
require 'simplecov'

if Rails.env == 'test' || Rails.env == 'development'
  require 'ci/reporter/rake/test_unit'
  require 'ci/reporter/rake/rspec'
end

SimpleCov.start 'rails' do
  add_filter "/test/"
  add_filter "/spec/"
end

-- spec/spec_helper.rb --
ENV["RAILS_ENV"] ||= 'test'

require 'simplecov'
SimpleCov.start 'rails'

require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'

-- test/test_helper.rb --
require 'simplecov'
SimpleCov.start 'rails' do
  add_filter "/vendor/"
end

ENV["RAILS_ENV"] = "test"

require File.expand_path('../../config/environment', __FILE__)

A: This doesn't answer your question directly, but if it helps, I have a bash script that does a lot of the work for you for porting from TestUnit to RSpec. It's at https://github.com/Noreaster76/porter. You could use it to convert your TestUnit files, and after cleaning up the results a bit, you wouldn't have the issue of having to run both RSpec and TestUnit.


text:
Q: Is it possible for a Mob to spawn *right next to* the player in Minecraft? According to Minepedia/Light, the changes that occurred in the Halloween update make torches useless for level 16 and below (incidentally, also the level where diamonds start).
Now, that's all fine and dandy, but if a Mob such as a Creeper spawns right next to the player, the player has no time to react. This is particularly bad with Creepers, because one spawning next to you is generally impossible to avoid, particularly in tunnels and such.
That doesn't seem like it would be fair at all (to make next-to-random insta-deaths-by-creeper for the player), and I would be surprised if it behaved that way, but I've not heard or seen anything that indicates that it does not operate that way.
More to the point, even in dark areas I've never had a mob spawn right in front of my face. Sometimes if I'm on top of a hill or something of that sort you can see one spawn in the distance, but never next to you. This leads me to believe that it can't happen, though again I've had no confirmation of this.
Can a mob spawn right next to you in Minecraft?
N.B. I'm referring to darkness-induced spawning. Of course a mob spawner can cause mobs that spawn right next to you ;)

A: In addition to the other answers, a recent change (pre-1.6.1 13w17a) has introduced a feature where a zombie can summon more zombies when they are damaged regardless of damage source, which ignores light level or player range.
Therefore, specifically for zombies, it is possible for a new zombie to randomly spawn near players within the player immobility range if a zombie was damaged and a new one randomly spawned.

A: Unless other changes have been made to the spawning code, enemy mobs can't spawn within 24 blocks of your current location.  The exception to this is of course mob spawners, but that's a different story.

A: They can't spawn right next to you; you have a 24-block radius of safety. They can approach you afterwards, but that's different.

A: Umm... I'm not quite sure, but I think it is possible if it meets all requirements for spawning there. If there's 2 block gap, light level below 7 it should be possible for creeper, zombie or a skeleton to spawn although it can't spawn on top of the player, because the spot where character is standing is already been taking so it's very unlikely
http://minecraft.gamepedia.com/Spawn

A: I have to disagree with the other answerers. Or at least while you are asleep, because I've recently had a skeleton who spawns right on top of me when I sleep and kills me.


text:
Q: Shared library to minimise size of FLA file In a project we use large flash FLA file with lots of graphic assets, but the actual data that is changed is just in a few symbols. Sometimes it is not very efficient to transfer the whole FLA file that comes up to 20MB now.
I was thinking about using Shared Libraries, but it seems that, even if you import external library, it still copies the whole assets into the destination file, but does not link it from external file. Consequently, size of the FLA file still remains the same.
Is there any way to split FLA files into few separate in order to minimise size of the most frequently updated file and keep all unchanged data in another file?

A: you can copy items into a swc file (example link) then link them to the project. If i were you id consider using a SVN client, that way you can upload/download only the changes made and work from there.

A: External library is definitely the solution. Put all the assets in a new FLA (or vice-versa), export the SWC. After that import the SWC to the main FLA as 'runtime shared library', that way nothing gets included at runtime, you just need to make sure you preload the SWF (related to the SWC) before you start accessing the assets.


text:
Q: Django admin customization with non-related models I am a django noob and am trying to figure out how to get the admin module to do something slightly different than the normal operation on a single model.  Essentially what I need is to run a query and display the results of the query as a view page and then allow the link to the edit page take the user to an existing model's edit view.  2 of the 3 tables in my query are related, but not all 3.
Example:
select a.foo, a.second_field, b.bar, c.unrelated_field
from a, b, c
where a.primary_key = b.foreign_key
and a.some_value = c.some_value

Note that a and c are not defined as related tables.
I would like to have a view of this query output and have a link to the edit view of the b model as a whole when selected.
I have created a view in the DB for this query and simply created a new model which makes it easy to get the view, but I'm not sure this is even the right approach to start with...but from there I can't seem to figure out how to make this link to the edit page for the B table.
Any pointers or advice on how best to accomplish something like this with django admin would be appreciated!
Using Django 1.3.1 by the way.
Cheers!

A: You can override change_view in your ModelAdmin so it will construct a list of dicts with all your needed data. Then override change_list.html template to display this data correctly and link it with change_form view for correct model. So it will flawlessly integrate in Django's admin site.
And I don't like DB views as long as it's possible to solve the problem without it. If data can be constructed in Python without massive performance gaps and lots of magic code, it should be processed in Python.


text:
Q: question about two different definitions of limit point From the definition of a limit point it follows  :

A limit point $x$ of a subset $S$ of a topological space $X$ is a point such that every neighborhood of $y$ has a point in common with $S$.

also based on Wikipedia :

it doesn't make a difference if we restrict the condition to open neighborhoods only.

I know that if every neighborhood of $y$ intersects $S$, then also open neighborhoods of $y$ has a point in common with $H$
but why we can claim that if every open neighborhood of $y$ intersects $S$ then, so does every neighborhood of $y$?

A: First, by your question, you seem to have understood this direction but I will write it anyways: open neighborhoods are a special case of neighborhoods. So, if every neighborhood of $y$ intersects $S$, the same can be said for every open neighborhood.
Now, for the other direction, assume every open neighborhood of $y$ intersects $S$ and let $V$ be a neighborhood of $y$. By definition, $V$ contains an open set $U$ which contains $y$. $U$ is an open neighborhood of $y$, so $U$ intersects $S$. But $U\subset V$, so $V$ also intersects $S$. $V$ is an arbitrary neighborhood, so every neighborhood intersects $S$.

A: Mathematicians often shorten the statement

$U$ is an open set containing $x$

to the phrase

$U$ is a neighborhood of $x$.

Borrowing from Munkres:

If $A$ is a subset of the topological space $X$ and if $x$ is a point
  of $X$, we say that $x$ is a limit point (or "cluster point", or
  "point of accumulation") of $A$ if every neighborhood of $x$
  intersects $A$ in some point other than $x$ itself. Said
  differently, $x$ is a limit point of $A$ if it belongs to the closure
  of $A − \{x\}$. The point $x$ may lie in $A$ or not; for this
  definition it does not matter.


text:
Q: Should I consider XMPP for any chat app For a chat app, with extended features (not related to chat but realtime data) with support for Websocket and SocketIO based server, do I really need to integrate or consider XMPP. Isn't XMPP overkill for a simple file sharing (S3 storage), chat and other data communication (server status etc).
In my application, custom data is fetched from different storage, need to push to Message Queue in some event, and store uploaded file in S3. All these are not XMPP supported, So anyhow I will have to customize XMPP server implementations a lot if I choose it as backend.
Do you think I would be better off implementing all these by my own, compleletly skipping XMPP.
Or, is there anything in XMPP which I may have missed for considering it.
Support required in app:

*

*Websocket

*Long polling ajax

*S3 storage

*Redis / Aerospike DB

*REST call to other services hosted on different machines

*Android Client

*iOS client

*Windows client based on Qt

A: XMPP, formerly Jabber, is based on XML. I'm an old hand with XML, yet even I can see that it was chatty and redundant in creating open and close element tags, and also required a heck of a lot of open and close quotes.
What seems to be far more popular these days, especially in the NoSQL arena, are syntactically terser codifications of data such as JSON, or BSON (Binary JSON).
JSON: http://www.json.org/
Binary JSON: http://bsonspec.org/
Is there something specific in the schema, syntax, parsing or web-baed reification of XML which is a reason you want to use XMPP? Otherwise, you might find JSON an easier and more efficient way to encode data.
Also let me know if this answer was useful.


text:
Q: How to load and initialize a class/jar/... at runtime even if it is out of the classPath? I want to initialize a class that is not known during compilation (yet implementing a known interface).
So I tried something like this :
Class<?> cls = class.foreName("NotKnown",true,ClassLoader.getSystemClassLoader());

It worked in Eclipse , but as a runnable jar file I found out this won't work because it won't load a class which is out of your classPath.
How can I make it work ?

A: You need to create new classloader that would load classes from the folder where your new class is located:
ClassLoader cl = new URLClassLoader(new URL[] { ... });
Class<?> cls = cl.loadClass("NotKnown");

I.e. if you have a class foo.bar.Baz and it was compiled to /someFolder/foo/bar/Baz.class, you should use new File("/someFolder").toURI().toURL() as a folder to load your class from.


text:
Q: Double-escaping regex from inside a Groovy expression Note: I had to simplify my actual use case to spare SO a lot of backstory. So if your first reaction to this question is: why would you ever do this, trust me, I just need to.
I'm trying to write a Groovy expression that replaces double-quotes (""") that appear in a string with single-quotes ("'").
// BEFORE: Replace my "double" quotes with 'single' quotes.
String toReplace = "Replace my \"double-quotes\" with 'single' quotes.";

// Wrong: compiler error
String replacerExpression = "toReplace.replace(""", "'");";

Binding binding = new Binding();
binding.setVariable("toReplace", toReplace);
GroovyShell shell = new GroovyShell(binding);

// AFTER: Replace my 'double' quotes with 'single' quotes.
String replacedString = (String)shell.evaluate(replacerExpression);

The problem is, I'm getting a compile error on the line where I assign replacerExpression:

Syntax error on token ""toReplace.replace("", { expected

I think it's because I need to escape the string that contains the double-quote character (""") but since it's a string-inside-a-string, I'm not sure how to properly escape it here. Any ideas?

A: You need to escape the quote within quotes in this line:
String replacerExpression = "toReplace.replace(""", "'");";

The string will be evaluated twice: once as a string literal, and once as a script.  This means you have to escape it with a backslash, and escape the backslash too.  Also, with the embedded quotes, it'll be much more readable if you use triple quotes.
Try this (in groovy):
String replacerExpression = """toReplace.replace("\\"", "'");""";

In Java, you're stuck with using backslashes to escape all the quotes and the embedded backslash:
String replacerExpression = "toReplace.replace(\"\\\"\", \"\'\");";

A: Triple-quotes work well, but one can also use single-quoted string to specify a double-quote, and a double-quoted string for a single-quote.
Consider this:
String toReplace = "Replace my \"double-quotes\" with 'single' quotes."

// key line:
String replacerExpression = """toReplace.replace('"', "'");"""

Binding binding = new Binding(); binding.setVariable("toReplace", toReplace)
GroovyShell shell = new GroovyShell(binding)

String replacedString = (String)shell.evaluate(replacerExpression)

That is, after the string literal evaluation, this is evaluated in the Groovy shell:
toReplace.replace('"', "'");

If that is too hard on the eyes, replace the "key line" above with another style (using slashy strings):
String ESC_DOUBLE_QUOTE = /'"'/
String ESC_SINGLE_QUOTE = /"'"/
String replacerExpression = """toReplace.replace(${ESC_DOUBLE_QUOTE}, ${ESC_SINGLE_QUOTE});"""

A: Please try to use regular expressions to solve this kind of problems, instead of messing your head to tackle the escaping of quotes.
I have put up a solution using groovy console. Please see if that helps.


text:
Q: How to prevent Next.js flash when visiting register page while being authenticated? So let me give you a brief background. I am using Laravel Breeze with Next.js. Everything works perfectly fine, but there's a slight problem. When I am authenticated while being on the /dashboard page and I load the /register page, there is a flash of the /register page before the redirection back to the /dashboard page.
Something similar also happens when I visit the /dashboard page while not being authenticated. I have done something to alleviate the /dashboard flash by putting up logic to show a loading... text though. However, it still seems like the page should not even load and the redirect should happen to /register using some middleware.
Dashboard.js
import BasicLayout from "@/components/layouts/BasicLayout";
import { useAuth } from "../src/hooks/auth";

const Dashboard = () => {
  const { logout, user } = useAuth({ middleware: "auth" });

  return (
    <>
      {!user &&
loading...
}
      {user &&
        <>

{user?.name}

            <button onClick={logout}>Sign out</button>
        </>
      }
    </>
  );
};

export default Dashboard;

Dashboard.getLayout = function getLayout(page) {
    return <BasicLayout>{page}</BasicLayout>;
  };

useAuth() hook
import axios from '@/src/lib/axios';
import { useEffect } from 'react'
import { useRouter } from 'next/router'
import useSWR from 'swr'

export const useAuth = ({ middleware, redirectIfAuthenticated } = {}) => {
    const router = useRouter()

    const { data: user, error, mutate } = useSWR('/api/user', () =>
        axios
            .get('/api/user')
            .then(res => res.data)
            .catch(error => {
                if (error.response.status !== 409) throw error

                router.push('/verify-email')
            }),
    )

    const csrf = () => axios.get('/sanctum/csrf-cookie', { withCredentials: true })

    const register = async ({ setErrors, ...props }) => {
        await csrf()

        setErrors([])

        axios
            .post('/register', props)
            .then(() => mutate())
            .catch(error => {
                if (error.response.status !== 422) throw error

                setErrors(Object.values(error.response.data.errors).flat())
            })
    }

    const login = async ({ setErrors, setStatus, ...props }) => {
        await csrf()

        setErrors([])
        setStatus(null)

        axios
            .post('/login', props)
            .then(() => mutate())
            .catch(error => {
                if (error.response.status !== 422) throw error

                setErrors(Object.values(error.response.data.errors).flat())
            })
    }

    const forgotPassword = async ({ setErrors, setStatus, email }) => {
        await csrf()

        setErrors([])
        setStatus(null)

        axios
            .post('/forgot-password', { email })
            .then(response => setStatus(response.data.status))
            .catch(error => {
                if (error.response.status !== 422) throw error

                setErrors(Object.values(error.response.data.errors).flat())
            })
    }

    const resetPassword = async ({ setErrors, setStatus, ...props }) => {
        await csrf()

        setErrors([])
        setStatus(null)

        axios
            .post('/reset-password', { token: router.query.token, ...props })
            .then(response => router.push('/login?reset=' + btoa(response.data.status)))
            .catch(error => {
                if (error.response.status !== 422) throw error

                setErrors(Object.values(error.response.data.errors).flat())
            })
    }

    const resendEmailVerification = ({ setStatus }) => {
        axios
            .post('/email/verification-notification')
            .then(response => setStatus(response.data.status))
    }

    const logout = async () => {
        if (! error) {
            await axios
                .post('/logout')
                .then(() => mutate())
        }

        window.location.pathname = '/login'
    }

    useEffect(() => {
        if (middleware === 'guest' && redirectIfAuthenticated && user) router.push(redirectIfAuthenticated)
        if (middleware === 'auth' && error) logout()
    }, [user, error])

    return {
        user,
        register,
        login,
        forgotPassword,
        resetPassword,
        resendEmailVerification,
        logout,
    }
}


text:
Q: .getValues(), .setValues(), and .clearContent() doesn't seem to work together in the way I am using it in Google Script for Google Sheets I have been fiddling with this super basic google script for hours and I can't figure it out. I want a user to be able to enter values to the range, 'inputR,' and have range paste values only to the bottom first empty space of my dataset, B59:L1051. Then I want 'inputR' to be cleared so additional entries can be made. Here is what I have so far:
function addData() {
  var app = SpreadsheetApp;
  var ss = app.openById('1MNYUjdt0OCeOZyoNVAZbIRoM7kevG12njF5i57FyR5A');
  var db = ss.getSheetByName('Dashboard');
  var inputR  = db.getRange('B54:L54')
  var data = db.getValues();
  var last = db.getRange('B59:L1051').getLastRow();
  db.getRange(last + 1, 2, 1, 11).setValues(data);
  inputR.clearContent();
}

Update (10/1/2021):
I have managed to function below. However, now it is not allowing me to assign the script to a button. It keeps giving me this error "Script function updateData could not be found." The file name and the function name are both 'updateData'. The function works perfectly now so there should be any errors that would prevent it from finding the script.
function updateData() {
  var app = SpreadsheetApp;
  var ss = app.openById('1MNYUjdt0OCeOZyoNVAZbIRoM7kevG12njF5i57FyR5A');
  var db = ss.getSheetByName('Dashboard');
  var inputR  = db.getRange('B54:L54');
  var inputV = inputR.getValues();
  var data = db.getRange('B59:L1051').getValues();
    for (var i = 0; i<data.length; i++) {
    if (!data[i].join("")) break;
  }
  var emptyRow = i + 1;
  db.getRange(58 + emptyRow, 2, 1, 11).setValues(inputV);
  inputR.clearContent();
  Logger.log(emptyRow);
  Logger.log(inputV);
}


text:
Q: Publishing Maven artifact to artifactory with different artifact ID New to Maven Publishing. Our team has started using Artifactory and I'm trying to figure out how to publish to it, but using a custom artifact ID. Here's the relevant part of my build.gradle file
def applicationName = 'example-api'
def applicationVersion = '1.0.0.1'
def group = 'com.example.api'
def archiveName = "${applicationName}##${applicationVersion}"

bootWar {
  archiveFileName = "${archiveName}.war"
}

publishing {
  publications {
    mavenJava(MavenPublication) {
      artifact(file("build/libs/${archiveName}.war"))
      afterEvaluate {
        artifactId archiveName
        groupId group
        version applicationVersion
      }
    }
  }
}

artifactory {
  contextUrl = "http://172.17.0.2:32447/artifactory"
  publish {
    repository {
      repoKey = 'libs-release-local'
      username = 'admin'
      password = 'password1'
      maven = true
    }

    defaults {
      publications('mavenJava')
      publishBuildInfo = true
      publishArtifacts = true
      publishPom = false
    }

  }

  clientConfig.info.setBuildName(applicationName)
  clientConfig.info.setBuildNumber(applicationVersion)
}

But it seems it's never keeps the same name as the WAR file that's produced in the build. This is the closest I've gotten:

Ideally, I'd like to have the artifact be called just 'example-api##1.0.0.1.war' since it will be deployed to Tomcat.
When I try to remove groupId, Artfactory seems unable to create a repo URL, and if I omit the the version, the artifact name is then example-api##1.0.0.1-unspecified.war
Any thoughts?

A: What you see is the expected behaviour.
Maven artifact names are strictly <artifactId>-<version>.<extension>.
So when you set the publication configuration as follows:

*

*artifactId = example-api##1.0.0.1

*version = 1.0.0.1

*extension = war
It results in an artifact named example-api##1.0.0.1-1.0.0.1.war
I would strongly recommend dropping the version from the artifactId part, to be better aligned with Maven conventions.
An alternative would be to use an Ivy repository, which has more flexibility around specifying the artifact name.


text:
Q: Initialize array of various length tuples? I have an array b = [1, 2, 1, 4]. These values can change. I need to create a SharedArray of Tuples each with b[i] Ints.
In other words, if I have b = [1, 2, 1, 4] I need:
x = SharedArray{Tuple{Int}, Tuple{Int,Int}, Tuple{Int}, Tuple{Int,Int,Int,Int}}
I can't for the life of me figure out how. Any ideas?

A: A SharedArray can only contain bits types, which a Tuple of Vararg is not... but here's a draft of @halirutan's idea of encoding the tuples into a flat array:
immutable SharedThing{T}
  data::SharedArray{T}
  strides::Vector{Int}
end

function SharedThing{T}(tuples::Tuple{Vararg{T}}...)
  strides = collect(map(length, tuples))
  data = SharedArray(T, sum(strides))
  i = 1
  for (s, t) in zip(strides, tuples)
    data[i:i+s-1] = collect(t)
    i += s
  end
  SharedThing{T}(data, strides)
end

function Base.getindex{T}(xs::SharedThing{T}, i)
  before = sum(xs.strides[1:i-1])
  tuple(xs.data[before+1:before + xs.strides[i]]...)
end

So:
julia> xs = SharedThing((1, 2,3), (22, 33))
SharedThing{Int64}([1,2,3,22,33],[3,2])

julia> xs[1]
(1,2,3)

julia> xs[2]
(22,33)

Of course, this is optimizable, does not pay attention to getting a good sharing structure for parallelism, and I also fear that its type handling is suboptimal... still, it can hopefully serve you as a basis.


text:
Q: set up a custom domain name on Google App engine to use with SSL I'm trying to set up a custom domain name on Google App engine to use with SSL.
I have a paid Google Apps account, the domain name is an Alias of my primary domain
I managed to set up the custom name via https://console.developers.google.com/project - > My project -> App engine -> Settings -> Custom domains
It works pretty well without https. But with https I have an error.
When I try https://appengine.google.com/ -> My project -> Application Settings -> Add Domain, I can select my domain name in the input box but when I click on "Add domain"
Google Ask to choose an account, I select my Google Apps account and I have this error:
You are trying to access Google Admin of example.com but you do not have a valid logged in account for it.
Sign into one of the existing accounts for example.com
This is weird because the domain name is an Alias as required by Google here: developers.google.com/appengine/docs/domain
I tried to do all this procedure in a clean browser with only the Google Apps account logged and I have the same issue.
Is it a limitation from Google or so?


text:
Q: docker-compose setting environment variables which the container cannot retrieve Sorry for bringing an old thread up but I feel Aurélien Bottazini would be able to help me here.
Same problem here. I feel I am close to what Aurélien Bottazini said here but not there yet. From my docker-compose file below
I already have a built image that I want to run
I would like that env variable (wtmsdemo_customerapi01) to be able to set to the API container that I am spinning up as well.
I am not able to read the environment variable from the docker-compose file below.

help ?

version: '3'

services:
  web:
    image: softwaremaker/web-w
    environment:
      - wtmsdemo_customerapi01=http://api/api/values
    ports:
      - "89:80"
    depends_on:
      - api
  api:
    image: softwaremaker/api-w

  networks:
    default:
      external:
        name: nat


text:
Q: How to convert string entries within a dataset to float? I am trying to convert string to float in a dataset. The dataset consists of several columns where one of the columns contains entries:

col1
col2

x
[1.1, 1.2, 1.3 ...

When I use pd.to_numeric I get the following error:
Unable to parse string "[1.1, 1.2........]" at position 0.
**This is a simplified version of my code, where the numbers resemble this 2.1874960973678963

A: elements are strings
Assuming you want to convert a string representation of a list of floats ("[1.1, 1.2, 1.3]") to a list of floats:
input:
df = pd.DataFrame({'col1':['x'], 'col2':'[1.1, 1.2, 1.3]'})

processing:
df['col2'] = df['col2'].apply(lambda s: list(map(float, s.strip('[]').split(', '))))

edit: check the link provided by @Henry Ecker, there is a nice solution with ast.literal_eval
import ast
df['col2'] = df['col2'].apply(ast.literal_eval)

elements are lists of strings
If your elements are already lists of strings (['1.1', '1.2', '1.3']), use:
df['col2'] = df['col2'].apply(lambda x: [float(i) for i in x])

or:
df['col2'] = df['col2'].apply(lambda x: list(map(float, x)))


text:
Q: How to find a child html element by id with jsoup? I am parsing the html code of one site with Jsoup. I need to find some html elements that has an specific id but their parent´s tree is complicating me the task. So I would like to know if is it possible to search an specific html element without having to search first all of their parents.
For instance I am doing the next:
Elements el=elements.select(".scroller.context-inplay").select(".zone.grid-1-1").select(".grid-1").select(".module-placeholder");

I would likte to know if there is a simple way to get the same element I get with this code searching by its id

A: The id of an html element should be unique within the page. Some html that you find in the wild breaks this requirement unfortunately tough. However, if your html source follows the standard you can simply use the # css operator to select the element in question:
 Element el = doc.select("#someID").first();

Alternatively you can directly use the getElmentById Jsoup method:
Element el = doc.getElmentById("someID");

Also, if you decide to go by class names as you suggest in your question, it is easy to combine all selects into one selector:
Elements els = elements.select(".scroller.context-inplay .zone.grid-1-1 .grid-1 .module-placeholder");

The spaces in the CSS selector mean that any subselector right of the space must be a child of the stuff on the left side.


text:
Q: How to separate sub-menu output and keep associated with parent I am creating a menu like this https://squareup.com/ I have the html,css, and jquery ready. Now, I am trying to:
Create the menu items with it's sub-menu items via wp-admin -> appearance -> menus ( which I have done )
output the menu item with it's corresponding sub-menu items separately and dynamically.

        <?php if ( get_field('landing_hero_image') ): ?>
                <div class="menu" style="background-image: url(<?php the_field('landing_hero_image'); ?>);">

                        main menu item

                    sub menu item associated with the main item

                <div class="banner" style="background-image: url(<?php the_field('landing_hero_image'); ?>);">

            <?php endif; ?>

So to summarize, how do I separate the output ( html ) menu items and their children?
Many thanks in advance.

A: Register the navigation menu location in your theme's functions.php file using the register_nav_menu() function, assign your custom menu to the location in Dashboard > Appearance > Menus, then use the wp_nav_menu() function in your theme's template files to print the menu's markup where appropriate.
Refer to the overview of Navigation Menus in the Codex.