text:
Q: How do you send a POST request for logging in, with Angular's $resource? I thought this would be simple to do but it terribly confusing.
I want to set my Angular login form to allow my users to login. On the login form, I want to take the input and send it as a POST request to my server for verification.
However, I cannot find a single example of $resource being used to send a POST request. Does anyone have any examples they can share?

A: After defining your resource, you can use the save method which is default action for post defined by $resource. The first parameter of save takes arguments used as url params, and the second parameter takes post data.
var LoginResource = $resource("/rest/path/login");
var bodyObject = {username:"test", password:"test"};
LoginResource.save({}, bodyObject);

Then you can access response to your request by using promise of $resource. To clarify I will give an sample service and controller which will make a post request.
angular.module('yourApp').
factory('yourService', ["$resource", function($resource){
    var LoginResource = $resource("/rest/path/login");
    var serviceObject = {loginUser: function (userName, password){
        return LoginResource.save({}, {userName: userName, password: password}).$promise; //this promise will be fulfilled when the response is retrieved for this call
    }};
    return serviceObject;
}];

angular.module("yourApp").controller("LoginCtrl", ["$scope", "yourService",
   function($scope, yourService){
    yourService.loginUser("test", "test").then(
        function(loginResult){
           console.log(loginResult);
        },
        function(err){
           console.error(err);
        }
    )
  }];

A: If you look on the docs: https://docs.angularjs.org/api/ngResource/service/$resource
Scroll down to where you can see Returns.
You will see this list:
{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'} };

This is where it tells you what is defined on the $resource object by default. As you can see if you call get then you will use HTTP GET, save => HTTP POST.
So if you define this:
var User = $resource('/user/:userId', {userId:'@id'});

Then you can perform a GET:
var user = User.get({userId:123}, function() {
  user.abc = true;
  user.$save();
});

If you define this:
var User = $resource('/user/:userId', {userId:'@id'}, {specialAction: {method: 'POST'}});

And call it:
User.specialAction({someParam:someValue});

You will perform the same action as save. You have just renamed it :)
So $resource just wraps around $http to make using RESTful API's easier. You can defined your own set of methods if you wish, you can specify to great detail how these are supposed to be executed.


text:
Q: Defining a new list so that modifications do not affect the original without importing copy I know that there have been several similar discussions on this topic and I have tried to implement at least one (a list comprehension). The main issue is that my original list (it is actually a matrix set up as a list of lists) is being modified by part of my code, but I can not seem to figure out why.
Here is the code that I have
def eliminate_row_column(mat,k,l):
    new_matrix = [i for i in mat]      #creates a new temp matrix
    new_matrix.pop(k)        #eliminates the kth row
    for i in range(len(new_matrix)):
        new_matrix[i].pop(l)     #eliminates the lth column
    return new_matrix

It appears to be removing the kth element (the kth row) without modifying the original. However, when I enter the for loop it appears to be modifying the original input list.
It appears that using a deep copy might resolve the issue, but I will need this code to work in context where (students) can not import in.
I am not a programmer by training and this one is giving me a bit of a headache.
Any help would be appreciated.

A: In this line, i references the existing lists, which are not copied.
new_matrix = [i for i in mat]

You can simply copy them:
new_matrix = [i.copy() for i in mat]

By the way, for what it's worth, a list of lists is not really a matrix. You could use a NumPy array if you wanted a proper matrix.

A: Thanks to Barmar for the correct solution. I am including the corrected code below to show the fix. Obviously you can use numpy instead, but this works without it.
def eliminate_row_column(mat,k,l):
    new_matrix = [[t for t in row ] for row in mat]    #creates a new temp matrix
    new_matrix.pop(k)        #eliminates the kth row
    for i in range(len(new_matrix)):
        new_matrix[i].pop(l)     #eliminates the lth column
    return new_matrix

redpajama_set_name: RedPajamaStackExchange


text:
Q: Inserting figures into Anki (LaTeX cards) causes no BoundingBox error I'm using latex to format my Anki cards and ran into an error:
"! LaTeX Error: Cannot determine size of graphic in"
\begin{center}
\includegraphics{supplementary.PNG}\\\relax {{c1::Supplementary angle}}
\end{center}

I'm using TexLive if this helps.


text:
Q: getNumColumns() for API 8 getNumColumns() for GridView is available since API 11, is there any way to get this method in API 8?

A: in this duplicated post, someone came with an answer which works for API 8 :
private int getNumColumnsCompat() {
    if (Build.VERSION.SDK_INT >= 11) {
        return getNumColumnsCompat11();

    } else {
        int columns = 0;
        int children = getChildCount();
        if (children > 0) {
            int width = getChildAt(0).getMeasuredWidth();
            if (width > 0) {
                columns = getWidth() / width;
            }
        }
        return columns > 0 ? columns : AUTO_FIT;
    }
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private int getNumColumnsCompat11() {
    return getNumColumns();
}

A: I added this implementation on a custom GridView subclass of mine, and it worked as expected. I checked the declared fields of the GridView class and at least on API 8 they do already have a field called mNumColumns (which is what is returned on API 18 by getNumColumns()). They probably haven't changed the field name to something else and then back between APIs 8 and 18, but I haven't checked.
@Override
public int getNumColumns() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        return super.getNumColumns();
    } else {
        try {
            Field numColumns = getClass().getSuperclass().getDeclaredField("mNumColumns");
            numColumns.setAccessible(true);
            return numColumns.getInt(this);
        } catch (Exception e) {
            return 1;
        }
    }
}

The @Override won't cause any errors since it's just a safety check annotation AFAIK.
I also don't know if there are any counter-recommendations of doing like this instead of having a separate getNumColumnsCompat() method (as on @elgui answer), but I found it to be pretty neat like this.

A: This probably isn't an answer you want to hear but you'll have to create a custom GridView' with it's API 11 functionality that fits with what's available in API 8.

A: Joining best answers, and boiling up:
@SuppressLint("NewApi")
@Override
public int getNumColumns() {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
      return super.getNumColumns();

   try {
      Field numColumns = getClass().getSuperclass().getDeclaredField("mNumColumns");
      numColumns.setAccessible(true);
      return numColumns.getInt(this);
   }
   catch (Exception e) {}

   int columns = AUTO_FIT;
   if (getChildCount() > 0) {
      int width = getChildAt(0).getMeasuredWidth();
      if (width > 0) columns = getWidth() / width;
   }
   return columns;
}

:D


text:
Q: Error NoClassDefFoundError when run jetty I try to create a jetty server in jar executable
I have maven 3.6.0 AND OpenJdk 11.0.4
my first run failed I receive the following error when I launch my code :

Exception in thread "main" java.lang.NoClassDefFoundError: javax/servlet/http/HttpServletResponse
          at com.my.test.Main.main(Main.java:13)
      Caused by: java.lang.ClassNotFoundException: javax.servlet.http.HttpServletResponse
          at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
          at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
          at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
          ... 1 more

Code :
import java.net.URL;
import java.security.ProtectionDomain;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;

public class Main {

    public static void main(String[] args) throws Exception {
        int port = Integer.parseInt(System.getProperty("port", "8080"));
        Server server = new Server(port);

        ProtectionDomain domain = Main.class.getProtectionDomain();
        URL location = domain.getCodeSource().getLocation();

        WebAppContext webapp = new WebAppContext();
        webapp.setContextPath("/");
        webapp.setDescriptor(location.toExternalForm() + "/WEB-INF/web.xml");
        webapp.setServer(server);
        webapp.setWar(location.toExternalForm());

        server.setHandler(webapp);
        server.start();
        server.join();
    }
}

pom.xml dependencies :
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>9.4.22.v20191022</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-util</artifactId>
            <version>9.4.22.v20191022</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <version>9.4.22.v20191022</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-plus</artifactId>
            <version>9.4.22.v20191022</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-webapp</artifactId>
            <version>${version.jetty}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>apache-jsp</artifactId>
            <version>${version.jetty}</version>
        </dependency>
    </dependencies>
</project>

I don't understand what's happend, someone can help ?
thank you by advance.

A: If you are doing embedded-jetty, then no dependencies on the server will ever be marked as ...
<scope>provided</scope>

The Server will never have dependencies "provided" outside of itself.
Provided dependencies is typical for war packaged projects, indicating that the server will provide that specific dependency for them at runtime.


text: Q: Instrumenting JDBC driver to log SQL queries I am trying to automatically build (with mvn) and instrument some java projects where the JDBC drivers are instrumented to log all sql queries. Can anyone point me to any resources for how I would go about doing this?


text:
Q: how to get div's background color translucent on hover by CSS? What effect should I use to get that light white layer on the top?Please see the picture attached.
I have used opacity but did not help !
http://i.stack.imgur.com/AxzVX.jpg
They are codes I have tryed but did not work !
.email-title{
             opacity: .50; /* Standard: FF gt 1.5, Opera, Safari, CSS3 */
            filter: alpha(opacity=50); /* IE lt 8 */
            -ms-filter: "alpha(opacity=50)"; /* IE 8 */
            -khtml-opacity: .50; /* Safari 1.x */
            -moz-opacity: .50; /* FF lt 1.5, Netscape */
            cursor: pointer;
    }


text:
Q: Where should the adverb "soon" be positioned? It says that the position of adverbs should come before the verb and the example they give is:

We will soon have a break.

In this example, is it not acceptable to have the adverb after the verb:

We will have a break soon.

Or to be technically correct, should it be future continuous:

We will be having a break soon.

A: *

*Soon, we will have a break.

Good.

*

*We soon will have a break.

Grammatically acceptable, but not commonly said/written.

*

*We will soon have a break.

Good.

*

*We will have soon a break.

Invalid word order. Sounds foreign.

*

*We will have a soon break.

Invalid word order.

*

*We will have a  break soon.

Good.
================
(There is no discernible difference in meaning among any of the "Good" constructions above.)

A: In his textbook TSPE, James McCawley gives an interesting taxonomy of adverbs which distinguishes them by what they modify.  Clausal adverbs can modify any of S, V' (i.e., VP), or V, and this difference in what they modify is one factor in determining their placement and interpretation.  Time adverbs like "soon", according to McCawley, are fundamentally V' modifiers, but they can be "Raised" to be S modifiers.
In general, McCawley says, we expect modifiers to occur either immediately before the constituent they modify or immediately after.  Then for a time adverb like "soon", we expect it will go immediately before the V' that it modifies, immediately after that V', or if it is raised to become an S modifier, it will come immediately before or immediately after the S that it modifies.
Since each auxiliary verb in English, according to McCawley, heads its own V', this leads us to expect at least 3 possible positions for "soon" in a simple clause with no auxiliaries.  "Soon he leaves" / ??"He soon leaves" / "He leaves soon".  When there are auxiliaries, such an adverb ought to also occur after any auxiliary verb.
Overall, McCawley's theory works only moderately well.  There are many problems.
Now, for something completely different, I'll outline my own theory of adverb placement in English.
Adverbs, as well as other clause constituents, have characteristic embeddedness, and since English is a right branching language, less embedded constituents come before more embedded constituents.  When two constituents have equal embeddedness, they can occur in either order.
The differing degrees of embeddedness are 0, 1, 2, 3, unspecified.  Except for 0, these correspond to the 1, 2, 3, chomeur of Relational Grammar.  The 0 degree of embeddedness is for vocative nominals, root clauses, and performative adverbs like "frankly".  "Soon" is a 2, so it should follow any 1 (subject).  I would need an arbitrary adjustment comparable to McCawley's "Raising" to account for sentence initial "soon".


text:
Q: How to solve Content not from webpack is served from I add react-app-rewired and customize-cra to my project.
when I use "npm start" run my project,and I get an error like Content not from webpack is served from
enter image description here
here's my package.json file
{
  "name": "geek-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "antd-mobile": "^2.3.4",
    "axios": "^0.21.1",
    "classnames": "^2.3.1",
    "dayjs": "^1.10.6",
    "dompurify": "^2.3.0",
    "formik": "^2.2.9",
    "highlight.js": "^11.1.0",
    "history": "4.10.1",
    "lodash": "^4.17.21",
    "postcss": "^7.0.39",
    "prop-types": "^15.7.2",
    "react": "^17.0.2",
    "react-content-loader": "^6.0.3",
    "react-dom": "^17.0.2",
    "react-redux": "^7.2.4",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "react-window": "^1.8.6",
    "react-window-infinite-loader": "^1.0.7",
    "redux": "^4.1.0",
    "redux-devtools-extension": "^2.13.9",
    "redux-thunk": "^2.3.0",
    "sass": "^1.35.2",
    "socket.io-client": "^4.1.3",
    "web-vitals": "^1.0.1",
    "yup": "^0.32.9"
  },
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "babel-plugin-import": "^1.13.3",
    "customize-cra": "^1.0.0",
    "postcss-px-to-viewport": "^1.1.1",
    "react-app-rewired": "^2.1.8"
  }
}

