text:
Q: NetworkX - creating a deep copy of reversed graph I'm having an issue when trying to create a deep copy of a reversed digraph in NetworkX and examining the PageRank of that copy. It doesn't appear that the issue is with PageRank, it just throws an exception when trying to calculate the PageRank of the broken reversed digraph.
First, I generate a digraph using this code, which basically just creates a bunch of nodes, randomly picks a few of them, and then draws directed edges from that node to another 50 or so randomly selected nodes. It then trims all nodes with degree 0.
def global_classroom(nodes):
    network = nx.DiGraph()
    network.add_nodes_from([User(i, "0.0.1") for i in range(nodes)])
    network_nodes = network.nodes()
    teachers = random.sample(network_nodes, nodes / 100)
    for teacher in teachers:
        for i in range(nodes / 20):
            student = network_nodes[random.randrange(nodes)]
            if teacher != student:
            network.add_edge(teacher, student)
    for node in network_nodes:
        if network.degree(node) == 0:
            network.remove_node(node)
    return network

Now, if I call this:
G = global_classroom(1000)
G.reverse(False)
print nx.pagerank(G)

Everything works perfectly fine. NetworkX is able to calculate the PageRank no problem.
But if I call this:
G = global_classroom(1000)
G_page_rank = G.reverse()
nx.pagerank(G_page_rank)

There is an exception thrown
  Traceback (most recent call last):
  File "a.py", line 62, in <module>
  rank = nx.pagerank(L_page_rank)
  File "<string>", line 2, in pagerank
  File "/Users/PSnyder/Documents/Git/infection/networkx/utils/decorators.py", line 68, in _not_implemented_for
  return f(*args,**kwargs)
  File "/Users/PSnyder/Documents/Git/infection/networkx/algorithms/link_analysis/pagerank_alg.py", line 140, in pagerank
  dangling_nodes = [n for n in W if W.out_degree(n, weight=weight) == 0.0]
  File "/Users/PSnyder/Documents/Git/infection/networkx/classes/digraph.py", line 1023, in out_degree
  return next(self.out_degree_iter(nbunch,weight))[1]
  File "/Users/PSnyder/Documents/Git/infection/networkx/classes/digraph.py", line 941, in out_degree_iter
  for n,nbrs in nodes_nbrs:
  File "/Users/PSnyder/Documents/Git/infection/networkx/classes/digraph.py", line 934, in <genexpr>
  nodes_nbrs=((n,self.succ[n]) for n in self.nbunch_iter(nbunch))
  KeyError: <__main__.User object at 0x104618050>

Where <__main__.User object at 0x104618050> is one of the many objects that make up the nodes in my digraph.
I'd like to be able to simply make a deep copy instead of needing to reverse my graph once again to revert it to its original form.
Here is the entirety of the User class which makes up my nodes:
class User(object):
    def __init__(self, name, version, teachers = [], students = []):
        self.name = name
        self.version = version
        G.add_node(self)
        self.add_teachers(teachers)
        self.add_students(students)

    def add_students(self, students):
        for student in students:
            G.add_edge(self, student)

    def add_teachers(self, teachers):
        for teacher in teachers:
            G.add_edge(teacher, self)

A: Maybe your User object is causing an issue?  You didn't include that so I can't see if this is a networkx bug or not.
This works (using integers instead of User())
import networkx as nx
import random

def global_classroom(nodes):
    network = nx.DiGraph()
    network.add_nodes_from([i for i in range(nodes)])
    network_nodes = network.nodes()
    teachers = random.sample(network_nodes, nodes / 100)
    for teacher in teachers:
        for i in range(nodes / 20):
            student = network_nodes[random.randrange(nodes)]
            if teacher != student:
                network.add_edge(teacher, student)
    for node in network_nodes:
        if network.degree(node) == 0:
            network.remove_node(node)
    return network

if __name__=='__main__':
    G = global_classroom(1000)
    G.reverse(False)
    print nx.pagerank(G).items()[0:5] # first 5


text:
Q: [23000][1062] Duplicate entry '0' for key 'PRIMARY' when I filled out the database, I received a problem in the form of duplication of the primary key entry, but the fact is that the field "status" field in my database is not the primary key or its part.
DB Script

CREATE TABLE IF NOT EXISTS travel.`users` (
  `login` VARCHAR(25) NOT NULL,
  `password` VARCHAR(25) NOT NULL,
  `email` VARCHAR(40) NOT NULL,
  `name` VARCHAR(20) NOT NULL,
  `surname` VARCHAR(20) NOT NULL,
  `telephone` VARCHAR(20) NOT NULL,
  `role` VARCHAR(30) NOT NULL,
  `status` TINYINT(1) NOT NULL,
  `image` VARCHAR(250) NOT NULL,
  PRIMARY KEY (`login`),
  UNIQUE INDEX `login_UNIQUE` (`login` ASC))
  ENGINE = InnoDB;

SQL Query

INSERT INTO users VALUES
  (login = 'admin', password = 'admin', email = 'admin@gmail.com', name = 'Иван',
   surname = 'Иванов', telephone = '+380674002092', role = 'ADMINISTRATOR', status = '0',
   image = 'D:/server/admin.img');

INSERT INTO users VALUES
  (login = 'manager', password = 'manager', email = 'manager@gmail.com', name = 'Петров',
   surname = 'Пётр', telephone = '+380964002092', role = 'MANAGER', status = '0',
   image = 'D:/server/manager.img');

During execution of the second INSERT I receive the following error [23000][1062] Duplicate entry '0' for key 'PRIMARY'

A: `user_id` int(8) NOT NULL AUTO_INCREMENT

you must have a auto increment field.

A: Remove the Column name .Do not need to specify the column.

INSERT INTO users VALUES
  ( 'admin',  'admin', 'admin@gmail.com',  'Иван',
    'Иванов',  '+380674002092',  'ADMINISTRATOR',  '0',
    'D:/server/admin.img');

INSERT INTO users VALUES
  ( 'manager',  'manager',  'manager@gmail.com',  'Петров',
    'Пётр', '+380964002092',  'MANAGER',  '0',
    'D:/server/manager.img');

A: Raja's answer is correct, but I want to add few more information for others
His answer..

Remove the Column name .Do not need to specify the column.
INSERT INTO users VALUES
    ( 'admin',  'admin', 'admin@gmail.com',  'Иван',
      'Иванов',  '+380674002092',  'ADMINISTRATOR',  '0',
      'D:/server/admin.img');
INSERT INTO users VALUES
    ( 'manager',  'manager',  'manager@gmail.com',  'Петров',
      'Пётр', '+380964002092',  'MANAGER',  '0',
      'D:/server/manager.img');

My additions...
We do not need to specify the columns if we are doing full insert, if we want to insert data to only some rows, we specify the only columns to that we are inserting in.
Here is a sample,
INSERT INTO users(login, password, status) VALUES
  ( 'manager1',  'manager1',  '0');

This will insert values only in login, password and status column.
Also, One suggestion, avoid using varchar datatype as Primary Key, as it would affect the performance for indexing in main memory. Instead use int or long (bigint in most of RDBMS).
And, you can set that to on Auto Increment and it makes easy to use them as Foreign Key.
Here is what you need to change if you want to make it AutoIncrement..
    CREATE TABLE IF NOT EXISTS travel.`users` (
        `id` int(8) NOT NULL AUTO_INCREMENT,
        `login` VARCHAR(25) NOT NULL,
         ....
        PRIMARY KEY (`id`),

redpajama_set_name: RedPajamaStackExchange


text:
Q: Any recommendation to resize 3d image array which consists of only 0 and 1? I want to resize(downscale) the ground truth 3d images of brain tumor segmentation.
Here are some g.t. + brain images:

G.t. images are 3d numpy array and consist of only 0 and 1 value(only green voxel and black voxel, brain is not included in g.t. image).
def resize(img, shape, mode='nearest', orig_shape=None, order=3):
    """
    Wrapper for scipy.ndimage.zoom suited for MRI images.
    """

    if orig_shape == None: orig_shape = img.shape

    assert len(shape) == 3, "Can not have more than 3 dimensions"
    factors = (
        shape[0]/orig_shape[0],
        shape[1]/orig_shape[1],
        shape[2]/orig_shape[2]
    )

    # Resize to the given shape
    return zoom(img, factors, mode=mode, order=order)

# original shape = (150, 512, 512)
# desired shape = (64, 192, 160)

I used scipy zoom, with order 3 and nearest mode. After resizing the images, some of them were ok but some weren't. You can see the problem in the 1st and 2nd images of the above. There are many holes in tumor area which were not there before resizing. The 3rd image doesn't seem to have the issue.
I tinkered some options in zoom function, but didn't find a proper solution. Please help me to solve this. Thank you.


text:
Q: Boto3 start glue crawler with new s3 input I have an amazon glue crawler, which looks at a specific s3 location, containing avro files.
I have a process which outputs files in a new subfolder of that location.
Once I manually run the crawler, the new subfolder will be seen as a new table in a database, and it will also be is query-able from Athena.
Is there a way I can automate the process, and call the crawler programatically, but only specifying that new subfolder, so that it doesn't have to scan the entire parent folder structure?
I want to add tables to a databases, and not partitions to an existing table.
I was looking for a Python option, and I have seen indeed that one can do:
import boto3
glue_client = boto3.client('glue', region_name='us-east-1')
glue_client.start_crawler(Name='avro-crawler')

I haven't seen an option to pass a folder to limit where the crawler is looking into. Because there are hundreds of folders/tables in that location, re-crawling everything takes a long time, which I'm trying to avoid.
What are my options here? Would I need to programatically create a new crawler with each new subfolder added to s3?
Or create a lambda function which gets triggered when a new subfolder gets added to s3? I've seen an answer here , but even with lambda, it still implies I call the start_crawler, which would crawl everything?
Thanks for any suggestions.

A: Update crawler_name to your crawler_name and update_path to your update path.
response = glue_client.update_crawler(Name=crawler_name,
                           Targets={'S3Targets': [{'Path':update_path}]})


text:
Q: Spring isn't loading CSS and gives a 404 when the page is loaded I'm running a Spring (not Boot) web app and it's finding my JSP views properly, but my CSS isn't being found for some reason. To be clear, the page is loading with the necessary elements, but any CSS styling from classes in my .css files is not being applied. The structure for the CSS file I'm trying to use is src/main/resources/css/style.css.
Below is the relevant code for my AppConfig class:
public class AppConfig implements WebMvcConfigurer {
    ...
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**")
                .addResourceLocations("/css/");
    }
    ...
}

And the JSP header:
 <link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css"/>

I've already checked some other questions asking after this issue and have had no luck. Several of them advised checking the config file for Spring Security to ensure that permission is granted for all requests using the resource file but based on what I can see, it shouldn't be prohibiting the CSS from being loaded:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Bean
    public BCryptPasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setPasswordEncoder(encoder());
        authenticationProvider.setUserDetailsService(userService);

        return authenticationProvider;
    }

}

A: For a non-Spring Boot project your css folder should be not in src/main/resources but in src/main/webapp.

