text:
Q: pandas: calculate diffs between rows I have this dataframe:
df = pd.DataFrame([{ "state": "CA", "total":2, "week": 10 },{ "state": "UT", "total": 7, "week": 10 },{ "state": "CA", "total": 14, "week": 11 },{ "state": "UT", "total":18, "week": 11 },{ "state": "CA", "total": 21, "week": 12 },{ "state": "UT", "total": 30, "week": 12 }])

The total field is cumulative, and I want to get the diffs by week. So I want to end up with this:
state,total,week,diff
CA,2,10,NaN
UT,7,10,NaN
CA,14,11,12
UT,18,11,11
CA,21,12,7
UT,30,12,12

How do I get there from here? I could do this by looping over the rows, but I don't know where to start to do this in pandas.

A: You can do it like
df['diff'] = df.groupby('state')['total'].diff()
df

Out:
  state  total  week  diff
0    CA      2    10   NaN
1    UT      7    10   NaN
2    CA     14    11  12.0
3    UT     18    11  11.0
4    CA     21    12   7.0
5    UT     30    12  12.0

Since pandas 0.24 you can use nullable int types but it's not  commonly used
df['diff'] = df.groupby('state')['total'].diff().astype(pd.Int64Dtype())
df

Out:
  state  total  week  diff
0    CA      2    10  <NA>
1    UT      7    10  <NA>
2    CA     14    11    12
3    UT     18    11    11
4    CA     21    12     7
5    UT     30    12    12


text:
Q: Django filtering results from database I have a movie model that's supposed to filter by date.
qs = Movie.objects.filter(visible=True,).order_by('-hot', '-showing', 'name')
...
if self.kwargs.get('shortcut', None):
    today = datetime.date.today()
    shortcut = self.kwargs['shortcut']
if shortcut == 'now-showing':
    qs = qs.filter(shows__starts__gte=today,)
elif shortcut == 'today':
    qs = qs.filter(shows__starts__exact=today)
elif shortcut == 'coming-soon':
    qs = qs.filter(coming_soon=True, coming_soon_starts__gte=today)
elif shortcut == 'tomorrow':
    qs = qs.filter(shows__starts__exact=today + datetime.timedelta(days=1))
elif shortcut == 'this-weekend': #Friday - Sunday
    days = 4 - today.weekday()
    starts = today + datetime.timedelta(days=days)
    ends = starts + datetime.timedelta(days=2)
    qs = qs.filter(shows__starts__range=(starts, ends))
elif shortcut == 'tickets':
    qs = qs.filter( Q(shows__venue__name__icontains='imax') | Q( shows__venue__name__icontains='anga' ) | Q( shows__venue__name__icontains='century-cinemax-junction' ) & Q(shows__new_price__gte=100) & Q( shows__venue__name__icontains='anga' ))

on the now-showing, coming-soon, this-weekend filter correctly but tickets brings movies with expired start_date and price.
I need to edit it so it checks whether the start date and price are there then whether the venue is from the three cinemas.