and here's my config-overrides.js file
const {
  override,
  addPostcssPlugins,
  addWebpackAlias,
  addBabelPlugins
} = require('customize-cra')
const pxToViewport = require('postcss-px-to-viewport')
const path = require('path')

const alias = addWebpackAlias({
  '@': path.resolve(__dirname, 'src'),

  '@scss': path.resolve(__dirname, 'src', 'assets', 'styles')
})

const viewport = pxToViewport({

  viewportWidth: 375

})

module.exports = override(
  addPostcssPlugins([viewport]),
  alias,
  ...addBabelPlugins(['import', { libraryName: 'antd-mobile', style: 'css' }])
)

I try to add a webpack.confing.js file in my project,but it seem like no effects.
const path = require('path')

module.exports = {
  //...
  devServer: {
    static: {
      directory: path.join(__dirname, '/')
    },
    compress: true,
    port: 9000
  }
}

A: The problem has been solved, I switched my node.js version to a lower level.


text:
Q: Firebase: Como excluir un atributo para que no se guarde en la BD Tengo la siguiente clase que uso para crear objetos que luego guardo en una BD Firebase Real Time:
import com.google.firebase.database.Exclude;

public class Empresa {

  @Exclude
  private String key;
  private String Codigo;
  private String Nombre;

Lo que necesito es que únicamente se guarden en la BD los campos codigo y nombre.
He encontrado páginas donde se indica que con @Exclude se excluye un atributo de la clase para que no se guarde en la BD, pero en mi caso no funciona y guardar los tres atributos.
¿Como se puede hacer?
Muchas gracias por la ayuda.

A: Cuando tenemos una clase POJO de la cual no queremos que se persistan en la BD alguno de sus atributos miembros debemos anteponer, tanto al atributo como a sus métodos getter y setter, la anotación @Exclude
Como ejemplo a continuación pueden ver tres atributos de la clase Empresa de los cuales únicamente dos atributos se guardaran en la BD:
  public class Empresa {

  @Exclude
  private String key;
  private String Codigo;
  private String Nombre;

  public Empresa(String codigo, String nombre) {
    Codigo = codigo;
    Nombre = nombre;
  }

  public Empresa(String key, String codigo, String nombre) {
    this.key = key;
    Codigo = codigo;
    Nombre = nombre;
  }

  public Empresa() {
  }

  @Exclude
  public String getKey() {
    return key;
  }

  @Exclude
  public void setKey(String key) {
    this.key = key;
  }

  public String getCodigo() {
    return Codigo;
  }

  public void setCodigo(String codigo) {
    Codigo = codigo;
  }

  public String getNombre() {
    return Nombre;
  }

  public void setNombre(String nombre) {
    Nombre = nombre;
  }