A: You need to tell spring security to ignore css files by overriding this method in WebSecurityConfigurerAdapter:
 @Override
 public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**","/vendor/**","/fonts/**").anyRequest();
 }

A: The configuration that you posted in your question:
public class AppConfig implements WebMvcConfigurer {
    ...
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**")
                .addResourceLocations("/css/");
    }
    ...
}

tells Spring MVC to serve /css/style.css from the css directory in your context directory. If it doesn't exist, you get a 404.
If you want to serve the file from the classpath (which is what your question seems to imply), then you should do this instead:
public class AppConfig implements WebMvcConfigurer {
    ...
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**")
                .addResourceLocations("classpath:/resources/css/");
    }
    ...
}

See the documentation of ResourceHandlerRegistry for more details.


text:
Q: Divisibility property involving binomial coefficients and largest prime power divisor Let $p$ be a prime, let $x$ be an integer not divisible by $p$, and let $j\geq 1$. Denote, as usual, by $\nu=\nu_p(j+1)$ the largest exponent such that $p^{\nu}$ divides $j+1$.
My question : is it true that $p^{\nu}$ always divides $\binom{x-1}{j}=\frac{(x-1)\ldots(x-j)}{j!}$ ?
My thoughts : I have checked that it holds for $p=2,3,5$ and $x\leq 1000$. It is also easy to check when $j$ is "small" compared to $p$ (for example when $j\lt p$, the numerator is divisible by $p$ but not the denominator, so we are done).
It is natural to use Legendre's formula here : we know that
$$
\nu_p(j!)=\sum_{t=1}^{\infty}\left \lfloor \frac{j}{p^t}\right\rfloor,
\nu_p((x-1)\ldots(x-j))=\sum_{t=1}^{\infty} \left\lfloor \frac{x-1}{p^t}\right\rfloor -\left \lfloor \frac{x-(j+1)}{p^t}\right\rfloor
$$
So, it would suffice to show the following inequality :
$$
\sum_{t=1}^{\infty}\left \lfloor \frac{x-1}{p^t}\right\rfloor - \left\lfloor \frac{x-(j+1)}{p^t}\right\rfloor - \left\lfloor \frac{j}{p^t}\right\rfloor \geq \nu
$$
But then I'm stuck.

A: The easy proof is that:
$$x\binom{x-1}{j}=(j+1)\binom{x}{j+1}\tag1$$
So $$\nu_p(x)+\nu_p\left(\binom {x-1}j\right)\geq \nu_p(j+1).$$
But $p\not\mid x$ means $\nu_p(x)=0.$
(1) shows more generally that if $d\mid j+1$ and $\gcd(d,x)=1,$ then $d\mid \binom{x-1}{j}.$

To extend your approach using Legendre.
If $p\not \mid x$ then show for $t>0:$ $$\left\lfloor \frac{x-1}{p^t}\right\rfloor=\left\lfloor\frac{x}{p^t}\right\rfloor$$
and, for $t\leq\nu,$ $$\left\lfloor\frac{x-(j+1)}{p^t}\right\rfloor =\left\lfloor\frac{x}{p^t}\right\rfloor-\frac{j+1}{p^t}$$
So (*):
$$
\begin{align}
\nu_p\left(\binom{x-1}j\right)&\geq \sum_{t=1}^{\nu}\left(\left \lfloor \frac{x-1}{p^t}\right\rfloor - \left\lfloor \frac{x-(j+1)}{p^t}\right\rfloor - \left\lfloor \frac{j}{p^t}\right\rfloor\right)\\
&=\sum_{t=1}^{\nu}\left(\frac{j+1}{p^t}-\left\lfloor\frac{j}{p^t}\right\rfloor\right)
\end{align}
$$
Finally, for $t\leq \nu,$ $$\left\lfloor\frac{j}{p^t}\right\rfloor =\frac{j+1}{p^t}-1.$$

Note: We get in (*) $$\sum_{t=1}^{\infty}\geq \sum_{t=1}^{\nu}$$ because all the terms in the infinite sum are non-negative, using the general inequality:
$$\lfloor \alpha+\beta\rfloor\geq \lfloor \alpha\rfloor +\lfloor\beta\rfloor.$$

A: Legendre's Formula can be written as $\nu _p(n!)=\frac{n-s_p(n)}{p-1}$, with $s_p(n)$ the sum of digits in base $p$ of $n$. On this view, you can write the inequality that you want as (this using that $\nu _p(j+1)=\nu _p((j+1)!/j!)$):
$$\frac{1+s_p(j)-s_p(j+1)}{p-1}\leq \frac{s_p(j)+s_p(x-1-j)-s_p(x-1)}{p-1},$$
which is equivalent to $$1-s_p(j+1)-s_p(x-(j+1))\leq -s_p(x-1),$$
adding both sides an $x$ and dividing over $p-1,$ using again Legendre's, one ends up on $$\frac{1}{p-1}+\nu _p(((j+1)!(x-1-j)!))\leq \frac{1}{p-1}+\nu _p((x-1)!)=\frac{1}{p-1}+\nu _p(x!),$$
which is true because $\binom{x}{j+1}$ is an integer.


text:
Q: How do I avoid using absolute filepaths if I want files created on a user's desktop? Right now my script uses an absolute filepath for the output folder on the desktop of a known user, but what if I want to allow the script to work on the desktop of a user whose username I do not know?
Example - here's the line I'm currently using.  It works fine, but will obviously only work for "John".  I need to make it work with any potential username - Tom, Dick, Harry, and so on and so forth.
' Creating log repository
objFSO.CreateFolder "C:\Users\John\Desktop\Output"

A: The easy way but fails if the desktop is not in the usual place for a user is, this may be coporate environments.
dir "%userprofile%\Desktop"

A better way is
for /f "skip=2 tokens=3" %A in ('Reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v "Desktop"') do set doc=%A

dir "%doc%" /a

(Remember %%A in a batch and %A if typing) I thought your question was about batch. Both methods are as easy as each other in VBScript.
set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo "WinDir is " & WshShell.ExpandEnvironmentStrings("%userprofile%\Desktop\Output")

or
bKey = WshShell.RegRead("HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Desktop")

or
     strDesktop = WshShell.SpecialFolders("Desktop")

A:
To avoid extended discussions in comments, here I place a self-explanatory example.
' helper function to quote strings
' useful in commands
Function Quot(str)
    Quot = Chr(34) & str & Chr(34)
End Function

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set WshShell = CreateObject("Wscript.Shell")

' get user's desktop directory and introduce a variable
currentDesktop = WshShell.SpecialFolders("Desktop") 'another way to do it

' introduce output directory variable <currentDesktop>\Output
outputDir = objFSO.BuildPath(currentDesktop, "Output")

' create <outputDir> if not exists
If Not objFSO.FolderExists(outputDir) Then
    objFSO.CreateFolder outputDir
End If

' example usage in a command
' send command output to <outputDir>\network_config.txt
WshShell.Run "%COMSPEC% /c ipconfig /all >" & Quot(objFSO.BuildPath(outputDir, "network_config.txt"))


text:
Q: ActionScript:ArrayCollection declaration I am new to ActionScript and Flex.I need to learn the application developed using Flex and ActionScript.I saw an ArrayCollection declaration :

    [Bindable]
    public var someThing:ArrayCollection = new ArrayCollection([[]]);

What does that declaration mean.Is it multi dimensional?What is it?

A: This would be an ArrayCollection which is a wrapper for an Array basically to give you sort and filter function capabilities (and other methods).  The constructor optionally takes an Array as an argument, [] is a new array with no elements.  [[]] is an array with one element in it that is an array with no elements in it.  So this is saying make a new ArrayCollection with it's source as an array which in turn contains one element that is an empty array.  Not sure why they would be doing this, but that's what it does.
To sum up, you can declare and instantiate an array in AS3 like:
var myArray:Array = [];

or
var myArray:Array = new Array();

To add since this is I believe ECMAScript specific as well you can instantiate an object similarly using {}.  Such as:
var myObj:Object = {};

or
var myObj:Object = new Object();

Either of these sites is good reference material for AS3:
http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7ee5.html#WS5b3ccc516d4fbf351e63e3d118a9b90204-7ee1
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html
When I first got started with Flex (having a background in HTML/JS, C, C++, and Java) I found these videos to be really useful (if not always 100% correct/up to date, they explain the overarching concepts):
http://www.adobe.com/devnet/flex/videotraining.html


text:
Q: D3.js: Measure frame rate Is there a good way to measure the number of frames drawn per second when rendering SVG?
I am working on a plot and wish to measure the render performance, but aside from the Chrome performance tools I'm not sure how to do so.
If there are helpers in the D3 ecosystem analogous to the stats package often used inside render loops, I'd be happy to look at that...

A: The same approach one uses in three.js appears to work in d3.js:

const getSize = () => ({
  w: window.innerWidth,
  h: window.innerHeight,
})

/**
* Config
**/

const k = 1;
const zoomBounds = [0.5, 32]; // min max zoom bounds
let size = getSize();

/**
* SVG
**/

const svg = d3.select('body').append('svg')
  .attr('id', 'scene')
  .attr('viewBox', [0, 0, size.w, size.h]);

/**
* Add grid
**/

const gGrid = svg.append('g').attr('id', 'grid');

const grid = (g, x, y) => {
  g
  .attr('stroke', '#eaeaea')
  .attr('stroke-opacity', 1)
  .call(g => g
    .selectAll('.x')
    .data(x.ticks(10 * k))
    .join(
      enter => enter.append('line').attr('class', 'x').attr('y2', size.h),
      update => update,
      exit => exit.remove()
    )
    .attr('x1', d => x(d))
    .attr('x2', d => x(d)))
  .call(g => g
    .selectAll('.y')
    .data(y.ticks(12 * k))
    .join(
      enter => enter.append('line').attr('class', 'y').attr('x2', size.w),
      update => update,
      exit => exit.remove()
    )
    .attr('y1', d => y(d))
    .attr('y2', d => y(d)));
}

const gVertex = svg.append('g')
  .attr('id', 'vertices')
  .attr('fill', 'none')
  .attr('stroke-linecap', 'round');

/**
* Domains
**/

const x = d3.scaleLinear()
  .domain([-100, 100])
  .range([0, size.w])

const y = d3.scaleLinear()
  .domain([-100, 100])
  .range([size.h, 0])

/**
* Add zoomability
**/

const zoom = d3.zoom()
  .scaleExtent(zoomBounds) // set bounds of zoomable area
  .on('zoom', function() {
    const transform = d3.event.transform; // contains zoom depth and x, y coords
    const zx = transform.rescaleX(x).interpolate(d3.interpolateRound);
    const zy = transform.rescaleY(y).interpolate(d3.interpolateRound);
    // run zoom operation on text layer
    gVertex.attr('transform', transform);
    // set the size of the text

    // update the grid sizing
    gGrid.call(grid, zx, zy);
  });

svg.call(zoom).call(zoom.transform, d3.zoomIdentity);

