text:
Q: NSException rethrowing with wrong stack in the debugger When I crash (for reasons I understand; that's not the problem) when I try to do something Cocoa isn't okay with, such as calling a method that doesn't exist or attempting to insert nil into a set, the debugger shows the stack from main() to __pthread_kill, without any of the frames that were present when the actual crashing code ran.  There is a frame (9th from main) called objc_exception_rethrow.  This leads me to believe that Cocoa Touch is trying to do something or other to recover all exceptions and die gracefully or something.  However, it is very irritating when debugging to not have the ability to actually use Xcode4's debugging tools to investigate the calling stack frames, or even see where in my code I crashed.
Is there some way to make the objc_exception_rethrow behavior not happen, and just crash as soon as an exception is raised?  Perhaps there's a debug setting that makes it crash earlier (at the right time)?  (I haven't messed with any of the build settings in this project yet.)

A: I don't know any Xcode setting that could disable re-throwing exceptions. To my knowledge they are re-thrown by the runtime. You could try running the app without the debugger attached and let it crash. The crash report should contain a section "Last Exception Backtrace" which will give you exactly what you need in this case.

A: I found the answer: set a breakpoint on Obj-C Exceptions.  It will go to the debugger when objc_exception_throw is hit, which is good.  Unfortunately, this happens before the exception is printed, but we can make that happen anyway (most of the time) by setting the breakpoint's action to be (Debugger Action) po *(id *)($ebp + 8).


text:
Q: Using visitor IP as proxy in PHP cURL Let say, visitor visited my website domain.com and his IP is recorded 172.1.1.x and i am using this IP to fetch real time string from example.com
My code
function file_get_contents_curl($url_curl) {
    $agent = $_SERVER['HTTP_USER_AGENT'];
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 1); // include headers in response
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url_curl);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);

    // Use the visitor's IP address as the proxy address
    $proxy_address = $_SERVER['REMOTE_ADDR'];
    curl_setopt($ch, CURLOPT_PROXY, $proxy_address);

   // Set the X-Forwarded-For header to the visitor's IP address
    //curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Forwarded-For: $proxy_address"));

    // Get the content type and content
    $response_curl = curl_exec($ch);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    $data_curl = substr($response_curl, $header_size);

    // Set the content type header (MIME Type)
    header('Content-Type:' . $content_type);

    curl_close($ch);

    return $data_curl;
}

// Usage example:
$homepage = file_get_contents_curl("https://example.com");

Normally, cURL use my server IP address for HTTP request to example.com, I want to use visitor IP address directly to make HTTP request to example.com

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create onClickListener in RecyclerView I tried to make a setListener on adapter to make something Action on the app. But the problem was when using this line of code to call setClickListener
adapter.setClickListener(this);

it gives me this error when using (this)
Required type:   ItemClickListener

Provided:        HomeImagesFragment

Here are my codes
Picassotest "Adapter for RecyclerView"
public class Picassotest extends RecyclerView.Adapter<Picassotest.ViewHolder> {

private String[] mData;
private Context context;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;

// data is passed into the constructor
public Picassotest(Context context, String[] data) {
    this.mInflater = LayoutInflater.from(context);
    this.mData = data;
    this.context = context;
}

// inflates the cell layout from xml when needed
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = mInflater.inflate(R.layout.images_list, parent, false);
    return new ViewHolder(view);
}

// binds the data to the TextView in each cell
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    Picasso
            .with(context)
            .load(mData[position])
            .fit() // to resize the image to imageView
            .placeholder(R.drawable.loading_image) // load image
            .transform(new PicassoRoundedTransformation(20, 0)) // Add radius to the images
            .noFade()
            .into(holder.mimageView);
}

// total number of cells
@Override
public int getItemCount() {
    return mData.length;
}

// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    ImageView mimageView;

    ViewHolder(View itemView) {
        super(itemView);
        mimageView = itemView.findViewById(R.id.list_image);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
    }
}

// convenience method for getting data at click position
public String getItem(int id) {
    return mData[id];
}

// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
    this.mClickListener = itemClickListener;
}

// parent activity will implement this method to respond to click events
public interface ItemClickListener {
    void onItemClick(View view, int position);
 }

}

HomeImagesFragment "Fragment"
public class HomeImagesFragment extends Fragment {

private Picassotest adapter;
String[] chooseImages;

public HomeImagesFragment(String[] chooseImages) {
    this.chooseImages = chooseImages;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.images_fragment_home, container, false);

    /* ArrayList for chooseImages */
    chooseImages = new String[]{
            "https://quotess.cc/wp-content/uploads/2020/01/4688.jpg",
            "https://whatt.cc/wp-content/uploads/2018/07/4443.jpg",
            "https://quotess.cc/wp-content/uploads/2020/01/4688.jpg",
    };

    /* make new object and find the view "GridView" */
    RecyclerView recyclerView = rootView.findViewById(R.id.recyclerview_image_choose);
    // Calculate the items and auto-fit it on the screen
    int mNoOfColumns = Utility.calculateNoOfColumns(getActivity(), 140);
    recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), mNoOfColumns));
    adapter = new Picassotest(getActivity(), chooseImages);
    adapter.setClickListener(this);
    recyclerView.setAdapter(adapter);

    return rootView;
}

public void onItemClick(int position) {
    // get the image
    String image = chooseImages[position];
    Intent intent = new Intent(getActivity(), PicassoImageDisplayWallpaperAdapter.class);
    intent.putExtra("imageUrl", image);
    getActivity().startActivity(intent);
}

A: You need to create an interface like below code
interface  ItemClickListener{
    public void onItemClick(int position);
}

You need to implements ItemClickListener in your HomeImagesFragment
SAMPLE CODE
public class HomeImagesFragment extends Fragment implements ItemClickListener{

private Picassotest adapter;
String[] chooseImages;

public HomeImagesFragment(String[] chooseImages) {
    this.chooseImages = chooseImages;
}

@Override
public void onItemClick(int position) {
 // you will clikcked item position here
 String image = chooseImages[position];
Intent intent = new Intent(getActivity(), PicassoImageDisplayWallpaperAdapter.class);
intent.putExtra("imageUrl", image);
getActivity().startActivity(intent);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.images_fragment_home, container, false);

    /* ArrayList for chooseImages */
    chooseImages = new String[]{
            "https://quotess.cc/wp-content/uploads/2020/01/4688.jpg",
            "https://whatt.cc/wp-content/uploads/2018/07/4443.jpg",
            "https://quotess.cc/wp-content/uploads/2020/01/4688.jpg",
    };

    /* make new object and find the view "GridView" */
    RecyclerView recyclerView = rootView.findViewById(R.id.recyclerview_image_choose);
    // Calculate the items and auto-fit it on the screen
    int mNoOfColumns = Utility.calculateNoOfColumns(getActivity(), 140);
    recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), mNoOfColumns));
    adapter = new Picassotest(getActivity(), chooseImages);
    adapter.setClickListener(this);
    recyclerView.setAdapter(adapter);

    return rootView;
}

public void onItemClick(int position) {
    // get the image
    String image = chooseImages[position];
    Intent intent = new Intent(getActivity(), PicassoImageDisplayWallpaperAdapter.class);
    intent.putExtra("imageUrl", image);
    getActivity().startActivity(intent);
}

A: (Additional) Another way if you use Kotlin:
Sample Code
In Adapter class (Picassotest):
class Picassotest : RecyclerView.Adapter<Picassotest.ViewHolder>{

    internal var itemClickListener: (Int) -> Unit = {}

    inner class ViewHolder(itemView:View):RecyclerView.ViewHolder(itemView){
        init{
            itemView.setOnClickListener{
                itemClickListener.invoke(adapterPosition)
            }
        }
    }

}

In HomeImagesFragment:
class HomeImagesFragment{

adapter = new Picassotest(getActivity(), chooseImages)
adapter.itemClickListener = { position->
                             //TODO handle item on click here
    }

}


text:
Q: Installing pyDev and other plugins for Eclipse I still can't install any plugin for eclipse because of a ValidatorException

Unable to read repository at http://www.pydev.org/updates/content.xml.

sun.security.validator.ValidationException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to
find valid certification path to requested target

What should I do in that case?

A: I think this is a common certificate issue, which can happen because of multiple reasons. I'll list the 2 most likely to be the case here:

*

*The URL mentioned in the error does a redirect from HTTP to HTTPS, which java does not seem to like.
I'm not sure if this is still an issue in recent Java versions, could not find a better reference but they mention it here: https://github.com/protegeproject/protege/issues/17
Please try to change the update-site URL from http://www.pydev.org/updates/ to what it redirects to (which currently is: https://dl.bintray.com/fabioz/pydev/5.3.1/)

*The certificate could not be validated because the certificate issuers root certificate is not in your keystore. Make sure you have the most recent version of java installed (each new version contains a new keystore). You can also add the issuers root certificate (or the certificate of the site) into your keystore using the keytool.


text:
Q: Embed images after query results are returned using R, Shiny, DT and DBI I'm creating a Data Table in R Shiny that gets populated by a SELECT statement that pulls from a table in SSMS. One of the columns returns the text of an image located in the www folder where R pulls from. For example, if my query was:
SELECT Fruit, Image, Description
FROM tblFruit

It may return something like this in SQL:
Fruit  |  Image      |  Description
-----------------------------------
apple  |  apple.png  |  red apple
orange |  orange.png |  orange orange
banana |  banana.png |  yellow banana

My Data Table in R resembles just that, but my goal is to replace the text "apple.png" with the actual image that lives in the www folder. Is this possible?
Here's a mock up/snippet of what my app.R looks like :
library(dplyr)
library(DBI)
library(plotly)
library(shiny)
library(shinydashboard)
library(RJDBC)
library(readxl)
library(DT)
library(htmltools)
library(shinyBS)

conn <- dbConnect(drv, "jdbc:sqlserver://SQLServer;databaseName=DEV", Sys.getenv("userid"), Sys.getenv("pwd"))

sqlSelect = trimws("SELECT Fruit, Image, Description FROM tblFruit ")
sqlWhere = "WHERE Fruit in ('Apple','Orange','Banana')"

body <- dashboardBody(class="text-center",
                        tabItem("fruit", class ="text-center",
                                fluidRow(
                                  tabBox(title = "Fruit", id = "FruitID",
                                         tabPanel(title = 'Fruit',
                                                  fluidRow(
                                                    box(width=12,
                                                        div(DT::dataTableOutput(outputId = "DT_Fruit"), style="font-size:125%", class ="text-left")
                                                    )
                                                  )
                                         )
                                  ) # tabBox
                                ) # fluidRow
                        ) # tabItem fruit
                      ) # tabItems
) # body

server <- function(input, output){
    output$DT_Fruit <- DT::renderDataTable({
      DT::datatable(options = list(dom = 't'), rowname = FALSE, dbGetQuery(conn, paste(sqlSelect, sqlWhere)))
    })
}