  @Exclude
  @Override
  public String toString() {
    return Nombre;
  }
}


text:
Q: Realizar um cálculo de valores anteriores em coluna no R Gostaria de montar uma coluna de acordo com o resultado de 2 linhas de uma outra coluna, segue a fórmula abaixo, não faço ideia de como montar isso no R ou no Python e gostaria de uma colaboração de vocês.
Dando um exemplo no Excel
                coluna 1   coluna 2
      célula D2 - 558,8       1
      célula D3 - 584,3       1
      célula D4 - 603,3   =SE(D4-D2>=D2*0,02;1;SE(D4-D2<=-D2*0,02;-1;0))

E assim sucessivamente...

A: Aqui está uma solução em R base, vetorizada com sign.
n <- nrow(dados)
inx <- seq_len(n)[-(1:2)]
dados$col2 <- 1
dados$col2[inx] <- sign(dados$col1[inx] - 1.02*dados$col1[inx - 2])

Dados de teste
col1 <- c(558.8, 584.3, 603.3)
dados <- data.frame(col1)

A: Talvez isso te ajude, utilizando dplyr
Data frame de teste
dados <- data.frame(coluna_1 = c(558.8, 584.3, 603.3))

A lógica
library(dplyr)

dados <- dados %>% mutate(coluna_2 = case_when(
  coluna_1 - lag(coluna_1, n = 2) >=  lag(coluna_1, n = 2) * 0.02 ~ 1,
  coluna_1 - lag(coluna_1, n = 2) <=  (-lag(coluna_1, n = 2)) * 0.02 ~ -1,
  T ~ 0
))
dados$coluna_2[1:2] <- 1

Com mutate criamos uma coluna nova chamada coluna_2, o case_when serve para fazer algo quando uma condição é aceita, o lag serve para dar um atraso, neste caso damos um lag de 2 que seriam duas linhas acima. O T ~ 0 é quando nenhuma condição foi encontrada então preenchemos com 0.

Obs: Como o calculo é feito voltando duas linhas os primeiros resultados vão ser zero, pois não tem como calcular.

Uma possibilidade em Python utilizando o pandas
import pandas as pd

dados = pd.DataFrame({'coluna_1': [558.8, 584.3, 603.3]})

dados.loc[dados['coluna_1'] - dados['coluna_1'].shift(2) >= dados['coluna_1'].shift(2) * 0.02, 'coluna_2'] = 1
dados.loc[dados['coluna_1'] - dados['coluna_1'].shift(2) <= -dados['coluna_1'].shift(2) * 0.02, 'coluna_2'] = -1
dados['coluna_2'].iloc[0:2] = 1
dados.fillna(0)


text:
Q: certain character in url cause error 500 After doing security scan on the website, these two characters <a can cause 500
http://domain.com/default.aspx?<a
The error is handled in Application_Error to redirect to the error.aspx page.
Application_Error()
{
 Response.Redirect("/error.aspx?asperrorpath=" + Context.Request.RawUrl);
}

But the RawUrl does not appear as just value for the param asperrorpath, the Redirect will cause another 500, and infinite redirect loop happens.
The only solution that I got to avoid redirect loop is to encode the RawUrl, but we want to see the real URL that the user requested, encoding may cause some lost of information. Have any other solution ?
Thanks

A: Not sure whether this will serve your purpose.  Maybe you can replace them
Application_Error()
{
   Response.Redirect("/error.aspx?asperrorpath=" + String.Replace(Context.Request.RawUrl,"<a","^^$$^^");
}

So if you see that pattern you can assume it is "< a"...  choose your combination so that it does not occur otherwise.

A: HttpUtility.UrlEncode(Context.Request.RawUrl);


text:
Q: catch exception thrown from deepest level call in upper method Catch the exception on upper class is what I wonder. I have more than one method call layer. In the deepest level, exception is thrown. In the top level how can I catch?
void foo() {
   bar(); <---- catch exception in here
}

void bar() {
   // .... <--- throws IOException or ExecutionException or InterruptedException
}

OR case two

void foo() {
   bar(); <---- catch exception in here
}

void bar() {
   gbr();
}

void gbr() {
      // .... <--- throws IOException or ExecutionException or InterruptedException
}

A: Exception handling
As described in the Java documentation, an Exception is caught by the first exception handler (try/catch block) in the call stack that can handle the thrown exception type.

Case 1
If you don't define an exception handler (a try/catch block) in bar you need to specify that the method throws some exceptions, which can be handled by foo (at the previous step of the call stack).
void foo() {
    try {
        bar();
    } catch (IOException io) {
        // Do something
    } catch (ExecutionException ee) {
        // Do something
    } catch (InterruptedException ie) {
        // Do something
    }
}

void bar() throws IOException, ExecutionException, InterruptedException {
    // .... <--- throws IOException or ExecutionException or InterruptedException
}

Case 2
If you don't define an exception handler either in gbr or in bar, you have to specify that both methods throw exceptions, which can be handled in foo.
void foo() {
    try {
        bar();
    } catch (IOException io) {
        // Do something
    } catch (ExecutionException ee) {
        // Do something
    } catch (InterruptedException ie) {
        // Do something
    }
}

void bar() throws IOException, ExecutionException, InterruptedException {
    gbr();
}

void gbr() throws IOException, ExecutionException, InterruptedException {
    // .... <--- throws IOException or ExecutionException or InterruptedException
}

General case
If you don't want to distinguish which exception was thrown you can use the class Exception which is an ancestor of all exceptions (docs), thus matches all of them:
void foo() {
    try {
        bar();
    } catch (Exception e) {
        // Do something
    }
}

void bar() throws Exception {
    // .... <--- throws IOException or ExecutionException or InterruptedException
}

A: A thrown exception will be caught by the first relevant try/catch block. If such a block doesn't exist, then the program will crash due to an unhandled exception.
Therefore, if gbr() throws an exception which isn't caught, it'll return to bar. If bar() doesn't catch it, then it'll return to foo(), etc until it'll return to main().


text:
Q: Cut and transpose in LibreOffice When using cut and pasting LibreOffice maintains exact formula used along with moving old references to point to the new location, however when using paste special: transpose it treats the past as if copy was used (recalculating references relative to new positions and breaking references to the moved cells)
Is there some way to prevent this change of behaviour when transposing or is there another way to transpose these cells whilst maintaining their exact references (as is) and the references to these cells.
Shift+F4 simply toggles the "absoluteness" of every reference within the cells, as some references within the range are absolute it cannot be used to make every reference within them exact.
Aside from manually moving each and every cell is there a method to do this? Even partial solutions appreciated.

A: You can use normal transpose method (see also ) or you can use transpose function in Calc. So you must select any cell that must transposed matrix be replaced there, then click on formulas section and choose transpose from list. after choosing main matrix, transposed matrix would be appeared.


text:
Q: localStorge ternary expression not working (React) I'm trying to do this.
const isUserConnected = localStorage.getItem('token')

{isUserConnected.length ? null :

     Register...

}

The ternary isn't acting in accordance to the localStorage content.
What is wrong?

A: isUserConnected is probably undefined.
In which case your code should look more like
const token = localStorage.getItem('token')
const isUserConnected = token && token.length

{isUserConnected &&

    Register...

}


text:
Q: Redux state variable is showing up as undefined I am making an application using React and redux. I am working to achieve the funcionaity where the "main-page" checks for auth, and if auth is "false" , it redirects to the "auth-page". This is how I am trying to achieve the said functionality.
index.js
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore } from "redux";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

import "./css/index.css";
import AppScreen from "./screens/appscreen";
import NotFoundScreen from "./screens/notfoundscreen";
import AuthScreen from "./screens/authscreen";

import isLoggedInReducer from "./redux/reducers/isLoggedInReducer";

ReactDOM.render(
    <Provider store={createStore(isLoggedInReducer,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() )}>
      <Router>
        <Switch>
          <Route path="/" exact>
            <AppScreen />
          </Route>
          <Route path="/auth">
            <AuthScreen />
          </Route>
          <Route path="*">
            <NotFoundScreen />
          </Route>
        </Switch>
      </Router>
    </Provider>,
  document.getElementById("root")
);

isLoggedIn reducer
const isLoggedInReducer = (isLoggedIn = true , action) => {
    switch(action.type){
        case 'LOG_IN':
            return true
        case 'LOG_OUT':
            return false
        default:
            return false
    }
}

export default isLoggedInReducer

main-app
import React from "react";
import { useSelector } from "react-redux";
import { Redirect } from "react-router";

import BottomBar from "../components/bottombar";
import Content from "../components/content";
import NavBar from "../components/navbar";

import "../css/screens/appscreen.css";

const AppScreen = () => {
  let isLoggedIn = useSelector((state) => {
    console.log(state)
    return state
  });
  // the value isLoggedIn is undefined here
  return isLoggedIn ? (
    <>
      <div className="appscreen">
        <NavBar />
        <Content />
        <BottomBar />
      </div>
    </>
  ) : (
    <>
      <Redirect to="/auth" push />
    </>
  );
};

export default AppScreen;

I tried to read the value from the store using the useSelector hook.But the variable is undefined. It does not show up in the redux dev tools, it doesnt exist nowhere. I am currently only trying to read the value from the variable
I would like to add I currently am not trying to change the value of the variable right now.
This is my first time with redux, and its already a bit confusing to wrap head around so much boilerplate code. I do thank you for your time !

A: First of all, the problem is in isLoggedInReducer function, you should understand Reducers, Reducers are functions that take the current state and an action as arguments, and return a new state result. In other words, (state, action) => newState. so you should defined an initialState and passe it to isLoggedInReducer function like that :
The state parameter that gets passed to the reducer function has to be the current state of the application. In this case, we're calling that our initialState because it will be the first (and current) state and nothing will precede it.
const initialState = { isLoggedIn : true };
const isLoggedInReducer = (state = initialState , action) => {
switch(action.type){
    case 'LOG_IN':
        return {...state ,  isLoggedIn : true };
    case 'LOG_OUT':
        return { ...state , isLoggedIn : false };
    default:
        return state;
  }
}

export default isLoggedInReducer;

you can check this Link for more infos about Reducer : https://redux.js.org/tutorials/fundamentals/part-3-state-actions-reducers#writing-reducers


text:
Q: Permutation test on dependent data Say that I have a sample of observations which are pairs of real numbers $(x_i, y_i)$. Pairs are i.i.d., but $x_i$ and $y_i$ are not independent. I want to test whether the mean of $x$ is equal to the mean of $y$ using a permutation test. I know that the correct way to do it is with a paired permutation test. But what happens if I insist on using a regular permutation test? Does the p-value become incorrect? Or does it affect only the power of the test?
What if the pairs are also not independent, e.g. from a time series? In that case even a paired permutation test would fail to reproduce the correlations in the sample. However the mean is permutation invariant, so I'm not sure that it would matter. Would the p-value be incorrect in this case?

A: Glen_b's comment was illuminating, so let me try to answer.
The null hypothesis for the paired permutation test is that $x_i$ and $y_i$ can be freely exchanged. That is, if $p(x, y)$ is the joint probability (density) of $x_i$ and $y_i$, then the null hypothesis is that $p$ is symmetric: $p(x, y) = p(y, x)$.
This condition implies that the mean of $x$ is equal to the mean of $y$, but the converse is not necessarily true. So the null hypothesis of the paired permutation test is more specific than the one I initially envisioned.
Now to answer what happens when the regular permutation test is used to test this hypothesis, instead of the paired permutation test.
Replicates generated by the paired permutation tests are composed of pairs $(x_i, y_i)$ or $(y_i, x_i)$. A regular permutation test will instead shuffle $(x_1, y_1, x_2, y_2, ...)$ and form new pairs, so the typical replicate pair will be $(x_i, y_j)$ or $(y_j, x_j)$ with $i\ne j$. Therefore, if $x$ and $y$ are positively correlated, the typical pair under the paired permutation test will have a smaller difference $|x - y|$ than the typical pair under the regular permutation test. Consequently the regular permutation test will have a lower probability of rejecting the null hypothesis than the paired permutation test, i.e. it will yield an incorrect p-value.


text:
Q: Parser error with non-type in recursion So a few days ago, SOCommunity helped me with a parser. ie this:
def MyList(self):
    class _MyList(list):
        def __init__(self, parent):
            self.parent = parent
            list.__init__(self)
    top = current = _MyList(None)
    ntab_old = 0
    for line in self.raw_data:
        ntab = line.count('\t')
        if(ntab_old > ntab):
            for _ in range(ntab_old-ntab):
                current = current.parent
        elif(ntab_old<ntab):
            current.append(_MyList(current))
            current = current[-1]
        current.append(line.strip('\t').strip('|'))
        ntab_old =ntab
    return top

Parsing through data like this:
 |[nothing detected] www.neopets.com/
        |status: (referer=http://www.google.com)saved 55189 bytes /fetch_d4cd213a56276ca726ddd437a1e75f1024ab7799
        |file: fetch_d4cd213a56276ca726ddd437a1e75f1024ab7799: 55189 bytes
        |file: decoding_367af53b4963986ecdeb9c09ce1a405b5b1ecd91: 68 bytes
        |[nothing detected] (script) images.neopets.com/js/common.js?v=6
            |status: (referer=http://www.google.com)saved 1523 bytes /fetch_8eeadcc08d4cb48c02dedf18648510b75190d1d7failure: [Errno 13] Permission denied: '/tmp/tmpsha1_8d7fb3ff1ef087c7ea2bf044dee294735a76ed4b.js'
            |file: fetch_8eeadcc08d4cb48c02dedf18648510b75190d1d7: 1523 bytes

This is supposed to return nested lists containing each sub section. However, out of nowhere, I'm getting these errors:
      current.append(line.strip('\t').strip('|'))
AttributeError: 'NoneType' object has no attribute 'append'

Any help would be appreciated

A: current.append(...)
AttributeError: 'NoneType' object has no attribute 'append'

is saying that at some point current is None.
So how is current being set to None? My guess is it probably happens here:
        for _ in range(ntab_old-ntab):
            current = current.parent

If current is set to its parent often enough, it will eventually get set to None since at the top level, _MyList is instantiated with None as the parent:
top = current = _MyList(None)

This code might also be problematic:
    elif(ntab_old<ntab):
        current.append(_MyList(current))
        current = current[-1]

If ntab is say 3, and ntab_old is 1, then might need to move in two levels of "indention", but the code only creates one nested _MyList.
You might think that your levels of indention never jump by two. But that might be hard to tell with your eyes especially if the data is long. The data may not be as regular as we think.
Also, if there is a stray '\t' on the right-hand side of the |, then it would affect the ntab count even though it probably should not affect the indention level.


text:
Q: jquery-select2 - add select2 to existing dropdown code to make searchable I have two dropdown select boxes that result in details of two careers being displayed in side-by-side columns of a table. The code has been edited down taking many of the actual options out for ease of use and modification. It works fine currently except there will be over 300 values to choose from which is a lot of scrolling. Therefore, I'd like to make the dorpdowns searchable. The two best options I've come across are Select2 and Chosen.
I can't seem to get Select2 or Chosen to work (i.e. does not make the dropdowns searchable). I've tried both and must be doing something wrong. I can get them to work if I start a jsfiddle from scratch but I can't seem to add it to my current code. I guess I'm just not sure how to integrate it into my current code. I've stripped out my attempts to show the code I'm starting with. Any help on where/how I should add Select2 to my two existing drop downs would be appreciated.
here is my jsfiddle
<link rel="stylesheet" href="style.css">

    Search over 300 careers below:

Career One:

    <select name="" id="my-select"></select>

    Career Two:

    <select name="" id="my-select-2"></select>

And the JS half...
    var myCareerInfo = {
  careers: [
  {
    name: 'Choose A Career',
    id: 100,
    careerInfo: {
      description: '',
      requiredEd: '',
      salary: '',
      curentJobs: '',
      jobGrowth: '',
      jobChange: '',
      category: '',
    }
  },
{
    name: 'Aerospace Engineering and Operations Technicians',
    id: 101,
    careerInfo: {
      description: 'Aerospace engineering and operations technicians operate and maintain equipment used in developing, testing, and producing new aircraft and spacecraft. Increasingly, these workers are using computer-based modeling and simulation tools and processes in their work.',
      requiredEd: 'Associate\'s degree',
      salary: '$66,180',
      curentJobs: '11,400',
      jobGrowth: '4% (Slower than average)',
      jobChange: '400',
      category: 'Architecture and Engineering',
    }
  },
{
    name: 'Agricultural Engineers',
    id: 103,
    careerInfo: {
      description: 'Agricultural engineers attempt to solve agricultural problems concerning power supplies, the efficiency of machinery, the use of structures and facilities, pollution and environmental issues, and the storage and processing of agricultural products.',
      requiredEd: 'Bachelor\'s degree',
      salary: '$75,090',
      curentJobs: '2,900',
      jobGrowth: '4% (Slower than average)',
      jobChange: '100',
      category: 'Architecture and Engineering',
    }
  },
{
    name: 'Architects',
    id: 104,
    careerInfo: {
      description: 'Architects plan and design houses, factories, office buildings, and other structures.',
      requiredEd: 'Bachelor\'s degree',
      salary: '$76,100',
      curentJobs: '112,600',
      jobGrowth: '7% (As fast as average)',
      jobChange: '7,800',
      category: 'Architecture and Engineering',
    }
  }
  ]
}

function populateSelectBoxes($select, data) {
  var careers = [];
  $.each(data, function() {
    careers.push('<option value="'+this.id+'">' + this.name + '</option>');
  });
  $select.append(careers.join(''));
  return $select; // Return populated select box.
}

function populateTableRow($tableBody, data, selectBoxes) {
  var career = [];

  selectBoxes.map(function(s){
        var currentId = s.val();
      return data.map(function(item){
            if(item.id == currentId) career.push(item);
      })
  });
  /* Comment out if you need to permit empty or unvalid selections
  while(career.length < 2)career.push({
    name: "",
    careerInfo: {
      salary: "",
      education: "",
      skills: "",
      description: "",
    }
  })
  //*/

  $tableBody.html('
'+
                                    '	'+
                     '' + career[0].name + '	'+
                     '' + career[1].name + '	'+
                     '
'+
                     '
' +
                     'Salary	'+
                     '' + career[0].careerInfo.salary +'	'+
                     '' + career[1].careerInfo.salary +'	'+
                     '
'+
                     '
' +
                     'Entry Level Education	'+
                     '' + career[0].careerInfo.requiredEd + '	'+
                     '' + career[1].careerInfo.requiredEd + '	'+
                     '
'+
                     '
' +
                     'Career Description	'+
                     '' + career[0].careerInfo.description + '	'+
                     '' + career[1].careerInfo.description + '	'+
                     '
'+
                     '
' +
                     'Number Of Current Jobs	'+
                     '' + career[0].careerInfo.curentJobs + '	'+
                     '' + career[1].careerInfo.curentJobs + '	'+
                     '
'+
                     '
' +
                     'Job Growth	'+
                     '' + career[0].careerInfo.jobGrowth + '	'+
                     '' + career[1].careerInfo.jobGrowth + '	'+
                     '
'+
                     '
' +
                     'Job Change	'+
                     '' + career[0].careerInfo.jobChange + '	'+
                     '' + career[1].careerInfo.jobChange + '	'+
                     '
'+
                     'Category	'+
                     '' + career[0].careerInfo.category + '	'+
                     '' + career[1].careerInfo.category + '	'+
                     '
'
                     );

}

var selectBoxes = [
  populateSelectBoxes($('#my-select'), myCareerInfo.careers),
  populateSelectBoxes($('#my-select-2'), myCareerInfo.careers),
]

$('#my-select').change(function() {
  populateTableRow($('#my-table tbody'), myCareerInfo.careers, selectBoxes);
});

$('#my-select-2').change(function() {
  populateTableRow($('#my-table tbody'), myCareerInfo.careers, selectBoxes);
});

A: Try this:

var myCareerInfo = {
    careers: [
        {
            text: 'Choose A Career',
            id: 100,
            careerInfo: {
                description: '',
                requiredEd: '',
                salary: '',
                curentJobs: '',
                jobGrowth: '',
                jobChange: '',
                category: '',
            }
        },
        {
            text: 'Aerospace Engineering and Operations Technicians',
            id: 101,
            careerInfo: {
                description: 'Aerospace engineering and operations technicians operate and maintain equipment used in developing, testing, and producing new aircraft and spacecraft. Increasingly, these workers are using computer-based modeling and simulation tools and processes in their work.',
                requiredEd: 'Associate\'s degree',
                salary: '$66,180',
                curentJobs: '11,400',
                jobGrowth: '4% (Slower than average)',
                jobChange: '400',
                category: 'Architecture and Engineering',
            }
        },
        {
            text: 'Agricultural Engineers',
            id: 103,
            careerInfo: {
                description: 'Agricultural engineers attempt to solve agricultural problems concerning power supplies, the efficiency of machinery, the use of structures and facilities, pollution and environmental issues, and the storage and processing of agricultural products.',
                requiredEd: 'Bachelor\'s degree',
                salary: '$75,090',
                curentJobs: '2,900',
                jobGrowth: '4% (Slower than average)',
                jobChange: '100',
                category: 'Architecture and Engineering',
            }
        },
        {
            text: 'Architects',
            id: 104,
            careerInfo: {
                description: 'Architects plan and design houses, factories, office buildings, and other structures.',
                requiredEd: 'Bachelor\'s degree',
                salary: '$76,100',
                curentJobs: '112,600',
                jobGrowth: '7% (As fast as average)',
                jobChange: '7,800',
                category: 'Architecture and Engineering',
            }
        }
    ]
}

$('#my-select').select2({
  data: myCareerInfo.careers
});

$('#my-select-2').select2({
  data: myCareerInfo.careers
});

var career = [{ id: 0, text: 'Physical Therapist' }, { id: 1, text: 'Another Career' }, { id: 2, text: 'Security Guard' }];
$('select#career').select2({
  data: career
});

function populateTableRow($tableBody, data, selectBoxes) {
  var career = [];

  selectBoxes.map(function(s){
        var currentId = s.val();
      return data.map(function(item){
            if(item.id == currentId) career.push(item);
      })
  });
  /* Comment out if you need to permit empty or unvalid selections
  while(career.length < 2)career.push({
    name: "",
    careerInfo: {
      salary: "",
      education: "",
      skills: "",
      description: "",
    }
  })
  //*/

  $tableBody.html('
'+
                                    '	'+
                     '' + career[0].name + '	'+
                     '' + career[1].name + '	'+
                     '
'+
                     '
' +
                     'Salary	'+
                     '' + career[0].careerInfo.salary +'	'+
                     '' + career[1].careerInfo.salary +'	'+
                     '
'+
                     '
' +
                     'Entry Level Education	'+
                     '' + career[0].careerInfo.requiredEd + '	'+
                     '' + career[1].careerInfo.requiredEd + '	'+
                     '
'+
                     '
' +
                     'Career Description	'+
                     '' + career[0].careerInfo.description + '	'+
                     '' + career[1].careerInfo.description + '	'+
                     '
'+
                     '
' +
                     'Number Of Current Jobs	'+
                     '' + career[0].careerInfo.curentJobs + '	'+
                     '' + career[1].careerInfo.curentJobs + '	'+
                     '
'+
                     '
' +
                     'Job Growth	'+
                     '' + career[0].careerInfo.jobGrowth + '	'+
                     '' + career[1].careerInfo.jobGrowth + '	'+
                     '
'+
                     '
' +
                     'Job Change	'+
                     '' + career[0].careerInfo.jobChange + '	'+
                     '' + career[1].careerInfo.jobChange + '	'+
                     '
'+
                     'Category	'+
                     '' + career[0].careerInfo.category + '	'+
                     '' + career[1].careerInfo.category + '	'+
                     '
'
                     );
}

var selectBoxes = [
  $('#my-select'),
  $('#my-select-2'),
];

$('#my-select').change(function() {
  populateTableRow($('#my-table tbody'), myCareerInfo.careers, selectBoxes);
});

$('#my-select-2').change(function() {
  populateTableRow($('#my-table tbody'), myCareerInfo.careers, selectBoxes);
});

    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />

        Search over 300 careers below:

Career One:

        <select name="" id="my-select"></select>

        Career Two:

        <select name="" id="my-select-2"></select>


text:
Q: Using "dynamic" layout pages in MVC3 I've got a question about layout pages in MVC3:
Is it possible to use a server-generated (e.g. loaded from a database) layout pages like:
@{
    Layout = "~/Views/Shared/Handler.ashx?layout=xyz";
}

Will code inside the layout like @RenderBody() work?
If anyone of you already tried something like this, I would be happy to hear about your experiences.

A: You could create a custom view engine and serve those views from wherever you want (including a database).


text:
Q: Cross field validation based on value If we are build a custom JSR 303 validator, is there any way, we can pass field's value to the validator instead of the field's name?
Here is what I am doing..
I need to build a custom class level validation which validates this case..
There are two fields A & B where B is a date field. If A's value is 1, verify that B is not null and its value is future date.
Now I was able to build a validation with these requirements following this post. In the FutureDateValidator's isValid() method, I have checked whether A's value is 1 or not and then I checked the date validity.
@CustomFutureDate(first = "dateOption", second = "date", message = "This must be a future date.")
Now I have new set of fields C and D, where D is again the date field. This time I need to verify that D is a future date if C's value is 2. In this case I cannot use the validator I already implemented because it has the first field's value hard-coded. So how do I solve this issue to reuse the same validator for these two cases.

A: To not hardcode values 1/2 made it customizable:
@CustomFutureDate(first = "dateOption", firstValue = "1", second = "date", message = "This must be a future date.")

To make it work you need to modify @CustomFutureDate annotation:
public @interface CustomFutureDate {
    String first();
    String firstValue();
    ...
}

and implementation:
public class CustomFutureDateValidator implements ConstraintValidator<CustomFutureDate, Object> {
    private String firstFieldName;
    private String firstFieldValue;
    ...

    @Override
    public void initialize(final CustomFutureDate constraintAnnotation) {
        firstFieldName = constraintAnnotation.first();
        firstFieldValue = constraintAnnotation.firstValue();
        ...
    }

    @Override
    public boolean isValid(final Object value, final ConstraintValidatorContext context) {
        // use firstFieldValue member
        ...
    }
}


text:
Q: Run Crawler using custom resource Lambda I am trying to create and invoke an AWS Glue crawler using cloud formation. The creation part of the crawler(dynamo DB as target) is in lambda function.
how can I achieve all this using cloud formation? i.e creation of lambda function from cod present in s3 , After lambda function is created, it should get triggered to create crawler and then crawler should be invoked to create targted tables. I want all of this is cloud formation.
link for reference: Is it possible to trigger a lambda on creation from CloudFormation template

A: You should write cloudformation to deploy crawler. And then in your ci/cd, write shell/python script to run crawler after it is deployed through cloudformation.


text:
Q: Replacing a delimiter symbol in a field I have a csv in where fields are delimited by |.
|time: 10:19 | Error: File not found| Condition: None | path: some

|time: 10:20 | Error: File not found| Condition: a|b | path: some

The delimiter | will sometimes appear in the 4th field (the Condition field). I want to replace this | with OR like:
Condition: a|b Will become:  Condition: a OR b
How can I use sed or awk for this?

A: awk -F'|' -v OFS='|' 'NF == 6 {$4 = $4 " OR " $5; $5=$6; NF--} 1' file

This just works with the number of pipe-separated fields. You expect there to be 5 but if there is one extra, join with the desired string.
Or, GNU sed:
sed 's/|/|/5; ta; n; :a; s/|/ OR /4' file

If there are 5 pipes, change the 4th one. Does not work with the default sed on MacOS --
 if the semicolons are replaced by newlines, MacOS sed is OK with these commands (it seems the label name must be followed by a newline with the BSD-derived sed).

What if there are more than 1 extra pipe? Consider this file:
|time: 10:19 | Error: File not found| Condition: None | path: some
|time: 10:20 | Error: File not found| Condition: a|b | path: someh
|time: 12:34 | NO ERROR | Condition: a|b AND c|d AND e|f | path: nil

Extending the sed solution is straightforward: add a "jump-if"
sed ':b; s/|/|/5; ta; n; :a; s/|/ OR /4; tb' file

The awk gets a bit wordier:
awk -F'|' -v O FS='|' '{
    while (NF > 5) {
        $4 = $4 " OR " $5
        for (i = 5; i < NF; i++)
            $i = $(i+1)
        NF--
    }
    print
}' file

A: Give a test to this:
sed 's/Condition:[ ]*\([a-zA-Z]*\)|\([a-zA-Z]*\)/Condition: \1 OR \2/g' your_file

Assuming a and b are alphabetic.

A: Python3 Script. Breaks the csv file into a list defined by delimiter '|' and then join the fields if there's an extra one and it starts with the word "Condition:"
import csv

for line in list(csv.reader(open('filename', 'r'), delimiter='|')):
    if len(line) > 5 and line[3].lstrip().startswith('Condition:'):
        print('|'.join(line[:3] + [line[3] + ' OR ' + line[4]]+line[5:]))
    else:
        print('|'.join(line))

A: With GNU sed you can do it as shown:
 $ sed -e '
   s/|/\n/4g
   s/\(.*\)\n/\1|/
   s/\n/ OR /g
 ' inp

 $ perl -lpe '1 while s/Condition:.*\K\|(?! path:)/ OR /' inp

 $ perl -lpe '
   /Condition:.*?(?=\|)/g;
   s/\G.(.*?)(?=\|)/ OR $1/g;
 ' inp

$ perl -F'[|]' -pale '
     $_ = join "|", @F[0..2], join(" OR ", @F[3..$#F-1]), $F[-1] if @F > 5;
 ' inp

 $ perl -lpe '
     my($dlim, $pos_f3, $pos_f4, $knt) = qw/|/;
     $pos_f3 = 1+index($_,$dlim,$pos_f3) while ++$knt < 4;
     $pos_f4 = rindex($_,$dlim);
     s/\Q$dlim\E/ OR /g for substr $_, $pos_f3, $pos_f4-$pos_f3;
 ' inp

A: The general approach to modifying a target field that can contain separators is:
/(match the fields before the target)(.*)(match the fields after the target)/ {
   modify the target which is the middle section, the string matching the ".*"
}

e.g. with GNU awk for the 3rd arg to match():
$ awk '
    match($0,/(([^|]*[|]){3})(.*)([|][^|]*)/,a) {
        gsub(/[|]/," OR ",a[3])
        $0 = a[1] a[3] a[4]
    }
1' file
|time: 10:19 | Error: File not found| Condition: None | path: some
|time: 10:20 | Error: File not found| Condition: a OR b | path: some

and given the more interesting input shown in Glenn's answer:
$ cat file
|time: 10:19 | Error: File not found| Condition: None | path: some
|time: 10:20 | Error: File not found| Condition: a|b | path: someh
|time: 12:34 | NO ERROR | Condition: a|b AND c|d AND e|f | path: nil

$ awk '
    match($0,/(([^|]*[|]){3})(.*)([|][^|]*)/,a) {
        gsub(/[|]/," OR ",a[3])
        $0 = a[1] a[3] a[4]
    }
1' file
|time: 10:19 | Error: File not found| Condition: None | path: some
|time: 10:20 | Error: File not found| Condition: a OR b | path: someh
|time: 12:34 | NO ERROR | Condition: a OR b AND c OR d AND e OR f | path: nil

With any awk it'd be:
$ awk '
    match($0,/(([^|]*[|]){3})/) {
        a[1] = substr($0,RSTART,RLENGTH)
        rest = substr($0,RSTART+RLENGTH)
        match(rest,/[|][^|]*$/)
        a[3] = substr(rest,1,RSTART-1)
        a[4] = substr(rest,RSTART,RLENGTH)
        gsub(/[|]/," OR ",a[3])
        $0 = a[1] a[3] a[4]
    }
1' file
|time: 10:19 | Error: File not found| Condition: None | path: some
|time: 10:20 | Error: File not found| Condition: a OR b | path: someh
|time: 12:34 | NO ERROR | Condition: a OR b AND c OR d AND e OR f | path: nil

A: From your code sample the defining rule appears to be that wherever | is not bounded on both sides by a space then you want if to become OR, so simply
sed -E 's/([^ ])\|([^ ])/\1 OR \2/g' test


text:
Q: MSTest no xml output on .NET Core RC2 I'm targeting dotnet-test-mstest": "1.0.1-preview on dotnet core rc2 in my test project.
Edit:
Okay. I'm targeting the the desktop .NET. But this should not make any difference.
project.json
{
    "version": "1.0.0-*",

    "testRunner": "mstest",

    "dependencies": {
        "Betgame": "1.0.0-*",
        "dotnet-test-mstest": "1.0.1-preview",
        "MSTest.TestAdapter": "1.0.0-preview",
        "MSTest.TestFramework": "1.0.0-preview",
        "NETStandard.Library": "1.5.0-rc2-24027"
    },

    "frameworks": {
        "net461": { }
    }
}

output when running dotnet test looks quite good!

How can i get the output as a xml file to process this in my build process? Any ideas? Or is it just not yet supported?
So far i tried dotnet test -xml test-results.xml but no output was generated.

A: Thank you for trying out the MSTest release.
Please use the following to generate a trx report (xml file):
vstest.console.exe project.json /UseVsixExtensions:true /logger:trx

The report gets generated in a TestResults folder.

A: Looking at the decompiled code of dotnet-test-mstest, I don't see any -xml option or anything similar. So I think it's not currently supported.


text:
Q: Facebook Android SDK 3.0 calls just show a white screen I have a lot of issues with the Facebook Android SDK 3.0 — a lot. Here's one which is particularly annoying: I have added the Facebook project to my workspace and linked it to my Android application. Now when I export my application (by right clicking on the project in Eclipse, selecting the Android Tools option and then clicking Export Signed Application Package), my signed application package exports okay. I notice however that around 50% of the time I export my APK, when I then make any Facebook SDK request using this APK (like opening a session or requesting additional permissions or anything of the like), I just get a white screen showing a progress bar which hangs indefinitely, as follows...

It hangs there until I press the device's Back button, at which point I get a SessionState.CLOSED_LOGIN_FAILED session callback. Basically, it builds badly on almost every other export. Is anyone else experiencing this or know how I can stop this from happening? It's very very time-consuming having to build two or three times until I get a good APK. I am refreshing the projects in my workspace and doing a Project -> Clean -> Clean all projects every time and even that doesn't do the trick.

A: What I've done the last few times I've had to export my signed application package is to go to my project's properties, open the Android option, remove the Facebook library reference and then re-add it. I've had five consecutive good exports doing this so I'm guessing this does the trick!


text:
Q: ACSL Logic Struct Declarations Not Working as in Reference Manual I would like to have a way to describe logic/spec level structs that include abstract lists. Example 2.2.7 on page 27 of the ACSL Reference Manual suggests that there is a
 way to do this and it is as follows:
//@ type point = struct { real x; real y; };
//@ type triangle = point[3];
//@ logic point origin = { .x = 0.0 , .y = 0.0 };
/*@ logic triangle t_iso = { [0] = origin,
@ [1] = { .y = 2.0 , .x = 0.0 }
@ [2] = { .x = 2.0 , .y = 0.0 }};
@*/
/*@ logic point centroid(triangle t) = {
@ .x = mean3(t[0].x,t[1].x,t[2].x);
@ .y = mean3(t[0].y,t[1].y,t[2].y);
@ };
@*/
//@ type polygon = point[];
/*@ logic perimeter(polygon p) =
@ \sum(0,\length(p)-1,\lambda integer i;d(p[i],p[(i+1) % \length(p)])) ;
@*/

If I copy/paste this exact code into a text editor and try to run this code with the wp plugin with:
frama-c -wp -wp-rte -wp-prover alt-ergo shapes.c
I get an error:
[kernel:annot-error] shapes.c:1: Warning: unexpected token '{'
If I give up on trying to write logic/spec level declarations of struct types, but would still like to write logic/spec level expressions that instantiate structs defined in C as follows:
struct somestruct {
     int x;
     int y;
 };

/*@
     logic struct somestruct foo = { .x = 3, .y = 4 };
*/

I still get an error:
[kernel:annot-error] aggregate_err.c:7: Warning:
  unsupported aggregated field construct. Ignoring global annotation

and not having a way to write particular values of structs as expressions in specifications leads to some fairly ugly specifications, so I am hoping that I am doing something wrong.
If I dig into the source of frama-C 20.0 to try to find the part of the parser-generator code for /*@ type declarations, it looks like the syntax in Ex 2.2.7 is not really implemented. It looks like the syntax for type level declarations is line 799 of
frama-c-20.0-Calcium/src/kernel_internals/parsing/logic_parser.mly
(called type_spec)
And the parse rule for type level declarations of structs is:
| STRUCT exit_rt_type identifier_or_typename { LTstruct $3 }

which looks like it would support
//@ type foo = struct c_struct;
but not something like what Ex 2.2.7 has as in:
//@ type point = struct { real x; real y; };
Is there something else I should be doing to have better support for structs in ACSL/Frama-C? Thanks!

A: Not all ACSL constructions are supported by the current Frama-C implementation. With each Frama-C release comes an ACSL implementation manual, which describes the constructions that are not yet implemented. For Frama-C 20.0 Calcium, this can be found here. In this document, unsupported constructions appear in red in the relevant BNF rule. Note however that other parts of the manual are left untouched. Notably, the fact that an example is included in the implementation manual does not imply that it is expected to be successfully parsed by the current Frama-C version. In your case, these are the rules of figure 2.17 on page 57, which show that indeed records are not implemented.
As you have already discovered by yourselves, it is indeed possible to define a C struct (possibly ghost) and an ACSL type out of it. Of course, since the struct lives in the C world, its fields must have C types (ACSL types in ghost declarations is unsupported as well).
Similarly, you can simulate the absence of direct record definition by an update (the \with construction) of all the fields of an arbitrary record, as in the following example:
//@ ghost struct c_s { float x; float y; };

//@ type point = struct c_s;

//@ axiomatic Arbitrary_point { logic point empty; }

//@ logic point my_point = {{ empty \with .x = (float)1. } \with .y = (float)2.};


text:
Q: User specific gems with RVM I am using RVM on my server to manage ruby.  I have a gem that is a daemon that I want to run as an unprivileged user, however, when I attempt to do so, I get a permissions error:
statusbot@host config]$ statusbot run
fatal: Not a git repository (or any of the parent directories): .git
/usr/local/rvm/gems/ruby-1.9.3-p374/gems/bundler-1.3.2/lib/bundler/definition.rb:235:in `rescue in lock': There was an error while trying to write to Gemfile.lock. It is likely that  (Bundler::InstallError)
you need to allow write permissions for the file at path:
/usr/local/rvm/gems/ruby-1.9.3-p374/gems/StatusBot-0.0.4/Gemfile.lock
    from /usr/local/rvm/gems/ruby-1.9.3-p374/gems/bundler-1.3.2/lib/bundler/definition.rb:220:in `lock'
    from /usr/local/rvm/gems/ruby-1.9.3-p374/gems/bundler-1.3.2/lib/bundler/environment.rb:34:in `lock'
    from /usr/local/rvm/gems/ruby-1.9.3-p374/gems/bundler-1.3.2/lib/bundler/runtime.rb:43:in `setup'
    from /usr/local/rvm/gems/ruby-1.9.3-p374/gems/bundler-1.3.2/lib/bundler.rb:120:in `setup'
    from /usr/local/rvm/gems/ruby-1.9.3-p374/gems/rubygems-bundler-1.1.1/lib/rubygems-bundler/noexec.rb:79:in `setup'
    from /usr/local/rvm/gems/ruby-1.9.3-p374/gems/rubygems-bundler-1.1.1/lib/rubygems-bundler/noexec.rb:91:in `<top (required)>'
    from /usr/local/rvm/rubies/ruby-1.9.3-p374/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:60:in `require'
    from /usr/local/rvm/rubies/ruby-1.9.3-p374/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:60:in `rescue in require'
    from /usr/local/rvm/rubies/ruby-1.9.3-p374/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:35:in `require'
    from /usr/local/rvm/gems/ruby-1.9.3-p374/bin/ruby_noexec_wrapper:9:in `<main>'

Likewise, I am unable to install gems on a per-user basis:
[statusbot@host ~]$ gem install ~/StatusBot-0.0.5.gem
ERROR:  While executing gem ... (Errno::EACCES)
    Permission denied - /usr/local/rvm/gems/ruby-1.9.3-p374/gems/StatusBot-0.0.5

A: Using RVM in multi user mode requires:

*

*RVM is installed using sudo not root user.

*All users wanting to install rubies / gems must be in the group rvm (an extra use case is OSX wher even you are in rvm group when checked with id1 - it could be still not effective for the shell and restart is needed)

The extra use case is mixed mode where only parts of RVM are in system and user can create gemsets in $HOME, read more about it at RVM site: https://rvm.io/rvm/install

A: It looks like a problem with a gem, according to https://stackoverflow.com/a/4151540/497756 and the followed article http://yehudakatz.com/2010/12/16/clarifying-the-roles-of-the-gemspec-and-gemfile/ from one of bundler authors Gemfile.lock should not be part of the gem.
Try:
 sudo rm -f /usr/local/rvm/gems/ruby-1.9.3-p374/gems/StatusBot-0.0.4/Gemfile.lock


text:
Q: Why does English hypenate compounds, while German just mashes them together? Since starting to learn German, I find myself wanting to use a non-hyphenated word in English, but I always end up adding the hyphen because otherwise it just seems wrong in English. Why is this? Is it merely convention?

A: First of all, note that the problem is a little bit more complex.
English can separate parts of a compound with a space (orange juice), nothing (football), or sometimes a letter (bridesmaid).
German can use nothing (Fußball), a letter (Orangensaft, not Orangesaft), or, rarely a hyphen (Drucker-Zeugnis) to avoid confusion.
That being said, this is primarily a spelling convention. There is no grammatical or pronunciation difference between an English compound like mathematics book and the German analogue Mathematikbuch.
However, there are some reasons why the English conventions would not work well for German:

*

*German uses joins compounds with interfixes (Fugenlaute) far more often than English.
As these interfixes do not belong to either part of the compound, splitting the compound in writing would pose a consistency and aesthetics problem.
When English uses these, it is either without hyphen or space (bridesmaid) or a double hyphen (annoy-o-tron).

*English has a comparably rigid word order for sentences which allows to identify compounds in writing by their position and without relying on the help from the orthography.
(In spoken language this is not so much of a problem thanks to pauses, stress, etc.)

*Since the German orthography capitalises all nouns, proper nouns are not as easy to identify and you could easily confuse a compound with a proper noun plus apposition.
For example der Flughafenwahn (compound noun) means the airport craze, but der Flughafen Wahn (proper noun plus apposition) is Wahn airport.
Now, if English orthography had these issues, it might employ the approach of only omitting the space when it would be causing confusion – which it indeed does to some extent, it indeed does, e.g., in bridesmaid.
However, German orthography champions consistency considerably more than the English one.

A: There are plenty of unhyphenated compound words in English (teaspoon, greenhouse, laptop...). Gyles Brandreth in Have you eaten, Grandma says that hyphenated words are becoming less common. Even co-operate, which you would think needed the hyphen to stop you from pronouncing the first syllable coop, is now often written without one. There are no hard and fast rules (though occasionally the presence of a hyphen changes the meaning, as in the words  recover and re-cover).
I can't see English speakers ever accepting those long strings of unhyphenated words that you get in German, though!


text:
Q: Access Back4App mongodb I'm trying to access my back4app app mongodb directly from a python script:
client = pymongo.MongoClient("mongodb://admin:AAA@mongodb4.back4app.com:27017/BBB?ssl=true")

And I see that it connects but can't go further and figure out db name and collection names. Appreciate any help.

A: The db name is "BBB"
In order to get the collections, try:
db = client['BBB']
cols = db.collection_names()
for col in cols:
  print col

Instead of accessing the database directly you can also try a python SDK (not official), like this:
https://github.com/milesrichardson/ParsePy


text:
Q: Fixing list output in Prolog I'm trying to make a solver for the Dutch National flag problem. Basically, given a list, I want to sort them in the order of Red-White-Blue. Red, White and Blue are defined by their predicates (i.e. red(x), white(x) etc.)
Currently, I have the following code:
red(1).
white(2).
blue(3).

dutch(Xs,Ys):-
    getRed(Xs,[], Red), getWhite(Xs,[],White), getBlue(Xs,[],Blue),
    append([], Red, Y1), append(Y1, White, Y2), append(Y2, Blue, Ys).

getRed([],Rs,Rs).
getRed([X|Rest], Acc, Rs) :- red(X), getRed(Rest, [X,Acc] , Rs).
getRed([X|Rest], Acc, Rs) :- getRed(Rest, Acc, Rs).

getWhite([],Rs,Rs).
getWhite([X|Rest], Acc, Rs) :- white(X), getWhite(Rest, [X,Acc], Rs).
getWhite([X|Rest], Acc, Rs) :- getWhite(Rest, Acc, Rs).

getBlue([],Rs,Rs).
getBlue([X|Rest], Acc, Rs) :- blue(X), getBlue(Rest, [X,Acc], Rs).
getBlue([X|Rest], Acc, Rs) :- getBlue(Rest, Acc, Rs).

My output looks like this :
?- dutch([1,2,3],R).
R = [1, [], 2, [], 3, []]
R = [1, [], 2, []]
R = [1, [], 3, []]
R = [1, []]
R = [2, [], 3, []]
R = [3, []]
R = []

What I want is for it to look like this:
R = [1, 2, 3]

I've tried a few ways to force the output to what i want, but haven't been able to get anywhere close.
Edit: Looks like i can solve it by using a brute force solution of permuting all possible sets and evaluating whether the set is in "Dutch Flag" order. Is there a better solution though?

A: A pure solution
Preface
I would like to add a pure, relational solution to the existing one.
Ideally, you can use a Prolog predicate in all directions, and I will now show an implementation that lets you do this: Not only can you sort an instantiated list according to your criteria, no, you can also generate solutions and complete partially instantiated solutions.
To do this, I am using the meta-predicate if_/3 from library(reif).
Reified predicates
I start with the reified versions of your predicates, also taking the liberty to use the more telling names red, white and blue to denote the colors:

red(R, T)   :- =(R, red, T).

white(W, T) :- =(W, white, T).

blue(B, T)  :- =(B, blue, T).

Note I am using (=)/3, which ships for free with library(reif).
Using DCGs to describe lists
Next, purely for convenience, I am using dcg notation to describe the subsequences of interest:

reds([]) --> [].
reds(Rs) -->
        [R],
        { if_(red(R), Rs = [R|Rest], Rs = Rest) },
        reds(Rest).

whites([]) --> [].
whites(Ws) --> [W],
        { if_(white(W), Ws = [W|Rest], Ws = Rest) },
        whites(Rest).

blues([]) --> [].
blues(Bs) --> [B],
        { if_(blue(B), Bs = [B|Rest], Bs = Rest) },
        blues(Rest).

I leave making this more concise as an easy exercise.
Solution
With these building blocks, we can express the overall solution:

dutch(Colors, Ds) :-
        phrase(reds(Rs), Colors),
        phrase(whites(Ws), Colors),
        phrase(blues(Bs), Colors),
        phrase((Rs,Ws,Bs), Ds).

Examples
Of course, this works in simple, instantiated cases like:

?- dutch([red,white,blue], Ds).
Ds = [red, white, blue] ;
false.

Now the point: This also works in the most general case, where all arguments are variables:

?- length(Cs, _), dutch(Cs, Ds).
Cs = Ds, Ds = [] ;
Cs = Ds, Ds = [red] ;
Cs = Ds, Ds = [white] ;
Cs = Ds, Ds = [blue] ;
Cs = [_G1322],
Ds = [],
dif(_G1322, blue),
dif(_G1322, white),
dif(_G1322, red) ;
Cs = Ds, Ds = [red, red] ;
Cs = Ds, Ds = [red, white] ;
Cs = Ds, Ds = [red, blue] ;
Cs = [red, _G1340],
Ds = [red],
dif(_G1340, blue),
dif(_G1340, white),
dif(_G1340, red) .

By adding further goals, we can specialize this query to observe concrete solutions that are now generated:

?- length(Cs, _), Cs = [_,_,_|_], dutch(Cs, Ds), ground(Cs).
Cs = Ds, Ds = [red, red, red] ;
Cs = Ds, Ds = [red, red, white] ;
Cs = Ds, Ds = [red, red, blue] ;
Cs = [red, white, red],
Ds = [red, red, white] ;
Cs = [red, blue, red],
Ds = [red, red, blue] .

Compare this with the other answer, which cannot be used to fairly enumerate solutions:

?- length(Xs, _), Xs = [_,_,_|_], dutch(Xs, Ys).
Xs = Ys, Ys = [1, 1, 1] ;
Xs = Ys, Ys = [1, 1, 1, 1] ;
Xs = Ys, Ys = [1, 1, 1, 1, 1] ;
Xs = Ys, Ys = [1, 1, 1, 1, 1, 1] ;
Xs = Ys, Ys = [1, 1, 1, 1, 1, 1, 1] .

Summary
Thus, by retaining logical-purity we have obtained a more general logic program, which we can use in all directions.
Admittedly, you did not request this generality. However, while we are at it, why waive it?

A: I see two errors in your code:
1) your terminal clauses getRed([],Rs,Rs), getWhite([],Rs,Rs), getBlue([],Rs,Rs) accepting, as value result, the empty list (when Rs is equal to []); I suggest to rewrite they as
getRed([],Rs,Rs)   :- Rs \= [].
getWhite([],Rs,Rs) :- Rs \= [].
getBlue([],Rs,Rs)  :- Rs \= [].

2) in the accepting clause (when X is the searched color), you add it in the accumulator with a comma when you should use a pipe ([X,Acc]; should be ([X|Acc]); I suggest to rewrite they as
getRed([X|Rest], Acc, Rs)   :- red(X),   getRed(Rest, [X|Acc], Rs).
getWhite([X|Rest], Acc, Rs) :- white(X), getWhite(Rest, [X|Acc] , Rs).
getBlue([X|Rest], Acc, Rs)  :- blue(X),  getBlue(Rest, [X|Acc], Rs).

Off Topic: There is no reason to append Red to an empty list; the result list (Y1) is Red itself; I suggest to semplify
append([], Red, Y1), append(Y1, White, Y2), append(Y2, Blue, Ys)

as follows
append(Red, White, Mid), append(Mid, Blue, Ys)

--- EDIT ---
Not sure about what do you exactly want but I suspect a third error in the third version clauses: when X isn't accumulated.
I think you should add a check to be sure that X isn't the searched color; I suggest to rewrite they as follows
getRed([X|Rest], Acc, Rs)   :- \+ red(X),   getRed(Rest, Acc, Rs).
getWhite([X|Rest], Acc, Rs) :- \+ white(X), getWhite(Rest, Acc, Rs).
getBlue([X|Rest], Acc, Rs)  :- \+ blue(X),  getBlue(Rest, Acc, Rs).

--- EDIT 2 ---
I don't see the need of an accumulator in your getRed/3, getWhite/3 and getBlue/3 clauses.
I propose a version with only 2 arguments
red(1).
white(2).
blue(3).

dutch(Xs,Ys):-
    getRed(Xs, Red), getWhite(Xs, White), getBlue(Xs, Blue),
    append(Red, White, Mid), append(Mid, Blue, Ys).

getRed([],[]).
getRed([X|Rest], [X|Rs]) :- red(X),    getRed(Rest, Rs).
getRed([X|Rest], Rs)     :- \+ red(X), getRed(Rest, Rs).

getWhite([],[]).
getWhite([X|Rest], [X|Rs]) :- white(X),    getWhite(Rest, Rs).
getWhite([X|Rest], Rs)     :- \+ white(X), getWhite(Rest, Rs).

getBlue([],[]).
getBlue([X|Rest], [X|Rs]) :- blue(X),    getBlue(Rest, Rs).
getBlue([X|Rest], Rs)     :- \+ blue(X), getBlue(Rest, Rs).


text:
Q: SQL - How to subtract / add two or more sub queries (looking for a more proficient way) I already know how to perform either subtraction/addition on two subqueries and then set the result as a new column, usually I've been copying the subqueries and placing them in brackets like so..
(
    (SELECT IIF(BL.value1)
    FROM Table1 T1
    INNER JOIN Table2 T2 ON T1.ID = T2.Table1ID
    Where T2.ID = TableMain.ID
    )

    -   ---<Subtraction here

    (SELECT SUM(T5.Value2)
    FROM Table4 T4
    INNER JOIN Table6 T6 ON T4.ID = T6.Table4ID
    INNER JOIN Table7 T7 ON T6.ID = T7.Table6ID
    WHERE
    T7.FIeld IN (40)
    )
) AS [Net Invoice Value]

What I'd like to know is if there's an easier way to do this by using just the aliases?
Thanks in advance


text:
Q: Paypal donation form I'm trying to make a custom Paypal donation form for my website where people could choose between 3 options. The first two options have a variable quantity, which would also change the total amount of money that would be donated. In this case, each 'item' would cost $1 (with the exception of Option 3).
Now is my problem, when I would choose 5 cookies for example, it would only charge $1 (because the Waffles are still stuck on 1) instead of $5.
Any thoughts on how to achieve choosing different quanitities without both values inflicting?
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
    <input name="item_number" type="text" placeholder="Your name here" required>

<input type="radio" name="amount" value="0.00" required><select name="amount"><option value="1.00">1 Cookie</option><option value="2.00">2 Cookies</option><option value="3.00">3 Cookies</option><option value="4.00">4 Cookies</option><option value="5.00">5 Cookies</option></select> Cookies

<input type="radio" name="amount" value="0.00" required><select name="amount"><option value="1.00">1 Waffle</option><option value="2.00">2 Waffles</option><option value="3.00">3 Waffles</option><option value="4.00">4 Waffles</option><option value="5.00">5 Waffles</option></select> Waffles

<input type="radio" name="amount" value="30.00" required> Option 3
    <input type="hidden" name="cmd" value="_donations">
    <input type="hidden" name="business" value="my@email.com">
    <input type="hidden" name="lc" value="US">
    <input type="hidden" name="item_name" value="Donation test">
    <input type="hidden" name="currency_code" value="USD">
    <input type="hidden" name="bn" value="PP-DonationsBF:btn_donateCC_LG.gif:NonHosted">

<input type="submit" src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" value="Confirm" alt="PayPal - The safer, easier way to pay online!">
</form>

A: In any PayPal button, only one drop-down menu option selection can have priced options.
As a workaround you can use Javascript to dynamically get the selected option price and send it to amount variable


text:
Q: Padding not applied on integer in a struct when it is followed by a char of size bigger than integer I have some structs for which i am checking their sizes. According to the rules of padding, i am expecting different results. When i have a char of size between 4 and 8, i see that padding is applied to the char up to size 8, but padding is not applied for the preceding integer or for the last integer/variable of the struct.
The main question here is why padding is not applied to integers whenever they are followed by char of size bigger than 4?
What is the meaning of applying padding to the char to reach 8 bytes, if integer still use 4 bytes?
Below, you can see the code why my questions in comments:
#include <stdio.h>

typedef struct {
    int i;
    char str[3]; //padding of 1
    int f;
} stru_10;

//size is 4+4+4 = 12

typedef struct {
    int i;       //why no padding applied here?
    char str[7]; // padding of one
    int f;       //why no padding applied here?
} stru_11;

//Actual result : size is 16. Why no padding on integers?

typedef struct {
    int i;       //why no padding applied here?
    char str[9]; // padding of 3
    int f;       //why no padding applied here?
} stru_12;

//Actual result : Size is 20. Why no padding on integers?

typedef struct {
    int i;        //why no padding applied here?
    char str[5];  // padding of 3
    int f;        //why no padding applied here?
} stru_13;

//Actual result : Size is 16. Why no padding on integers?

typedef struct {
    int i;
    char c;  // padding of 3
    int f;
} stru_14;

//Actual result. Size is 12 as expected.

typedef struct {
    int i;    // padding of 4
    char *c;  // padding of 3
    int f;    //padding of 4
} stru_15;

//Actual result. Size is 24 as expected(8*3).

int main(void) {

    printf("Size of stru_10 is %d\n",sizeof(stru_10)); //12
    printf("Size of stru_11 is %d\n",sizeof(stru_11)); //16
    printf("Size of stru_12 is %d\n",sizeof(stru_12)); //20
    printf("Size of stru_13 is %d\n",sizeof(stru_13)); //16
    printf("Size of stru_14 is %d\n",sizeof(stru_14)); //12
    printf("Size of stru_15 is %d\n",sizeof(stru_15)); //24

    return 0;
}

A:
but padding is not applied for the preceding integer or for the last integer/variable of the struct.

Why would it be?
Don't think of it as "padding". What's going on in most cases is this:
Fundamental data types (ints, floats, doubles, etc.) need to be properly aligned in memory so that the CPU can read them efficiently (or even at all since certain CPUs will just crash your program when you're reading data that isn't correctly aligned). This applies even if they are part of a struct. To achieve that alignment almost everyone follows this model:

*

*each struct member is aligned within the struct on their natural alignment.

*the size of the struct is rounded up to be a multiple of the required alignment of its most strictly aligned member.

*the alignment of an array is the same as the alignment of its elements.

The C standard allows for much more than this, but in practice this is what pretty much everyone does because it solves all problems of alignment for all data types, structs and arrays of structs. Unless you have a really weird CPU.
In your examples, the alignment requirement for int is most likely 4 and 1 for char. From the above rules you can figure out how the elements will be laid out. What you call "padding" is just the bits that are left over when things are properly aligned.
Let's take one of your examples.
typedef struct {
    int i;       //why no padding applied here?
    char str[7]; // padding of one
    int f;       //why no padding applied here?
} stru_11;

i needs to be aligned at 4. It is at offset 0. (0 % 4) == 0, so the alignment is good. str needs to be aligned at 1. The first free offset in the struct is 4. (4 % 1) == 0, so that's good enough. str is put at offset 4. f needs to be aligned at 4, the first free offset in the struct is 11. (11 % 4) == 3, so that's not good enough. But 12 is good enough, let's put f at 12. The size of the struct is now 16 and the alignment of the largest member of the struct is 4, (16 % 4) == 0, that fullfils all the requirements of struct member alignment, we can leave the struct as size 16, no further alignment or padding necessary.
Please note that what I wrote above is not mandated by the language standard. The mechanism for laying out struct members is part of other standards that are called ABI (application binary interface) and each operating system + CPU combo can have their own ABI. Most ABIs define things to be done like this because it's the easiest and most efficient way of doing it, but in case of doubt you need to find the particular documentation from your OS+CPU combo (if it exists at all).


text:
Q: How do I get a child from WPF tooltip I have code like this
<Setter Property="ToolTip" >
   <Setter.Value>
      <ToolTip>
         <StackPanel>
            <TextBlock Text="Assignment Name : " FontSize="18">
            <TextBlock Name="asn" FontSize="18" Foreground="GreenYellow" Text="nothing here"/>
            </TextBlock>
         </StackPanel>
      </ToolTip>
   </Setter.Value>
</Setter>
<EventSetter Event="ToolTipOpening" Handler="ToolTip_Opening"/>

I want to get the textblock with the name asn , To get text property from it.
Is this possible ?
Edit 1 : if i want to use binding for the textblock with the name :asn
to an image source
i.e.
 : show the image source property in the asn textblock
(text block is placed on a custom control that has an image child)
<Style TargetType="Controls:Tile">
     ...
        <Setter Property="ToolTip" >
         <Setter.Value>
           <ToolTip>
               <StackPanel>
                   <TextBlock Text="Assignment Name : " FontSize="18">
                         <TextBlock Name="asn" FontSize="18" Foreground="GreenYellow" Text="nothing here"/>
                    </TextBlock>
                </StackPanel>
           </ToolTip>
        </Setter.Value>
   </Setter>
    <EventSetter Event="ToolTipOpening" Handler="ToolTip_Opening"/>
  </Style>

A: You need to go through PlacementTarget to find the TextBlock, because the tooltip isn't in the same visual tree as the TextBlock.
very similar: RelativeSource binding from a ToolTip or ContextMenu

A: Could you not name your Image control with x:Name and then bind to it?
e.g.
<Image x:Name="MyImage" Source="Stuff"/>
<TextBlock Text="{Binding ElementName=MyImage, Path=Source}"/>

A: ok solved this thanks to @John Gardner
solution is pretty simple
<TextBlock  FontSize="18" Foreground="DarkGreen" Text="{Binding IsAsync=True, Path=PlacementTarget,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ToolTip},Converter={StaticResource myconvertortool}}"/>

this will pass the custom control instance to the converter which simply gets the image from it
   Public Class ToolTipToSourceConverter
    Implements IValueConverter

    Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
        If value Is Nothing Then
            Return "Error "
        End If
        Try
            Dim sndr = DirectCast(value, MahApps.Metro.Controls.Tile)
            Dim sndrimage = DirectCast(sndr.GetChildObjects(False)(0), Image)
            Dim imgname As String = sndrimage.Source.ToString.Substring(sndrimage.Source.ToString.LastIndexOf("/"c) + 1)

            Return StatsDict.InquireForAssignment(imgname).Name.ToString.Replace("_", " ")
        Catch ex As Exception
            Return value.GetType.ToString
        End Try
        'if is connected to master True then hide
    End Function

    Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
        Throw New NotImplementedException
    End Function
End Class


text:
Q: Simple C Program Lags [Homework] For an assignment I have we are to find vulnerabilities in a certain C program and exploit them using various buffer overflow attacks. However when I run the .out file in the terminal with it's input argument it just stalls and doesn't do anything.
Even when I run GDB, that just lags too. I'm not looking for a solution to the assignment, I'm just looking for reasons why it's not running?
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

void partialwin()
{
  printf("Achieved 1/2!\n");
}

void fullwin(){
  printf("Achieved 2/2\n");
}
void vuln(){
  char buffer[36];

  gets(buffer);
  printf("Buffer contents are %s\n",buffer);
}

int main(int argc,char**argv){
  vuln();
}

A: Providing your sourc file is called assignment1.c and you're using gcc this should work, $  being your command prompt (which could be different on your platform)
$ gcc assignment1.c
$ a.out
Hello
Buffer contents are Hello
$


text:
Q: How to get maximum for a field based on a date and get other fields also? I know my question is bit confusing but if I show you data it will make more sense what I am trying to achieve.
I am reading everything from one table T only.
I am reading 6 fields from that table T.
StartKey
Name
Min
LName
MName
ID
Top Table is data, and bottom table is what I am trying to achieve.
I need to get for each startkey get max(minutes)
 FORGOT TO INCLUDE 20130221 in output.

Here is what I tried so far
select
       startkey,
       name,
       min,
       lname,
       mname,
       id
from T
where startkey >= '20130118'
group by startkey,name,lname,mname,id
order by startkey

but it doesn't work

A: For each start-key, you want to find the Max "min" value. this can be done via a nested sub-query. Then , select only where the min is equal to the max(min).
Also, if you have a situation where two records can have the same value of startkey and min, then you will need to resolve that, otherwise you will select them both.
select  startkey, name, min, lname, mname, id
from T T1
where min =
 (select max(min) from T T2 where T1.startkey=T2.startkey)

order by startkey

A: I don't know if I understood your question correctly, but from what I get you're trying to get a specific set of data.. You can force the filters by getting only the StartKeys you need. This should work:
SELECT StartKey, Name, Min, Lname, Mname, ID
FROM T
WHERE StartKey IN ('20130118','20130119','20130120')

If that doesn't work, you can try this:
SELECT StartKey, Name, Min, Lname, Mname, ID
FROM T
WHERE Month(StartKey) >= 1

Assuming that StartKey is a Date field.

A: select startkey, name, min, lname, mname, id
  from (select startkey, name, min, lname, mname, id,
               row_number() over (partition by startkey order by min desc) rn
          from t)
 where rn = 1;

should do that.
eg: http://sqlfiddle.com/#!4/59f6a0/1
note that if you have 2+ rows with the same time and you want to return them all, change row_number to rank. if you only want one of them then row_number is what you want (though you can add extra ordering to pick a specific one.

A: Select *
  From T
      Inner Join (Select StartKey, Max(Min) AS MaxMinutes
                    From T
                   Group By StartKey
                  ) DerrivedView
    On T.Start = DerrivedView.StartKey And
       T.Min = DerrivedView.MaxMinutes


text:
Q: weird issue with html: markup is correct but dev tools show  moving to  I've got this weird issue going on. I'm using Codeigniter 3.0-dev and Smarty 3.1.4 in the backend, but I don't think it's relevant.
I have this really simple html:
<!DOCTYPE HTML>
<html>
<head>
    <title>some page</title>
</head>
<body>
asd
</body>
</html>

now. when I view the source of this page, on any browser (tried Opera 10.52, Firefox 7.0.1, Chrome 14 and 15, IE9) the markup is exactly like above. now, when I use firebug or chrome's dev tools it moves the title tag in the <body>, and if I have meta or anything else in the <head>, it moves those items in the <body> aswell. firefox's firebug shows me this:
<html>
<head></head>
<body>

<title>test</title>
asd
</body>
</html>

why does this happen? any ideas, at all?

A: Elements that appear to be in head in the mark-up, can end up inside body in the DOM, if the parser sees something before the moved elements that is only permissible in the body of HTML. For example, a double BOM (byte-order-mark) at the start of the file may not show up in View Source, but will cause the parser to think that it has entered the html body section, and all the head elements in the mark-up will end up in the body in the DOM.

A: What Alohci said, plus both Firebug and the Chrome debugger often move things around to suit themselves. The source then looks wrong when viewed in those debuggers.


text:
Q: Postgresql - merge time and date of csv on import to timestamp I'm trying to import data from a csv file into postgresql, unfortunately it's not perfectly formatted.
Example:
DATE,TIME,NUMERIC,NUMERIC,NUMERIC,NUMERIC,INTEGER

I want to import the data into a table with the columns:
timestamp with timezone, numeric, numeric, numeric, numeric, integer

For importing the data I use copy:
COPY tabledata FROM 'c:\Users\Public\Downloads\test.csv' DELIMITERS ',' CSV;

Of course it does not work, since date and time are separated by ',' so postgresql assumes that those are 2 separate data fields.
I've managed it to import the .csv into a table that is setup just like the .csv, however I need to have date and time as timestamp with timezone later on, and because I will be handling huge amounts of data a post import conversion would be my last choice because of performance issues.
I've tried to edit the .csv file prior to import with "sed 's/,/ /' EURUSD30.csv > EURUSD30E.csv" however I get an error saying that the command "'s/" is typed wrong or could not be found. I'm rather clueless because this seems to work for everybody else, but this would not be my first choice either.
It would be easier if postgresql could simply be told upon import to merge time and date into one timestamp value. Any ideas?
Thanks

A: Your best bet is to COPY the data to a TEMPORARY or UNLOGGED table, and from there do an:
INSERT INTO real_table
SELECT col1, col2, col3, datecol + timecol, col6, ...
FROM temp_copy_table;

You can do any other required data massaging during that process too.
Consider timezones when merging. DATE + TIME produces a timestamp without time zone:
regress=# SELECT pg_typeof(DATE '2012-02-01' + TIME '10:00');
          pg_typeof
-----------------------------
 timestamp without time zone
(1 row)

and you probably want to store a timestamp with time zone, so you might want to tell Pg to interpret the date+time as being at a particular time zone with:
(datecol + timecol) AT TIME ZONE 'UTC'

or whatever the local time zone of the time stamps is.


text:
Q: QML Chart interactive I have a pie chart created dynamically, that uses function createPieChart() described below. When a slice is clicked, I want to call a function to print out the label and value of that slice.
I am facing 2 problems:

*

*Although I connect "clicked" or "pressed" or "released" signals, the slot is not reached. I am using qtcharts 2.0 (I cannot update right now).

*I am able to connect "hovered" signal, but without passing any parameter, so I don't know what slice I am into.

These are the other functions:
function createPieChart(data){
    pieserieschart.clear();
    slices.splice(0, slices.length) //clear slices array

    for (var prop in data) {
        slices.unshift(pieserieschart.append(prop, data[prop]));

        //I get "Cannot read property 'label' of undefined using this method
        slices[0].hovered.connect(function(){mouseHoverSlice(slices[0].label));

        //WORKS, but I want to pass the label of that slice (and the value if possible)
        slices[0].hovered.connect(mouseHoverSlice);

        //it is not working at all
        slices[i].clicked.connect(sliceClicked);
    }

 function sliceClicked(){
     console.log("Slice Clicked"); //I cannot see this printed
 }

 function mouseHoverSlice(info){
     console.log("Slice hover: " + info);
 }

Any idea of how to do it? Thanks!

A: After upgrade to QtCharts 2.2 I was able to solve it like this:
For pie & line & scatter plots, I used onClicked, which returns the slice/point. So you don't need to connect any signal when creating the slices or points dynamically.
For bar charts, I was able to connect the barset created
var barvalues = barserieschart.append("label",values)
barvalues.clicked.connect(barClicked)

...

ChartView {
        PieSeries {id: pieserieschart; onClicked: sliceClicked(slice) }
        BarSeries {id: barserieschart }
        ScatterSeries{id: scatterserieschart; onClicked: scatterclicked(point)}
}


text:
Q: glm in R, give all comparisons Simple logistic regression example.
set.seed(1)
df <- data.frame(out=c(0,1,0,1,0,1,0,1,0),
           y=rep(c('A', 'B', 'C'), 3))

result <-glm(out~factor(y), family = 'binomial', data=df)
summary(result)

#Call:
#glm(formula = out ~ factor(y), family = "binomial", data = df)

#Deviance Residuals:
#    Min       1Q   Median       3Q      Max
#-1.4823  -0.9005  -0.9005   0.9005   1.4823

#Coefficients:
#              Estimate Std. Error z value Pr(>|z|)
#(Intercept) -6.931e-01  1.225e+00  -0.566    0.571
#factor(y)B   1.386e+00  1.732e+00   0.800    0.423
#factor(y)C   3.950e-16  1.732e+00   0.000    1.000

#(Dispersion parameter for binomial family taken to be 1)

#     Null deviance: 12.365  on 8  degrees of freedom
#Residual deviance: 11.457  on 6  degrees of freedom
#AIC: 17.457

#Number of Fisher Scoring iterations: 4

My reference category is now A; results for B and C relative to A are given. I would also like to get the results when B and C are the reference. One can change the reference manually by using levels = in factor(); but this would require fitting 3 models. Is it possible to do this in one go? Or what would be a more efficient approach?

A: If you want to do all pairwise comparisons, you should usually also do a correction for alpha-error inflation due to multiple testing. You can easily do a Tukey test with package multcomp.
set.seed(1)
df <- data.frame(out=c(0,1,0,1,0,1,0,1,0),
                 y=rep(c('A', 'B', 'C'), 3))

#y is already a factor, if not, coerce before the model fit
result <-glm(out~y, family = 'binomial', data=df)
summary(result)

library(multcomp)
comps <- glht(result, linfct = mcp(y = "Tukey"))
summary(comps)
#Simultaneous Tests for General Linear Hypotheses
#
#Multiple Comparisons of Means: Tukey Contrasts
#
#
#Fit: glm(formula = out ~ y, family = "binomial", data = df)
#
#Linear Hypotheses:
#  Estimate Std. Error z value Pr(>|z|)
#B - A == 0  1.386e+00  1.732e+00     0.8    0.703
#C - A == 0  1.923e-16  1.732e+00     0.0    1.000
#C - B == 0 -1.386e+00  1.732e+00    -0.8    0.703
#(Adjusted p values reported -- single-step method)

#letter notation often used in graphs and tables
cld(comps)
#  A   B   C
#"a" "a" "a"


text:
Q: Error running Weblogic12.2.1.2.0: Weblogic installation registry file is not found recently I have deinstalled my weblogic 12.1.1.0 from drive C, based on instruction of uninstallaiton, and I installed new version of weblogic "Quick Installer for Mac OSX, Windows and Linux" 12.2.1.2.0 in drive C but different folder. when I want to run weblogic in intellije I recieve the following error in intellij:
Error running Weblogic12.2.1.2.0: Weblogic installation registry file is not found
what is the problem?

A: I was having the same problem.

This problem occurs because the IntelliJ IDEA is getting the path (WEBLOGIC_HOME) for your wrong destination (your old installation).
So, to solve this you need to set a new path installation for your Weblogic settings in the IDE.
To do this, go tho your Run settings and click the Configure button on your Application Server settings, and then in your Weblogic Home set your new path, as the following image:

After this, you will run your Weblogic properly!

A: I also had the same issue because I deleted my weblogic and reinstalled it at a different location. All I did to fix it was change the location of my weblogic home within IntelliJ to match the new location.


text:
Q: WP Paths in a Plugin - how to include I'm working on my first WP plugin, and I'm having trouble getting a file include to work. My directory structure looks like this:

*

*myPlugin

*

*classes

*templates

*css

*js

*myplugin.php

My main plugin file (myplugin.php) includes / requires various files in the classes directory, and that works fine. However, one of the files in the classes directory is supposed to include a file from the templates directory. I've tried everything I can think of, from plugins_url() to plugin_basename() to plugin_dir_path() but nothing seems to work.
How should this statement look to get it to do what I'm trying to accomplish?

A: Put this in the main plugin file (myplugin.php):
defined( 'MY_PLUGIN_URL' ) || define( 'MY_PLUGIN_URL', plugin_dir_url(__FILE__) );
defined( 'MY_PLUGIN_PATH' ) || define( 'MY_PLUGIN_PATH', plugin_dir_path(__FILE__) );

right before any other code, and use MY_PLUGIN_PATH to include files, or MY_PLUGIN_URL to load your assets.
E.G:

*

*require_once MY_PLUGIN_PATH . 'templates/se.php';

*wp_enqueue_style( 'my-css', MY_PLUGIN_URL . 'assets/css/style.css' );
Those constants can be accessible from any other file including the main plugin loader file and the files within the sub-directories. As long as the plugin is loaded correctly.
Hope that helps.