A: Try this:
qs = qs.filter(Q(shows__new_price__gte=100), Q(shows__starts__gte=today), Q(shows__venue__name__icontains='imax') | Q(shows__venue__name__icontains='anga' ) | Q(shows__venue__name__icontains='century-cinemax-junction')

From the django docs:

If you provide multiple Q object arguments to a lookup function, the arguments will be "AND"ed together.

redpajama_set_name: RedPajamaStackExchange


text:
Q: nginx proxy cache mp4 streaming Sorry for my question,
the schema like this:
there are upstream which is a IIS server where locates video files.
my nginx is an proxy caching server, I need to cache mp4 file when client starts playing it in his browser and send/stream it to client.
if index of mp4 file locates at the beginning of file, then its ok, it works good.
but if index of file locates at the end of mp4 file then I have problems
I am looking up to cache and see that nginx caching from upstream file till the end and deliting it and for next section of file it caching it again fully sending section and delete cache... I do not understand why :( also it send many error headers as incorrect length in this case player stops :(
(RAM Cache definitions)
1 level server defs
server {
    listen        front.network;
     server_name   .mybox.com;

    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

    max_ranges 1024;

    proxy_cache ssd;
    proxy_cache_valid 200 600s;
    proxy_cache_lock on;
    proxy_read_timeout 10m;
    proxy_send_timeout 10m;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote_addr;
    add_header Accept-Ranges bytes;
    proxy_cache_min_uses 1;
    proxy_force_ranges on;

    proxy_cache_key   $uri$is_args$args;

    # Immediately forward requests to the origin if we are filling the cache
    proxy_cache_lock_timeout 0s;

    # Set the 'age' to a value larger than the expected fill time
    proxy_cache_lock_age 200s;
    proxy_cache_valid 200 206 301 302 48h ;

    proxy_cache_use_stale updating;

    location /5 {
        proxy_set_header Host $redirect_host;
        proxy_pass http://$redirect_upstream;
    }
}


text:
Q: ArcGIS Server 10 on Ubuntu or CentOS? I know Solaris is on the way out with 10.1
I also know that v10 is only supported on 32bit flavours of RedHat & SUSE.
What I do want to know, has anyone had any luck installing it on either Ubuntu or CentOS?
Google only told me of this blog which had revolved around Engine 9.2.
--EDIT--
Looks like Ubuntu support for may arrive at 10.1.  Ease of use and lower costs on AWS look to be the reasons (over CentOS)

A: CentOS will work if you stick with a version that corresponds to one of the supported versions of RHEL but I doubt you'll have much luck with Ubuntu.

A: I have it on a verbal authority from ESRI that they were looking at Ubuntu during the ArcGIS 10 Beta. so based on this it is in the pipeline but how far they have gotten I could only speculate

A: While the ArcGIs 9.4 (later 10) Beta was underway I was made aware that Esri was looking into Ubuntu but at this stage it is not supported, and does not work.
In saying this it does depend on which portion of ArcGIS Server you are looking at. If you are looking at the database portion, then you can install the database on your Ubuntu Server and then install SDE on another machine pointing to your database. At this stage this is the only way Ubuntu can be included in the server operations of ArcGIS Server.
Sorry for the bad news,
CDB

A: The main problem is as soon as you install any OS to the VirtualBox it will be a non-licensed copy or it will cost as licensed. It would be better to install ArcGIS to a Ubuntu computer itself without anything in between ...

A: Here's a thread in Ubuntu forums where several people say they've had success running ArcGIS on Ubuntu machines via VirtualBox:
http://ubuntuforums.org/showthread.php?t=553968
-Trevor


text:
Q: Getting my character to move fluidly in Pygame I am trying to create a pygame for my com sci final, but my teacher has not done an excellent job at explaining how pygame works. My trouble here is I need make my character, a custom sprite I created, move fluidly when any of the 4 arrow keys are held. So far, all I've been able to do is make it move with every individual key press, and I have no idea how to fix this.
I'm not sure if my code is the most efficient, but essentially depending on what key you press, not only do the X and Y coordinates change, but the png image changes to face the appropriate direction. This is all draw using blits.
import pygame

pygame.init()

def redraw_game_window(texture):
    screen = pygame.display.set_mode(size)
    background_image = pygame.image.load("lava.jpg").convert()
    background_image = pygame.transform.scale(background_image, (size))
    screen.blit(background_image, [0, 0])
    texture= pygame.transform.scale(texture, (65,64))
    texture=texture.convert_alpha()
    screen.blit(texture,(EarlX,EarlY))

size=1200,600
EarlWidth=65
EarlLength=64
texture = pygame.image.load("UpFacingEarl.png")
EarlX=500
EarlY=150
speed=50

inPlay= True
while inPlay:
    redraw_game_window(texture)
    pygame.time.delay(20)

    keys = pygame.key.get_pressed()
    if keys[pygame.K_ESCAPE]:
        inPlay = False
    if keys[pygame.K_LEFT]:
        texture = pygame.image.load("LeftFacingEarl.png")
        EarlX-=speed
    if keys[pygame.K_RIGHT]:
       texture = pygame.image.load("RightFacingEarl.png")
       EarlX+=speed
    if keys[pygame.K_UP]:
        texture = pygame.image.load("UpFacingEarl.png")
        EarlY-=speed
    if keys[pygame.K_DOWN]:
       texture = pygame.image.load("DownFacingEarl.png")
       EarlY+=speed

    pygame.display.flip()

Any help on how to improve my code would be greatly appreciated, I know im not including the png's but theres not much I can do there.

A: First, you don't need to double space your code. Now that we've gotten that out of the way:
screen = pygame.display.set_mode(size)

should only called at the beginning of the program. Not every time! This is the reason your program isn't working.
Here are other less important things to fix:
this should also only be called at the beginning:
background_image = pygame.image.load("lava.jpg").convert()
background_image = pygame.transform.scale(background_image, (size))

all in all, you redraw_game_window function should look like:
def redraw_game_window(texture, EarlX, EarlY, screen): #you should pass all the variables you are using to the function. Python doesn't work well with global variables. if you really want to use global variables like you did here, use the global keyword
    screen.fill((0,0,0)) #clear the screen

    screen.blit(background_image, [0, 0]) #draw new background

    texture = pygame.transform.scale(texture, (65,64))
    texture = texture.convert_alpha()
    screen.blit(texture,(EarlX,EarlY)) #draw earl

This event loop is fine:
for event in pygame.event.get():
    if event.type == pygame.QUIT: #you need this or else pressing the red "x" on the window won't close it
        quit()

keys = pygame.key.get_pressed()

if keys[pygame.K_ESCAPE]: #press esc to exit program
    quit()

if keys[pygame.K_UP]:
    EarlY -= 1

if keys[pygame.K_DOWN]:
    EarlY -= -1

if keys[pygame.K_LEFT]:
    EarlX += -1

if keys[pygame.K_RIGHT]:
    EarlX += 1


text:
Q: Closing the background activity which has the same name I'm trying to develop an app which has two editText fields for entering location. So I made two java files
1.MapsActivity.java(with activity_maps.xml)
2.AutoComplete.java(with autocomplete.xml)
In MapsActivity while clicking the 'from' text field, it will open the AutoComplete activity and after clicking any of the suggestions in it will open a fresh MapsActivity and places the clicked item . Likewise for 'to' text field also.
I am using Intents to pass the clicked values. So at last, five activities are opened when the two text boxes are filled. When I click back button ,it is showing the auto complete activity used the previous time.
Question:

*

*Is any other way to close a particular activity with same name running behind?

*Is there any other way to pass values by super.backpressed(); ?
enter image description here

A: You can try using startActivityForResult() method. That way you can use the result from the second activity in the first and also you wouldn't need to start a new activity. You can read up on it here startActivityForResult

A: try to clear backstack/clear_top/single_top using the intent.
Just add/set flags in intent.
or
finish activity after startActivity.
or
you can override the onBackPressed method to call the specific activity.


text:
Q: Draw perpendicular arrows in TikZ How can I draw straight vertical arrow in my tikzpicture using
\draw[arrow](position1)--node{text}(position2);

My diagram looks like
\tikzstyle{kaesten}=[rectangle, rounded corners, minimum width=3cm, minimum height=1cm, text centered, text width=4cm, text=TUMWhite, fill=TUMBlue]

\tikzstyle{pdm}=[rectangle, rounded corners, minimum width=5cm, minimum height=2cm, text centered, text=TUMWhite, fill=TUMBlue1]

\tikzstyle{arrow}=[thick,->,>=stealth]
\tikzstyle{arrow_beidseitig}=[thick,<->,>=stealth]

\begin{figure}[H]
\centering
\begin{tikzpicture}[node distance=3.5cm]
\node(aenderungsverwaltung)[kaesten, scale=0.7]{Änderungsverwaltung};
\node(verwaltung)[kaesten, below of=aenderungsverwaltung, scale=0.7]{Verwaltung freigegebener Dokumente};
\node(freigabe)[kaesten, left of=verwaltung, scale=0.7]{Freigabe};
\node(konstruktion)[kaesten, left of=freigabe, scale=0.7]{Konstruktion};
\node(fertigungsvorbereitung)[kaesten, right of=verwaltung, scale=0.7]{Fertigungsvorbereitung};
\node(fertigung)[kaesten, right of=fertigungsvorbereitung, scale=0.7]{Fertigung};
\node(pdm)[pdm, text width=14cm, below of=verwaltung,scale=0.7]{Product Data Management (PDM)
\begin{itemize}
    \color{TUMWhite}
    \item Archivierung
    \item Datenmanagement
    \item Prozessmanagement
    \item dokumentenorientiert
\end{itemize}
};

\footnotesize
\draw [arrow] (aenderungsverwaltung) -| node[align=left, anchor=south]{Änderungsauftrag} (konstruktion);
\draw[arrow] (konstruktion) -- (freigabe);
\draw[arrow] (freigabe)--(verwaltung);
\draw[arrow] (verwaltung)--(fertigungsvorbereitung);
\draw[arrow] (fertigungsvorbereitung)--(fertigung);
\draw[arrow_beidseitig] (konstruktion)|-node[align=left, anchor=east]{\hspace*{-1.5cm}Laufende \\ \hspace*{-1.5cm}Arbeiten}(pdm);
\draw[arrow_beidseitig] (freigabe)--node[align=left, anchor=south west]{\hspace*{-3cm}Freigegebene \\ \hspace*{-3cm}Konstruktion}(pdm);
\draw[arrow_beidseitig] (verwaltung)--node[align=left, anchor=south east]{\hspace*{4cm}Zugriff auf \\ \hspace*{4cm}Konstruktionen}(pdm);
\draw[arrow_beidseitig] (fertigungsvorbereitung)--node[align=left]{\hspace*{4cm}Freigegebene \\ \hspace*{4cm}Konstruktionen}(pdm);
\draw[arrow] (fertigungsvorbereitung)|-(aenderungsverwaltung);
\draw[arrow] (fertigung)|-node[anchor=south]{Änderungsanforderung}(aenderungsverwaltung);

\end{tikzpicture}
\caption{Informationsfluss in Konstruktion und Entwicklung}
\label{fig:informationsfluss}
\end{figure}

How can I adjust my code to get straight lines like in the following figure

Thank you so much for your help.

A: I replaced your TUM.. colours by standard colour names, as you didn't provide those definitions.
To answer your specific question, use e.g. (freigabe|-pdm.north) as the end coordinate. See TikZ: What EXACTLY does the the |- notation for arrows do? for an explanation of perpendicular coordinates.

In the code below I also modernized a couple of things. Generally, \tikzset{foo/.style={..},bar/.style={..}} is recommended over \tikzstyle{foo}=[..]. And the right of=.. syntax is deprecated, instead load the positioning library and use right=of .. (Difference between "right of=" and "right=of" in PGF/TikZ).
Finally, instead of using things like node[left] {\hspace{<length>}..., pass a length to left, i.e. node[left=5mm] {.... It's also possible to use e.g. node[xshift=1cm,yshift=2cm] ...

\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
\tikzset{
 kaesten/.style={rectangle, rounded corners, minimum width=3cm, minimum height=1cm, text centered, text width=4cm, text=white, fill=blue},
 pdm/.style={rectangle, rounded corners, minimum width=5cm, minimum height=2cm, text centered, text=white, fill=blue},
 arrow/.style={thick,->,>=stealth},
 arrow_beidseitig/.style={thick,<->,>=stealth}
}
\begin{document}

\begin{tikzpicture}[node distance=2.5cm and 1cm]
\node(aenderungsverwaltung)[kaesten, scale=0.7]{Änderungsverwaltung};
\node(verwaltung)[kaesten, below=of aenderungsverwaltung, scale=0.7]{Verwaltung freigegebener Dokumente};
\node(freigabe)[kaesten, left=of verwaltung, scale=0.7]{Freigabe};
\node(konstruktion)[kaesten, left=of freigabe, scale=0.7]{Konstruktion};
\node(fertigungsvorbereitung)[kaesten, right=of verwaltung, scale=0.7]{Fertigungsvorbereitung};
\node(fertigung)[kaesten, right=of fertigungsvorbereitung, scale=0.7]{Fertigung};
\node(pdm)[pdm, text width=14cm, below=of verwaltung,scale=0.7]{Product Data Management (PDM)
\begin{itemize}
%    \color{TUMWhite}
    \item Archivierung
    \item Datenmanagement
    \item Prozessmanagement
    \item dokumentenorientiert
\end{itemize}
};

\footnotesize
\draw [arrow] (aenderungsverwaltung) -| node[align=left, anchor=south]{Änderungsauftrag} (konstruktion);
\draw[arrow] (konstruktion) -- (freigabe);
\draw[arrow] (freigabe)--(verwaltung);
\draw[arrow] (verwaltung)--(fertigungsvorbereitung);
\draw[arrow] (fertigungsvorbereitung)--(fertigung);

\draw[arrow_beidseitig] (konstruktion)|-node[align=left, left]{Laufende \\ Arbeiten}(pdm);
\draw[arrow_beidseitig] (freigabe)--node[align=left, left]{Freigegebene \\ Konstruktion}(freigabe|-pdm.north);
\draw[arrow_beidseitig] (verwaltung)--node[align=left, left]{Zugriff auf \\ Konstruktionen}(pdm);
\draw[arrow_beidseitig] (fertigungsvorbereitung)--node[align=left,left]{Freigegebene \\ Konstruktionen}(fertigungsvorbereitung|-pdm.north);
\draw[arrow] (fertigungsvorbereitung)|-(aenderungsverwaltung);
\draw[arrow] (fertigung)|-node[anchor=south]{Änderungsanforderung}(aenderungsverwaltung);
\end{tikzpicture}
\end{document}

A: Mainly off-topic (where are between others considered @ Alenanno comments) of nice @Torbjørn T. answer (+1):
\documentclass[tikz, margin=3.14159mm]{standalone}
\usetikzlibrary{arrows.meta,
                chains,
                fit,
                positioning,
                quotes}
\usepackage{enumitem}

\begin{document}
\tikzset{
kaesten/.style args = {#1/#2}{rectangle, rounded corners, fill=#1,
                  text width=#2, minimum height=1cm,
                  align=center, text=yellow},
kaesten/.default = cyan!90!black/42mm,
    arr/.style = {-Stealth, semithick},
    alr/.style = {Stealth-Stealth, semithick},
    lbl/.style = {font=\footnotesize, align=left, #1},% #1=positioing
    lbl/.default = left
        }

    \begin{tikzpicture}[scale=0.7,
node distance = 12mm and 3mm,
  start chain = A going right
                        ]
    \begin{scope}[nodes={kaesten, on chain=A, join=by arr}]
\node   {Konstruktion};     % name: A-1
\node   {Freigabe};
\node   {Verwaltung freigegebener Dokumente};
\node   {Fertigungsvorbereitung};
\node   {Fertigung};        % name: A-5
    \end{scope}
\node (A-0) [kaesten,
             above=of A-3] {Änderungsverwaltung};

\node (pdm) [kaesten=cyan!80!black/42mm,
             fit=(A-2) (A-4),
             inner xsep=0ex, inner ysep=3.3ex,
             below=of A-3] {\hfil\textbf{Product Data Management (PDM)}
\begin{itemize}[nosep]
    \item Archivierung
    \item Datenmanagement
    \item Prozessmanagement
    \item dokumentenorientiert
\end{itemize}
};
% above chain
\draw [arr] (A-0) -| node[lbl=above] {Änderungsauftrag}      (A-1);
\draw [arr] (A-5) |- node[lbl=above] {Änderungsanforderung}  (A-0);
\draw       (A-4) -- (A-4 |- A-0);
% below chain
\draw[alr] (A-1) |- node[lbl]  {Laufende \\ Arbeiten}  (pdm);
%
\draw[alr] (A-2) -- node[lbl]  {Freigegebene \\ Konstruktionen} (A-2 |- pdm.north);
\draw[alr] (A-3) -- node[lbl]  {Zugriff auf  \\ Konstruktion}   (A-3 |- pdm.north);
\draw[alr] (A-4) -- node[lbl]  {Freigegebene \\ Konstruktionen} (A-4 |- pdm.north);
    \end{tikzpicture}
\end{document}


text:
Q: How to animate zooming in Android I'm developing an Android application, I used this library

barteksc:android-pdf-viewer:2.3.0

I have to implement a simple animation, this is the code that I have implemented:
private void selectArea(){
    /* Stop movement, jump to page 2, disable all action on PDFView*/
    pdfView.stopFling();
    pdfView.jumpTo(2);
    pdfView.setEnabled(false);
    pdfView.zoomWithAnimation(0, 1500, (float) 1.95);
}

private void resetAnimation() {
   pdfView.resetZoomWithAnimation();
}

I need to select a certain area, reset the zoom and select again the area, so the problem is :
When I call selectarea () function shows the area that I want to show, when it resetarea call () the zoom is restored, if i call again the selectarea function the pdfView.resetZoomWithAnimation() call is ignored, and I don't understand why.
Pseudocode of my app.
selectArea();
//do stuff
resetAnimation()
selectArea();

A: **** SOLUTION ****
After hours of attempts I found a solution of my problem:
private void selectAreaToSign(){
    /* Stop movement, jump to page 2, disable all action on PDFView*/
    pdfView.stopFling();
    pdfView.clearFocus();
    pdfView.jumpTo(2);
    pdfView.setEnabled(false);
    pdfView.clearAnimation();
    pdfView.clearFocus();

    if(isFirstTime){
        pdfView.zoomWithAnimation(0, 1700, (float) 2.00);
    }else{
        resetAnimation();

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                sv.setVisibility(View.VISIBLE);
                pdfView.zoomWithAnimation(4500, 1700, (float) 2.00);
            }
        }, 1000);
    }
}

private void resetAnimation() {
    pdfView.resetZoomWithAnimation();
    sv.setVisibility(View.INVISIBLE);
    pdfView.zoomTo(1);
}


text:
Q: how to fix issue sometims load page get error js? I have installed magento 2.1.7 version. Now I get error sometime I reload page get error
sometimes get another js error and sometime is good. I have tried deploy but not change. so pls let me how to fix this.
Note: In backend panel I had set merge and Minify JavaScript Files.
Thank advance!


text:
Q: Filter array to show rows with a specific value in a specific column Let's say i have a multidimensional list l:
l = [['a', 1],['b', 2],['c', 3],['a', 4]]

and I want to return another list consisting only of the rows that has 'a' in their first list element:
m = [['a', 1],['a', 4]]

What's a good and efficient way of doing this?

A: Definitely a case for a list comprehension:
m = [row for row in l if 'a' in row[0]]

Here I'm taking your "having 'a' in the first element" literally, whence the use of the in operator.  If you want to restrict this to "having 'a' as the first element" (a very different thing from what you actually wrote!-), then
m = [row for row in l if 'a' == row[0]]

is more like it;-).

A: m = [i for i in l if i[0] == 'a']

A: With the filter function:
m = filter(lambda x: x[0] == 'a', l)

or as a list comprehension:
m = [x for x in l where x[0] == 'a']

A: What's wrong with just:
m = [i for i in l if i[0] == 'a']

Or:
m = filter(lambda x: x[0] == 'a', l)

I doubt the difference between these will be significant performance-wise. Use whichever is most convenient. I don't like lambdas, but the filter can be replaced with itertools.ifilter for larger lists if that's a problem, but you can also change the list comprehension to a generator (change the [] to ()) to achieve the same general result. Other than that, they're probably identical.

A: [i for i in l if i[0]=='a']

btw, take a look at Python's list comprehension with conditions.


text:
Q: Unable to run "mvn verify clean --offline" in a fresh Maven installation I'm working on a linux (RHEL) box not connected to the internet. I currently have the "apache-maven-3.2.3-bin.tar.gz" from the maven-apache download page.
When I run "mvn verify clean --offline" in a terminal I get the following error:
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------
[INFO] Building ABC 2-SNAPSHOT
[INFO] ------------------------------------------------------
[WARNING] The POM for org.apache.maven.plugins:maven-=clean-plugin:jar:2.5
          is missing, no dependency information available
[INFO] ------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------
[INFO] ................
[INFO] ------------------------------------------------------
[ERROR] Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its
        dependencies could not be resolved: Could not find artifact
        org.apache.maven.plugins:maven-clean-plugin:jar:2.5 -> [Help 1]
[ERROR]
[ERROR] ................
[ERROR]

(I'm removing extraneous info. If you want me to add the flag -X or -e ask me to do so and I'll post the results. I didn't think they'd be useful.)
I followed the instructions on the download page to configure my box for "Unix-based Operating Systems" and converted my Eclipse 3.x RCP Application to a Maven Project, which created a pom.xml.
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.oirg/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>data.git_repo.abc_repos</groupId>
  <artifactId>cem.abc</artifactId>
  <version>2-SNAPSHOT</version>
  <packaging>pom</packaging>
  <name>RDC</name>

  <properties>
    <tycho-version>0.21.0</tycho-version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEnconding>
  </properties>

  <profiles>
    <profile>
      <id>abc</id>
      <activation>
        <activeByDefault>true</activeByDefault>
        <property>
          <name>offline</name>
          <value>true</value>
        </property>
      </activation
    </profile>
  </profiles>

  <repositories>
    <repository>
      <id>central</id>
      <name>abc_repo</name>
      <layout>default</layout>
      <url>file:///data/git_repos/abc_repos/cem.abc</url>
      <releases>
        <enabled>false</enabled>
        <updatePolicy>never</updatePolicy>
      </releases>
    </repository>
  </repositories>

  <pluginRepositories>
    <pluginRepository>
      <id>central</id>
      <name>abc_repo</name>
      <layout>default</layout>
      <url>file:///data/git_repos/abc_repos/cem.abc</url>
      <snapshots>
        <enabled>true</enabled>
      <snapshots>
      <releases>
        <enabled>false</enabled>
        <updatePolicy>never</updatePolicy>
      </releases>
    <pluginRepository>
  </pluginRepositories>

  <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resources>
        <directory>src<directory>
      </resources>
    <resources>

    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.eclipse.tycho</groupId>
          <artifactId>target-platform-configuration</artifactId>
          <version>${tycho.version}</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

A: To work off-line with Maven, you need a local Maven repository which has all the needed artifacts. Maven automatically downloads them when you are building without the --offline switch.
If you have a machine without Internet access, you can still build your project in the following way:

*

*Build the on a machine with Internet access.

*Copy the local Maven repository ~/.m2/repository/ from the on-line machine to the off-line machine.

*Build the project with --offline.


text:
Q: How To Remove The "Click here to cancel reply" Link From The Wordpress Comment Form I am trying to remove the "Click here to cancel reply" link from the Wordpress comment form on my posts. In the document there is an argument you can supply to the comment form function to remove the link, but it doesn't appear to be working. The documentation link: http://codex.wordpress.org/Function_Reference/comment_form
I have tried different values for the cancel_reply_link value including double quotes, double quotes with a space between them, a zero and a value of false; all of which were to no avail. Surely I am overlooking something here as removing that link is pretty common in Wordpress installations.
Here is the current function call with parameters that I am using at present:
<?php comment_form(

array(
    'comment_notes_before' => FALSE,
    'comment_notes_after'  => FALSE,
    'cancel_reply_link'    => FALSE
)

);
?>
Your help is gratefully appreciated.

A: add_filter( 'cancel_comment_reply_link', '__return_false' );

See /wp-includes/comment-template.php#function get_cancel_comment_reply_link() for more background.
But if you do that the reply form will not move to the comment. The more interesting question is: Why doesn't the link work for you? Do you have this line in your footer?
is_singular() and get_option( 'thread_comments' ) and wp_print_scripts( 'comment-reply' );

A: When you pass false to that argument get_cancel_comment_reply_link() function that is used down the chain falls back to default value.
Pass something else (like single space) or filter cancel_comment_reply_link hook to override output.


text:
Q: How to add validation in entry widget in python , i want name , last name and course should only accept letter else print the error
class Add(Tk):
    def __init__(self):
        super().__init__()
        self.maxsize(500,417)
        self.minsize(500,417)
        self.title('Add Student')
        self.canvas = Canvas(width=500, height=417, bg='gray')
        self.canvas.pack()
        fname = StringVar()
        lname = StringVar()
        cn = IntVar(value="")
        gender = StringVar()
        add = StringVar()
        c = StringVar()

        def asi():
                try:
                    self.conn = mysql.connector.connect(host='localhost',
                                                        database='crud',
                                                        user='root',
                                                        password='')
                    self.myCursor = self.conn.cursor()
                    first = fname.get()
                    last = lname.get()
                    contact = cn.get()
                    gend = gender.get()
                    address = add.get()
                    course = c.get()

                    self.myCursor.execute("Insert into tbl_student(FirstName,LastName,Gender,Address,ContactNumber,Course) values (%s,%s,%s,%s,%s,%s)",[first,last,gend,address,contact,course])
                    self.conn.commit()
                    messagebox.showinfo("Done","Student Inserted Successfully")
                    ask = messagebox.askyesno("Confirm","Do you want to add another student?")
                    if ask:
                     self.destroy()
                     os.system('%s %s' % (py, 'Add.py'))
                    else:
                     self.destroy()
                     self.myCursor.close()
                     self.conn.close()
                except Error:
                    messagebox.showerror("Error","Something goes wrong")

        Label(self, text='Student Details',bg='gray', fg='white', font=('Courier new', 25, 'bold')).pack()
        Label(self, text='First Name:', bg='gray', font=('Courier new', 10, 'bold')).place(x=70, y=102)
        Entry(self, textvariable=fname, width=30).place(x=200, y=104)
        Label(self, text='Last Name:', bg='gray', font=('Courier new', 10, 'bold')).place(x=70, y=150)
        Entry(self, textvariable=lname, width=30).place(x=200, y=152)
        Label(self, text='Gender:', bg='gray', font=('Courier new', 10, 'bold')).place(x=70, y=200)
        Entry(self, textvariable=gender, width=30).place(x=200, y=202)
        Label(self, text='Address:', bg='gray', font=('Courier new', 10, 'bold')).place(x=70, y=250)
        Entry(self, textvariable=add, width=30).place(x=200, y=250)
        Label(self, text='Contact Number:', bg='gray', font=('Courier new', 10, 'bold')).place(x=70, y=300)
        Entry(self, textvariable=cn, width=30).place(x=200, y=300)
        Label(self, text='Course:', bg='gray', font=('Courier new', 10, 'bold')).place(x=70, y=350)
        Entry(self, textvariable=c, width=30).place(x=200, y=350)
        Button(self, text="Save", bg='blue', width=15, command=asi).place(x=230, y=380)

Add().mainloop()


text:
Q: Cómo leer este json Al hacer la siguiente petición:

$.ajax({

url: "...",
type: "GET",

sucess: function(response) {

console.log(response);

}

});

Me da como resultado:

/*O_o*/
google.visualization.Query.setResponse({"version":"0.6","reqId":"0","status":"ok","sig":"2146391061","table":{"cols":[{"id":"A","label":"Marca temporal","type":"datetime","pattern":"d/MM/yyyy H:mm:ss"},{"id":"B","label":"Purple #1","type":"string"},{"id":"C","label":"Purple #2","type":"string"}],"rows":[{"c":[{"v":"Date(2022,5,25,1,23,20)","f":"25/06/2022 1:23:21"},{"v":"blue"},{"v":"yellow"}]},{"c":[{"v":"Date(2022,5,25,2,8,5)","f":"25/06/2022 2:08:05"},{"v":"red"},{"v":"black"}]},{"c":[{"v":"Date(2022,5,25,2,8,13)","f":"25/06/2022 2:08:13"},{"v":"tomato"},{"v":"gray"}]},{"c":[{"v":"Date(2022,5,25,2,8,21)","f":"25/06/2022 2:08:22"},{"v":"green"},{"v":"pink"}]},{"c":[{"v":"Date(2022,5,25,2,8,55)","f":"25/06/2022 2:08:55"},{"v":"orange"},{"v":"turqoise"}]},{"c":[{"v":"Date(2022,5,25,2,9,28)","f":"25/06/2022 2:09:29"},{"v":"violet"},{"v":"purple"}]}],"parsedNumHeaders":1}});

Pero no logro leerlo incluso usando JSON.parse()

A: La respuesta que estás recibiendo no es un Json, así que hay que transformarlo en uno.
Por ejemplo podrías hacer lo siguiente:
    response = response.replace(/(^\/\*O_o\*\/([\s\S]*[\n\r]*)google\.visualization\.Query\.setResponse\(|\);$)/g,'');

    responseJSON = JSON.parse(response);

Y así en responseJSON tendrías lo que buscas.


text:
Q: Statistical method used to compare internet speed A cable provider received a complaint from a customer. The
customer is complaining that the internet service is too low. The
cable company servicer measured the internet speed at two locations
in the house at the cable box and in the living room. He did 8
measurements at each location. The recorder measurements are in the
table below.

It is expected to lose 15% of internet speed from the cable box
to the living room.
Redo the table by dropping the internet speed measurements at
cable box for 15% percent. Then compare the two location
measurement using appropriate statistical method.
What statistical method did you use?
Is there enough statistical evidence to accept the methods
results as significant? Explain.
What is the final conclusion?
**Note: Must use only this statistical method:
Linear Regression


text:
Q: Lambda MSK event source have some gaps while processing This image is logs generated from a lambda program processing events from MSK topics. I put 100k events in a topic so it can process.

There are some gaps (1-2 minutes) that the it not process anything (hence no log produced).
Does anyone know what are those? and how to improve it?


text:
Q: Creating a list of regex matches from a data frame in Python and then counting the number of matches I'm trying to
-match the number of times a dollar/cent/percent appears in a column in a data frame  -create a function that lists all of these matches  -create a function that  count the number of matches
I'm able to successfully use regex to find the matches, but I'm unable to get a list to appear and count them. I tried using str.extract() to list out all of the matches and str.contains().sum() to count the number of matches. However, I can't get these to work at the same time and I'm not sure if this is even the right approach.
Here's what I have so far:
(?:^|\s)(\$?(?:\d[ ,.]?)+%?)(?=\s|$)

This will match any dollar/cent or percent, and accounts for a bunch of different typos that I'm trying to include so the regex string is fine.
import re
import pandas as pd

sample_csv = pd.DataFrame({'SMS_text': ['$1', '214-233-4455'],
                           'SMS_number': ['1', '1'],
                           'Amount': ['12.12%', '$10.12'],
                           'Percent': ['10%', '1']})

sample_csv.Amount.str.extract(r'(\$?(?:\d[ ,.]?)+%?)(?=\s|$)')

This will list out the matches from the Amount column.
0    12.12%
1    $10.12
Name: Amount, dtype: object

And if I substitute str.extract() with sample_csv.Amount.str.contains(r'(\$?(?:\d[ ,.]?)+%?)(?=\s|$)').sum() it will tell me how many matches there are (i.e. 2) but again, I can't get them to work at the same time.
Is this the right approach or am I setting this up wrong? Seems like maybe a findall() or maybe an re.compile() might work better, but I'm not sure how to get these to work properly.
My desired output from above would be something like:
regex_number_matches = ['12.12%', '$10.12']
regex_number_matches_count = 2

A: If you want total number of times % or $ appears in your dataframe, try
sample_csv.stack().str.contains('%|\$').sum()

It returns 4
If you want all the instance of the cells in which those appear, try
sample_csv[sample_csv.stack().str.contains('%|\$').unstack()]

And you get
    Amount  Percent SMS_number  SMS_text
0   12.12%  10%     NaN         $1
1   $10.12  NaN     NaN         NaN

A: It seems (to me) you want to find those values in the Amount column that can't be converted to numbers:
Assuming you have the following DF:
In [107]: sample_csv
Out[107]:
   Amount Percent  SMS_number      SMS_text
0  12.12%     10%           1            $1
1  $10.12       1           1  214-233-4455
2    1.23       2           1  214-233-4455
3    33,5       3           1  214-233-4455

first create a boolean mask of those rows where Amount can't be converted to numeric value:
In [108]: mask = pd.to_numeric(sample_csv['Amount'], errors='coerce').isnull()

In [109]: mask
Out[109]:
0     True
1     True
2    False
3     True
Name: Amount, dtype: bool

now you can easily filter DF, using this mask:
In [110]: sample_csv.loc[mask, 'Amount']
Out[110]:
0    12.12%
1    $10.12
3      33,5
Name: Amount, dtype: object

In [111]: sample_csv.loc[mask, 'Amount'].tolist()
Out[111]: ['12.12%', '$10.12', '33,5']

In [112]: len(sample_csv.loc[mask, 'Amount'])
Out[112]: 3


text:
Q: Issues in Java Swing i have created a Java program to save MAC Addresses to an external File. Below is the code:
import java.io.*;

public class MAC{

public static void main(String[] args) throws IOException{
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Enter the MAC Addres : ");
   File file = new File("mac.txt");

   FileWriter fstream = new FileWriter("mac.txt",true);
   BufferedWriter out = new BufferedWriter(fstream);

   out.write(in.readLine());
   out.newLine();
   out.close();
   }
}

I have also created a Swing Application. I am done with the Front End, but now I can't save MAC address to a external file using swing.
In my ActionListener, I am getting the values, but I have no idea how to save the details to a external file.
I am able to print the ActionListener values to the screen, but I want it to be saved in the external file.
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;

    import java.io.*;

    public class TextForm extends JPanel {

        private JTextField[] fields;

        // Create a form with the specified labels, tooltips, and sizes.
        public TextForm(String[] labels, int[] widths) {
            super(new BorderLayout());
            JPanel labelPanel = new JPanel(new GridLayout(labels.length, 1));
            JPanel fieldPanel = new JPanel(new GridLayout(labels.length, 1));
            add(labelPanel, BorderLayout.WEST);
            add(fieldPanel, BorderLayout.CENTER);
            fields = new JTextField[labels.length];

            for (int i = 0; i < labels.length; i += 1) {
                fields[i] = new JTextField();
                if (i < widths.length)
                    fields[i].setColumns(widths[i]);

               JLabel lab = new JLabel(labels[i], JLabel.RIGHT);
               lab.setLabelFor(fields[i]);

                labelPanel.add(lab);
                JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
                p.add(fields[i]);
                fieldPanel.add(p);
            }
    }

        public String getText(int i) {
            return (fields[i].getText());
        }

        public static void main(String[] args) {
            String[] labels = { "Enter MAC Address : "};
            int[] widths = { 17 };
            final TextForm form = new TextForm(labels, widths);
            JButton submit = new JButton("Submit");
            submit.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    System.out.println(form.getText(0));

                }
            });

            JFrame f = new JFrame("Text Form Example");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(form, BorderLayout.NORTH);
            JPanel p = new JPanel();
            p.add(submit);
            f.getContentPane().add(p, BorderLayout.SOUTH);
            f.pack();
            f.setVisible(true);
        }
    }