/**
* Stats
**/

const stats = new Stats();
stats.showPanel(0);
document.body.appendChild(stats.dom);

/**
* Render
**/

function render() {
  // fetch data from api
  const data = ["Curtis Gilbert", "Ann Boyd", "Kimberly Hicks", "Dawn Braun", "Gabriela Vega", "Cory Morgan", "Stuart Lopez", "Anthony Paul", "Jeffrey Frye", "Andre Nicholson", "Jeffrey Summers", "Kayla Jackson", "Melissa Campbell", "Lisa Rodriguez", "Kevin Hernandez", "Mr. Dean Brooks", "Angela Mckinney", "Gabrielle Stewart PhD", "Vanessa Massey", "Mr. Jose Mcdonald MD", "Jennifer Brown", "Albert Baxter", "Chris Todd", "Vanessa Leonard", "Kevin Johnson", "Spencer Martinez", "Linda Lee", "Lauren Stewart", "Chad Powell", "Jennifer Mathis", "Elizabeth Webster", "James Patterson MD", "Brandon Davidson", "David Evans", "Kathleen Pena", "Donald Osborne", "Sarah Ross", "Jeremy Burke", "Matthew Miller MD", "Janet Abbott", "Andrew Miller", "Anthony Mack", "Joshua Gomez", "Glenn Doyle", "Joseph Hall", "James Martin", "Roger Delgado", "Shannon Jimenez", "Christina Thompson", "Angela Moore", "Lisa Hatfield", "Stephen Wilson", "Janice Wong", "Jon Frey MD", "Veronica Booker", "Jennifer Martinez", "James Santiago", "Linda Singleton PhD", "Heidi Hill", "Timothy Torres", "Jonathan Reid", "Brittney White", "Amanda Gomez", "Katelyn Richards", "Christian Macdonald", "Michelle Hunt", "Francisco Herrera", "Hector Sherman", "Adam Arias", "Rita Murray", "Thomas Wood", "Robert Munoz", "Mark Richard", "Barbara Mckay", "Sabrina Buck", "Mrs. Regina Murphy", "Derek Pace", "Edward Lucas", "Nancy Bailey", "George Brown", "John Turner", "Leroy Holt", "Audrey Nunez", "Crystal Thompson", "Isaac Butler", "Keith Guzman", "Stephanie Holland", "Nicole Pugh", "Megan Bauer", "Derek Green", "Miranda Ellis", "Hannah Buckley", "Sergio Cox", "Andrea Wood", "Stephen Walker", "Michelle Smith", "Carl Brown", "Gerald Mejia", "Mary Monroe", "Corey Moore"]

  // draw the points
  const vertices = gVertex.selectAll('.vertex').data(data)

  vertices.enter()
    .append('text')
      .attr('class', 'vertex')
      .attr('x', d => Math.random() * 300)
      .attr('y', d => Math.random() * 300)
      .text(d => d)
}

/**
* Main
**/

function animate() {
  stats.begin();
  render();
  stats.end();
  requestAnimationFrame(animate);
}

requestAnimationFrame(animate);
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>title</title>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/d3/5.16.0/d3.min.js'></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/stats.js/16/Stats.js'></script>
  </head>
  <style>
  * {
    margin: 0;
    padding: 0;
  }

  html,
  body {
    height: 100%;
  }

  html,
  body,
  svg {
    background-color: #f9f9f9;
  }

  text {
    fill: black;
    font-family: courier;
    font-size: 12px;
  }
  </style>
  <body></body>
</html>

As long as all the action happens inside the render loop, you can measure performance with Stats.js...


text:
Q: Display Cursor In An VB ActiveX TextBox I have the following code for an existing Word 2007 form which my companby uses and i have been asked to see if i can add the cusror to display in a ActiveX TextBox when its enabled.
There is on question on the form which has 3 OptionButtons and 2 TextBoxes and depending on the radio button select will enable the relevent TextBox but i can seem to get a cursor displayed in the TextBox when it's enabled.
There are various other TextBoxes on the form all of which are ArctiveX so i dont think i can use it on the 'Load', or can i?
Private Sub OptionButton1_Click()

If OptionButton1.Value = True Then
TextBox1.Enabled = False
TextBox2.Enabled = False
TextBox1.BackColor = &HE0E0E0
TextBox2.BackColor = &HE0E0E0
TextBox1.Text = Empty
TextBox2.Text = Empty
End If

End Sub

----------------------------------------------

Private Sub OptionButton2_Click()

If OptionButton2.Value = True Then
TextBox1.Enabled = True
TextBox2.Enabled = False
TextBox1.BackColor = &HFFFFFF
TextBox2.BackColor = &HE0E0E0
TextBox2.Text = Empty
End If

End Sub

----------------------------------------------

Private Sub OptionButton3_Click()

If OptionButton3.Value = True Then
TextBox1.Enabled = False
TextBox2.Enabled = True
TextBox1.BackColor = &HE0E0E0
TextBox2.BackColor = &HFFFFFF
TextBox1.Text = Empty
End If

End Sub

----------------------------------------------

Private Sub TextBox1_Change()

End Sub

----------------------------------------------

Private Sub TextBox2_Change()

End Sub

A: If I understand your question correct then, It ll solve your problem
TextBox1.Enabled = True
TextBox1.SetFocus

A: You need to Activate the textbox, e.g.
TextBox1.Activate


text:
Q: My app crashes when I try to navigate, can't seem to find issue I can't seem to find whats wrong with my application...
Here is the logcat:
11-05 16:37:30.030 7867-7867/com.capstone.miguel.studentassistant E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.capstone.miguel.studentassistant, PID: 7867
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{com.capstone.miguel.studentassistant/com.capstone.miguel.studentassistant.user_sign.LoginActivity}: java.lang.ClassCastException: android.support.design.widget.TextInputEditText cannot be cast to android.support.design.widget.TextInputLayout
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                                Caused by: java.lang.ClassCastException: android.support.design.widget.TextInputEditText cannot be cast to android.support.design.widget.TextInputLayout
                                                                                at com.capstone.miguel.studentassistant.user_sign.LoginActivity.onCreate(LoginActivity.java:34)
                                                                                at android.app.Activity.performCreate(Activity.java:6679)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Any idea why the application crashes?

A: This line is the problem
Caused by: java.lang.ClassCastException: android.support.design.widget.TextInputEditText cannot be cast to android.support.design.widget.TextInputLayout

Check the declared types match those in the layout file

A: It looks like you have wrong casting: java.lang.ClassCastException: android.support.design.widget.TextInputEditText cannot be cast to android.support.design.widget.TextInputLayout
Check if you use the same types in xml and in your code, probably they are different.

A: private TextInputEditText inputEmail, inputPass;
inputEmail = (TextInputEditText) findViewById(R.id.input_log_email);
inputPass = (TextInputEditText) findViewById(R.id.input_log_pass);


text:
Q: Getting weird behavior from Oracle database running on a RDS I created stored functionsin my ORACLE database 10 days ago. They were working fine at that time, but now they don't work anymore even though they are still visible in my ORACLE SQL developer. I had to recompile them in order to get them work. Why is this happening?.
EDIT: I am returning cursors in my stored functions. Maybe I am using them in the wrong way.
create or replace FUNCTION GETREQUESTBYEMPLOYEEID (ID_ IN REIMBREQUEST.EMPLOYEEID%TYPE)
    RETURN SYS_REFCURSOR
AS
  request_cursor SYS_REFCURSOR;
BEGIN
    OPEN request_cursor FOR
    SELECT *
    FROM REIMBREQUEST
    WHERE REIMBREQUEST.EMPLOYEEID = ID_;
    RETURN request_cursor;
END GETREQUESTBYEMPLOYEEID;

A: To expand on the comment by @thatjeffsmith, changes made to an object, such as tables or views, will invalidate code objects which refer to whatever was changed. For instance, if you'd altered the REIMBREQUEST table I'd expect it would have invalidated this procedure. I don't know about other sites, but in our development databases at work we have a procedure which is run every minute which hunts down invalid code objects and recompiles them. If we didn't have something like this developers would spend inordinate amounts of time determining database dependencies and rebuilding code.


text:
Q: Changing words on my website whilesomeone is logged in How can I set words on a page, in my case the words: "sign up/login" change to "profile" when someone is logged in on my site?
I also want to add words that say, "welcome (profile name)
(Website is in html5 and the page has a .php extension, on windows 10 if that helps)

A: Here is a simplest sort of way to show you what to do:
<?php
session_start(); // initialize session to store username to. always do this at the very start of your scripts that use sessions

if(isset($_POST['submit'])) {

    // do some validation ...

    // get user from data source like mysql database with username/password combo
    $valid_user = [
        'username' => 'demo',
        'password' => 'demopass',
        'full_name' => 'Some Name'
    ];

    if($_POST['password'] == $valid_user['password']) {

        $_SESSION['user_session_id'] = session_id();
        $_SESSION['full_name'] = $valid_user['full_name'];

    }

}

if(isset($_SESSION['user_session_id'])) {

    echo 'Hello ' . $_SESSION['full_name'] .'!';

} else {

    $form = '<form method="post">';
    $form .= '<input type="text" name="username" value="">';
    $form .= '<input type="text" name="password" value="">';
    $form .= '<input type="submit" name="submit" value="Login">';
    $form .= '</form>';
    echo $form;

}
?>


text:
Q: jsf - commandLink in a dataTable for delete row I want to put a h:commandLink in a h:dataTable to delete a single row. Here I have a code which does not work and I hope you can help me. This code doesn't even call my delete method.
The data for the h:dataTable comes from a database.
XHTML
        <h:form>
            <div class="center">
                <h:dataTable id="list" value="#{firstBackingBean.list}"
                    var="first" styleClass="center">

                    <!-- other columns (take data from firstBackingBean) -->

                    <h:column>
                        <f:facet name="header" />
                        <h:commandLink value="delete" action="#{secondBackingBean.delete}" >
                            <f:ajax execute="@form" render="list" />
                            <f:param name="id" value="#{first.id}"/>
                        </h:commandLink>
                    </h:column>
                </h:dataTable>
            </div>
        </h:form>

FirstBackingBean
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean
@ViewScoped
public class FirstBackingBean {
    public void delete() {
        System.out.println("\nBUTTON CLICKED\n");
    }
}

SecondBackingBean
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class SecondBackingBean {
    // ...
}

A: When an UICommand component inside an UIData component doesn't invoke its action, then it often means that the model behind the value attribute of the UIData component has incompatibly changed between the request of displaying the form with the table and the subsequent request of submitting the form.
This can happen if the backing bean is request scoped and the model is preinitialized based on a request scoped variable (such as a request parameter), which isn't present during the form submit request anymore.
Placing the bean in the view scope should fix it.
See also:

*

*commandButton/commandLink/ajax action/listener method not invoked or input value not updated

*How can I pass selected row to commandLink inside dataTable?

A: I've the answer!
I've 2 BackingBeans, the firstBackingBean needs the @SessionScoped annotation and the secondBackingBean needs the @ViewScoped annotation.
Thanks a lot for the other answers.