Edit: Per the first comment here, I'm not having issues reading from the www folder. I'm wanting to replace the text (ex. "apple.png") returned from my query with an image named apple.png from the www folder. I'm more or less looking for direction/advice on how to best approach this.

A: It still seems like you are having issue displaying images in DT table, if that's your question.
Convert apple.png to a img tag in HTML using glue::glue() or paste0(), and set escapse = FALSE so DT will parse it as HTML.
Please see the example below, just replace value in src with your image path.
library(DT)
DT::datatable(
    data.frame(
        images = c(
            "",
            ""
        )
    ),escape = FALSE
)

A: Could you try this:
render <- c(
  "function(data, type, row, meta) {",
  "  if(type === 'display'){",
  "    var img = '';",
  "    return img;",
  "  }else{",
  "    return data;",
  "  }",
  "}"
)

and in server:
output$DT_Fruit <- renderDT({
  datatable(
    dbGetQuery(conn, paste(sqlSelect, sqlWhere)),
    rownames = FALSE,
    options = list(
      dom = "t",
      columnDefs = list(
        list(targets = 1, render = JS(render))
      )
    )
  )
})


text:
Q: Como hago para que el programa detecte datos duplicados dentro de una matriz en java Basicamente lo que quiero hacer es, dentro de java, que el programa vaya comparando con una variable una matriz con todos los nombres ya existentes, y de ahi detecte si hay dos o varios nombres repetidos y me lo cuente.
public static void main(String[] args) {
    String [][] nombres = new String [1][6];
    String repetido="";
    int contador = 1;

    nombres[0][0]="Juan";
    nombres[0][1]="Aurelia";
    nombres[0][2]="Martin";
    nombres[0][3]="Mauro";
    nombres[0][4]="Juan";
    nombres[0][5]="Martin";

    for (int i = 0; i < 1; i++) {
        for (int j = 0; j < 6; j++) {
            for (int k = 0; k < 1; k++) {
                for (int l = 0; l < 6; l++) {
                    repetido = nombres [k][l];
                    if (repetido.equals(nombres[k][l])){
                        System.out.println("{"+k+"] "+"{"+l+"}");
                        contador++;
                    }else{
                        return;
                    }
                }
            }
        }
    }
    System.out.println(contador);
}

}

A: No necesitas un array bidimensional para almacenar una lista de nombres, por lo demás, aquí te dejo un ejemplo de cómo podrías comparar los nombres de un array, si quieres hacerlo bidimensional solo tienes que adaptarlo como veas oportuno.
    public static void main(String[] args) {
        String[] nombres = new String[6];
        int contador = 0; //Inicializamos contador a 0

        nombres[0]="Juan";
        nombres[1]="Aurelia";
        nombres[2]="Martin";
        nombres[3]="Mauro";
        nombres[4]="Juan";
        nombres[5]="Martin";

        for(int i=0;i<nombres.length;i++){//Primer bucle para recorrer el array nombre por nombre
            if(nombres[i].equals(""))//Si el nombre ha sido eliminado, continua sin entrar al bucle de j
                continue;
            for(int j=0;j<nombres.length;j++){//Segundo bucle para comparar cada nombre con todos los demás
                if(j != i && nombres[i].equals(nombres[j])){/*Si i es igual a j, está
                comparando el mismo nombre, eso sería un falso positivo así que lo evito*/
                    nombres[j] = "";//Borro el nombre para evitar compararlo de nuevo
                    contador++;
                }
            }
        }
        System.out.println(contador);
    }

Te dejo aclaraciones en los comentarios

A: Utilizando como base lo propuesto por @Benito-B, utilize solo un arreglo de (String[]) en lugar de un array (String[][]).
Lo que te propongo es que crees un Diccionario (Aquí la implementación de la clase Dictionary es HashTable) con ese arreglo, que pongas como llave el nombre de las personas, y como el valor que posee esa llave el número de repeticiones del nombre. Así podrás en una sola iteración imprimir los nombres repetidos.
Enseguida te muestro el código que elabore:
import java.util.Hashtable;
import java.util.Enumeration;
import java.util.List;
import java.util.Arrays;

class Main {
  public static void main(String[] args) {
    List<String> nombres = Arrays.asList(new String[]{"Juan","Aurelia","Martin","Mauro","Juan","Martin","Martin"});
    Hashtable<String,Integer> diccionario = new Hashtable<>();
    for(String nombre: nombres) {
      if(diccionario.containsKey(nombre)){
        diccionario.put(nombre,diccionario.get(nombre).intValue() + 1);
      } else {
        diccionario.put(nombre,1);
      }
    }
    for(Enumeration<String> claves = diccionario.keys(); claves.hasMoreElements();) {
      String nombreActual = claves.nextElement();
      int repetido = diccionario.get(nombreActual);
      if(repetido > 1){
        System.out.printf("El nombre %s esta repetido %d veces.\n", nombreActual, repetido);
      }
    }
  }
}


text:
Q: how to have nested lists in Lua I am trying to solve this problem from the 99 lisp problems