Thank you.

A: Copy the working method into the actionPerformed method and swap.
out.write(in.readLine());

For:
out.write(form.getText(0));

Then wrap the lot of it in a try/catch.


text:
Q: Async tasks in Ansible I have a question about the working of async tasks in ansible.
Suppose, I open 2 terminals, and run sudo apt-get update on both. Obviously, it will not run on both due to the lock file.
luvpreet@DHARI-Inspiron-3542:/etc/ansible$ sudo apt-get update
Reading package lists... Done
E: Could not get lock /var/lib/apt/lists/lock - open (11: Resource temporarily unavailable)
E: Unable to lock directory /var/lib/apt/lists/

Now, on ansible, I did this,
- name: update cache
  apt:
    update_cache: yes
  async: 1
  poll: 0

- name: update cache
  apt:
    update_cache: yes
  async: 1
  poll: 0

Now, the role containing these 2 consecutive tasks should never be completed as ansible cannot run 2 update tasks simultaneously.
But still it did, and did not threw any error. Why is it so ?

A: As you have used poll: 0, ie: fire-and-forget, for just 1 second, as specified in async: 1, your shell terminal session is active for just one second, that is after the very first second of running updating command at the remote node, it will be terminated and thus giving the second task a chance to do the same for the next 1second releasing the lock from
/var/lib/apt/list/lock