text: Q: Name for largest subset of image whose preimage is contained in the original set? Given a function $f:X \to Y$ and a subset $A \subseteq X$ let $A^*$ be the largest subset of $f(A)$ such that $f^{-1}(A^*) \subseteq A$. Is there a name for $A^*$?


text:
Q: C++ - Search vector via custom key based on elements I have a vector of structs which have about 100 members within the struct. The vector itself can grow to be as large as 1000 elements. I am trying to find a simple way to search the list based on a set of 3 elements every struct contains amongst its many members:

*

*std::string firstName;

*std::string lastName;

*size_t age;

I'm trying to find a way to search the vector based on a key derived from these three values, rather than iterating through the list and doing something like:
for ( int i = 0; i < list.length(); i++ )
{
   if (element[i].lastName  == lastNameToFind  &&
       element[i].firstName == firstNameToFind &&
       element[i].age       == ageToFind)
   {
      // found the element
   }
}

I am looking for faster methods that take advantage of the underlying logic in std::vector to operate more efficiently, and if I want to search by different key tuples, I just change a couple lines of code rather than writing another search function. Is such an approach possible?

A: You could use std::find_if and provide a lambda as a predicate. It will be simpler and more flexible but I'm not sure it will necessarily be faster.
auto findByNameAndAge = [&lastNameToFind, &firstNameToFind, &ageToFind]
                        (const MyStruct& s) {
                            return s.lastName  == lastNameToFind &&
                                   s.firstName == firstNameToFind &&
                                   s.age       == ageToFind;
                        };
auto result = std::find_if(list.begin(), list.end(), findByNameAndAge);

Live demo.
Alternatively, you could create a comparison operator with a key tuple or struct
using MyKey = std::tuple<std::string, std::string, int>;

bool operator==(const MyStruct& s, const MyKey& key){
  return std::tie(s.lastName, s.firstName, s.age) == key;
}

and use std::find:
auto key = MyKey{"Smith", "John", 10};
auto result = std::find(list.begin(), list.end(), key);

Live demo.
If you want faster search you might need to reconsider how you are storing the structs. Perhaps maintain indexes or keep the vector sorted but this may impact the performance of insertions.

A: The first off, why put it in a vector?  I believe an urordered_map might be better off with the hash:
[&last_name, &first_name, age]()
{
   return std::hash<std::string>(last_name+","+first_name) ^ age;
};

I think ^ is a good way of merging two hashes into one. Maybe google that part?
If you insist on a vector, maybe make a smart_ptr and store that in your vector then an unordered_map with the smart_ptr as a value.
PS:
OK xor is a crappy way to hash. use boost::hash_combine or this answer.


text:
Q: Firebase Database Query Error : child is not a function I have a table users in Firebase with these data
{
  "users" :
  [
   {"id": 1,
     "fcmToken" : "APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7hdiWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h",
     "fName" : "John",
     "lName" : "Doe",
     "phone" : "9786770861"
   },
   {"id": 2,
     "fcmToken" : "APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7hdiWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h",
     "fName" : "Jane",
     "lName" : "Doe",
     "phone" : "6178779690"
   }

 ]
}

after import I get this

I tried to query it using NodeJS
/*================================
=            Database            =
================================*/

var admin = require("firebase-admin");

var serviceAccount = require('/Users/john/Desktop/Apps/APNS/node/mhn-app-firebase-adminsdk-bs45c-5ac3770488.json');

var firebase = admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://mhn-app.firebaseio.com"
});

var db = firebase.database();
var users = db.child('users');
var query = users.orderByChild('fcmToken');

console.log(users);

I kept getting this error :
⚡  node  node app.js
/Users/john/Desktop/Apps/APNS/node/app.js:17
var users = db.child('users');
               ^