Flatten a nested list structure.
Transform a list, possibly holding lists as elements into a `flat' list by replacing each list with its elements (recursively).
Example:

(my-flatten '(a (b (c d) e)))
(A B C D E)

Hint: Use the predefined functions list and append.

Problem is, I don't know how to create that nested list to begin with so I can try to flatten it myself. Please help thankyou

A: In Lua "a list possibly holding lists as elements" is just a table possibly holding tables as elements.
From the Lua manual:

Tables can be heterogeneous; that is, they can contain values of all
types (except nil).
...
Like indices, the values of table fields can be of any type

That of course includes tables.
The most trivial case is local t = {{}} or for the mentioned example (a (b (c d) e)) local t = {a, {b, {c, d}, e}}
Assuming a,b,c,d and e are strings your list would look like so:
local t = {"a", {"b", {"c", "d"}, "e"}


text:
Q: using Twitter API Stream for multiple twitter accounts? I am working on a project where audio files on a raspberry pi are triggered by tweets from specific accounts.
I am using node.js and the npm twit package. I have been able to get it work when using two different twitter accounts. However, when I try to do it with multiple accounts (15+), it is not working.
My working code is this:
var userID1 = 'XXXXXXX'; //userID of first account
var userID2 = 'XXXXXXX'; //UserdIp of Second account

//Following code set up stream just for USERID1
var stream = T.stream('statuses/filter', { follow: ( userID1 ) });
stream.on('tweet', function (tweet) {

// two variables to store tweet time  and actual tweet
var tweetTime = new Date().toLocaleString();
var printTweet = tweet.text;

if (tweet.user.id == userID1 ) {

    printTweet.toString()//converts printTweet to String
    console.log(printTweet) //prints tweet as variable
    console.log("Tweet has been received from UserID1 + tweetTime");
    audio();
  }
});

//Following code set up stream just for USERID2
var stream = T.stream('statuses/filter', { follow: (  userID2 ) });
stream.on('tweet', function (tweet) {

// two variables to store tweet time  and actual tweet
var tweetTime2 = new Date().toLocaleString();
var printTweet2 = tweet.text;

    if(tweet.user.id == userID2 ) {

        printTweet2.toString()//converts printTweet to String
        console.log(printTweet2) //prints tweet as variable
        console.log("Tweet has been received from UserID2" + tweetTime2);
        audio();

    }

 });

As I mentioend when I add multiple accounts it does not work.
It does not throw up an error message instead it just freezes (no reaction to tweets).  I thought the problem might be that I only needed either one var stream or one instance of stream.on so I tried this:
var userID1 = 'XXXXXXX'; //userID of first account
var userID2 = 'XXXXXXX'; //UserdID of Second account
var userID3 = 'xxxxxxx'; //user ID pf third account
//I then have userID of another 15 accounts.

//Following code set up stream just for all user IDs
var stream = T.stream('statuses/filter', { follow: ( userID1, userID2, ****15 more userID***** ) });

//just one stream.on for all followed twitter accounts
stream.on('tweet', function (tweet) {

//conditional for userID1
if (tweet.user.id == userID1 ) {

    // two variables to store tweet time and actual tweet
    var tweetTime = new Date().toLocaleString();
    var printTweet = tweet.text;

    printTweet.toString()//converts printTweet to String
    console.log(printTweet) //prints tweet as variable
    console.log("Tweet has been received from UserID1 + tweetTime");
    audio();
  }

//conditional for userID2
    if(tweet.user.id == userID2 ) {

        // two variables to store tweet time and actual tweet
        var tweetTime = new Date().toLocaleString();
        var printTweet = tweet.text;

        printTweet2.toString()//converts printTweet to String
        console.log(printTweet2) //prints tweet as variable
        console.log("Tweet has been received from UserID2" + tweetTime2);
        audio();

}

//same conditional above done 15 more times for other accounts

 });

But again it just freezes.
Any suggestion would be great.

A: There's a problem with the way you declare follow list. It should be a comma-separated list of user ids, while in your code you just use comma-operator. Try changing it to something like this:
{ follow: [ userID1, userID2, ... , userID17 ].join(',') }

in your second example of code (which is better in my opinion), so the resulting code would look like this:
var stream = T.stream('statuses/filter', { follow: [ userID1, userID2, ... , userID17 ].join(',') });

//just one stream.on for all followed twitter accounts
stream.on('tweet', function (tweet) {

//conditional for userID1
if (tweet.user.id == userID1 ) {

    // two variables to store tweet time and actual tweet
    var tweetTime = new Date().toLocaleString();
    var printTweet = tweet.text;

    printTweet.toString()//converts printTweet to String
    console.log(printTweet) //prints tweet as variable
    console.log("Tweet has been received from UserID1 + tweetTime");
    audio();
  }

//conditional for userID2
    if(tweet.user.id == userID2 ) {

        // two variables to store tweet time and actual tweet
        var tweetTime = new Date().toLocaleString();
        var printTweet = tweet.text;

        printTweet2.toString()//converts printTweet to String
        console.log(printTweet2) //prints tweet as variable
        console.log("Tweet has been received from UserID2" + tweetTime2);
        audio();

}

//same conditional above done 15 more times for other accounts

 });


text:
Q: Installing ubuntu to a specific disk drive alongside Windows 7 on separate disk I have deleted an entire disk drive (120 GB ssd) for ubuntu to be installed on.  However, when I install ubuntu 13.04 from DVD, it never prompts me as to which disk drive to install on.
Unfortunately, something is failing at the very end, so I have no idea where ubuntu is trying to install, but I'd at least like to make sure it is installing to the completely unallocated disk drive.

A: When you get the options on where to install Ubuntu you can chose between installing it alongside Windows, erasing the disk or something else.
Installing it alongside Windows will shrink your Windows partition and create a new one. If you already created one, that isn't detected. So what you want to chose is something else.
Just follow the official instructions on this.
If you already picked the first option you might now have ended up with a Windows partition that is too small to boot. You can fix this by booting the Live-CD/USB to the desktop ("just try Ubuntu, don't install"). Now run gparted to view all your harddrives and partitions. Delete the Ubuntu partitions and resize the Windows partition to the maximum. While you're at it, you can also use gparted to easily create the partitions you need on your second drive (chose it in the top right) and then just select them in the Ubuntu installer.
When manually installing Ubuntu on a second harddrive (/dev/sdb) you probably want the bootloader GRUB to be on the first harddrive (/dev/sda) so make sure your selection looks sound.

A: I used to installing ubuntu in a separate drive using the installation process guide.  It is simple, easy if you follow the steps well, also I advice to install the grub on the same drive to prevent problems with my windows drive beside if you decide or accedently format your ubuntu drive you still have your. Windows drive untouched.


text:
Q: Mixing Gremlin, OpenCypher and SPARQL AWS Neptune being on a lower level a triple-store (presumably a BlazeGraph fork), it can be queried via SPARQL. At the same time, one can use Gremlin and OpenCypher but as far as I can tell these do not access the triple data (and vice versa). That is, it looks like the property graph is separate from the triples. Is this correct or am I missing something obvious? Can one fetch property-graph data with SPARQL, can one query triples with Gremlin/OpenCypher?

A: Property Graph and RDF data are stored separately inside of Neptune.  If you write data via the /sparql endpoint, it can then only be accessed via SPARQL thereafter.  Similar situation if you write via the /gremlin or /oc endpoints, although Property Graph data can be simultaneously accessed via either Gremlin or openCypher.


text:
Q: mongo aggregation:- push all fields using Spring if I have a collection of books :-
{author: "tolstoy", title:"war & peace", price:100, pages:800}
{author: "tolstoy", title:"Ivan Ilyich", price:50,  pages:100}

and if i want a result like this after grouping them by author :-
{ author: "tolstoy",
   books: [
      {author: "tolstoy", title:"war & peace", price:100, pages:800}
      {author: "tolstoy", title:"Ivan Ilyich", price:50,  pages:100}
]
}

using raw mongo queries I can do something like this:-
{$group: {
 _id: "$author",
 books:{$push: {author:"$author", title:"$title", price:"$price", pages:"$pages"}},
}}

But how do I do this using spring , I tried something like this:-
 private GroupOperation getGroupOperation() {
    return group("author").push("title").as("title").push("price").as("price").push("pages").as("pages");
}

but this does not seem to work. Any help would be appreciated.

UPDATE:-
I used the solution as in the link suggested by @Veeram and it works great but I ran into another issue when I project it. I have my projection class which looks like:-
public class BookSummary{

private String author;

private List<Book> bookList;
  //all getters and setters below
}

The group method looks like this:-
 private GroupOperation getGroupOperation() {
    return group("author").push(new BasicDBObject("id","$_id").append("title","$title").append("pages","$pages").append("price","$price")).as("bookList");
}

the projection method looks like this:-
private ProjectionOperation getProjectOperation() {
    return project("author").and("bookList").as("bookList");
}

and the final aggregation operation:-
mongoTemplate.aggregate(Aggregation.newAggregation(groupOperation,projectionOperation), Book.class, BookSummary.class).getMappedResults();

However this gives the result:-
[
{
    "author": null,
    "bookList": [
        {
            "id": null,
            "title": "title1",
            "pages": "100",
            "price":"some price"
        },
        {
            "id": null,
            "title": "title2",
            "pages": "200",
            "price":"some price"
        }
    ]
}
]

Why is the author and id null here? Any help would be appreciated

A: You should be projecting using _id instead in the project phase.
private ProjectionOperation getProjectOperation() {
    return project("_id").and("bookList").as("bookList");
}


text: Q: Не пушатся изменения в репозиторий git Я создаю репозиторий git в Linux. И когда пытаюсь записать изменения в этот репозиторий из под Windows, изменения не записываются. Ошибок не выдаёт. Зависает в момент команды git push origin master. Иногда когда принудительно отменяешь выгрузку изменений, изменения появляются в репозитории. Как с этим бороться? Как следует настроить репозиторий из под Linux, чтоб в него выгружались изменения из Windows?


text:
Q: F# - Which ORM to choose? I've just started playing with F#, and was wondering whether there is any recommended ORM's out there, for F#.
In C# I used NHibernate, which seems to be quite hard and ugly to implement in F#. I've also thought about using plain old System.Data.SqlClient, but thats like going back to the stone age...
Any suggestions?

A: I've been using F# support for LINQ to SQL when working on fssnip.net. It is fine when you need to load, edit, insert entities and it is fine for writing simple queries. It has some nice aspects e.g. you can use splicing to compose parts of a query.
However, the current implementation of F# to LINQ translator doesn't handle complex queries (nested function calls, advanced grouping and joins), so I wrote a few stored procedures. These can be nicely called via generated LINQ objects, but you have to write some SQL.
Alternatively, if you wanted to use the old fashioned SqlClient, you could make it nicer by using the dynamic (?) operator. I wrote about this in this blog post. For simple scenarios, this could be quite good technique, because it is very simple.

A: This may be missing the point (like if this is just for education or fun), but if you already know how to use an ORM in C#, why not just do it in C# as a library and then do the rest of the logic in F#?  One of the major selling points for .NET languages is interoperability.

A: I've been using LINQ to SQL via the F# PowerPack. I'm using manual mapping (ie. creating my datacontext by hand, creating my POCO classes as well as writing the XML file to define my database layout). It seems to work well in F# from what I've done so far.

A: Two options for interacting with databases using F# that might be of use are FSharp.Data.SqlClient and SQLProvider.


text:
Q: See who is on the same page in CodeIgniter I am using CodeIgniter and I connect to a remote database. Only people who are in the table "users" are allowed to log in through session. Some of the tables in the DB can be edited on the site and a form sends the info to the Model (which then updates the info to the DB), what I want to do is the site to tell you who is on the edit page aswell like "John Doe is already editing this table". Is it possible to achieve it with session or something else?
Thankfull for any response.

A: You can get the current URI with this method (be sure to load the URI helper):
$this->uri->uri_string();

Then I would keep a users table, since they're required to log in, you should already have this, then also keep a field which indicates whether they are logged in or not, then a nullable field indicating which page they are on. Then when you're on an admin/edit page, you can query all users which page = {admin/edit page}, and display which users are on this page.
Let me know if you have any other questions.


text:
Q: this._super() issue when an object is created In the new EmberRC1 version, it seems that we cannot call super class method from a created object. I have some standard mixins and views which i use to either create or extend to some other objects. I have some methods overriden, but still i needed to execute super methods which we can acheive in previous versions using this._super(). But in the newer version, when i create an object, this is not happening.
    window.App = Ember.Application.create();

App.Router.map(function(){
    this.resource("users");
});

App.UsersView = Ember.ContainerView.extend({
    init : function(){
        this._super();
        this.pushObject(App.TestView.create({
            didInsertElement : function() {
               this.$().append('

Appended at Object
 ');
            }
        }))
    }
});

App.TestView=Ember.View.extend({
    templateName:'test',
    didInsertElement : function() {
       this.$().append('

Appended at Class
 ');
    }
});

So is this part completely removed or we can acheive this super calling some other way?
To understand my problem here is the jsfiddle.
PS: I know that i can have the code that needs to be executed with some other methodname and call the same method. But it would be nice if i have solution for this.

A: You can still call this._super() from an init method and it will call the parent. What has been removed is calling create on an object and passing in an init method. There is a createWithMixin method that still allows that functionality.
There is a pretty detailed post about this functionality here:
Difference between .create() and .createWithMixins() in ember


text:
Q: How to create initialized Spring bean (in session scope) I am trying to create multi-tab (JavaScript tabs) interface for Spring/facelets application and I have s.c. window manager that holds array of windows (tabs). Each window (tab) contains Spring bean (session scope) which receive (as injections) other spring beans, e.g. for business services, DAO beans and so on. I am using Primefaces p:tabView for facelets part.
When user creates new tab, the new Spring bean (as part of the window/tab) should be created and added to the window manager bean (WindowManager.addWindow(...) has method that is colled from the p:commandButton and that creates window/tab and its session been). The question is - how to create this bean and initialize it (with injected beans)? One solution maybe is to call ctx.getBean("beanName"), but I am afraid to use this because it has name and this name seems to be unique.
Maybe programmatical creation of Spring beans is not good design (they should be created automatically but the web server/Spring context when they process the web requests), but it seems to be necessary in my case.

A: You must define that bean with scope "prototype", this setting causes that Spring context create a new fresh instance in every call to context.getBean("beanName");
To configure that, you can use:
@scope("prototype")

or
<bean id="beanName" class="com.foo.myBean" scope="prototype"/>

Depending on whether you are using java or xml configuration. Take a look to the Spring documentation for more details:
http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch04s04.html


text:
Q: XSL Transformation - Turning a list into nested elements, How Can I do that? I have a bunch of messages that are in older schema version. I want to consume the messages
from the older schema and then transform them to the new schema form. I really appreciate it
if anyone can help me with this.
My New Schema
<Audit>
       <time>12:35</time>
       <number>13354</number>
       <previousAudit>
               <time>2:54</time>
               <number>12667</number>
               <previousAudit>
                      <time>7:05</time>
                      <number>10659</number>
                      <previousAudit/>
               </previousAudit>
       </previousAudit>
</Audit>

My Old Schema
-------------

<MyAuditList>
<Audit>
       <time>12:35</time>
       <number>13354</number>
</Audit>
<Audit>
       <time>1:27</time>
       <number>13650</number>
</Audit>
<Audit>
       <time>7:05</time>
       <number>10659</number>
</Audit>
</MyAuditList>

So I want to recursively read my Old Schema (Message's Audit List and Nest it in Previous Audit form as above) , How
can I acheieve something like this in xsl ? Thank you so much in advanced for your help.

A: Use:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="MyAuditList">
    <Audit>
      <xsl:copy-of select="Audit[1]/*"/>
      <xsl:apply-templates select="Audit[2]"/>
    </Audit>
  </xsl:template>

  <xsl:template match="Audit">
    <previousAudit>
      <xsl:copy-of select="*"/>
      <xsl:apply-templates select="following-sibling::Audit"/>
    </previousAudit>
  </xsl:template>

</xsl:stylesheet>

Output:
<Audit>
  <time>12:35</time>
  <number>13354</number>
  <previousAudit>
    <time>1:27</time>
    <number>13650</number>
    <previousAudit>
      <time>7:05</time>
      <number>10659</number>
    </previousAudit>
  </previousAudit>
</Audit>

If you have to output empty previousAudit use this one:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="MyAuditList">
    <Audit>
      <xsl:copy-of select="Audit[1]/*"/>
      <previousAudit>
        <xsl:apply-templates select="Audit[2]"/>
      </previousAudit>
    </Audit>
  </xsl:template>

  <xsl:template match="Audit">
    <xsl:copy-of select="*"/>
    <previousAudit>
      <xsl:apply-templates select="following-sibling::Audit"/>
    </previousAudit>
  </xsl:template>

</xsl:stylesheet>

Output:
<Audit>
  <time>12:35</time>
  <number>13354</number>
  <previousAudit>
    <time>1:27</time>
    <number>13650</number>
    <previousAudit>
      <time>7:05</time>
      <number>10659</number>
      <previousAudit />
    </previousAudit>
  </previousAudit>
</Audit>


text:
Q: Build size is much larger than what's logged in editor.log to my knowledge the "Complete size" value in the editor log should be the total size of my build. But as you can see from the screenshot below, my editor.log is saying that the "Completed size" is 27.7MB, while the build size in the file system is actually 145MB. Am I missing something here, or am I doing something wrong? Thanks in advance!
Editor.log screenshot:

Screenshot of size in the file system:

A: See the links,

*

*Build options can make different size for outputs.  such as Arm, Fat and etc..
 etc..

*"Resources", "Streaming Assets" directory are not included in Editor.log file. so check that your project directories, If you have, output size will be bigger than description of Editor.log file.


text:
Q: my python3 threading prog didnt work with fifo-queue That's my code:
import threading
import queue

qq=queue.Queue(10)
def x11grab(n):
    print('haha')
    while True:
        a='abcd'+str(n)
        n+=1
        qq.put(a)
        print('put queue:',a)

def rtpsend():
    while True:
        s=qq.get()
        head=s[:4]
        body=s[4:]
        print('head',head)
        print('body',body)

t1=threading.Thread(target=x11grab,args=(1,))
t2=threading.Thread(target=rtpsend)
t1.start
t2.start

I wanna x11grab() function put string 'abcd1','abcd2'... into queue,and rtpsend() function get the string from queue, and display it. It's a demo, but it didn't work. I think your advice could be helpful.:-)

A: You never start your threads! change
t1.start
t2.start

to
t1.start()
t2.start()


text:
Q: Getting error while adding data to Silverlight charts? I tried to add values to a silverlight line chart. For that i created a line chart and then the data in that chart is being added using wcf ria services.
Everthing works fine but when i try to run my website it loads some dummy data in the chart. There is no data like that in my windows azure sql table.
It access the azure sql table and works fine but the values are not same in my database.
To show access the database from azure app, i used ado.net entity model and which created a  waterinfodomain and i used this code and similar of other line charts.
I used :
    private GetTemprature()
            {
                //shows and gives garden uses from sql table
                context = new WaterDomainContext();
                context.FarmTemps.Clear();
                var query = context.GetFarmTempsQuery();
                LoadTemp = context.Load<FarmTemp>(query);
                LoadTemp.Completed += new EventHandler(LoadTemp_Completed);
            }

            private void LoadTemp_Completed(object sender, EventArgs e)
            {
                //Draw values from a table for Performance
                List<Temprature> tmp = new List<Temprature>();
                if (LoadTemp.Entities != null || LoadTemp.Entities.Count() > 0)
                {
                    foreach (FarmTemp item in LoadTemp.Entities)
                    {
                        tmp.Add(new Temprature()
                        {
                            Temp = (float)(item.Temp),
                            Date = Convert.ToDateTime(item.ODate)
                        });
                    }
                }
                LineSeries tmpv = FarmCondtion.Series[0] as LineSeries;
                tmpv.ItemsSource = tmp;

            }

I have added this snapshot of what chart i am getting here : http://i.imgur.com/bZkxZ.png
Now you can see the dates are not in regular order [Also these are not the date which are in my database] and only Dots are shown instead of lines.
But my database does have only regular values of date for last seven days and other values.
Why this is happening
Please tell me
Thanks

A: My first bet would be that the problem lies with the Convert.ToDateTime method. I suppose that item.ODate is a string you're converting to DateTime.
It would be safer to convert to DateTime by passing the correct culture. For example, 10/1/2012 isn't the same in en-US as it is in nl-BE. That's why it's important to always specify in which culture you're converting the string from (reference: http://msdn.microsoft.com/en-us/library/9xk1h71t.aspx).
Now on the other hand. Why are you expecting to see the dates in the right order? I don't see any code that sorts the items based on the date. Are you doing this in the backend?

A: You mentioned the same data works fine in one chart, but not in another. Are there any differences between the two charts? I think the issue is on the client side, as you've verified the data is fine in both database and one of the chart. So please focus on the client side now, check how you configure the charts' data source. By the way, as far as I can tell from the screenshot, the date is in order. It starts from 11/1/2011, goes to 12/1/2011, and then 1/1/2012, all the way to 10/1/2012. The chart is a little small, so the labels are displayed on two lines. Please do not read the first line and then the second line. Instead, read the two lines together, from left to right. Something like:
1   3   5
  2    4   6

If you mean the date should not be in the future, then please check if you have any code that may alter the dates.
Best Regards,
Ming Xu.


text:
Q: authenticated and anonymous for the same endpoind (spring security) What i want is, for
localhost:8080/home -> should be open to only authenticated - home page after login
localhost:8080/home?msg=asdsada -> should be open to anonymous - for login errors like wrong password

This is endpoind:
@GetMapping(value = { "/home"})
    public ModelAndView getLoginPage(
                                     @RequestParam(value = "msg", required = false) String message) throws IOException

I tried to add this to security config of spring
.regexMatchers("/home").authenticated()
.regexMatchers("/home?msg=.*").permitAll()

So config became like this:
http
            .authorizeRequests().antMatchers(anonymousEndpoints).anonymous()
            .antMatchers(permittedEndpoints).permitAll()
            .regexMatchers("/home").authenticated()
            .regexMatchers("/home?msg=.*").anonymous()
            .and()
            .authorizeRequests().anyRequest().fullyAuthenticated()

But for wrong password, it does not go to endpoind
localhost:8080/home?msg=asdsada

For logged user, it can go to
localhost:8080/home

also it can go to
localhost:8080/home?msg=asdsada

What am I doing wrong? I can also use endpoind to check if logged in or not. Like:
But i want spring scurity to do this. Give 403 forbidden for example.
@GetMapping(value = { "/home"})
    public ModelAndView getLoginPage(
                                     @RequestParam(value = "msg", required = false) String message) throws IOException{

        Authentication authentication = SecurityUtil.getAuthentication(false);
        if (authentication != null) {
            logger.info("User: {} already logged in, redirecting to dashboard", authentication.getName());
            web.response.sendRedirect("/dashboard");
            return null;
        }
else{//not logged in

if (msg != null)//and msg is not null so like wrong password
//do smth
}
return null;
}

A: Don't configure the specific path in Spring Security Config, just analyze it in the controller method. In config set permitAll for this path, but add an authentication or principal parameter in the method signature:
@GetMapping(value = { "/home"})
public ModelAndView getLoginPage(@RequestParam(value = "msg", required = false) String message, Authentication authentication) throws IOException {
    if (msg != null) {
        ...
    } else if (!authentication.isAuthenticated()) {
        ...
    }
    ...
}

P.S. Method arguments: https://docs.spring.io/spring/docs/5.2.x/spring-framework-reference/web.html#mvc-ann-arguments


text:
Q: Alternating sum of Stirling numbers equals 0 How can I prove that the following formula is true for Stirling numbers of first kind.

For any $n \geq 2$, we have
$$\sum_{k=1}^n(-1)^k\left[\begin{matrix} n\\k\end{matrix}\right] =0$$

Actually I want to prove that the number of permutations of $\left\{1,2,\ldots,n\right\}$ with an even number of cycles equals the number of permutations of $\left\{1,2,\ldots,n\right\}$ with an odd number of cycles. This is equivalent to the above identity by the combinatorial interpretation of Stirling numbers.

A: Note that you have to assume that $n \geq 2$: when $n = 1$, the sum equals $-1$.
Combinatorial proof
It's enough to find a bijection on permutations which changes the parity of the number of cycles. One possibility is the following. Write a permutation as a product of cycles. If $1$ and $2$ belong to the same cycle $(1\alpha 2\beta)$, replace it with two cycles $(1\alpha)(2\beta)$; and vice versa. For example, here is the bijection for $S_4$:
$$
(1)(2)(3)(4) \leftrightarrow (12)(3)(4) \\
(1)(2)(34) \leftrightarrow (12)(34) \\
(13)(2)(4) \leftrightarrow (132)(4) \\
(14)(2)(3) \leftrightarrow (142)(3) \\
(134)(2) \leftrightarrow (1342) \\
(143)(2) \leftrightarrow (1432) \\
(1)(23)(4) \leftrightarrow (123)(4) \\
(1)(24)(3) \leftrightarrow (124)(3) \\
(1)(234) \leftrightarrow (1234) \\
(1)(243) \leftrightarrow(1243) \\
(13)(24) \leftrightarrow (1324) \\
(14)(23) \leftrightarrow (1423)
$$
Inductive proof
Another option is to use the formula
$$
\newcommand{\stirling}[2]{\left[{#1 \atop #2}\right]}
\stirling{n+1}{k} = n\stirling{n}{k} + \stirling{n}{k-1}.
$$
When $n=2$ the claim is true by inspection. Suppose now that it holds for some $n$. Then
$$
\begin{align*}
\sum_{k=1}^{n+1} (-1)^k \stirling{n+1}{k} &= n\sum_{k=1}^n (-1)^k \stirling{n}{k} + \sum_{k=2}^{n+1} (-1)^k \stirling{n}{k-1} \\ &=
n\sum_{k=1}^n (-1)^k \stirling{n}{k} - \sum_{k=1}^n (-1)^k \stirling{n}{k} \\ &= 0.
\end{align*}
$$

A: Here is an algebraic proof. The combinatorial species of permutations with cycles marked is given by $$\mathfrak{P}(\mathcal{U}\mathfrak{C}(\mathcal{Z}))$$
which yields the generating function
$$G(z,u) = \exp\left(u\log\frac{1}{1-z}\right).$$
This immediately produces
$$\left[ n\atop k\right] = n! [z^n] \frac{1}{k!}\left(\log\frac{1}{1-z}\right)^k.$$
Substitute this into the sum to get
$$n! [z^n] \sum_{k=1}^n \frac{(-1)^k}{k!}\left(\log\frac{1}{1-z}\right)^k.$$
Supposing we have $n\ge 1$ we may extend the lower limit to include zero and the upper limit to infinity because $\log\frac{1}{1-z}$ starts at $z.$ This gives
$$n! [z^n] \sum_{k=0}^\infty \frac{(-1)^k}{k!}\left(\log\frac{1}{1-z}\right)^k.$$
Simplify to obtain
$$n! [z^n] \exp\left(-\log\frac{1}{1-z}\right) = n! [z^n] (1-z).$$
We assumed that $n\ge 1$ so this gives minus one for $n=1$ and zero otherwise. Indeed there is one permutation on $1$ element and it consists of a single odd cycle.


text:
Q: $f(x)=\frac{9}{2x-3}$ as a series? The issue here (I think) is just the $c$ part:
I have to represent
$$f(x)=\frac{9}{2x-3}$$ as a series at center $c=6$, I don't want to see any Taylor Series or Maclaurin Series (we'll be working with that this week).
I started by trying to represent it as $\frac{a}{1-r}$ which equals the series
$$\sum_{n=1}^{\infty}ar^n$$
so here goes:
$$f(x)=\frac{9}{2x-3}$$
$$=\frac{9}{-3-(-2x)}$$
$$=\frac{-3}{1-(\frac{2}{3}x)}$$
$$=\sum_{n=1}^{\infty}(-3)\biggl(\frac{2}{3}x\biggr)^n$$
But I'm confused on how to deal with the $c=6$ part, I tried
$$=\sum_{n=1}^{\infty}(-3)\biggl(\frac{2}{3}(x-6)\biggr)^n$$ but it was wrong according to my homework, how do I deal with center at $c=6$?

A: Hint: $\dfrac{9}{2x-3} = \dfrac{9}{2(x-6)+9} = \dfrac{1}{\frac{2}{9}(x-6)+1}$

A: Hint:
$$f(x) = \frac{9}{2x-3} = \frac{9}{2(x - 6) + 9}.$$
Can you continue? Take $z = x - 6$ if required.


text:
Q: Make two simple regex's into one I am trying to make a regex that will look behind .txt and then behind the "-" and get the first digit .... in the example, it would be a 1.
$record_pattern = '/.txt.+/';
preg_match($record_pattern, $decklist, $record);
print_r($record);

.txt?n=chihoi%20%283-1%29

I want to write this as one expression but can only seem to do it as two.  This is the first time working with regex's.

A: You can use this:
$record_pattern = '/\.txt.+-(\d)/';

Now, the first group contains what you want.

A: Your regex would be,
\.txt[^-]*-\K\d

You don't need for any groups. It just matches from the .txt and upto the literal -. Because of \K in our regex, it discards the previously matched characters. In our case it discards .txt?n=chihoi%20%283- string. Then it starts matching again the first digit which was just after to -
DEMO
Your PHP code would be,
<?php
$mystring = ".txt?n=chihoi%20%283-1%29";
$regex = '~\.txt[^-]*-\K\d~';
if (preg_match($regex, $mystring, $m)) {
    $yourmatch = $m[0];
    echo $yourmatch;
    }
?> //=> 1


text:
Q: Blackberry Facebook prob: Could not select proper Transport decriptor I am using Blackberry Facebook SDK (FacebookBlackBerrySDK-v0.8.25.jar) for facebook integration for my app. I am using the following code.
ApplicationSettings as = new ApplicationSettings(NEXT_URL, APPLICATION_ID, APPLICATION_SECRET, PERMISSIONS);
Facebook fb = Facebook.getInstance(as);
User user = fb.getCurrentUser();

I have tested the app in simulator of OS 5.0 and device and simulator of OS 6.0. it is working fine. But when I am testing the same in a device of OS 5.0, it is giving "Could not select proper Transport descriptor". What may be the problem behind it? Is it related to the device? How to solve the problem?

A: Download the SDK source code and change the ConnectionFactory parameters in  com.blackberry.util.ui.BrowserScreen.


text:
Q: Find $f$, such that $e^{f'(x)}+f(x)=e^{-x^2}+e^{-2xe^{-x^2}},\ \forall x\in\mathbb{R}$ I have constructed a great exercise but now I don't know how to solve it without using sequences. My original thought was kind of "EVT in an open interval" with reductio ad absurdum. Can you help me solve it?

Let $f:\mathbb{R}\to\mathbb{R}$ be a differentiable function, such
  that $e^{f'(x)}+f(x)=e^{-x^2}+e^{-2xe^{-x^2}},\ \forall x\in\mathbb{R}$ and $\lim_\limits{x\to +\infty}{f(x)}=\lim_\limits{x\to -\infty}{f(x)}=0$. Find $f$.

A: Well, simply by inspection:
$$e^{\color{red}{f'(x)}}+\color{blue}{f(x)}=\color{blue}{e^{-x^2}}+e^{\color{red}{-2xe^{-x^2}}}$$
Gives you $\color{blue}{f(x)=e^{-x^2}}$...
This also satisfies:
$$\lim_{x \to +\infty} e^{-x^2} = \lim_{x \to -\infty} e^{-x^2} = 0$$
But I assume you're looking for a more general approach?


text:
Q: Django upload multiple files many to many I want to know, is it my code ok?
What i want: create form with feature uploading multiple files.
Can someone say about many-to-many? Is it ok?
I want to upload many files. How it can be?

from __future__ import unicode_literals
import uuid
from django.db import models

def get_file_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return os.path.join('file_uploads/%Y/%m', filename)

# Create your models here.
class Order(models.Model):
    name = models.CharField(max_length=255)
    email = models.CharField(max_length=255)
    phone = models.CharField(max_length=255, blank=True)
    reference = models.CharField(max_length=255)
    files = models.ManyToManyField(File)
    deadline = models.DateTimeField(auto_now_add=False, auto_now=False)

class File(models.Model):
    name = models.CharField(max_length=255)
    file = models.FileField(upload_to=get_file_path)

Updated: I get error when i'm trying to makemigrations command:
File "/home/dima/web/files_2016_04/fileupl/flpp/models.py", line 11, in <module>
    class Order(models.Model):
  File "/home/dima/web/files_2016_04/fileupl/flpp/models.py", line 16, in Order
    files = models.ManyToManyField(File)
NameError: name 'File' is not defined

But it defined. Whats wrong?
Updated: i solve this problem moving File class before Order class
UPD Thanks, i solved problem with ForeignKey('File') with quotes

A: You just need to declare File class upper than Order class
# Create your models here.
class File(models.Model):
    name = models.CharField(max_length=255)
    file = models.FileField(upload_to=get_file_path)

class Order(models.Model):
    name = models.CharField(max_length=255)
    email = models.CharField(max_length=255)
    phone = models.CharField(max_length=255, blank=True)
    reference = models.CharField(max_length=255)
    files = models.ManyToManyField(File)
    deadline = models.DateTimeField(auto_now_add=False, auto_now=False)

A: If you want to keep the current structure, you'll need to put it in quotes:
files = models.ManyToManyField('File')


text:
Q: C low-level validation of function arguments Say we have some function and we want to validate the arguments. For instance for not being NULL:
void* myFunction(char* str1, char* str2){
    if(str1==NULL || str2==NULL) return NULL;
    ...
}

My question is what it is called a good low-level (APIs) validation like it is made by standard C libraries.
Thanks.

A: C is a what you ask is what you get language with lots of rope to hang yourself and very little safety nets.  Take for example this implementation of strcpy from Apple, but they all look very much alike:
char *strcpy(char *s1, const char *s2)
{
    char *s = s1;
    while ((*s++ = *s2++) != 0)
    ;
    return (s1);
}

As C doesn't know the concept of exceptions, all error signalling has to be done via the return value of the function and sometimes via the global variable errno, which of course somewhat limits the expressivity of errors.
So, if you want to keep in line with what the standard library does, very little safety needs to be provided.

A: The key thing is to "do what you say" and "say what you do". "What you say" needs clearly described. The description should be in the documentation, but can also be in comments or the function name or parameter names.
Having stated the requirement, make really sure that you then meet that requirement. If you define error cases to trap, make sure that the caller can determine this using errno or otherwise.


text:
Q: Can I build a high-frequency SMPS choke out of an arbitrary coil of wire? Suppose I want to build a boost converter that runs at 100 kHz, with an input voltage of 600VDC and an input current of 100 amps. (This is hypothetical, I know the semiconductors involved would be exotic.) I'd need a pretty custom choke to do that; laminated steel probably won't handle that kind of frequency, and there's not much off-the-shelf to be had in this power and frequency range. So I'll build my own! What could possibly go wrong?
One possible way of building a choke to handle this is to use an air core. No core losses if there's no core! No component sourcing issues, less knowledge of magnetics required. The obvious down-sides are that I'll need many more turns of wire, more volume in my chassis, there will be higher resistive drop in the path... so maybe it's not a cost-effective approach. But let's assume it is for a moment.
So now I'm building an air-core choke out of something like 6AWG welding cable. Of course, skin effect will kill me, so I really need some sort of equivalent flat wire or heavy foil. The inductance calculations are straightforward, just a matter of turns and geometry. But what's going to happen when I actually try to run that in my hypothetical boost converter? Am I prone to insulation breakdown? Do I need to vacuum-impregnate the whole thing to with varnish to avoid that? Is there some other reliability problem with what I'm describing?
Basically I'm asking, what black magic am I prone to run into when running high currents, high voltages, and high frequencies?

A: Yes you could use an air cored coil .BUT there are some issues.1 you will want to shield it because of EMC and it could muck up other parts of your circuit.Air cored coils are worse for radiation than ferrite coils.Now if you do a toroidal air cored coil which I havent done you will get a worse resistance to inductance ratio which at 100KHz will be crippling.2 Your real SMPS coil carries the DC load current and some AC current .The AC current heats the wire more than expected due to skin and proximity effects.In fact its possible to design a coil that has a AC resistance 10 to 100 times its DC resistance.So you must design for low AC resistance .Litz wire ,Single layer ,Brooks dimensions,Spacing turns by one wire diameter are some of the things that are accepted ways of minimising AC resistance .The importance of this AC resistance stuff depends on your convertor waveform.You may set up your convertor to keep the ratio of AC to DC currents reasonable.3 your coil will be bigger than a ferrite which may not be a problem when the size of your hypothetical product is determined by heatsinks anyway.By the way I did a 36 to 12V buck with an air cored coil that produced 5 amp .It was fine.

A: For high power applications, Copper tubing is the most popular method to recognize the skin effect losses in the wire core.
Details in the design are often overlooked with the geometry and dielectric effects of insulation which results in Interwinding capacitance.  This can be controlled by winding forms,  single or Litz magnet wire.
These  are all considered to make high Q, high f, and low impedance resonant SMPS with zero-valley switching.
EMI stray effects can be problematic, so orientation, shields, ferrite chokes for immunity are considered.
Induction heaters often use Litz wire coils to heat up iron or aluminum pots at higher frequency with special plastic film caps to handle the ripple current.


text:
Q: Running web application components as a single service versus multiple services in Kubernetes I have a web applicaton (e.g. "india") that depends on postgres and redis (e.g. a typical Rails application).
I have a docker-compose.yml file that composes the containers to start this application.
version: '3'
services:

  redis-india:
    image: redis:5.0.6-alpine
    # .....

  postgres-india:
    image: postgres:11.5-alpine
    # ....

  india:
    depends_on:
      - postgres-india
      - redis-india
    image: india/india:local
    # ....

I'd like to run this application deployment with Kubernetes. I'm trying to figure out how to build the k8s resource objects correctly, and I'm weighing two options:

*

*I can build india, postgres-india, and redis-india as separate deployments (and therefore separate Services) in k8s

*I can build india, postgres-india, and redis-india as a single deployment (and therfore a single pod / service)
#2 makes more sense to me personally - all 3 items here comprise the entire "application service" that should be exposed as a single service URL (i.e. the frontend for the web application).
However, if I use an automated tool like kompose to translate my docker-compose.yml file into k8s resources, it follows approach #1 and creates three individual k8s Services.
Is there a "right way" or standard I should follow?
Thanks!

A: Independent components
Your three components should run as separate deployments on Kubernetes. You want these three components to be:

*

*Independently upgradable and deployable (e.g. you deploy a new version of Redis but not your app or database)

*Independently scalable - e.g. you might get many users and want to scale up to multiple instances (e.g. 5 replicas) of your app.

State
Your app should be designed to be stateless, and can be deployed as a Deployment. But the Redis and PostgreSQL are stateful components and should be deployed as StatefulSet.
Availability
In a production environment, you typically want to:

*

*Avoid downtime when upgrading any application or database

*Avoid downtime if you or the cloud provider upgrade the node

*Avoid downtime if the node crash, e.g. due to hardware failure or kernel crash.

With a stateless app deployed as a Deployment, this is trivial to solve - run at least two instances (replicas) of it - and make sure they are deployed on different nodes in the cluster. You can do this using Topology Spread Constraints.
With a stateful component as e.g. Redis or PostgreSQL, this is more difficult. You typically need to run it as a cluster. See e.g. Redis Cluster. But it is more difficult for PostgreSQL, you could consider a PostgreSQL-compatible db that has a distributed design, e.g. CockroachDB that is designed to be run on Kubernetes or perhaps consider CrunchyData PostgreSQL Operator.
Pod with multiple containers
When you deploy a Pod with multiple containers, one container is the "main" application and the other containers are supposed to be "helper" / "utility" containers to fix a problem for the "main container" - e.g. if your app logs to two different files - you could have helper containers to tail those files and output it to stdout, as is the recommended log output in Twelve-Factor App. You typically only use "multiple containers" for apps that are not designed to be run on Kubernetes, or if you want to extend with some functionality like e.g. a Service Mesh.


text:
Q: Realm Filter nested Array I have three object
class YearDatabaseModel: Object {
    @Persisted var year: Int
    @Persisted var months = List<MonthsDatabaseModel>()

    override static func primaryKey() -> String? {
        return "year"
    }
}

final class MonthsDatabaseModel: Object {
    @Persisted var id: String
    @Persisted var media = List<Model>()

    override static func primaryKey() -> String? {
        return "id"
    }
}

public class Model: Object {
    @Persisted public var id: String
    @Persisted public var type: String
}

I need to return all the Year models with filter nested Month. Model items with their type for example just return models items in month with type == "audio"
I did use this SUBQUERY but it just filter the year list not filter the model list
 let predicate = NSPredicate(
                format: "SUBQUERY(months.media, $media, $media.type = %@).@count > 0",
 "audio")

And I don't want to get the realm result then filter models by flat mapping the list of models I want to use realm query power to filter neseted objects from big model
Here's a diagram

A: This is a very challenging query due to the depth and dealing with Lists, but the subquery is likely the best solution unless you want to leverage high-level Swift functions.
I think this will get your result but it's a two part query. As is, the current SwiftSDK doesn't have a (good) implementation for subqueries per se so I'm using an old school NSPredicate combined with the newer type safe query to get the result
let predicate = NSPredicate(format: "SUBQUERY(media, $m, $m.type == 'm0 type 0').@count > 0")
let months = realm.objects(MonthsDatabaseModel.self).filter(predicate)

let years = realm.objects(YearDatabaseModel.self).where { $0.months.containsAny(in: months) }
print(years)

We use the subquery to get all of the months MonthsDatabaseModel that have a Model with type = "audio"
Then we use those results to get the YearDatabaseModel that have months in their list that match.
Edit:
Here's a sample set of data (that matches the diagram in the question, noting there were two Year 2's so I used 2022 and 2023)
year 2021
 month:  year 2021 month 1
  media: video
  media: image
  media: video
 month:  year 2021 month 2
  media: image
  media: image
  media: image
 month:  year 2021 month 3
  media: video
  media: image
  media: video

year 2022  (note, no video media values in the child list)
 month:  year 2022 month 1
  media: image
  media: image
  media: image

year 2023
 month:  year 2023 month 1
  media: video
  media: image
  media: image

and when the code above is run against that data this it returns year 2021 and year 2023, omitting year 2022 because it does not have any video child values in the media List
year 2021
year 2023


text:
Q: google script loop performance I am new to google scripts and I am not sure why I am experiencing such poor performances compared to Excel VBA for a simple loop.
I attached the code below which is a loop on ~1200 rows and it is deleting about 2-3 rows per second!
Is the script I wrote very inefficient? I am not familiar with Javascript yet, but it does not look so inefficient to me.
Is it normal? Is it the server very slow now, but usually much better?
var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Sheet1");
  var drng = sheet.getDataRange();
  var rng = sheet.getRange(2,1, drng.getLastRow()-1,26);

  var rangeformula = sheet.getRange(2,26, drng.getLastRow()-1);
  rangeformula.setFormula('=SUM(K2:V2)'); var rngA = rng.getValues();

var len = rngA.length;
for(var i = len; i>=1; i--) {

  if(rngA[i-2][25] == 0){

    sheet.deleteRow(i);}}

A: Ok, it is not obvious for a beginner that deleting rows is such an expensive process (compared to VBA). Here is a work around I used to avoid deleting rows inside a loop.
PS: I am new to this, so it is not the most elegant way, but could be helpful for others.
function removeEmpty() {

var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Sheet1");
  var drng = sheet.getDataRange();
  var rng = sheet.getRange(2,1, drng.getLastRow()-1,26);
  var rangeformula = sheet.getRange(2,26, drng.getLastRow()-1);
  rangeformula.setFormula('=SUM(K2:V2)');
  var rngA = rng.getValues();
  var newRangeVals = [];
  var len = rngA.length+1;
  for(var i = len; i >=2; i--){
    if(rngA[i-2][25] != 0){

  newRangeVals.push(rngA[i-2]);
};
  };

rng.clearContent();

  var newRange = sheet.getRange(2,1,newRangeVals.length, newRangeVals[0].length);
  newRange.setValues(newRangeVals);

}

A: *

*You want to reduce the process cost of your script.

Modification points:

*

*In your script, I think that the reason of your issue is due to the cost of deleteRow rather than the cost of for loop. In this case, in order to reduce the cost, I would like to propose to use Sheets API. When Sheets API is used, the each rows can be deleted by one API call. By this, I think that the cost can be reduced.

*In your for loop, rngA[i-2] is run in the loop of for(var i = len; i>=1; i--). In this case, I think that when i is 1, an error occurs. So if you want to loop from before one element from the last element to the 1st element, please modify to for(var i = len; i>=2; i--) {.

*But in this modification, the for loop is not used.

Modified script:
When your script is modified, please modify as follows. Before you run the script, please enable Sheets API at Advanced Google services.
From:
var len = rngA.length;
for(var i = len; i>=1; i--) {

  if(rngA[i-2][25] == 0){

    sheet.deleteRow(i);}}

To:
const sheetId = sheet.getSheetId();
const requests = rngA.reduce((ar, r, i) => {
  if (r[25] === 0) {
    ar.push({deleteDimension: {range: {sheetId: sheetId, startIndex: i + 1, endIndex: i + 2, dimension: "ROWS"}}});
  }
  return ar;
}, []).reverse();
Sheets.Spreadsheets.batchUpdate({requests: requests}, ss.getId());

Note:

*

*Please run the script with enabling V8.

References:

*

*Advanced Google services

*Method: spreadsheets.batchUpdate

*DeleteDimensionRequest

A: function myfunction() {
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var sheet=ss.getSheetByName("Sheet1");
  var drng=sheet.getDataRange();
  var rng=sheet.getRange(2,1,sheet.getLastRow()-1,26);
  var vA=rng.getValues();
  var d=0;
  for(var i=0;i<vA.length;i++) {
    if(vA[i][25]==0){
      sheet.deleteRow(i+2-d++);
    }
  }
}


text:
Q: I need to add .drl files at runtime (From an S3 bucket) and supply it to drools rule engine Unable to add rules at runtime through ResourceFactory.newURLResource()
Also , KnowledgeBase is deprecated or cannot be resolved
I have tried all the snippets from the documentation
public class RuleRunner {
public RuleRunner() {
}

public void runRules(String[] rules,
                     Object[] facts) throws Exception {

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    for ( int i = 0; i < rules.length; i++ ) {
        String ruleFile = rules[i];
        System.out.println( "Loading file: " + ruleFile );
        kbuilder.add( ResourceFactory.newClassPathResource( ruleFile,
                                                            RuleRunner.class ),
                      ResourceType.DRL );
    }

    Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();
    kbase.addKnowledgePackages( pkgs );
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    for ( int i = 0; i < facts.length; i++ ) {
        Object fact = facts[i];
        System.out.println( "Inserting fact: " + fact );
        ksession.insert( fact );
    }

    ksession.fireAllRules();
}

}
public KieContainer getKieContainer() {
    String drlURL ="https://s3.amazonaws.com/somebucket4/rules.drl";
    KieServices kieServices = KieServices.Factory.get();
    KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
    kieFileSystem.write(ResourceFactory.newUrlResource(drlURL));
    KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
    kieBuilder.buildAll();
    KieModule kieModule = kieBuilder.getKieModule();
    return kieServices.newKieContainer(kieModule.getReleaseId());
}

A: In Drools, now everything is jar oriented. So you need to rebuild your KJar (it could be a "virtual KJar" (KieModule) written just to the in-memory filesystem) with newly created rules. To see examples, please check e.g. IncrementalCompilationTest class in Drools [1]. You could find also other test classes with examples if you search the Drools codebase. E.g. this [2].
[1] https://github.com/kiegroup/drools/blob/221cb15cde3ab5ea7388281d2c96158117ee3e19/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/incrementalcompilation/IncrementalCompilationTest.java#L178
[2] https://github.com/kiegroup/drools/blob/a62949b27d35b423725da493bf53c252608438c7/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/IncrementalCompilationTest.java#L31


text:
Q: iphone Core Data - Filtering NSFetchedResultController? I was given a framework written by other programmers to access the core data.
In this situation i receive a pre-loaded NSFetchedResultController which I need to filter, to display a part of it's data.
Here is what I tried:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"category==%@", @"current"];
[NSFetchedResultsController deleteCacheWithName:@"Root"];
[myResultController.fetchRequest setPredicate:predicate];
myResultController.fetchedObjects = [myResultController.fetchedObjects filteredArrayUsingPredicate:predicate];

And i get an error saying that object cannot be set, either setter method is missing, or object is read-only.
So whats the best way to filter an NSFetchResultController which is already loaded, without having to store the filtered data into another array?

A: fetchedObjects is readonly. You cannot set it manualy.
What you need to do is to perform a new fetch with your myResultController.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"category==%@", @"current"];
[NSFetchedResultsController deleteCacheWithName:@"Root"];
[myResultController.fetchRequest setPredicate:predicate];
//myResultController.fetchedObjects = [myResultController.fetchedObjects filteredArrayUsingPredicate:predicate];
[myResultController performFetch:nil];


text:
Q: Inequality in complex numbers Prove that for all $z\in \mathbb{C}$
$$\frac{\Vert z+i\Vert z\Vert \Vert}{\Vert z+1\Vert}\leq \frac{2\Vert z \Vert}{\Vert z \Vert +1}$$

A: The inequality is wrong
if $z=i$, then
$$\frac{\Vert z+i\Vert z\Vert \Vert}{\Vert z+1\Vert}= \frac{\Vert i+i\vert\vert}{\Vert i+1\Vert}=\sqrt2$$
but
$$\frac{2\Vert z \Vert}{\Vert z \Vert +1}= \frac{2}{\Vert i\Vert +1}=1$$

A: Let $z = r ( \cos t + i \sin t)$. Then the inequality says that
$$r \frac{\sqrt{ 2 + 2 \cos t}}{\sqrt{r^2 + 2r \cos t + 1}} \leq \frac{2r}{r+1}\ .$$
When this is squared and multiplied out, there is a factor of 1 - cos t which cancels, leaving the condition
$$r^2 - 2 r + 1 > 0\ .$$


text:
Q: How to program an Operating System? I love to code, but I am currently only doing web development.  I'd like to do something that will be unique and fun and very different from web programming.
Yeah, this might be a dumb question, but I think it would be really cool to build a really simple Operating System.  So please do not say anything rude.  I just want to know the following things:
*Where to start?
*Resources
*What language would I use?
I was thinking something simple like a cmd based

A: Switching from webdev to backend will be quite frustrating.
First, choose a board/hardware/architecture - maybe even go with an OS simulator which you can run on your machine. Learn C and some assembly (intel, MIPS, ARM, coldfire/motorolla 68k) depending on which CPU architecture you are building your OS for.
I've have seen C++ packages which will allow you to make an OS in C++, then convert it automatically for you to assembly, but it is such a headache to get them to convert properly. I would not recommend them.
Before you start writing code, you should design your OS. Maybe even put your design decisions in a 50 page paper with some diagrams as well.
Some things to think about:

*

*memory map (where exactly in memory do you load parts of your OS; where will it reside)

*how your scheduler would work (process and/or thread aware, priorities). Perhaps a diagram with queues for different priorities; also a diagram for process states in different queues (Ready, blocked, waiting for msg, running, executing, interrupted, etc)

*how to do interprocess communication (mailboxes, mutexes, atomicity, synchronous vs asynchronous communication, format of message envelopes {sender process id, receiver process id, message type, message})

*how to handle kernel vs user modes

*memory allocation algorithms - you will write your own malloc/free operator (how do you keep track when user allocates memory dynamically? will you use a buddy tree algo? linked list? stack? etc)

*how to handle interrupts (also context switch goes in here - how will you save all registers and restore them: you have one stack you need to keep track of where you are on it)

*standard processes: keyboard process, monitor output, timing,

*how to add timing services

*how to load user processes and run them

*to add preemption or not

*add hotkeys (useful to debug your OS esp. in case it freezes, you can add hot keys to inspect memory)

*testing your OS

EDIT - URL update
Developing Your Own 32-Bit Operating System is out of print but is available online:
http://www.ipdatacorp.com/mmurtl/mmurtlv1.pdf

A: Here are some links to get you started:
http://www.brokenthorn.com/Resources
http://wiki.osdev.org/Main_Page/
Your gonna need GCC and NASM.
I think you can also use GASM.
Learn BIOS interrupts.
Also before you even start grab a bunch of standards such as:
APIC
A20 Gate
PCI & PCIEx - Good luck trying to obtain one of those. Cost some change.
Intel & AMD - Look at these, gives you a lot of information.
VGA
ATA & SATA
etc... There are a lot.
Also grab emulators like: bochs and qemu
Understand how the computer works, that is, how it boots up.
There is a lot of information out there you just gotta do your research.
Good luck.

A: Start by reading some operating system books - like Tanenbaums' Modern operating systems.
This should give you an understanding of what problems you need to solve in order to write an operating system.

A: The absolute "bible" on operating system design is and was Andrew Tanenbaum's Operating Systems Design and Implementation - the "Dragon" book :-)

There are plenty of other references, too, e.g. Developing Your Own 32-Bit Operating System.
Microsoft Research also has/had a project on creating an operating system in managed code (C#) called Singularity - that might provide some insights/papers etc.
Writing a complete OS is neither a trivial nor a quick task, though.....

A: I guess you better start exploring Andrew S. Tanenbaum's work.

A: There are quite some resources when you google for them, but I would encourage you not to take this step yet!
For writing an OS, even a simple one, you will need a good understanding of how your computer works at a low level, and you'll need at least C or C++ and preferably Assembly as well. Without these skills it will be a tedious and frustrating project. It is hard and challenging even for skilled C programmers.

A: Writing an OS is hard. I recommend becoming a developer before becoming an OS developer. You will need to know C/C++ and assembly to make a basic operating system. you will need to think about how to make your OS, i.e. type of kernel, real mode or protected mode, memory maps, and many other things.


text:
Q: QCom Decoder Output YUV Buffer Distrubed I'm trying to get images from HD Live Stream. Getting OMX Decoder YUV Streams and converting them into JPG. JPEG is completely disturbed. Tried some suggestions from group but not working.
My resolution is 320x240.
i will get buffer length is (386 * 256 * 1.5) for configured 320 * 240 resolution. I'm not getting how to get this new width and height information.
JPG conversion code i have in Java and using OMXCodec is in Native. Please help me.
    final int frameSize = width * height;
    final int qFrameSize = frameSize/4;
    int padding = 0;/*(width*height + 2047) & ~2047;

    if ((width % 32) != 0) {
        padding = (width*height) % 1024;
    } else {
        padding = (width*height) % 2048;
    }

    System.arraycopy(input, 0, output, 0, frameSize); // Y

    for (int i = 0; i < qFrameSize; i++) {
        output[frameSize + i*2 + padding] = input[frameSize + i + qFrameSize ]; // Cb (U)
        output[frameSize + i*2 + 1 + padding] = input[frameSize + i ]; // Cr (V)
    }
    return ;
}

thank you,
Raghu

A: The output of QCom video decoder is usually a specific custom color format which is typically known as tiled format. Please refer to these questions which have more inputs on how to convert the data to a more cleaner frame
QOMX_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka converter
QOMX_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka color format


text:
Q: Let be: one verb or two? My apologies if my question is not appropriate for this forum. In mathematical writing, one often needs to let certain letters denote certain mathematical objects. For example:
"Let X be a number. Let Y be a set."
I am confident the following examples are correct ways to combine the above two sentences into one.

*

*"Let X be a number; let Y be a set."

*"Let X be a number, and let Y be a set."

However, I do not know if either of the following are correct.

*

*"Let X be a number and Y be a set."

*"Let X be a number and Y a set."

My question is this: which of the latter two are grammatically correct (or incorrect) and why?

A: Both are fine, as Barrie said.  What may be making you question your own judgment here is the novelty of the locution or the fact that you are talking about X's and Y's.  Under these circumstances, if you're wondering about grammaticality, it is often useful to preserve the grammatical form while switching to more familiar words.  If you ask whether the following are grammatical, the answer is (hopefully) an obvious "yes":

Let Mary eat bread and John drink chocolate.
Let Mary eat bread and John, chocolate.

And, if they are grammatical, then so are the sentences you gave.

A: Both are grammatical. The second has the advantage of being slightly shorter.


text:
Q: Getting "java.lang.NoSuchMethodError: org.springframework.test.context.MergedContextConfiguration" with spring-boot 1.4.0 I am using Spring-boot managed artifacts only. With all dependencies defined in the parent pom, test in a module is failing with the above error.
When I  looked at the Dependency Tree, I see that 2 versions of spring-test is included and both are referenced by the spring-boot-starter-test:jar:1.4.0.BUILD-SNAPSHOT:compile. Please find the portions of dep tree output:
    |  +- org.springframework.boot:spring-boot-starter-test:jar:1.4.0.BUILD-SNAPSHOT:compile
    |  |  +- org.springframework.boot:spring-boot-test:jar:1.4.0.BUILD-SNAPSHOT:compile
    |  |  +- org.springframework.boot:spring-boot-test-autoconfigure:jar:1.4.0.BUILD-SNAPSHOT:compile
    |  |  +- com.jayway.jsonpath:json-path:jar:2.2.0:compile
    |  |  |  \- net.minidev:json-smart:jar:2.2.1:compile
    |  |  |     \- net.minidev:accessors-smart:jar:1.1:compile
    |  |  |        \- org.ow2.asm:asm:jar:5.0.3:compile
    |  |  +- junit:junit:jar:4.12:compile
    |  |  +- org.assertj:assertj-core:jar:2.4.1:compile
    |  |  +- org.mockito:mockito-core:jar:1.10.19:compile
    |  |  |  \- org.objenesis:objenesis:jar:2.1:runtime
    |  |  +- org.hamcrest:hamcrest-core:jar:1.3:compile
    |  |  +- org.hamcrest:hamcrest-library:jar:1.3:compile
    |  |  +- org.skyscreamer:jsonassert:jar:1.3.0:compile
    |  |  |  \- org.json:json:jar:20140107:compile
    |  |  \- org.springframework:spring-test:jar:4.0.1.RELEASE:compile

    +- org.springframework.boot:spring-boot-starter-test:jar:1.4.0.BUILD-SNAPSHOT:compile
    |  +- org.springframework.boot:spring-boot-test:jar:1.4.0.BUILD-SNAPSHOT:compile
    |  +- org.springframework.boot:spring-boot-test-autoconfigure:jar:1.4.0.BUILD-SNAPSHOT:compile
    |  +- com.jayway.jsonpath:json-path:jar:2.2.0:compile
    |  |  \- net.minidev:json-smart:jar:2.2.1:compile
    |  |     \- net.minidev:accessors-smart:jar:1.1:compile
    |  +- junit:junit:jar:4.12:compile
    |  +- org.assertj:assertj-core:jar:2.4.1:compile
    |  +- org.hamcrest:hamcrest-core:jar:1.3:compile
    |  +- org.hamcrest:hamcrest-library:jar:1.3:compile
    |  +- org.skyscreamer:jsonassert:jar:1.3.0:compile
    |  |  \- org.json:json:jar:20140107:compile
    |  \- org.springframework:spring-test:jar:4.2.6.RELEASE:compile

Please let me know if any additional details are needed.
Thanks
Parent POM: Removed all 3rd party
    <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <artifactId>log4j-over-slf4j</artifactId>
                <groupId>org.slf4j</groupId>
            </exclusion>
            <exclusion>
                <artifactId>javax.transaction-api</artifactId>
                <groupId>javax.transaction</groupId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <artifactId>xml-apis</artifactId>
                <groupId>xml-apis</groupId>
            </exclusion>
            <exclusion>
                <artifactId>tomcat-jdbc</artifactId>
                <groupId>org.apache.tomcat</groupId>
            </exclusion>
            <exclusion>
                <artifactId>tomcat-juli</artifactId>
                <groupId>org.apache.tomcat</groupId>
            </exclusion>
            <exclusion>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-websocket</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-logging-juli</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-el</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-core</artifactId>
            </exclusion>
            <exclusion>
                <artifactId>javax.transaction-api</artifactId>
                <groupId>javax.transaction</groupId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
        <exclusions>
            <exclusion>
                <artifactId>xml-apis</artifactId>
                <groupId>xml-apis</groupId>
            </exclusion>
            <exclusion>
                <artifactId>tomcat-jdbc</artifactId>
                <groupId>org.apache.tomcat</groupId>
            </exclusion>
            <exclusion>
                <artifactId>tomcat-juli</artifactId>
                <groupId>org.apache.tomcat</groupId>
            </exclusion>
            <exclusion>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-websocket</artifactId>
            </exclusion>
            <exclusion>
                <artifactId>javax.transaction-api</artifactId>
                <groupId>javax.transaction</groupId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependency-tools</artifactId>
        <version>1.3.0.BUILD-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
        <exclusions>
            <exclusion>
                <artifactId>xml-apis</artifactId>
                <groupId>xml-apis</groupId>
            </exclusion>
            <exclusion>
                <artifactId>tomcat-jdbc</artifactId>
                <groupId>org.apache.tomcat</groupId>
            </exclusion>
            <exclusion>
                <artifactId>tomcat-juli</artifactId>
                <groupId>org.apache.tomcat</groupId>
            </exclusion>
            <exclusion>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-websocket</artifactId>
            </exclusion>
            <exclusion>
                <artifactId>javax.transaction-api</artifactId>
                <groupId>javax.transaction</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-ws</artifactId>
        <exclusions>
            <exclusion>
                <artifactId>tomcat-embed-core</artifactId>
                <groupId>org.apache.tomcat.embed</groupId>
            </exclusion>
            <exclusion>
                <artifactId>tomcat-embed-websocket</artifactId>
                <groupId>org.apache.tomcat.embed</groupId>
            </exclusion>
            <exclusion>
                <artifactId>tomcat-embed-el</artifactId>
                <groupId>org.apache.tomcat.embed</groupId>
            </exclusion>
            <exclusion>
                <artifactId>tomcat-embed-logging-juli</artifactId>
                <groupId>org.apache.tomcat.embed</groupId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springmodules</groupId>
        <artifactId>spring-modules-jakarta-commons</artifactId>
        <version>0.8</version>
        <exclusions>
            <exclusion>
                <artifactId>xercesImpl</artifactId>
                <groupId>xerces</groupId>
            </exclusion>
            <exclusion>
                <artifactId>jdom</artifactId>
                <groupId>jdom</groupId>
            </exclusion>
            <exclusion>
                <artifactId>xerces</artifactId>
                <groupId>xerces</groupId>
            </exclusion>
            <exclusion>
                <artifactId>servlet-api</artifactId>
                <groupId>javax.servlet</groupId>
            </exclusion>
            <exclusion>
                <artifactId>xml-apis</artifactId>
                <groupId>xml-apis</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-all</artifactId>
        <version>1.9.5</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-all</artifactId>
        <version>1.9.5</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>1.9.5</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.spockframework</groupId>
        <artifactId>spock-core</artifactId>
        <version>1.0-groovy-2.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.spockframework</groupId>
        <artifactId>spock-spring</artifactId>
        <version>1.0-groovy-2.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
        <version>LATEST</version>
        <scope>test</scope>
    </dependency>

</dependencies>

The POM for the module that has reference to older spring-test
    <parent>
        <groupId>com.abc.xyz.dm</groupId>
        <artifactId>decisionmanagement</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../dm-parent/pom.xml</relativePath>
      </parent>
      <artifactId>rms-inspection-model-services</artifactId>
      <url>http://maven.apache.org</url>
      <name>rms-inspection-model-services</name>
      <dependencies>
          <dependency>
              <groupId>com.abc.xyz.dm</groupId>
              <artifactId>dm-common</artifactId>
            <version>${parent.version}</version>
        </dependency>
          <dependency>
              <groupId>com.abc.xyz.dm</groupId>
              <artifactId>dm-generated-classes</artifactId>
            <version>${parent.version}</version>
        </dependency>
      </dependencies>
    </project>

The module with correct 'spring-test' version
    <parent>
            <artifactId>decisionmanagement-parent</artifactId>
            <groupId>com.abc.xyz.dm</groupId>
            <version>1.0-SNAPSHOT</version>
            <relativePath>../dm-parent/pom.xml</relativePath>

        </parent>
        <artifactId>inspection-services</artifactId>
        <name>inspection-services</name>
        <url>http://maven.apache.org</url>
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>
        <dependencies>
            <dependency>
                <groupId>com.abc.xyz.dm</groupId>
                <artifactId>dm-common</artifactId>
                <version>${parent.version}</version>
            </dependency>
            <dependency>
                <groupId>com.abc.xyz.dm</groupId>
                <artifactId>dm-generated-classes</artifactId>
                <version>${parent.version}</version>
            </dependency>

        </dependencies>


text:
Q: jQuery: make a div fadeOut + .live() + .delay() functions merge Hi all
I want this div to dissapear when it show up.
It is working now this way, but since sometimes the div is added after a load() I would need to merge it somehow with a live() I guess....
//Fade out the result alert.

$('.Alert').delay(6000).fadeOut(500);

Any ideas of how to do this?
Thanks in advance

A: It depends on how you add your div to the page after the load().
After you add the element to your page, add the handler or function you want them to have.
Example :
$('

').appendTo('body').delay(6000).fadeOut(500);

Live example


text:
Q: How to set up a keyvault using secp256k1 algorithm in GCP? I have to set up a keyvault using secp256k1 algorithm as a Google Cloud Platform service and don't know where to start.
I checked available options and found only Elliptic Curve P-256 - SHA256 digest support. Is this the same as secp256k1?

A: If what you mean by your first sentence is having the analogous (at least partially) service of Key Vault with Google Cloud Platform (with this being Cloud Key Management Service aka KMS) then the answer is no.
While for Azure's Key Vault the elliptic curve SECP256K1 is available, at the moment for Cloud KMS the only elliptic curves  available are P-256 and P-384.
The P-256 and SECP256K1 curves are not the same and, as of now, P-256 is defined in FIPS-186-4 and SECP256K1 in Standards for Efficient Cryptography Version 2.
Anyways, to back all of this, you can run the following experiment.
Create a ASYMMETRIC_SIGN purpose key with Cloud SDK (see how-to):
keyring=keyring0
key=key0
location=US
gcloud kms keyrings create $keyring --location=$location
gcloud kms keys create $key --location $location --keyring $keyring --purpose asymmetric-signing --default-algorithm ec-sign-p256-sha256 --protection-level software

Sign a message and import the public key of the previously generated (KMS-generated that is) key pair.
message=message
signature=message.sig
echo $(date):$(uname -a) > $message
gcloud kms asymmetric-sign --keyring=$keyring --key=$key --location=$location --input-file=$message --signature-file=$signature --digest-algorithm=sha256 --version=1
gcloud kms keys versions get-public-key 1 --location=$location --keyring=$keyring --key=$key --output-file=./$keyring-$key.pub

Now you could verify the signature it with openssl dgst -verify $keyring-$key.pub -signature $signature $message but you won't get information about the elliptic curve used to generate the key pair of which the secret key was used to do the signing.
To get that information, we could install a Python third-party library:
virtualenv --python=/usr/bin/python3 ecdsa
cd ecdsa
source bin/activate
pip install ecdsa

And run the following command to verify the signature and see the curve used by KMS when the signing algorithm ec-sign-p256-sha256 was chosen:
python3 -c """
from pathlib import Path
import hashlib
from ecdsa import VerifyingKey, BadSignatureError

publickey = Path('$keyring-$key.pub')
signature = Path('$signature')
message = Path('$message')

def read_signature(signature):
    '''
    workaround for https://github.com/warner/python-ecdsa/issues/67
    more background on why's that in https://tools.ietf.org/html/rfc5652
    '''
    LEN = 64
    LENHALF = LEN//2
    with signature.open('rb') as fp:
        sig = fp.read()

    offset = 4 if sig[4] else 5
    slice_s, slice_r =  slice(offset, offset + LENHALF), slice(-LENHALF, len(sig))
    s,r = sig[slice_s], sig[slice_r]
    return s + r

def verify(publickey, signature, message):

    with publickey.open() as pkfp, message.open('br') as messagefp:
        vk = VerifyingKey.from_pem(pkfp.read())
        try:
            print('Verifying with public key associated with curve', repr(vk.curve.name))
            vk.verify(read_signature(signature), messagefp.read(), hashfunc=hashlib.sha256)
            print('Verify Success')
        except BadSignatureError:
            print('Verify Failure')

verify(publickey, signature, message)
"""

To hammer the point home of the elliptic curve used in KMS in this example being NIST's P-256 and its parameter differences with SECP256K1, check out the following snippet:
python3 -c """
from collections import namedtuple
from operator import attrgetter
from ecdsa import NIST256p, SECP256k1

sextuple = namedtuple('T', 'p, a, b, G, n, h')

ag_curve = attrgetter(*('curve._CurveFp__'+c for c in 'abp'))
ag_generator = attrgetter(*('generator._Point__'+c for c in 'x y order'.split()))

def make_sextuple(curve, h=1):
    n, G_x, G_y = ag_generator(curve)
    return sextuple(*ag_curve(curve), n=n, G=(G_x, G_y), h=h)

T_NIST256p = make_sextuple(NIST256p)
T_SECP256k1 = make_sextuple(SECP256k1)

if T_NIST256p != T_SECP256k1:
    for k in sextuple._fields:
        ag_k = attrgetter(k)
        v0, v1 = ag_k(T_NIST256p), ag_k(T_SECP256k1)
        if v0 != v1:
            print('Different values for parameter ', k,)
            print(v0)
            print(v1)
"""