I hope this explains the scenerio :)


text:
Q: python: удалить все строки в начале txt файла до определённой строки есть txt файл - надо удалить все строки с начала файла до строки которая начинается с    1.
f = open('C:\\test.txt', 'w')
sep = '1.'
f.write(split(sep, 1)[0])
f.close()

текст файла примерно такой
start in row
5364
test
789

go www
1.
46712341
3412341
4523452
434323342

надо чтоб после осталось
1.
46712341
3412341
4523452
434323342

A: with open('C:\stest.txt', 'r') as f:
   data = f.readlines()
pos = data.index("1.\n")
with open('C:\stest.txt', 'w') as f:
   f.writelines(data[pos:])


text:
Q: What's the best way to create a working copy of a SQL Server database? I have a SQL database that I am currently converting from an Access database.  One of the features of the Access database is to 'Copy DB' and is used when working in a 'dev' site - it copies all of the production data by physically copying the production file into the dev site.  In this way, all production data and structure and queries and everything is duplicated into the dev version.  This only needs to be done occasionally when we are testing why something is occurring and we don't want to play in production data; not rare, but not frequent either - perhaps once or twice a month.  I'm wondering what have other people done to accomplish this when working in SQL?
I'm thinking that I could do a DB backup followed by a restore to the DEV version, but I don't want this backup to interfere with normal backup processes.  Is there any way to do this from one DB straight to another instead of going to the file system, and have the backup seem like it never happened (i.e. the REAL backup will still back up all items that really needed to be backed up)?
What other options are there?  I have SQL Compare and SQL Data Compare from Red Gate, but I need to expose this functionality to certain users (with high privs and access to the DEV site), and they don't have it.

A: Ok well after looking around a bit, I've come to the conclusion that I do have to go thru the file system, but there is a way to do a backup/restore without affecting the normal backup process by using 'Copy Only' mode.  Here's script to do it:
BACKUP DATABASE [ProductionDB]
TO DISK = N'D:\ProductionDBToDevTransfer.bak'
WITH
    COPY_ONLY,
    NOFORMAT,
    INIT,
    NAME = N'DB-Full Backup',
    SKIP,
    NOREWIND,
    NOUNLOAD,
    STATS = 10

RESTORE DATABASE [DevDB]
FROM DISK = N'D:\ProductionDBToDevTransfer.bak'
WITH
    FILE = 1,
    MOVE N'ProductionDB' TO N'D:\Microsoft\SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\DevDB.mdf',
    MOVE N'ProductionDB_log' TO N'D:\Microsoft\SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\DevDB_log.ldf',
    NOUNLOAD,
    REPLACE,
    STATS = 10

Take particular note of the MOVE statements in the RESTORE command...   by default, the RESTORE will restore files to the originally backed up physical files, NOT the Dev DB files, despite the fact that you are restoring to the DEV db...   I ALMOST found out the hard way, when I did the restore, and SSMS complained that the files were in use by ANOTHER db...   OMG, how non-intuitive.

A: The script above works, but doesn't change the logical file name for the copied server.  So, if you try and run it again to reverse the process it will fail in the MOVE statements.
I modified the script a little and came up with the following which seems to work for me.  I'm new to this, so be careful!
DECLARE @SOURCEDB nvarchar(100)
DECLARE @SOURCEDBLOG nvarchar(100)
DECLARE @DESTINATIONDB nvarchar(100)
DECLARE @DESTINATIONDBLOG nvarchar(100)
DECLARE @BACKUPDIR nvarchar(100)
DECLARE @BACKUPFILE nvarchar(100)
DECLARE @BACKUPNAME nvarchar(100)
DECLARE @SQLDATADIR nvarchar(100)
DECLARE @SQLDATABACKUPFILE nvarchar(100)
DECLARE @SQLDATABACKUPLOGFILE nvarchar(100)

--CHANGE THESE VALUES TO MATCH YOUR SYSTEM
SET @SOURCEDB = N'test'
SET @DESTINATIONDB = N'test-backup'
SET @BACKUPDIR = N'C:\SHARED\'
SET @SQLDATADIR = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\'

--CALCULATED VALUES
SET @SOURCEDBLOG = @SOURCEDB + N'_log'
SET @DESTINATIONDBLOG = @DESTINATIONDB + N'_log'
SET @BACKUPFILE = @BACKUPDIR + @SOURCEDB + N'-to-' + @DESTINATIONDB + N'.bak'
SET @BACKUPNAME = @SOURCEDB + N'-Full Backup'
SET @SQLDATABACKUPFILE = @SQLDATADIR + @DESTINATIONDB + N'.mdf'
SET @SQLDATABACKUPLOGFILE = @SQLDATADIR + @DESTINATIONDBLOG + N'.ldf'

--BACKUP THE DATABASE
BACKUP DATABASE @SOURCEDB
TO DISK = @BACKUPFILE
WITH
        COPY_ONLY,
        NOFORMAT,
        INIT,
        NAME = @BACKUPNAME,
        SKIP,
        NOREWIND,
        NOUNLOAD,
        STATS = 10

--RESTORE THE BACKUP TO THE NEW DATABASE NAME
RESTORE DATABASE @DESTINATIONDB
FROM DISK = @BACKUPFILE
WITH
        FILE = 1,
        MOVE @SOURCEDB TO @SQLDATABACKUPFILE,
        MOVE @SOURCEDBLOG TO @SQLDATABACKUPLOGFILE,
        NOUNLOAD,
        REPLACE,
        STATS = 10