TypeError: db.child is not a function
    at Object.<anonymous> (/Users/john/Desktop/Apps/APNS/node/app.js:17:16)
    at Module._compile (module.js:643:30)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Function.Module.runMain (module.js:684:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

db.child is not a function

I followed the exact syntax from Firebase tutorial:
https://www.youtube.com/watch?v=3WTQZV5-roY
Look at 4:33 minutes you will see it

I hope someone can shed some lights on this

A: I don't know where did you find this example (apparently from the YouTube Firebase channel !??) but the child() method is a method of a Reference, not of the Database.
You should therefore do:
var db = firebase.database();
var users = db.ref().child('users');
var query = users.orderByChild('fcmToken');

or directly:
var db = firebase.database();
var users = db.ref('users');
var query = users.orderByChild('fcmToken');


text:
Q: How to clear dialog in jQuery UI tabs I use jquery ui tabs with conten via Ajax. In content1.html have a dialog and a button.
When I select "Ajax tab1", click "Open" button to open dlg_set_awd dialog, close this dialog, I select another tab, and then select "Ajax tab1" again, click "Open" button there are two dialog opened with the same ID. How can I clear the dialog when I select another tab?
My code below:
Tab file :
</script>
    <link type="text/css" href="../demos.css" rel="stylesheet" />

HTML :

Nunc tincidunt

Ajax Tab 1

Ajax Tab 2

ABC

content1.html

HTML :
<form id="form1">

First name

                <input type='text' id="first_name" style="width:90px" class="ui-widget-content" />

Last name

                <input type='text' id="last_name" style="width:90px" class="ui-widget-content" />

<button id='open' type="button">Open dialog</button>
</form>

A: Use this code for binding the click event:
    $('#open').unbind('click.myNameSpace').bind("click.myNameSpace", function() {
        if($('#dlg_set_awd').dialog('isOpen')!='true')
        {
            $('#dlg_set_awd').dialog('open');
        }
    });


text:
Q: Easytether .deb won't install due to errors I am running Ubuntu 12.4 64amd. I cant get easy tether to install regardless of which version I use (32 or 64bit) but I keep getting an error when I try to run it in the command line.
It tells me it not a valid deb file. If I click it on the desktop the install manager comes up but the install button is not highlighted for me to click to install it that way.
When I run sudo dpkg -i easytether_0.7.3-1_i386.deb on the package the output is:

dpkg-deb: error: `easytether_0.7.3-1_i386.deb' is not a debian format archive dpkg: error processing easytether_0.7.3-1_i386.deb (--install): subprocess dpkg-deb --control returned error exit status 2 Errors were encountered while processing: easytether_0.7.3-1_i386.deb

Please help. I'll be using my phone as internet modem.

A: Open a terminal ( by pressing Ctrl+Alt+T keyboard shortcut ) and type easytether connect and hit Enter, then minimize the terminal - if you close it it will end. No sudo and you don't really need to install the deb package as long as its there to be accessed.
Hope this helps.


text:
Q: Viewing file in Chinese as UTF-8 encoded on Solaris without changing the locale to Chinese Use Case:
I have a client server setup where server is a Solaris machine and client can be any windows, linux, etc. Client while coming up needs to create a resource bundle object based on client's locale which in turn fetches a Chinese property file maintained at the server (for some design reasons).
Requirement:
I need to maintain the Chinese file at server (utf-8 encoded) without changing server's locale to Chinese. (Similarly, may be later, we may introduce support for some other language. So practically we can't keep server to point to multiple locale simultaneously. Hope I made my point here!)
Problem:
I create Chinese property file on windows machine and then FTP it to Solaris machine and try to view it using VI editor. It gets encoded to some default solaris encoding as shown below:
\217\251\300disk-redundancy.mirrors.label=\207\376\251\207\251\226\207\242\346\206\304\272\205\326\277\207\326\251\205\273\362
LoginWindow.login_label=\207\326\251\205\273\362 Id:
P.S. Changing the locale on the server can't be the part of the solution as already explained above.
FYI:
LANG=
LC_CTYPE="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_COLLATE="C"
LC_MONETARY="C"
LC_MESSAGES="C"
LC_ALL=

Note:
1. cat is showing different result when compared to what described above in VI. Please find below output of cat:
▒▒▒disk-redundancy.mirrors.label=▒▒▒▒▒▒▒▒▒ĺ▒ֿ▒֩▒▒▒ LoginWindow.login_label=▒֩▒▒▒ Id:
I tried to programmatically access file without opening it any editor which, I presume, indicates that the problem is not with the editor.
java DebugTool ?? Id:

*Also encoding finder tool on solaris returns UTF-8.

auto_ef -a chinese.properties
UTF-8 1.00

*I tried to download this file back to windows and view it in an editor and could successfully view it as Chinese file.

disk-redundancy.mirrors.label=系统监控器登录
disk-redundancy.mirrors.value=登录 Id:


text:
Q: Semantical Markup: address, em Im writing a markup and have a doubt at this part:
And here is my markup:

<address>Phone: 1.800.corp</address>

<address>Email: office@corpora.com</address>

<address>Follow Us: </address>

Have I used tags address and em in right way or maybe there are more semantic ones? And maybe  some other mistakes.. Thanks everyone for help.
[Edit]:
According to the answers I've written this:

Phone: 1.800.corp

Email: office@corpora.com

Follow Us:

This contact information is really not mine and as I understand address have nothing to do here. Also I've changed em's on span's. Thanks for help.

A: I think you're using <address> the wrong way. Based on what you can read from the specs, a better way to have your code is to have the <address> as parent. Moreover, the  is to specify stress emphasis and this is not the case. So you should get rid of it. However, if you want it so style differently, you can use a  element to have your CSS hook:
<address>

Phone: 1.800.corp

Email: office@corpora.com

Follow Us:

</address>

A: The address element is defined as providing contact information about the author of the document. This does not look like such contact information. However, hardly any software uses address elements in any particular way, apart from some default styling (e.g., italic font) in some browsers.
The em element is subject to many interpretations, and HTML5 drafts make things even more messy. In practice, it does not matter much. The use of em makes the font italic by default. That's about it. There are rumors about search engines giving em elements larger relative weight within a page. It's questionable whether this would be useful here.


text:
Q: React: setState to a single component from multiple mapped instances of the same component I have a hover state that changes div background color and adds a
 tag to a mapped component:
const [isHover, setIsHover] = useState(false)

Here is the mapped component where I set the state:
const AddSectionButton = ({
  isHover,
  setIsHover,
  sections,
  setSections,
  nextSectionId,
  setNextSectionId,
  sectionTitle,
  setSectionTitle,
  sectionId,
}) => {
  return (
    <AddSectionDiv
      onMouseEnter={() => {
        setIsHover(!isHover);
      }}
      onMouseLeave={() => {
        setIsHover(!isHover);
      }}
      style={isHover && { backgroundColor: "#A4AAE0" }}
    >
      {isHover &&
Add Section
}
    </AddSectionDiv>
  );
};

Whenever I hover to a single mapped component, the rest of the mapped components trigger the hover effect as well.
How do I set the state to only the hovered component and not affect the rest?
I thought about using a key, where as you can see in my mapped component, I passed a sectionId prop which contains the key, but I'm confused as to how I should use it.

A: You can, and should, use a key or any value/property that uniquely identifies the element being hovered.
In the parent use an initially null isHover state.
const [isHover, setIsHover] = useState(null);

And in the children set or clear the isHover state by their id. And check if the current isHover value matches the current sectionId value.
const AddSectionButton = ({
  isHover,
  setIsHover,
  sections,
  setSections,
  nextSectionId,
  setNextSectionId,
  sectionTitle,
  setSectionTitle,
  sectionId,
}) => {
  return (
    <AddSectionDiv
      onMouseEnter={() => {
        setIsHover(sectionId);
      }}
      onMouseLeave={() => {
        setIsHover(null);
      }}
      style={isHover === sectionId && { backgroundColor: "#A4AAE0" }}
    >
      {isHover === sectionId &&
Add Section
}
    </AddSectionDiv>
  );
};

Consider moving/implementing this isHover state internally to each component, the parent component likely doesn't need to concern itself with the hover status of any of its children. Do this and your original logic is fine.
const AddSectionButton = ({
  sections,
  setSections,
  nextSectionId,
  setNextSectionId,
  sectionTitle,
  setSectionTitle,
  sectionId,
}) => {
  const [isHover, setIsHover] = useState(false);

  return (
    <AddSectionDiv
      onMouseEnter={() => {
        setIsHover(true);
      }}
      onMouseLeave={() => {
        setIsHover(false);
      }}
      style={isHover && { backgroundColor: "#A4AAE0" }}
    >
      {isHover &&
Add Section
}
    </AddSectionDiv>
  );
};


text:
Q: In which sense we have unicity of solution in stochastic differential equation? Let $$dX_t=f(X_t)dt+g(X_t)dB_t,$$
and SDE with $f$ and $g$ nice enough to have existence and unicity of the solution. I'm not sure what mean unicity here. For example, consider the equation $dX_t=dB_t\quad \text{and}\quad X_0=0.\tag{E}$ Does it mean that $X_t$ is a standard brownian motion, or do we really have $\mathbb P(\forall s, X_s=B_s)=1$ ? (or maybe rather $\forall s, \mathbb P(X_s=B_s)=1$). Or does it mean that $(X_t)$ and $(B_t)$ has same finite dimensional distribution ? For example, $(tB_{1/t})_t$ is also a solution of $(E)$ ?


text:
Q: Proving that a product of two compact metric spaces is compact. (basic real analysis) I'm not really sure if this sort of question is frowned upon here, but I don't understand a proposed solution to an exercise I was given. Let me know if it's an inappropriate question and I won't ask similar ones again.
Let K be a compact metric space with metric d.
Exercise: Show that the product $K \times K$ with the metric
$d_{MH}((x_1,x_2)(y_1,y_2)) = d(x_1,y_1) + d(x_2,y_2)$ is compact.
Solution (or at least the part of it I'm not understanding):
"Now if we let $(z_n) = (x_n,y _n)$ be a sequence in $K\times K$. Then $x_n$ is a sequence in K, so has a convergent subsequence, say ${x_n}_k$, which converges to some $x\in K$. The corresponding subsequence ${y_n}_k$ is again a sequence in K, so has a convergent subsequence, say ${{y_n}_k}_l$, which converges to $y \in K$. Then ${{x_n}_k}_l$ is a subsequence of the convergent sequence ${x_n}_k$, so it converges to the same element x."
Question: Why do we need the sub subsequences: ${{x_n}_k}_l$ and ${{y_n}_k}_l$?
I thought it was sufficient to show that all sequences had a convergent subsequence in order to show that $K\times K$ was compact.

A: We cannot use the subsequence $(x_{nk}, y_{nk})$ of $(x_n, y_n)$ because although the subsequence $x_{nk}$ of $x_n$ is convergent, there is no guarantee that the corresponding $y_{nk}$ of $y_n$ is convergent. But $y_{nk}$ must have a convergent subsequence and its corresponding subsequence in $x_{nk}$ must also be convergent (being a subsequence of a convergent sequence). This gives us a convergent subsequence of $(x_{nk}, y_{nk})$ and hence a convergent subsequence of $(x_n, y_n)$.


text:
Q: How do I select rows from one table filtered by another table in MySQL? I have a table members:
member_id, points

And I have another table bets:
member_id, finished

Consider following data for table members:
1 0
2 15000
3 0

And for bets:
1 -1
1  0
2  1
3  1
3 -1

In the table bets finished = -1 marks the bet as lost, 0 as unfinished and 1 as won.
How can I select member id's which have 0 points and all their bets are finished? With the data I have given, it should return one row with member id = 3.

A: You could use EXISTS clause:
select members.id
from members
where
  points=0
  and not exists (select null from bets where bets.id=members.id and status=0)

You can also use a LEFT JOIN:
select members.id
from
  members left join bets
  on members.id = bets.id
     and bets.status=0
where
  bets.id is null
  and members.points=0

A: Use a JOIN, like so:
select members.member_id, members.points, bets.finished
  from members
  join bets on bets.member_id = members.member_id
  where bets.finished <> 0 and members.points = 0;

A: You can use an inner join
SELECT member_id FROM members m
INNER JOIN bets b
ON m.member_id = b.member_id
WHERE b.finished = 0 AND m.points = 0

An inner join is the most common join operation used in applications and can be regarded as the default join-type. Inner join creates a new result table by combining column values of two tables (A and B) based upon the join-predicate. The query compares each row of A with each row of B to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied, column values for each matched pair of rows of A and B are combined into a result row.

http://en.wikipedia.org/wiki/Join_(SQL)#Inner_join
In your case, the join-predicate is m.member_id = b.member_id.

A: -- Most of the answers don't address your key issue - All of the bets are placed not just one of them
-- Here you go
Select memberid
  from members
 where points = 0
   and member id not in (select member id from bets where bet <> -1 )

Or For Even Greater Efficiency as data grows to very very high volume
Select memberid
  from members
 where points = 0
   and member id not in (select member id from bets where bet <> -1 and bets.memberid = members.memberid)

A: try this
   SELECT m.member_id , b.finished FROM members m
   INNER JOIN bets b
   ON m.member_id = b.member_id
   WHERE m.points = 0
   and b.finished = 1

LOOK DEMO SQLFIDDLE


text:
Q: Aggregate POLYGONs to MULTIPOLYGONs and keep data.frame I have a sf object of POLYGON geometry type. I would like to aggregate these polygons into MULTIPOLYGONs using grouping attribute (group_attr) and join a new MULTIPOLYGON object with a attribute table. So, as a result, I will have a sf object with two rows and three columns (group_attr, second_attr, geometry). I've already tried to used st_cast - it works well on sfc objects, but not on sf objects. Is it possible to do this using sf package?
p1 <- rbind(c(0,0), c(1,0), c(3,2), c(2,4), c(1,4), c(0,0))
pol1 <-st_polygon(list(p1))
p2 <- rbind(c(3,0), c(4,0), c(4,1), c(3,1), c(3,0))
pol2 <-st_polygon(list(p2))
p3 <- rbind(c(4,0), c(4,1), c(5,1), c(5,0),c(4,0))
pol3 <-st_polygon(list(p3))
p4 <- rbind(c(3,3), c(4,2), c(4,3), c(3,3))
pol4 <-st_polygon(list(p4))

d <- data.frame(group_attr = c(1, 1, 2, 2),
                second_attr = c('forest', 'forest', 'lake', 'lake'))
d$geometry <- st_sfc(pol1, pol2, pol3, pol4)
df<- st_as_sf(d)
plot(df)
df

Simple feature collection with 4 features and 2 fields
geometry type:  POLYGON
dimension:      XY
bbox:           xmin: 0 ymin: 0 xmax: 5 ymax: 4
epsg (SRID):    NA
proj4string:    NA
  group_attr second_attr                       geometry
1          1      forest POLYGON((0 0, 1 0, 3 2, 2 4...
2          1      forest POLYGON((3 0, 4 0, 4 1, 3 1...
3          2        lake POLYGON((4 0, 4 1, 5 1, 5 0...
4          2        lake  POLYGON((3 3, 4 2, 4 3, 3 3))

A: A new approach based on https://github.com/r-spatial/sf/issues/634#issuecomment-365151794:
library(dplyr)

df_new <- df %>%
  group_by(group_attr) %>%
  summarise_all(first)
df_new

Simple feature collection with 2 features and 2 fields
geometry type:  MULTIPOLYGON
dimension:      XY
bbox:           xmin: 0 ymin: 0 xmax: 5 ymax: 4
epsg (SRID):    NA
proj4string:    NA
# A tibble: 2 x 3
  group_attr second_attr                                                        geometry
       <dbl> <fct>                                                        <MULTIPOLYGON>
1       1.00 forest      (((3 0, 3 1, 4 1, 4 0, 3 0)), ((0 0, 1 4, 2 4, 3 2, 1 0, 0 0)))
2       2.00 lake                  (((4 0, 4 1, 5 1, 5 0, 4 0)), ((3 3, 4 2, 4 3, 3 3)))

A: or:
> aggregate(df, list(df$second_attr), function(x) x[1])
Simple feature collection with 2 features and 3 fields
Attribute-geometry relationship: 0 constant, 2 aggregate, 1 identity
geometry type:  MULTIPOLYGON
dimension:      XY
bbox:           xmin: 0 ymin: 0 xmax: 5 ymax: 4
epsg (SRID):    NA
proj4string:    NA
  Group.1 group_attr second_attr                       geometry
1  forest          1      forest MULTIPOLYGON(((3 0, 3 1, 4 ...
2    lake          2        lake MULTIPOLYGON(((4 0, 4 1, 5 ...

A: Very hacky (or naive) approach:
attr_table <- df %>%
        as_data_frame() %>%
        select(-geometry) %>%
        unique()

new_df <- df %>%
        group_by(group_attr) %>%
        summarise() %>%
        as.data.frame(.) %>%
        left_join(., attr_table, by='group_attr')   %>%
        st_as_sf()

new_df

Simple feature collection with 2 features and 2 fields
geometry type:  MULTIPOLYGON
dimension:      XY
bbox:           xmin: 0 ymin: 0 xmax: 5 ymax: 4
epsg (SRID):    NA
proj4string:    NA
  group_attr second_attr                       geometry
1          1      forest MULTIPOLYGON(((3 0, 3 1, 4 ...
2          2        lake MULTIPOLYGON(((4 0, 4 1, 5 ...


text:
Q: Resampling a 2D signal using linear interpolation Standard algorithm
I'm currently implementing a modified range migration algorithm for processing synthetic aperture radar (SAR) data. The algorithm contains a step called Stolt interpolation, which resamples the data $f(K_X, K_R)$ uniformly sampled along the $K_X$ and $K_R$ dimensions, where $K_R$ is a radial coordinate measured from the origin, to a Cartesian coordinate system $g(K_X, K_Y)$ such that the samples are uniformly spaced on the $K_X$,$K_Y$ grid.
In order to do this, the change of variables $\sqrt{K_R^2 - K_X^2} \rightarrow K_Y$ is performed using linear interpolation, i.e. $g(K_X, K_Y) = f(K_X, \sqrt{K_X^2 + K_Y^2})$, where $K_X \in [-\frac{B}{2}, \frac{B}{2}]$ and $K_R > 0$.
In order to determine the set of $K_Y$ for which to evaluate $K_R = \sqrt{K_X^2 + K_Y^2}$, we can easily see that $K_Y \in \left[\sqrt{K_{Rmin}^2 - K_{Xmax}^2};K_R \right]$.
Modified algorithm
Now I would like to perform a slightly different change of variables. The change of variables is
$\sqrt{K_R^2 - \left[aK_R + (1-a^2)K_X\right]^2} \rightarrow K_Y$, where $a \in [0;1]$.
Once again I tried to find a solution for $K_R$ based on $K_Y$:
$K_Y = \sqrt{K_R^2 - \left[aK_R + (1-a^2)K_X\right]^2} = \sqrt{(1-a^2)K_R^2 - 2a(1-a^2)K_X K_R - (1-a^2)^2K_X^2}$
squaring both sides and rearranging leads me to
$K_R^2 - 2 a K_X K_R - (1-a^2)K_X^2 - \frac{K_Y^2}{1-a^2} = 0$
with the solutions
$K_{R1/2} = aK_X \pm \sqrt{K_X^2 + \frac{K_Y^2}{1-a^2}}$.
Because I know that $K_R \geq 0$ I can choose $K_R = aK_X + \sqrt{K_X^2 + \frac{K_Y^2}{1-a^2}}$.
And we have the resampled signal $g(K_X, K_Y) = f(K_X, aK_X + \sqrt{K_X^2 + \frac{K_Y^2}{1-a^2}})$.
However I'm not quite sure how to determine the limits of $K_Y$ for the resamping operation, because $K_R$ and $K_X$ are now coupled.
For the maximum value of $K_Y$ I have $K_{Ymax} = K_{Rmax}$, however I'm not so sure about the minimum value for $K_Y$ because the global minimum of $K_Y$ at $K_X = K_R = 0$ is not useful due to $K_R > 0$.
How do I determine $K_{Ymin}$?
This is my first time using linear interpolation for multidimensional signal resampling so I'm really not sure about my chosen methodology. The text books about SAR processing conveniently omit the details of this interpolation step.
I'd be grateful for any help!


text:
Q: How to use contact events On my HTC Desire phone I have 'events' field on contact level. It allows to add some information to contact such as birthday and so on.
I have 2 question regarding it:

*

*I cannot find such a field on Android emulator? Does it exist? If yes how to turn it on?

*Is HTC "events" the same as Android standard (from SDK) "events" or is it HTC specific feature?

Thanks in advance!


text:
Q: mounted directory has the wrong ownership I have the following kubernetes yaml file:
1   apiVersion: apps/v1
  1 kind: Deployment
  2 metadata:
  3   name: postgres-deployment
  4 spec:
  5   replicas: 1
  6   selector:
  7     matchLabels:
  8       component: postgres
  9   template:
 10     metadata:
 11       labels:
 12         component: postgres
 13     spec:
 14       securityContext:
 15           runAsUser: 999
 16           runAsGroup: 999
 17           fsGroup: 999
 18       volumes:
 19         - name: postgres-storage
 20           persistentVolumeClaim:
 21             claimName: postgres-persistent-volume-claim
 22       containers:
 23         - name: postgres
 24           image: prikshet/postgres
 25           ports:
 26             - containerPort: 5432
 27           volumeMounts:
 28             - name: postgres-storage
 29               mountPath: /var/lib/postgresql/data
 30               subPath: postgres
 31           imagePullPolicy: Always

But the pod is giving the following logs:
2021-08-11 06:06:15.749 GMT [8] LOG:  skipping missing configuration file "/var/lib/postgresql/data/postgresql.auto.conf"
2021-08-11 06:06:15.750 UTC [8] FATAL:  data directory "/var/lib/postgresql/data" has wrong ownership
2021-08-11 06:06:15.750 UTC [8] HINT:  The server must be started by the user that owns the data directory.

Whereas clearly I have the fsGroup, runAsUser and runAsGroup specified. What might be causing this error?

A: The problem here is that you might have many available PersistentVolumes backed with local storage and the postgres pod is randomly assigned to one of them, but you only changed the ownership of one PV to the correct values. So if your pod is assigned to any of the other PVs it will crash.
In particular, this can happen on the next redeploy, even if the first deploy ran alright. That's because Kubernetes has a bug where deleted PersistentVolumeClaims keeps the PersistentVolumes in "Released" status forever (at least for the local storage class). So your pod will never be assigned to the "fixed" mount point, it will be stuck in Pending or assigned to another local PV with wrong permissions on its point.
You need to identify the PersistentVolume that is being used by the pod using something like kubectl get pv and then inside their mount points, change the owner and group of all local, available volumes to 999:999.
Some Postgres instances installed from Bitnami's Helm charts also raise this error but those permissions have to be changed to 1001:1001 instead on all available mount points. Bounded mount points do not have to be changed.

A: I would use an initContainer: to chmod just like you and this answer will might help you.init Container and security context


text:
Q: Regular expressions do not work when combined In an Intro to Data Science course, the assignment is to find four regular expressions to match the IP address, the time, the user name, and the HTTP method from a file called "logdata" and build a list of dictionaries.
A typical line from the file looks like:
146.204.224.152 - feest6811 [21/Jun/2019:15:45:24 -0700] "POST /incentivize HTTP/1.1" 302 4622

Using re.findall(), the following regular expressions work:
re.findall('(?P<time>\[(.+?)\])', logdata)

re.findall('(?P<method>".*?")', logdata)

re.findall('(?P<host>\d+\.\d+\.\d+\.\d+)', logdata)

re.findall('(?P<user_name>-\s[\w-]*)', logdata)

but when putting them together for an iteration (using re.finditer()), such as:
for i in re.finditer('(?P<time>\[(.+?)\])(?P<host>(\d+\.\d+\.\d+\.\d+)(?P<tag>".*?")(?P<host>\d+\.\d+\.\d+\.\d+)', logdata):
    f = i.groupdict()  #f is a list

it does not work.

A: When breaking up a log messaGe like this using regex, I would typically recommend building up your regex one piece at a time, remembering to account for every character in a line., including separating spaces:
So, here is our log line:
146.204.224.152 - feest6811 [21/Jun/2019:15:45:24 -0700] "POST /incentivize HTTP/1.1" 302 4622

Now, let's start with the ip address:
for i in re.finditer('^(?P<host>\d+\.\d+\.\d+\.\d+)', logdata):
    print(i.groupdict())

After the ip address, we see a space, followed by the username, so now we add that to our re:
for i in re.finditer('^(?P<host>\d+\.\d+\.\d+\.\d+) \- (?P<user_name>[\w]+)', logdata):
    print(i.groupdict())

note a couple of things above, the - shouldn't be part of the captured user_name, and it should have one or more characters.
Third, we have another space between the username and the time, and you'll see we did the same thing here that we did with the - in front o fthe usernawme, leaving the [] out of the captured group for the time:
for i in re.finditer('^(?P<host>\d+\.\d+\.\d+\.\d+) \- (?P<user_name>[\w]+) \[(?P<time>(.+?))\]', logdata):
    print(i.groupdict())

and now for the method, it's the same thing, a space, with the method as the first part after the quote:
for i in re.finditer('^(?P<host>\d+\.\d+\.\d+\.\d+) \- (?P<user_name>[\w]+) \[(?P<time>(.+?))\] "(?P<method>POST|PATCH|HEAD|GET|DELETE|PUT|CONNECT|OPTIONS|TRACE)', logdata):
    print(i.groupdict())

I used a tighter expression since technically, valid methods are only the first word, but you can use your existing regex if you want to capture the route as well as the http version.

A: *

*You have two host groups,

*One closing parenthesis is missing.

More importantly, if you want only one loop, the resulting regular expression should be a new one, reflecting the real structure of the access log: not only the parts that interest you but also what is in between.
Like this:
^(?P<host>\d+\.\d+\.\d+\.\d+)\s+(?P<user_name>-\s[\w-]*)\s+(?P<time>\[(.+?)\])\s+(?P<method>".*?")\s+\d+\s+\d+$, with re.M.
Also, I think, your regular expressions for the IP address, time, etc. are not specific enough for real usage. E.g. (?P<IP>\d{1,3}(\.\d{1,3}){3}) for IP address is better, though still not pefect (will allow 300.300.300.300, for example).
https://regex101.com/r/amAN54/1


text:
Q: Xamarin Form - Can't get return value data from Service class method into MainPage method for filtering I'm new to Xamarin, I have an app in Xamarin-Form that it's fetching data from web api and getting user input from Entry control.
The web api service class is working fine and reaches the deserialization in the getCourses method as seen below in Code Snippet 1.
The Entry control as well is working fine until it retrieves the user input on the MainPage class, OnOkGetCourseButton method as seen below Code Snippet 2.
What I want to achieve is, inside MainPage.xaml.cs, I create a method that takes the user input data and check agaisnt the deseriaized json data (the Id specially),
if it finds the Id in deserialized List of data, then it can send the found data to another ViewPage and display them.
if It cannot find the data, it shows a dialog box.
So far, I tried to call Task<ObservableCollection> getCourses() method from the MainPage class, inside CheckCourseComplete as seen below but it giving me no value/nothing, some kind of null value.
I don't want to filter the user input against web api json response inside getCourses(),
I want to do that in a separate method to follow S-OLID (Single Responsibility Principle).
If it's not possible in a separate method, then I just need to get it worked.
Please what is the best way to achieve it?
Code Snippet 1
       public class CourseService : ICourseService
       {

           string Base_Url = "https://www.test.com/api/TheCourse";

           public async Task<ObservableCollection<Course>> getCourses()
           {
               try
               {
                   string url = Base_Url;

                   HttpClient client = new HttpClient();
                   HttpResponseMessage responseMessage = await client.GetAsync(url);

                   if (responseMessage.StatusCode == System.Net.HttpStatusCode.OK)
                   {
                       var result = await responseMessage.Content.ReadAsStringAsync();
                       var deserializedClass = JsonConvert.DeserializeObject<ObservableCollection<Course>>(result);

                       // I don't want to do that here, as it will violate SRP (SOLID)

                       return deserializedClass;
                   }

                   return null;
               }
               catch (Exception)
               {
                   throw;
               }
           }

       }

Code Snippet 2
namespace CourseMobile
{
    public partial class MainPage : ContentPage
    {
        private string _getEntryText;

        private readonly CourseViewModel orderViewModel;
        public Course FetchCourse { get; set; }

        public MainPage()
        {
            InitializeComponent();
            CheckCourseComplete();
            BindingContext = new CourseViewModel();
        }

        public string GetEntryText
        {
            get => _getEntryText;
            set => _getEntryText = value;
        }

        public async void OnOkGetCourseButton(object sender, EventArgs e)
        {
            var inputtedCourseNumber = this.GetEntryText;

            if(inputtedCourseNumber == string.Empty)
            {
                await DisplayAlert("", "Please enter your Course number", "OK 3");
            }
            else
            {
                CheckCourseComplete();

                this.GetEntryText = inputtedCourseNumber;

                await DisplayAlert("New Text", inputtedCourseNumber, "OK 2");
            }
        }

        void Entry_TextChanged(object sender, TextChangedEventArgs e)
        {
            var newText = e.NewTextValue;
            this.GetEntryText = newText;
        }

        public async void CheckCourseComplete()
        {
            CourseService myCourse = new CourseService();

            await myCourse.getCourses();            // It doesn't return the json data (web api data)

            // I need to check user input + (web api data) here

        }

    }
}

A: getCourses is async, so you need to use await when calling it
    public async void CheckCourseComplete()
    {
        CourseService myCourse = new CourseService();

        var data = await myCourse.getCourses();

        // now filter data
    }


text:
Q: Java class whose fields are only accessible to its subclasses (without getters/setters)? What I really want is a class with a generic constructor, and when a subclass' identical constructor is invoked, the subclass will have access to the same fields.  Here is an example of what I would like to do:
public abstract class Command{
    private Mediator m

    public Command(Mediator med){
       m = med;
    }

    abstract void exec();
}

public class FoobarCommand extends Command{
    public FoobarCommand(Mediator med){
        super(med);
    }

    public void exec(){
        med.doAFoobar()
    }
 }

public static void main(String[] args){
    Mediator m = new Mediator();
    Command c = new FoobarCommand(m);
    c.exec();
}

Obviously this won't work because FoobarCommand doesn't have direct access to Mediator med.  So how would you access the med field?  I don't want anyone else but the subclasses to have access to it, and "protected" is not an option because I want people to be able to create their own commands (which obviously would be outside the package).

A: Declare Mediator Med as "protected" not private.

A: you need to declare Mediator m protected in your mother class.
Moreover, in the exec() method in your subclass , you need to do m.doAFoobar() instead of med.doAFoobar() since med is not a member but a formal parameter of your constructor.

A: There is actually no such access modifier, strictly speaking.  It's impossible to declare a field (or method/class, for that matter) only accessible to subclasses; the most restrictive modifier you can use is protected, which still allows access to other classes in the parent class' package.
But other than that niggle, protected is the way to go.
Edit: to clarify that protected is an option.  To access a protected method, you must be either a subclass or within the same package; you don't have to be both.  So a subclass of Command created in a different package would still be able to access (super).m.

A: abstract class Command {
    protected Mediator m

    public Command(Mediator med){
        m = med;
    }

    abstract void exec();
}

The class is not public, so it can only be extended by other classes in the same package and 'm' is protected so it can be accessed by derived classes.

A: If you give med protected access it will be available to subclasses outside of the package.
http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html

A: If you want a field to be accessible to only the class itself and any derived classes and other classes in that package, use the protected keyword.  That's what it's there for, and it should still work even outside the package.  Instead of having them call med.doFoobar();, they need to call m.doFoobar();
Alternately, you could create a protected (or public, even) get function.  That way you expose the ability to get the mediator, but you don't have to let them overwrite it after it's declared.
However, what you want (unable to be read inside the package) is impossible in java keywording.  But, since you're the one writing this particular package, couldn't you just not access it from inside the package?  Or create your own package with just this file?  There's no way to allow subclasses access and not allow classes in the package.

A: What you can do is give the subclass a variable that is named the exact same thing, then set it equal to the superclass using constructors and methods like
public abstract class Command{
    private Mediator m

    public Command(Mediator med){
       m = med;
    }

    abstract void exec();
}

public class FoobarCommand extends Command{

    private Mediator m;

    public FoobarCommand(Mediator med){
        super(med);
        m = med;
    }

    public void exec(){
        m.doAFoobar()
    }
 }

public static void main(String[] args){
    Mediator m = new Mediator();
    Command c = new FoobarCommand(m);
    c.exec();
}

However, this is limited in what it can do.  As m is an object reference, changes to m in the subclass will be reflected in the superclass; however, this would not occur if the class member was a primitive.  (Given all primitives have an object equivalent, this can be worked around if slightly clunky)
The subclass must also directly receive the reference, as that's where a copy to the reference is stored.  For abstract superclasses this is fine as you are guaranteed a subclass, but below that you have to be careful how you handle the data.


text:
Q: Snipcart or other similar solutions I am developing a website for a small business in Spain with Java, Bootstrap, jQuery and I need to integrate an ecommerce platform
Is Snipcart the best option or do you recommend any of the similar solutions that for some reason you will agree is better?
Thank you

A: Disclaimer: I work for Snipcart
The advantage of Snipcart over other solutions is that it's independent of your other stack choices. You can select your backend tech based on what you're the most comfortable with.
If Java, Bootstrap and jQuery are requirements for the project, Snipcart won't get in the way of those. That's one of the big selling points, it can provide a lot of features for platforms that don't have a feature-full ecommerce framework.
I wouldn't know which Java-based ecommerce platform to recommend and compare to. There seems to be a few but none with big market shares or recognized name.
If Java isn't a strong requirement of the project, I'd look into PHP and Ruby/Rails solutions as they have more mature ecommerce solutions.


text:
Q: How to trigger an any aws resource based on creation of another aws resource? I am using cloudformation template to build a dynamo db ( see below), once the stack builds successfully, I would like to alert/notify/trigger another aws resource, like a lambda function or a step function or a aws data pipeline to start such that I can start populating the dynamo. what is the best way to trigger another process or aws resource once cloudformation stack creation is successful ?
AWSTemplateFormatVersion: 2010-09-09
Description: AWS CloudFormation Template To Create a DynamoDB

Parameters:
  HashKeyElementName:
    Type: String
    Default: Id
    Description: Hash Key Name
  HashKeyElementType:
    Type: String
    Default: S
    Description: Hash Key Type
Resources:
  Table:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: MyTable
      AttributeDefinitions:
        -
          AttributeName: !Ref HashKeyElementName
          AttributeType: !Ref HashKeyElementType
      KeySchema:
        -
          AttributeName: !Ref HashKeyElementName
          KeyType: HASH
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5
Outputs:
  MyTable:
    Description: Table Created using this template.
    Value: !Ref Table

A: You can setup SNS topic and a lambda function to get events from stack creation. An example of how to do it is given in AWS docs:

*

*How can I receive an email alert when my AWS CloudFormation stack enters ROLLBACK_IN_PROGRESS status?
You would have to adapt the example and the lambda to suit your needs.


text:
Q: Triggering events based on choices made inside of system dialogs (e.g. window close) I'm trying to arrange for Mathematica to perform a certain action every time a notebook is saved or closed (with or without saving).  The obvious way to do this would be through event handling.  So, for example, I have the bit of code
SetOptions[$FrontEnd,
   FrontEndEventActions -> {
        {"MenuCommand", "Save"} :> DoMyThing[],
        PassEventsDown -> True
    }
];

that performs the action DoMyThing[ ] whenever a notebook is saved (via either the File menu, or Ctrl-s shortcut).  This also gets triggered when a modified notebook is closed by the user and they choose to save at that point (via the "Save changes to... ?" system dialog window).  This is all as I want it so far.
The thing I cannot work out is how to set up different behavior based on the user clicking the "Don't Save" or "Cancel" buttons in the "Save changes to... ?" dialog.  Something like
SetOptions[$FrontEnd,
    NotebookEventActions -> {
        "WindowClose" :> DoMyThing[],
        PassEventsDown -> True
    }
];

will trigger DoMyThing[ ] as soon as the user tries to close the window, even if they proceed to select "Cancel" in the subsequent dialog window, which is NOT what I want.  Is there a way to capture the user input to this system dialog and direct alternate behavior from within NotebookEventActions based on their choice?  Failing that, is there another solution that will do what I want?  I can't see a way, for example, even to check whether the notebook in question is still open after the user makes their choice, since my custom event actions are triggered ~before~ the "WindowClose" event is passed down to the system's lower-level event-handler (unless I can control that order of operations somehow through an option of which I am unaware). Thanks for your help!
p.s.- I suppose that I could override the default behavior and write my own window-close dialog (setting PassEventsDown -> False in that case), but that seems like a sledgehammer approach, and I'm hoping there's a simpler way.

A: As you mentioned,*EventActions are called before any lower-level stuff, so yes this means you could write your own window-close dialog, but there's another way, assuming you're not killing the kernel too. It's obviously not ideal, but you can do this via RunScheduledTask and really quite simply too.
This is what I often do for event actions when I need them to apply after the default and when either the event will be done quick or the "didn't happen action" isn't time sensitive. That isn't necessarily the case here, but it's still a somewhat workable solution.
First a little macro to build our conditional events:
conditionalEvent[
   test_, true_, false_,
   timeout_: 5, poll_: .1] :=
  (With[{now = Now},
     RunScheduledTask[
      If[test // TrueQ,
       true;
       RemoveScheduledTask@$ScheduledTask,
       If[Quantity[timeout, "Seconds"] < Now - now,
        false;
        RemoveScheduledTask@$ScheduledTask
        ]
       ],
      {poll, \[Infinity]}
      ]
     ] &);
conditionalEvent~SetAttributes~HoldAll

And then we just have to write the appropriate test. In our "WindowClose" case this could be something like NotebookInformation@nb===$Failed (note that we'll have to provide a NotebookObject as we can't depend on EvaluationNotebook[] to give us what we really want.
Then just do something like this:
With[{e = EvaluationNotebook[]},
  conditionalEvent[
   NotebookInformation@e===$Failed,
   MessageDialog["Closed!"],
   MessageDialog["Still open..."]
   ]
  ][]

And for the {"MenuCommand","Save"} call we can use "ModifiedInMemory"/.NotebookInformation@nb as our test so we have:
With[{e = EvaluationNotebook[]},
  conditionalEvent[
   ! ("ModifiedInMemory" /. NotebookInformation@e),
   MessageDialog["Saved!"],
   MessageDialog["Not saved..."]
   ]
  ][]

Then just put this all together:
With[{e=EvaluationNotebook[]},
 With[{
  closeCMD=
   conditionalEvent[
    NotebookInformation@e===$Failed,
    DoMyClosingThing[],
    TwiddleMyThumbs[]
    ],
  saveCMD=
   conditionalEvent[
    ! ("ModifiedInMemory" /. NotebookInformation@e),
    DoMySavingThing[],
    TwiddleMyUnsavedThumbs[]
    ]
  },
  SetOptions[e,
   NotebookEventActions->{
    "WindowClose":>closeCMD[],
    {"MenuCommand","Save"}:>saveCMD[],
    PassEventsDown->True
    }
  ]
]

Obviously if you can find a way to check that the notebook is locked to clicking that obviates the need for any checking of this nature. Notably this isn't possible to discover via any of the Notebook options, as far as I could see (e.g. Selectable, WindowClickSelect, Editable, etc. were unchanged by the appearance of this dialog). This might be something that you could spelunk up, as there are lots of dialogs that the front end generates that attach to the Notebook window in the same way (or at least they attach on Mac) and it might be possible to snoop out what's going on there although I highly doubt this is exposed as a Mathematica code, honestly.


text:
Q: How to monitor a group of tasks in celery? I have a situation where a periodic monthly big_task reads a file and enqueue one chained-task per row in this file, where the chained tasks are small_task_1 and small_task_2:
class BigTask(PeriodicTask):

    run_every = crontab(hour=00, minute=00, day_of_month=1)

    def run(self):
        task_list = []
        with open("the_file.csv" as f:
            for row in f:
                t = chain(
                        small_task_1.s(row),
                        small_task_2.s(),
                     )
                task_list.append(t)
            gr = group(*task_list)
            r = gr.apply_async()

I would like to get statistics about the number of enqueued, failed tasks (and detail about the exception) for each small_task, as soon as all of them are finished (whatever the status is) to send a summary email to the project admins.
I first thought of using chord, but callback is not executed if any of the headers task fails, which will surely happen in my case.
I could also use r.get() in the BigTask, very convenient, but not recommended to wait for a task result into another task (even if here, I guess the risk of worker deadlock is poor since task will be executed only once a month).
Important note: input file contains ~700k rows.
How would you recommend to proceed?

A: I'm not sure if it can help you to monitor, but about the chord and the callback issue you could use link_error callback (for catching exceptions). In your case for example you can use it like:
small_task_1.s(row).set(link_error=error_task))

and implement celery error_task that send you notification or whatever.
In celery 4, you can set it once for the all canvas (but it didn't work for me in 3.1):
r = gr.apply_async(link_error=error_task)

For the monitoring part, you can use flower of course.
Hope that help
EDIT: An alternative (without using additional persistency) would be to catch the exception and add some logic to the result and the callback. For example:
def small_task_1():
    try:
       // do stuff
       return 'success', result
    except:
       return 'fail', result

and then in your callback task iterate over the results tuples and check for fails because doing the actual logic.

A: I found the best solution to be iterate over the group results, after the group is ready.
When you issue a Group, you have a ResultSet object. You can .save() this object, to get it later and check if .is_ready, or you can call .join() and wait for the results.
When it ends, you can access .results and you have a list of AsyncResult objects. These objects all have a .state property that you can access and check if the task was successul or not.
However, you can only check the results after the group ends. During the process, you can get the value of .completed_count() and have an idea of group progress.
https://docs.celeryproject.org/en/latest/reference/celery.result.html#celery.result.ResultSet

A: The solution we use for a partly similar problem where celery builtin stuff (tasks states etc) doesn't really cut it is to manually store desired informations in Redis and retrieve them when needed.


text:
Q: Max and min values in pandas I have the following data:
High    Low Open    Close   Volume  Adj Close
Date
1999-12-31  1472.420044 1458.189941 1464.469971 1469.250000 374050000   1469.250000
2000-01-03  1478.000000 1438.359985 1469.250000 1455.219971 931800000   1455.219971
2000-01-04  1455.219971 1397.430054 1455.219971 1399.420044 1009000000  1399.420044
2000-01-05  1413.270020 1377.680054 1399.420044 1402.109985 1085500000  1402.109985
2000-01-06  1411.900024 1392.099976 1402.109985 1403.449951 1092300000  1403.449951
... ... ... ... ... ... ...
2020-01-06  3246.840088 3214.639893 3217.550049 3246.280029 3674070000  3246.280029
2020-01-07  3244.909912 3232.429932 3241.860107 3237.179932 3420380000  3237.179932
2020-01-08  3267.070068 3236.669922 3238.590088 3253.050049 3720890000  3253.050049
2020-01-09  3275.580078 3263.669922 3266.030029 3274.699951 3638390000  3274.699951
2020-01-10  3282.989990 3268.010010 3281.810059 3273.739990 920449258   3273.739990
5039 rows × 6 columns

Since this is the daily data this was resampled to weekly to find the 52 week high and low.
weekly_high = data.High.groupby(pd.Grouper(freq='M')).tail(52)
weekly_low = data.Low.groupby(pd.Grouper(freq='M')).tail(52)

Here is the problem:
weekly_high.max()

yields: 3282.989990234375
weekly_low.min()

yeilds: 666.7899780273438
These value are are issue because 3283.0 is the high so why am i getting in deimals? Secondly weekly low is is 666 which i know for a fact is incorrect. How can i fix this?

A: hi you can try the following code:
data['52weekhigh'] = data.High.rolling(252).max()
data['52weeklow'] = data.Low.rolling(252).min()

This allows you to prevent having to resample on a monthly basis and gives you the rolling 52 week high (52 weeks == 252 trading days) Let me know if you need any further clarification.


text:
Q: What makes RecordIO attractive I have been reading about RecordIO here and there and checking different implementations on github here, and there.
I'm simply trying to wrap my head around the pros of such a file format.
The pros I see are the following:

*

*Block compression. It will be faster if you need to read only a few records because less to decompress.

*Because of the somehow indexed structure you could lookup a specific record in acceptable time (assuming keys are sorted). This can be useful to quickly locate a record in an adhoc fashion.

*I can also imagine that with such a file format you can have finer sharding strategies. Instead of sharding per file you can shard per block.

But I fail to see how such a file format is faster for reading over some plain protobuf with compression.
Essentially I fail to see a big pro in this format.


text:
Q: Use Keras Model on new data I successfully trained a ConvNet in Keras, and now I'd like to apply it on new data.
Sure, I can use model.save and load_model, but as this loads my whole model for every classification, it takes really long. Is there a more elegant way to do so?
I tried to "rebuild" my model via saving the weights and biases and applying them on my data, together with the activation functions I used. However, I don't obtain the same results like when using load_model, so I must have made a mistake ...
Is this rebuilding approach correct, or is there a more elegant way?
EDIT: I added my code, hope it's understandable ...
# sl: List containing for each layer: number of parameter matrices (=2 for conv or fully
# connected layer, =0 for flatten layer) & shapes of the matrices
# weight_list_lc: List containing my weight matrices
# biases_list_lc: List containing my biases
def Is_Trip_ConvNet(inp):
    n_layers = len(sl)
    curr_dim = inp.shape
    for l in range(1,n_layers):
        if sl[l][0] > 0: # weights available
            weights = np.array(weight_list_lc[l-1])
            weights = weights.reshape(np.array(sl[l][1])) # correct shape
            biases = bias_list_lc[l-1]
            if len(sl[l][1]) == 3: # ConvLayer
                field_size = sl[l][1][0]
                n_nodes = int(curr_dim[0]-field_size+1)
                n_filt = sl[l][1][2]
                out = np.zeros((n_nodes,n_filt))
                for n in range(0,n_nodes):
                    for f in range(0,n_filt):
                        out[n,f] = np.sum(np.multiply(inp[n:n+field_size,:],weights[:,:,f]))
                    out[n,:] = out[n,:]+biases
            else: # Fully Connected Layer
                out = inp.dot(weights)
                out = out + biases
            if l == n_layers-1: # Output Unit
                out = 1/(1+np.exp(-out)) # Sigmoid
            else:
                out = out*(out>0) # ReLU
        else: # no weights available --> Flatten Layer
            out = inp.reshape(-1)
        inp = out
        curr_dim = inp.shape
    return (out > 0.5)

My input shape is (18 x 8) (18 time steps, 8 features).
My network currently consists of a convolutional layer (receptive field size=5, kernel=6), flatten layer, fully connected layer with 10 nodes and 1 output node. All activation functions are rectifier, except the output one, this is sigmoid.
I carefully checked the indices of my lists, they are correct. Sorry I can't upload all my data sets. If you have any idea what could be missing, I'm happy to hear it!


text:
Q: Stored procedure with params in excel without Ado.net I have a stored procedure with params on sql server 2000 and i am trying to run it from excel 2003.
I did setup the DSN for the db and now when i am in MS Query form Excel, i tried to execute the SP using the syntax
{CALL mystoredProc (?,?,?)}
After i say ok it does ask me for the parameters after that the result set that i am getting has all the column names but no data.
The result set should have atleast 200 rows because i do get them if i run it using the QueryAnalyzer.
Please advice me i am a newbie and apologize if this is a silly question..
Thanks

A: Why not use ADO?
With ado you can use ADODB.Command, And pass parameters to object using append method.
Other way to your proc don´t work is if your parameter is date and a format is wrong.
if is a date try pass a date with format
format(date(),"yyyy-mm-dd")

In Sql is a default format of dates.
[]´s


text:
Q: How to convert arrays to map? I have a spark dataframe like this:

The schema is:

I want to have the final result like this:

Namely, to create a map between _1: integer and _2: map in site_group.
How to do this in scala spark?

A: Here is one solution. First lets create some sample data similar to yours, btw it would be much more helpful to post a question with reproducible input and output data as discussed here.
val df = Seq(
(999, "2019-05-23", Seq((0,Map(2154 -> 0.545)))),
(511, "2019-06-30", Seq((1,Map(564654 -> 0.255699)))),
(322, "2019-02-10", Seq((2,Map(122 -> 0.896)))))
.toDF("user_id","dt", "site_group_collect")

// +-------+----------+---------------------------+
// |user_id|dt        |site_group_collect         |
// +-------+----------+---------------------------+
// |999    |2019-05-23|[[0, [2154 -> 0.545]]]     |
// |511    |2019-06-30|[[1, [564654 -> 0.255699]]]|
// |322    |2019-02-10|[[2, [122 -> 0.896]]]      |
// +-------+----------+---------------------------+

Then we iterate through each item and transform the values of site_group_collect using the map function of the dataframe:
df.map{case Row(uid: Int, dt: String, group: Seq[Row]) =>
     val transformed = group.map{ r => Map(r.getInt(0) -> r.get(1).asInstanceOf[Map[Int, Double]]) }
     (uid, dt, transformed)
}
.toDF("user_id","dt", "site_group_collect")
.show(false)

// +-------+----------+-----------------------------+
// |user_id|dt        |site_group_collect           |
// +-------+----------+-----------------------------+
// |999    |2019-05-23|[[0 -> [2154 -> 0.545]]]     |
// |511    |2019-06-30|[[1 -> [564654 -> 0.255699]]]|
// |322    |2019-02-10|[[2 -> [122 -> 0.896]]]      |
// +-------+----------+-----------------------------+

The key point here is the representation of the array of tuples [[0, [2154 -> 0.545]]] as an array of Rows. Another approach would be to represent the tuple as a case class i.e:
case class Item(pk: Int, m: Map[Int, Double])

The line:
val transformed = group.map{ r => Map(r.getInt(0) -> r.get(1).asInstanceOf[Map[Int, Double]]) }

Will extract the key/value combination from the existing tuple and assign it to the new created Map.
Some related posts:

*

*GenericRowWithSchema exception in casting ArrayBuffer to HashSet in DataFrame to RDD from Hive table

*Extracting `Seq[(String,String,String)]` from spark DataFrame

*How to add a new Struct column to a DataFrame