--UPDATE THE LOGICAL FILE NAMES
DECLARE @TEMPLATE varchar(500)
DECLARE @SCRIPT varchar(500)
SET @TEMPLATE = N'ALTER DATABASE [{DBNAME}] MODIFY FILE (NAME = [{OLD}], NEWNAME = [{NEW}])'
SET @SCRIPT = REPLACE(REPLACE(REPLACE(@TEMPLATE, '{DBNAME}', @DESTINATIONDB),'{OLD}',@SOURCEDB),'{NEW}',@DESTINATIONDB)
EXEC(@SCRIPT)
SET @SCRIPT = REPLACE(REPLACE(REPLACE(@TEMPLATE, '{DBNAME}', @DESTINATIONDB),'{OLD}',@SOURCEDBLOG),'{NEW}',@DESTINATIONDBLOG)
EXEC(@SCRIPT)

A: You can restore a database directly from another database.
If you're using SQL Management Studio, select "From database" instead of "From device" in the Restore Database dialog box.

A: You generally want to restore a whole database from a backup. Trying to do it directly from a live running prod database could cause locking issues for your users. You can do this using SSIS, but it is neither a simple nor quick thing to set up properly.
Another possibility is if you can turn off prod for a time being (only if you have a time period when users are not inthe database). Then detach the database. Detach the dev database and delete it. Copy the file to the dev server and attach both databases again. This can be faster than a restore, but it is a rare environment now that doesn't have 24 hour data access on production.
Incidentally it is very much preferable to have dev and prod on separate servers.
And if you are restoring to dev, you need to make sure any dev changes that have not yet been committed to prod are scripted, so they can be run immediately after the restore. It's best if you script any and all database changes and store them in source control. That makes it easier to do this.

A: We do an on-demand backup of the production data, and then restore the backup on the dev machine.


text:
Q: Generate CSV from entity based on columns reordering How to achieve this concept based on generating CSV in case of:

*

*Ignoring field that am not interested in (Could be obtain in OpenCSV based on MappingStrategy)

*Order columns from the list
My entity consist of 14 variables (id, number, surname...), for ignoring specific files i used new StatefulBeanToCsv.withMappingStrategyand it works properly, but additionaly i have f.e List of Fields/String that correspond to my entity, but generated csv should be exactly same ordered like list.

How to achieve this in OpenCSV, alternetively it could be any other lib


text:
Q: Vuetify: checkbox shows status is checked when it is unchecked, and vice versa Let me simplify the issue:
I have a checkbox in my Vue.js template (using Vuetify components):
<v-checkbox
   v-model="selected"
   label="John"
   value="John"
   id ="john"
   @click.native="checkit">
</v-checkbox>

The checkit() method code is:
checkit: function() {
  let elt = document.getElementById('john')
  if(elt.checked) {
    console.log('checked')
  } else {
    console.log('unchecked')
  }
}

But I am getting the opposite result: when it is checked it says it is unchecked and vice versa.
What causes this and how to fix it?
Codepen demo

A: the console.log you get is triggered before the action of checking or unchecking the checkbox. So this is what happen:

*

*The user clicks on the checkbox

*The Javascript executes the listener

*If the event is not canceled in any of the listener, it continues and sets the checkbox as checked or unchecked.

What you could use is listen on the change event: https://codepen.io/anon/pen/VGOMPB?editors=1011
The second thing is that, by using document.getElementById('john') you are relying on the DOM here to check if the checkbox is checked or not. Why don't you rely on the selected property? DOM is updated after all the JS has been executed in order to avoid refreshing the DOM too frequently. If you want to wait the DOM to be updated, you can use the $nextTick helper: https://codepen.io/anon/pen/BOewpg?editors=1011
checkit: function () {
    this.$nextTick(() => {
        let elt = document.getElementById('john')
        if(elt.checked) {
            console.log('checked')
        } else {
            console.log('unchecked')
        }
    })

    //this.selected.push('Vuejs')
    //this.selected.push('Paris')
}


text:
Q: Keyboard acts as though SHIFT is stuck I am running a Windows 10 laptop and some of the keys are not working, such as "K", and all numbers (I currently use a USB keyboard anyway, since it feels easier -- plus all the keys from it work. BUT the problem being typed still remains below, even on the USB keyboard)
One of these (being the most important of them all since I use a USB keyboard anyway) is the SHIFT key. Mainly the right shift key, turning all my numbers from "123" to "!@#", and all letters cap. Using the "Caps Lock" key while this troublesome thing is going on, I can revert to small letters, but not numbers. I'm well aware that this is caused by dirt or ants or something of the sort -- as this laptop wasn't being used often before and it was just sitting there. (It wasn't mine, but a friend's at the time. I had a desktop). But if I can just disable the laptop's keyboard, then a USB keyboard should work, right?
I tried to uninstall the standard PS/2 Keyboard, but then it asks me to restart for it to work, and when it turns on again... the keyboard is still there.

A: Instead of uninstalling the keyboard, try using Device Manager to Disable the keyboard. Its worth a shot. if not, rip the shift button off the board.
https://www.itsupportguides.com/windows-10/windows-10-how-to-disable-devices-using-the-device-manager/


text:
Q: How to use a module with the `test` attribute within doc tests? I have a module which I would like to use within a code block in my documentation.
This module is only used for tests, so it has the #![cfg(test)] attribute which it should keep.
However, as a result, this file does not seem to be included when running tests on the documentation.
Take a look at the MVCE:
lib.rs
//! ```
//! use example::mock::Number;
//! ```
pub mod mock;

pub fn main() {}

mock.rs
#![cfg(test)]

pub type Number = i32;

This fails with:
---- src/lib.rs -  (line 1) stdout ----
error[E0432]: unresolved import `example::mock`
 --> src/lib.rs:2:14
  |
4 | use example::mock::Number;
  |              ^^^^ could not find `mock` in `example`

Is there a way to make my documentation test code use these files which are configured for tests?

A: This is a known limitation of doctest (Issue #45599). Sadly there is no real progress since the start of the issue (late 2017).
As a workaround, it is suggested that you add a feature to your Cargo.toml
[features]
test = []

Instead of checking for #[cfg(test)] you can then do #[cfg(feature = "test")].


text:
Q: How browsers identify a video? How can Search Engines identify a video?
An img tag has alt attribute:

A link tag has title:
this is a link

What about video tags?
I have been searching and it does not seem to have any kind of attribute to help
browsers to identify the video
https://www.w3.org/wiki/HTML/Elements/video
https://www.w3schools.com/tags/tag_video.asp
<video width="320" height="240" controls>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
  Your browser does not support the video tag.
</video>

Not even an embed YouTube:
<iframe width="560" height="315"
src="https://www.youtube.com/embed/zuCJYhLCN4E" frameborder="0" allowfullscreen

A: When one retrieves the resource using HTTP there is a Content-Type header returned that defines a type of the content located behind the URL.
This header gives the client a clue on how to treat if this is an image or a video or any other type of the data. So the search engine may perform bypassing the resources described in the document and decide if they are actually the videos.

A: In-Page markup using the itemtype="http://schema.org/VideoObject schema:

On-page markup is hidden descriptive data that is added to the source code of your web page. Google recommends using the schema.org, a new markup format that has been collaboratively designed and is supported by Google, Bing, and Yahoo!

See here.
(The links on that page that point to www.schema.org are broken, they should be just schema.org/)


text:
Q: FFMPEG: Generated video will not concat with the rest I am trying to make a video with FFMPEG, and I am concat'ing several videos together. However, the last two are generated from a PNG image using the -loop option.
ffmpeg -loop 1 -i img001.png -filter crop=768:432:128:72 -c:v libxvid -q 1 -t 5 -s 360x288 -aspect 16:9 out1.mp4
ffmpeg -loop 1 -i img002.png -filter crop=768:432:128:72 -c:v libxvid -q 1 -t 5 -s 360x288 -aspect 16:9 out2.mp4

Then I add silence to it using a wav file.
ffmpeg -i out1.mp4 -i silence.wav -shortest -c:v copy -c:a ac3 out11.mp4
ffmpeg -i out2.mp4 -i silence.wav -shortest -c:v copy -c:a ac3 out21.mp4

After that I expect that it is ready, so I run the concat filter.
ffmpeg -f concat -i full.txt -c copy "Q1-Full.mp4"

full.txt contains
file 'Likoonl-Q1-Intro.mp4'
file 'Likoonl-Q1-All.mp4'
file 'Likoonl-Q1-X2.mp4'
file 'out11.mp4'
file 'out21.mp4'

And right at the end of the run, I get this output.
[mp4 @ 049e6a80] st:0 PTS: 98240188 DTS: 98240188 < 689858768 invalid, clipping

When I play Q1-Full.mp4, it has the correct duration, but stops playing at the end of 'Likoonl-Q1-X2.mp4'.

A: ffmpeg -i Q1-Full.mp4 -i Q1-Contact.mp4 -filter_complex "[0:0] [0:1] [1:0] [1:1] concat=n=2:v=1:a=1 [v] [a]" -map "[v]" -map "[a]"


text:
Q: Subspace don't heritate the source_files and resources property in cocoa pods: why? I'm trying to exclude files depending on subspecs. Roughlt, my (local) podspec looks like
s.source_files = "all"
s.resources = "some"

s.subspec 'CoreData' do |sp|
   sp.exclude_files = ...
end
s.subspec 'Realm' do |sp|
   sp.exclude_files = ...
end

When in my Podfile I call pod 'MyPod/Realm', no file is imported.
I am missing something?
Should I add sp.source_files = "all" to my subspecs and if yes why?
It seems that subspecs don't heritate the source_files property nor the resources property.

A: So far, my solution is to do
  #s.source_files = "all"
  #s.resources = "some"

  s.subspec 'CoreData' do |sp|
    sp.source_files = "all"
    sp.resources = "some"
    sp.exclude_files = ...
  end

  s.subspec 'Realm' do |sp|
    sp.source_files = "all"
    sp.resources = "some"
    sp.exclude_files = ...
  end


text:
Q: Derivation of reversible flow work for open systems In derivation of steady reversible flow work, what sort of model are we considering, when we write the differential form of first law as $$\delta w=\delta q- dh-vdv - gdz $$
for one inflow and one outflow. I read somewhere that we consider a differential system that causes the system change but not very clear about it. Also we write $Tds = \delta q_{rev}$ from the 2nd law.  In flow systems usually heat input and output occurs at different temperatures so in what sense are we applying the 2 nd law here. Can someone help me with a rigorous proof for an open finitely extended system where the heat interactions are occuring at diffrent temperatures?
Thank you

A: Usually the contribution of axial heat conduction in the entering and exiting streams is neglected, and only convection of entropy by these streams is included in the open system versions of the 2nd law.  So for steady state, with a single inlet and outlet stream, the open system version of the 1st law would read $$\sum_i{\dot{Q_i}}-\dot{W_S}=\dot{m}\Delta \left(h+\frac{v^2}{2}+gz\right)$$where $\dot{Q_i}$ is the rate of heat flow from the i'th heat reservoir in contact with the control volume at its boundary, $\dot{W_S}$ is the rate of doing shaft work on the surroundings, and the $\Delta$ refers to the change between the inlet and outlet streams. And the open system version of the 2nd law would read $$\sum_i{\frac{\dot{Q_i}}{T_{Bi}}}+\dot{\sigma}=\dot{m}\Delta s$$where $T_{Bi}$ is the temperature of the i'th heat reservoir in contact with the control volume at its boundary and $\dot{\sigma}$ is the rate of entropy generation within the control volume.
For the special case where we use a single constant temperature reservoir at the same temperature T as that of our inlet flow stream and where we allow the residence time in the control volume be sufficient such that the outlet stream is also at temperature T, these equations reduce to:$$\dot{Q}-\dot{W_S}=\dot{m}\Delta \left(h+\frac{v^2}{2}+gz\right)$$and$$\frac{\dot{Q}}{T}+\dot{\sigma}=\dot{m}\Delta s$$From this last equation, we have $$\dot{Q}=\dot{m}T\Delta s-T\dot{\sigma}$$Subtracting this from our 1st law equation then yields:  $$-\dot{W_S}=\dot{m}\Delta \left(h-Ts+\frac{v^2}{2}+gz\right)+T\dot{\sigma}$$$$=\dot{m}\Delta \left(g+\frac{v^2}{2}+gz\right)+T\dot{\sigma}$$where g is the free energy per mole.


text:
Q: Google app engine RAM not increasing so i was receiving this error:
Exceeded soft private memory limit of 128 MB with 138 MB after servicing 200 requests total
So i upgraded my tier in app.yaml:
instance_class: B4_1G
basic_scaling:
max_instances: 25
idle_timeout: 10m

after deploying I should be getting 512 MB of RAM but I still get the same error as above. Is there a lag until the RAM kicks in or do I have to do something else besides change the app.yaml file?

A: The problem turned out to be: old instances running w/the previous config -- the solution is to stop all of them from the admin console and that the default version is set to the latest one.
Just pushing a new version is not sufficient.  The older version still exists, archived on the servers, and instances of it keep getting created because it's still the default version.
To change the default version, e.g, from the google developers console: log in to console.cloud.google.com, pick your project, then, from the menu on the top left, compute, app engine, versions.


text: Q: cross compiled core dump analysis I have a arm cross compiled application which has generated a core dump. I want to use the core dump along with the corresponding source code to debug the issue. which tool can be used to analyze a specific core dump against the corresponding source code?


text:
Q: AngularJS trigger for select box I use trigger('click') for radio buttons and select box. It works for radio button right :
angular.forEach(angular.element.find('input'), function(node){
    angular.forEach(result.data.test, function(value, key){
        if(node.value == value.FieldValue) {

            // ** JUST SEE THIS LINE ** //
            // This works fine in radio button
            angular.element("#" + node.id).trigger('click');

        }
    });
});

See line **.
But it doesn't work for select box :
angular.forEach(angular.element.find('select, option'), function(node){

    angular.forEach(result.data.test, function(value, key){
        if(node.value == value.FieldValue) {

            // This line doesn't work!!! //
            angular.element("#" + node.id).trigger('click');

        }
    });
});

A: why trigger is not working with select element is because select element selection is decided by value.
you can set each options value as node.id
and in your forEach loop you can set value to node.id insted of triggering click.
angular.forEach(angular.element.find('select, option'), function(node){
    angular.forEach(result.data.test, function(value, key){
        if(node.value == value.FieldValue) {
            angular.element.find('select').val(node.id);
        }
    });
});


text:
Q: CORS: credentials mode is 'include' Yes, I know what you are thinking - yet another CORS question, but this time I'm stumped.
So to start off, the actual error message:

XMLHttpRequest cannot load http://localhost/Foo.API/token. The
value of the 'Access-Control-Allow-Origin' header in the response must
not be the wildcard '*' when the request's credentials mode is
'include'. Origin 'http://localhost:5000' is therefore not allowed
access. The credentials mode of requests initiated by the
XMLHttpRequest is controlled by the withCredentials attribute.

I'm not sure what is meant by credentials mode is 'include'?
So when I perform the request in postman, I experience no such error:

But when I access the same request through my angularjs web app, I am stumped by this error. Here is my angualrjs request/response. As you'll see the response is OK 200, but I still receive the CORS error:
Fiddler Request and Response:
The following image demonstrates the request and response from web front-end to API

So based on all the other posts I've read online, it seems like I'm doing the right thing, that's why I cannot understand the error. Lastly, here is the code I use within angualrjs (login factory):

CORS Implementation in API - Reference purposes:
Method 1 used:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        EnableCrossSiteRequests(config);
    }

    private static void EnableCrossSiteRequests(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("*", "*", "*")
        {
            SupportsCredentials = true
        };
        config.EnableCors(cors);
    }
}

Method 2 used:
public void Configuration(IAppBuilder app)
{
    HttpConfiguration config = new HttpConfiguration();

    ConfigureOAuth(app);

    WebApiConfig.Register(config);
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    app.UseWebApi(config);

}

A: If you're using .NET Core, you will have to .AllowCredentials() when configuring CORS in Startup.CS.
Inside of ConfigureServices
services.AddCors(o => {
    o.AddPolicy("AllowSetOrigins", options =>
    {
        options.WithOrigins("https://localhost:xxxx");
        options.AllowAnyHeader();
        options.AllowAnyMethod();
        options.AllowCredentials();
    });
});

services.AddMvc();

Then inside of Configure:
app.UseCors("AllowSetOrigins");
app.UseMvc(routes =>
    {
        // Routing code here
    });

For me, it was specifically just missing options.AllowCredentials() that caused the error you mentioned.  As a side note in general for others having CORS issues as well, the order matters and AddCors() must be registered before AddMVC() inside of your Startup class.

A: If you are using CORS middleware and you want to send withCredentials boolean true, you can configure CORS like this:

var cors = require('cors');
app.use(cors({credentials: true, origin: 'http://localhost:5000'}));

A: The issue stems from your Angular code:
When withCredentials is set to true, it is trying to send credentials or cookies along with the request. As that means another origin is potentially trying to do authenticated requests, the wildcard ("*") is not permitted as the "Access-Control-Allow-Origin" header.
You would have to explicitly respond with the origin that made the request in the "Access-Control-Allow-Origin" header to make this work.
I would recommend to explicitly whitelist the origins that you want to allow to make authenticated requests, because simply responding with the origin from the request means that any given website can make authenticated calls to your backend if the user happens to have a valid session.
I explain this stuff in this article I wrote a while back.
So you can either set withCredentials to false or implement an origin whitelist and respond to CORS requests with a valid origin whenever credentials are involved

A: Customizing CORS for Angular 5 and Spring Security (Cookie base solution)
On the Angular side required adding option flag withCredentials: true for Cookie transport:
constructor(public http: HttpClient) {
}

public get(url: string = ''): Observable<any> {
    return this.http.get(url, { withCredentials: true });
}

On Java server-side required adding CorsConfigurationSource for configuration CORS policy:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // This Origin header you can see that in Network tab
        configuration.setAllowedOrigins(Arrays.asList("http:/url_1", "http:/url_2"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowedHeaders(Arrays.asList("content-type"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

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

Method configure(HttpSecurity http) by default will use corsConfigurationSource for http.cors()

A: If it helps, I was using centrifuge with my reactjs app,
and, after checking some comments below, I looked at the centrifuge.js library file, which in my version, had the following code snippet:
if ('withCredentials' in xhr) {
 xhr.withCredentials = true;
}

After I removed these three lines, the app worked fine, as expected.
Hope it helps!


text:
Q: History of asset in Hyperledger Fabric I am using node.js to write chaincode and I want to get the history of drug in pharmaceutical supply chain. I deployed chaincode, invoked manufacture and buy contract which modifies the drug's current state from one owner to another owner. Infact, I just modified commercial paper chaincode for this. The change in owner is reflected in couchdb database. But when I try to get the history of drug by drug key it doesn't work as expected.
Code I used

const promiseOfIterator = this.ctx.stub.getHistoryForKey(drugKey);
const results = [];
for await (const keyMod of promiseOfIterator) {

            const resp = {
                timestamp: keyMod.timestamp,
                txid: keyMod.tx_id
            }
            if (keyMod.is_delete) {
                resp.data = 'KEY DELETED';
            } else {
                resp.data = keyMod.value.toString('utf8');
            }
            results.push(resp);
        }
return results;

When I printed the results, it gives: []
And when I do this: Drug.fromBuffer(getDrugHistoryResponse); and print it, it gives Drug { class: 'org.medicochainnet.drug', key: ':', currentState: null }
How to make this work? What am I doing wrong here? Please help me.

A: the function
ctx.stub.getHistoryForKey(drugKey);

is an asynchronous function. So you need to add await
const promiseOfIterator = await this.ctx.stub.getHistoryForKey(drugKey);

Then you can iterate over the result.

A: I have done it in a demo like that:
const promiseOfIterator = await this.ctx.stub.getHistoryForKey(drugKey);
const results = [];
while(true){
 let res = await promiseOfIterator.next();
  //In the loop you have to check if the iterator has values or if its done
  if(res.value){do your actions}
  if(res.done){
   // close the iterator
   await promiseOfIterator.close()
   // exit the loop
   return results
   }
}

Check the Mozilla Documentation for more information about Iterators in Javascript. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators


text:
Q: What is the deal with this usb drive with a second block device? I have a giveaway usb stick and when I plug it into my computer and run lsblk it shows two block devices, i.e. sdb and sdc. sdb of them contains almost all the free space ( ~15G) and the sdc one is very small (32M) and contains stuff like images of the company who gave the usb stick away.
I would like to get rid of the sdc one (more out of curiosity). However, these are apparently not partitions on the same hard drive (otherwise lsblk would show something like sdb1 and sdb2, right?).
Last but not least I can't even run fdisk /dev/sdc as it's apparently a Read-only file system.
Can I get rid of this sdc device or at least wipe it clean. And what are the inner workings of this? Is sdc a second physical drive?

A: There are USB sticks that present itself as two drives: a CD-ROM (readonly) and  a mass-storage device (read/write).
This was invented to allow auto-starting an application when the USB stick is plugged in on a windows system.
There may exist a removal tool from the manufacturer.
Example: Sandisk U3. Search for keywords: sandisk remove u3 launchpad


text:
Q: Socket / Http Request What is the difference between using socket to connect to a site, and simply making an HTTP request?
Does the connection established by the sockets make it possible not to authenticate during the request?

A:
What is the difference between using socket to connect to a site, and simply making an HTTP request?

The act of using socket to connect to a site is more basic than making an HTTP request — the former is required by the latter, since a HTTP/TCP request cannot be sent without an established connection.

Does the connection established by the sockets make it possible not to authenticate during the request?

HTTP neither implies authentication.


text:
Q: Why do I get a 'conformability error' when I attempt to convert water in GNU units? I've been using the GNU units program and I seem to think that I should be able to convert water between a volume and a weight.
Examples:
You have: 1 gram water
You want: cm^3
conformability error
    1 gram water = 9.80665 kg^2 / m^2 s^2
    cm^3 = 1e-06 m^3

and
You have: 1 gallon water
You want: pounds
conformability error
    1 gallon water = 37.122208 kg m / s^2
    pounds = 0.45359237 kg

A: The water unit is the specific weight of water at the standard temperature of 0°C. A cm water is a unit of pressure, like the cm Hg.
You have: water
You want:
        Definition: gram force/cm^3 = 9806.65 kg / m^2 s^2

You have: 1cm Hg
You want: cm water
        * 13.5951
        / 0.073555914

A gram water is a unit of mass times pressume divided by length, which I don't recognize as a common physical quantity. Units has waterdensity defined to be the density of water at 4°C and 1atm, which is (to a very good precision) 1kg/m³.
You have: 1g/waterdensity
You want: cm^3
        * 1
        / 1

If you want density in other conditions or of other materials, either type out the constant or put it in your own unit definition file (units -f '' -f ~/.units.data).

A: Technically speaking, you're trying to convert volume into mass or weight.  Sure, you wrote "water", but at what temperature and pressure?  It makes a difference.  And what if you wrote "1 gram mercury"?
You're asking for something that can't be done in the simplistic context in which units works.  I think you're going to have to look up the density of the fluid you're interested in, and multiply by yourself.


text:
Q: Adding jquery validation to Chosen drop down list on post in ASP.NET MVC page I'm using a default site template from Visual Studio 2013 preview which integrates Bootstrap by default (which I replaced with v3)
In a form, the Jquery validate on POST correctly highlights error fields, except for drop down boxes that I've styled with the Chosen plugin.

My code for the drop down list in question is:
@Html.DropDownListFor(
    x => x.Job.State,
    Model.States,
    "Select a State", new { @class = "form-control chosen-select"})
    @Html.ValidationMessageFor(model => model.Job.State)

This renders as follows:
<select class="input-validation-error form-control chosen-select" id="Job_State" name="Job.State" style="width: 50%; display: none;">
    <option value="">Select a State</option>
    <option value="ACT">ACT</option>
    <option value="NSW">NSW</option>
    <option value="QLD">QLD</option>
    <option value="TAS">TAS</option>
    <option value="NT">NT</option>
    <option value="VIC">VIC</option>
    <option value="WA">WA</option>
</select>

Select a State

            <input type="text" autocomplete="off">

Select a State

ACT

NSW

QLD

TAS

NT

VIC

WA

State is required.

Notice that the input-validation-error class is being added to an element that Chosen sets to display:none so obviously the border doesn't get shown.
Ideally if I can add the input-validation-error class to the div that's within the select, then this will fix my problem, but I don't know how to do that, so any assistance would be greatly welcome!
Note - I'm actually not after client side validation, I'm only using validation on POST.

A: @Bartek Marnane, You're going to need to override the highlight and unhighlight callbacks that jQuery Validate uses by default when applying it's failed validation css class.  What you'll want to do is inspect the element on highlight and unhighlight to see if it's a chosen drop down list to apply/remove the css class from the element that is presenting the list.
I haven't verified the highlight and unhighlight function for chosen because I've not worked with that plugin before.  If anything you'll end up tweaking my css class check on the element to see if it is a chosen drop down or not.  Realize that the element that will fire validation will be the one that is not visible.  If it's not firing validation then there is a setting in jQuery validate to ignore certain elements.
// This script block should be placed after jQuery, jQuery Validate and jQuery Validate
// Unobtrusive plugins have been loaded.
$(function () {
    // retrieves the current jQuery validator for the form
    var $validator = $("form").validate();
    // We're going to override the default highlight method from jQuery when applying
    // our css class for an error
    $validator.settings.highlight = function (element, errorClass, validClass) {
        var $element = $(element);
        if ($element.hasClass("chosen-select")) {
            // It's a chosen element so move to the next element in the DOM
            // which should be your container for chosen.  Add the error class to
            // that instead of the hidden select
            $element.next().addClass(errorClass).removeClass(validClass);
        }
        else if (element.type === "radio") {
            this.findByName(element.name).addClass(errorClass).removeClass(validClass);
        } else {
            $element.addClass(errorClass).removeClass(validClass);
        }
    };
    // We're going to override the default unhighlight method from jQuery when removing
    // our css class for an error
    $validator.settings.unhighlight = function (element, errorClass, validClass) {
        var $element = $(element);
        if ($element.hasClass("chosen-select")) {
            // It's a chosen element so move to the next element in the DOM
            // which should be your container for chosen.  Add the error class to
            // that instead of the hidden select
            $element.next().removeClass(errorClass).addClass(validClass);
        }
        else if (element.type === "radio") {
            this.findByName(element.name).removeClass(errorClass).addClass(validClass);
        } else {
            $element.removeClass(errorClass).addClass(validClass);
        }
    };
});

A: I have never used chosen but I think you might be able to set the input-validation-error class in your view by checking the ModelState:
@if(!ModelState.IsValid){
    Html.DropDownListFor(
        x => x.Job.State,
        Model.States,
        "Select a State", new { @class = "input-validation-error form-control chosen-select"})
        Html.ValidationMessageFor(model => model.Job.State)
}


text:
Q: Passing jQuery Autocomplete search method value to search event I am making a call to the search method and passing a value
$('myelem').autocomplete('search','test');

Then I have an event handler for the search event
search: function (event,ui){

//I need to access the value 'test' passed from the search method in the search event

}

So far I can not find out how to access the value in the search event handler. The value is available in the source: function (request, response) event handler in the request.term property.

A: The documentation reads:
search: function(event, ui) { ... }

However, the ui parameter turns out to be an empty object.


text:
Q: Control ASDoc Tooltips in Eclipse In Eclipse (w/ Flash Builder 4.6) if you add ASDocs to your Actionscript the tooltip for that class/method/property will include that ASDoc and use the tags to do some formatting. Is there a way to change how it formats as well as add tags for it to use?

A: Here is a list of tags that can be used.
ASDoc tags
Then you can use the ASDoc tool to export them into full HTML documents, which all come from your comments, and appear the same as they do in the tooltips within Flex.


text:
Q: Make IFormFile function to work with model I have a function in my controller that takes a file sent by an ajax call and saves it to a specified path. I was wondering how I could make this work with a model instead as I am hoping to send more data than just the image.
ViewModel:
public class PhotoViewModel
{
    // Other strings

    public IFormFile userimage { get; set; }
}

Controller: Without model (working)
[HttpPost]
public async Task<IActionResult> Post(IFormFile file)
{
    var filePath = Path.GetFullPath(@"C:\Users\me\documents\" + file.FileName);

    if (file.Length > 0)
    {
        using (var stream = new FileStream(filePath, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }
    }

    return StatusCode(200);
}

Attempt at Version with Model:
[HttpPost]
public async Task<IActionResult> PhotoData(PhotoViewModel model)
{
    var filePath = Path.GetFullPath(@"C:\Users\me\documents\" + model.userimage.FileName);

    if (ModelState.IsValid)
    {
        if (model.userimage.Length > 0)
        {
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await model.userimage.CopyToAsync(stream);
            }
        }
    }

    return StatusCode(200);
}

This attempt doesn't get me far. By setting a breakpoint I can see it fails at setting the filePath but I'm not sure how to work with the model. Any help is appreciated.

A: What is the error message you are getting and what is the client side code you are using to send the API request?
You will have to use a FormData object and fill the FormData object with the required properties.
var formData = new FormData();
formData.append(add PhotoViewModel properties)
formData.append(userimage, <file>);


text:
Q: getting/setting browser_id with Products.BeakerSessionDataManager I'm having a problem associating a browser_id to a session when using Products.BeakerSessionDataManager.  I'm working on Plone 5.
As far as I understand Zope sessions, as soon as .getSessionData() is called on a session data manager, a session data container is created if it did not exist.  Furthermore, this data will contain a token, which is the same as the browser_id associated with the browser making the request.  And finally, a cookie is set on the response with the name _ZopeId (and the value is the same as the token).  Thus, when I use the default session data manager that come with Zope, I get this:

ipdb> context.session_data_manager.getSessionData()
id: 14737473151418102847, token: 38878600A7nh90DE9ao, content keys: []

However, when I use Products.BeakerSessionDataManager, the same call gives me this:

ipdb> context.session_data_manager.getSessionData()
{'_accessed_time': 1473745441.437582, '_creation_time': 1473745441.437582}

Moreover, no cookie is set.
Perusing some old Zope docs, I found a reference to getContainerKey(), so I thought that might get me the browser_id.  However, the returned value is different on every request, so that does not work.  Also, calling .getBrowserIdManager().getBrowserId() on the session_data_manager throws an error, because Beaker does not support browser id managers.
I want to set a cookie, and I want a token. I'm doing this so that I can identify anonymous clients in a voting application, so that they will not cast multiple votes (at least not in the same session - there are other mechanisms to allow voting only when certain other conditions are met).
Am I misunderstanding the machinery, or am I missing something?


text:
Q: Divided differences polynomial $p[z, a_1, a_2,...,a_n]$ Let's consider complex points $a_1,a_2,..., a_n \in \mathbb C$, and polynomial $p$ of degree $\deg p \ge n \ge 1$. I want to prove that function $q$:
$$q(z) = p[z, a_1,a_2,...,a_n]$$
has to be polynomial of degree $\deg p - n$.
My solution
From mean value theorem, we know that:
$$\forall_{z \in \mathbb C} \exists_{\epsilon_z \in (\min(z, a_1,...,a_n), \max(z,a_1,...,a_n))}: p[z, a_1,...,a_n] =  \frac{p^{(n)}(\epsilon_z)}{n!}$$
Now, since $p$ is polynomial of degree $\deg p$, then $p^{(n)}$ will be polynomial of degree $\deg p - n$, and this is sufficient fact to say that $q$ has to be polynomial of degree $\deg p - n$.
Is my justification correct?


text:
Q: How to display a page with a sorted drop down list? I have a select list

<select id="select_zone">
  <option value="north">North</option>
  <option value="east">East</option>
  <option value="south">South</option>
  <option value="west">West</option>
</select>

Now I want the items in the list to appear in a sorted manner using jquery. I should be able to add items in the list in the html code manually (in a random order). BUT they should appear alphabetically sorted in the browser page.
I have been breaking my head and have done a lot of R&D. But not being able to find a way to sort the dropdpwnlist at the time the page is loaded.
Please help!

A: here is a working fiddle using code from :
http://sebastienayotte.wordpress.com/2009/08/04/sorting-drop-down-list-with-jquery/
http://jsfiddle.net/Rz6xv/
code:
function sortDropDownListByText() {
    // Loop for each select element on the page.
    $("select").each(function() {

        // Keep track of the selected option.
        var selectedValue = $(this).val();

        // Sort all the options by text. I could easily sort these by val.
        $(this).html($("option", $(this)).sort(function(a, b) {
            return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
        }));

        // Select one option.
        $(this).val(selectedValue);
    });
}

A: write a method and call on document ready()
function sortMycombo() {
   $("#select_zone").html($('#select_zone option').sort(function(x, y) {
         return $(x).text() < $(y).text() ? -1 : 1;
   }))
   $("#select_zone").get(0).selectedIndex = 0;
   e.preventDefault();
});

A: You could use jQuery and something like this:
$("#id").html($("#id option").sort(function (a, b) {
    return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))


text:
Q: Why would fish appear to ignore the second 'set' command in a function? When I run this function, JAVA_HOME gets set, JUG_BT_ARCH does not get set, and 'gello' gets echoed. I'm sure I'm missing something really obvious.
function j8
  set -x JAVA_HOME /Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/
  set -x JUG_BT_ARCH amd64-darwin11-xcode4
  echo gello
end

A: Variables by default have function-scope, so when the function ends, they go away. You can make them global via --global or -g:
set -gx JUG_BT_ARCH amd64-darwin11-xcode4

Now when you run the function, this variable will stick around.


text:
Q: Why is the sum of the numbers $1+2+3+4+\dots+N$ equal to the integral $\int_{0}^{N}x+0.5$, rather than $\int_{0}^{N}x$? Sorry if this question has been asked in the past, or if it seems silly, but I couldn't find anything on Google or SE, and we didn't cover series in our math classes.
So basically, I'm working on something requiring the use of a triangular kernel, so I need to find the total sum of each point sampled. To make it easier for myself, I used a single side (result multiplied by two when I'm done), so it takes the form of an easier linear equation.
I thought that to find the result of summing each point along the line y=x would be the same as taking the definite integral of 0->N to find the area under the curve (or line, in this case):
$\sum_{n=1}^{N}n = \int_{0}^{N}x\cdot dx = \frac{N^2}{2}$
However, that obviously didn't work. So then I put the sum series through Microsoft Math which gave me $\sum_{n=1}^{N}n = \frac{N^2+N}{2}$
Differentiating it, I found that the integral I was after was actually $\int_{0}^{N}(x+0.5)\cdot dx$
Why does the integral require the 0.5 offset for the sum to work the way I intended? I thought that a possible reason for this was that the integral took one number too many (ie. added N+1 to the result), but I found that wasn't the case.

A: Here is a picture for $n = 10$.  The blue rectangles have width $1$ and height $0, 1, 2, \ldots, n-1$.  Adding the red unit squares on top, we see the total shaded area is the sum $1 + 2 + \cdots + n$.  The integral $\int_{x=0}^n x \, dx$ is the area under the line $y = x$.  You can see that the two areas don't match up:  The triangle doesn't include half of the area of all the red squares.  But since there are $n$ red squares, their area is $n \times 1 = n$, and half of this is $n/2$.  So the sum of $1 + 2 + \cdots + n$ is equal to $n^2/2 + n/2$.


text:
Q: change tab displays all images and after min it shows original images I am using javascript easyslider for images
And the issue is I have four tabs, when i click on next tab it shows me image of next tab also, at the time of loading.
Please suggest any way ???
here are script :---

    $(document).ready(function() {
  $('#reviews').imagesLoaded(function() {
          $("#slider1").easySlider({
                nextId: "slidernext1",
                prevId: "sliderprev1",
                speed: 150
            });
            if ($(".reviewsImage").find('li').length <= 1)
                {
                    $("#slidernext1").hide();
                    $("#sliderprev1").hide();
                }
        }


text:
Q: Error in Tableau Custom Query I have written the following query in Tableau as a custom query but as I have 2 fields with the same name I get the following error message:
Oracle database error 904: ORA-00904: "Custom SQL Query"."EID": invalid identifier

and I am not sure how to fix this.
My query is the following:
SELECT * FROM TABLE1 Q FULL OUTER JOIN TABLE2 C ON Q.EID = C.EID

Would appreciate any advice on how I can fix this.


text:
Q: VBA Count occurrence of an element in a multi-dimensional array, how? I have defined a multi-dimensional array using range in vba, for example
Dim Arr() as Variant
Arr = Range("A1:F5")

This resulted the a 5x6 array Arr(1,1) to Arr(5,6)
I want to count the occurrence of a string, say "ABC" in Arr(5) (i.e. Row 5) only.
The following code can find the count of "ABC" in the all of the array
For Each x in Arr
  if x = "ABC" then Cnt = Cnt + 1
Next

But if only want to count dimension 5, Arr(5) return an error.

A: Use Index to peel off the last 'row' from the second rank. Splitting the Joined result will return a case-sensitive COUNTIF result.
Dim Arr() As Variant, tmp As String, d As String, cs As Boolean

Arr = Range("A1:F5").Value2

d = ChrW(8203)
cs = False

tmp = d & Join(Application.Index(Arr, 5, 0), d) & d

If cs Then
    Debug.Print UBound(Split(tmp, "ABC"))
Else
    Debug.Print UBound(Split(LCase(tmp), LCase("ABC")))
End If

A non-case-sensitive result can be returned by converting both the joined array and the criteria to a common case.

A: Sub FindABC()
    Dim Arr(), cnt, x
    Const ROW_NUM = 5
    Arr = Range("A1:F5")
    For x = 1 To UBound(Arr, 2)
        cnt = cnt + IIf(Arr(ROW_NUM, x) = "ABC", 1, 0)
    Next
    MsgBox cnt
End Sub


text:
Q: Jquery $('.article.active').next Issue I got something like a slider , at least it should be.But something is not working here is the code :
$('div.app').on('click' , function(){
var current = $('.article.active');
if(current.next('.article').length > 0)  {
    current.next('.article')
        .effect("slide" ,{direction:'left', mode:'hide'},1000)
        .addClass('active')
        .removeClass('hide');
    current.effect("slide",{direction:'right',mode:'show'},1000)
        .removeClass('active')

}   else {
         $('.article:first').removeClass('hide').addClass('active');
}

});

And the JSFiddle : http://jsfiddle.net/u4m0oLsc/.

A: var current = $('.article.active'); should be declared inside the click event function like:
$('div.app').on('click' , function() {
  var current = $('.article.active');
  ...
}

Fiddle


text:
Q: flutter draggable button in specific area I trying to learn draggable widgets. I found something in internet but i faced some bugs. while i drag the button if i drop it in bottom bar it become invisible. Button stays behind bottom bar i think. Also if i drop it in tabbar ,the same things happend. Button become invisible. Button must be moveable between bottom and tabbar i guess . But i dont know how can i do that. Can any one help me?
How can i solve it?
My codes are below;
Offset position = Offset(320, 200);

Scaffold(
          backgroundColor: Colors.transparent,
          appBar: AppBar(
            title: Text("Test"),

          ),
          body: Stack(
            children: [
              GridView(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisSpacing: 0,
                    mainAxisSpacing: 10,
                    crossAxisCount: 3,
                    childAspectRatio: 0.41),
                children: [
                  TestWidget(),
                  TestWidget(),
                  TestWidget(),
                  TestWidget(),
                  TestWidget(),
                  TestWidget(),
                  TestWidget(),
                ],
              ),
              Positioned(
                left: position.dx,
                top: position.dy,
                child: Draggable(
                  onDragEnd: (details) {
                    setState(() {
                      position = details.offset;
                    });
                    print(position);
                    print(x);
                  },
                  feedback: FloatingActionButton(
                    child: Icon(Icons.shopping_cart),
                    onPressed: () {},
                  ),
                  child: FloatingActionButton(
                    child: Icon(Icons.shopping_cart),
                    onPressed: () {

                    },
                  ),
                ),
              ),
            ],
          ),
        ),


text:
Q: automatic page update appengine I have an application that uses Python appengine, there is a service that updates the status of users, if an admin person has a page open, I would need it to update in real time. I know that appengine has CRON and task queues, what would be the correct way to handle this? Should I set an update flag in the models that that triggers jscript?

A: The Channel API can be used to send real-time(ish) data to clients, without the need of clients polling the server.


text:
Q: Applescript to Delete Watched TV Shows from iTunes Library Here is what I'm trying to do with the actual code:
if (there are multiple episodes in a tvshow folder AND at least one episode is marked as unwatched){
delete the watched episodes
}

My goal here is to always leave a single episode in the TVShow folder. Even if that show is marked as watched or unwatched. The only condition where deletion occurs is when there are multiple episodes and one of those episodes is marked as unwatched. I need this script to run on ALL the tvshows in iTunes. This will keep my iTunes account smaller and auto delete watched shows for me. Anyone know how to do this? I'm very new to Applescripting.

BTW, and if it matters, the TVShows I'm referring to are ones that I've added to the iTunes library OUTSIDE of the iTunes store. This script will not be deleting purchased tvshows. I appreciate any help!

A: Providing a script which deletes something is always quite dangerous.
As your request is a bit ambiguous

… at least one episode is marked as unwatched
     and
… a single episode … even if that show is marked as watched or unwatched

the script is going to delete all watched episodes in the playlist TV Shows if there is at least one unwatched episode.
All unwatched episodes are not deleted.
There are two scripts one for testing and and one for deleting.

Script #1 doesn't delete anything but displays the list of the items which are supposed to be deleted.
tell application "iTunes"
    set watchedEpisodes to tracks of playlist "TV Shows" whose unplayed is false and played count > 0
    set unwatchedEpisodes to tracks of playlist "TV Shows" whose unplayed is true
    if (count unwatchedEpisodes) > 0 then
        set trackNames to {}
        repeat with anEpisode in watchedEpisodes
            set end of trackNames to ((name of anEpisode) as text) & " of show " & show of anEpisode
        end repeat

        set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}
        display dialog trackNames as text
        set AppleScript's text item delimiters to TID
    end if
end tell

Please check the output carefully

Script #2 deletes the items matching the criteria
tell application "iTunes"
    set watchedEpisodes to tracks of playlist "TV Shows" whose unplayed is false and played count > 0
    set unwatchedEpisodes to tracks of playlist "TV Shows" whose unplayed is true

    if (count unwatchedEpisodes) > 0 then
        repeat with anEpisode in watchedEpisodes
            delete anEpisode
        end repeat
    end if
end tell


text:
Q: Openshift cannot create any pods I am testing a openshift v3 starter (ca-central-1) and created a project from custom docker image stream (from github). It was running fine, but after I changed a config map, rescaled the deployment to 0 pods, upscaled it to 1 pod, openshift can no longer start any pods.
The error in web interface is (in Events tab):
Failed create pod sandbox: rpc error: code = Unknown desc = failed to start sandbox container
for pod "hass-19-98vws": Error response from daemon: grpc: the connection is unavailable.

Pod sandbox changed, it will be killed and re-created.

These messages appear in a endless loop. I tried to deploy new deployment but it gives same logs.
What am I doing wring?

A: Ok, it seems that I was affected by an upgrade of cluster. The issue resolved itself after a 2 days.


text:
Q: How long does it take to transfer 1GB via USB2? Let's say you are transferring a 1 GB file from your USB storage device to your computer. You connect your USB storage device to a USB 2.0 port, how long does it take to transfer the files?

A: It depends on the performance of the USB device, the USB subsystem, the storage system and the computer you're connecting the USB device to. Theoretically USB 2.0 has a bandwidth of 480 Mbit/s, which is about 57 MiB/s. However, due to encoding overhead and inefficiencies in the protocol this speed is not obtainable and ideal conditions would probably yield around 30-40 MiB/s.
Based on this it's guaranteed to take more than 18.5 seconds, half a minute would be fast and if conditions are particularly poor you're still waiting.


text:
Q: How to prevent system from gettin Freezed on launching any software? I'm using a computer system with the following system specification:
System:        HP-Compaq-dc7100-SFF-DX878AV
Memory:        1GB
Processor:     Intel Pentium(R) 4 CPU 3.00GHz x 2
Graphics:      Intel 915Gx86/MMX/SSE2
OS type:       32-bit
Disk:          16.4GB

This specification is far more than specified on Ubuntu 14.04 LTS Page.
But my system often gets hanged/freeze. This is very annoying. What might be the problem?
I haven't installed any heavy software like 'Krita Image Editor' or 'Nebteans IDE'.
Even if when I just start my computer it's resources normally used are as follow:
Memory: 550 MB
CPU:    aoubt 60% to 80%

Why is it so high usage of resources? Can any one help about this?

A: Ubuntu is too heavy for this old computer.
I would suggest installing Lubuntu 14.04.
1 GB of RAM is just enough. And Ubuntu graphical effects drain all CPU and GPU resources.
Minimal requirements just let OS start and work some way. They do not guarantee any comfortable work.