text:
Q: Why are public properties being serialized w/ an underscore in MVC4? In the following class
using System;

namespace Beverati.Repository.ViewModel
{

[Serializable]
public class CollectionItem : EditableEntityBase
{

public CollectionItem() {}

private int? _quantity;
private string _retailValue;
private string _currencyName;

public int? quantity
{
  get { return this._quantity ?? NULL_INTEGER; }
  set { this._quantity = value; }
}

public string retailValue
{
  get { return this._retailValue ?? String.Empty; }
  set { this._retailValue = value; }
}

public string currencyName
{
  get { return this._currencyName ?? String.Empty; }
  set { this._currencyName = value; }
}

}
}

returned in this controller action
public IEnumerable<Repository.ViewModel.CollectionItem> GetAll()

produces this JSON output with MVC2 the JSON output like this
{
  quantity:2
  retailValue: 50.00
  currencyName: USD
}

However, when I installed MVC4 the JSON returned looks like this
{
  _quantity:2
  _retailValue: 50.00
  _currencyName: USD
}

All the property names have an underscore prefix. Why is the underscore being used and what should be done to have the public property names returned in the JSON?

A: The [Serializable] attribute is what's doing it - Assuming you don't need it for another purpose - remove the attribute and all should be well.


text:
Q: find common index in two python list that exists in the third list I have three python lists: list_a, list_b and list_c. The lengths of list_a and list_b are both about 10000. The elements in the two lists are String. The length of list_c are about 1000. And all the elements of list_c exist in list_a. I want to find all the same indices i that list_a[i] in list_c and list_b[i] in list_c.

list_a = create_list_a()
list_b = create_list_b()
length = len(list_a)
result = []

for j in range(1000000):
    list_c = get_list_c(some_arguments)
    tmp = [i for i in range(length) if list_a[i] in list_c and list_b[i] in list_c]
    result.append(tmp)

The piece of code runs slowly. Is there any method to improve the speed of this code. BTW, can bloom filter fit for this question?

A: Making list_c a set:
set_c = set(list_c)
result = [i for i, (a, b) in enumerate(zip(list_a, list_b)) if a in set_c and b in set_c]

A: You have two big lists that don't get updated much, so you can build a dictionary for them to avoid having to search them naively. Instead, you can iterate through list_c which is smaller and query them using the dictionaries. For each iteration that list_c is created you find the set of indices in list_a and list_b and compute their intersection in tmp, and append it to the result. I tried this approach and the code runs relatively much faster. I've added some indicator to see how fast the code is running.
dict_a = dict()
for i,l in enumerate(list_a):
    if l not in dict_a.keys():
        dict_a[l] = []
    dict_a[l].append(i)
dict_b = dict()
for i,l in enumerate(list_b):
    if l not in dict_b.keys():
        dict_b[l] = []
    dict_b[l].append(i)

for j in range(1000000):
    if (j % 10000)==0:
        print('progress = ', int(100*j/1e6), '%')
    list_c = get_list_c(some_arguments)
    indices1 = []
    indices2 = []
    for l in list_c:
        if l not in dict_a.keys():
            s1 = []
        else:
            s1 = dict_a[l]
        if l not in dict_b.keys():
            s2 = []
        else:
            s2 = dict_b[l]
        indices1.extend(s1)
        indices2.extend(s2)
    indices1 = set(indices1)
    indices2 = set(indices2)
    tmp = list(indices1.intersection(indices2))
    result.append(tmp)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Year 0000 in java When I parse a date with the year 0000 it appears to be stored as the year 0001.
See below for code:
String dateStr = "00000102";
System.out.println(dateStr);
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date date = dateFormat.parse("00000102");
String convertedStr = dateFormat.format(date);
System.out.println(convertedStr);

The output is as per below:
00000102
00010102

Is there a way to represent the year 0000 in Java using the standard Java API?

A: I don't think the calendar is zero-based. Before 1 AD there was 1 BC. No 0.
Also: what kind of application are you building that needs to handle dates from that era? And if you need to cover that area, consider this: "Dates obtained using GregorianCalendar are historically accurate only from March 1, 4 AD onward, when modern Julian calendar rules were adopted. Before this date, leap year rules were applied irregularly, and before 45 BC the Julian calendar did not even exist."

A: I don't believe it's possible, since java.util.Date is based on UTC, which is based on the Gregorian calendar, and the Gregorian calendar has no year zero.

...the traditional proleptic Gregorian calendar (like the Julian calendar) does not have a year 0 and instead uses the ordinal numbers 1, 2, … both for years AD and BC. Thus the traditional time line is 2 BC, 1 BC, AD 1, and AD 2.

(Source: The Wikipedia article on the Gregorian calendar)

A: Year 0 does not exist in the Gregorian calendar. From Year 0 at Wikipedia:

"Year zero" does not exist in the widely used Gregorian calendar or in its predecessor, the Julian calendar. Under those systems, the year 1 BC is followed by AD 1.
...
The absence of a year 0 leads to some confusion concerning the boundaries of longer decimal intervals, such as decades and centuries. For example, the third millennium of the Gregorian calendar began on Monday, 1 January, 2001, rather than the widely celebrated Saturday, 1 January, 2000. Likewise, the 20th century began on 1 January 1901.
...

A: java.time
I recommend that you use java.time, the modern Java date and time API, for your date work.
As others have said, the Julian/Gregorian calendar that the old Date and SimpleDateFormat classes used does not have a year zero. Before year one in the current era (CE also known as AD) came year 1 before the current era (BCE also known as BC).
A side effect of using java.time is that you do get a year zero! That's right. java.time uses the proleptic Gregorian calendar, a modern inventions that not only extends the rules of the Gregorian back into times before the Gregorian calendar was invented, but also includes a year 0 before year 1, and a year -1 (minus one) before that. You may say that year 0 corresponds to 1 BCE and -1 to 2 BCE, etc.
So parsing your string is no problem. There's even a built-in formatter for it.
    String dateStr = "00000102";
    LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.BASIC_ISO_DATE);
    System.out.println("Parsed date is " + date);
    String convertedStr = date.format(DateTimeFormatter.BASIC_ISO_DATE);
    System.out.println(convertedStr);

Output:

Parsed date is 0000-01-02
00000102

We see that in both output lines year 0000 is printed back as expected.
What went wrong in your code?
When we all agree that there was no year 0, we should have expected your parsing to fail with an exception because of the invalid year. Why didn't it? It's one of the many problems with the old SimpleDateFormat class: with default settings it just extrapolates and takes year 0000 to mean the year before year 0001, so year 1 BCE. And falsely pretends that all is well. This explains why year 0001 was printed back: it meant year 1 BCE, but since you didn't print the era too, this was really hard to tell.
Links

*

*Oracle tutorial: Date Time explaining how to use java.time.

*Proleptic Gregorian calendar on Wikipedia.


text:
Q: ¿cómo agregar más de una coordenada a la vez en una matriz con una sola entrada de datos? estoy tratando de hacer un battle ship en C o C++ y tengo un problema: no sé cómo hacer que los barcos midan más que un solo punto del tablero. El maestro nos pidió que deben de haber barcos que ocupen 1,2,3 y 4 espacios dentro de un tablero (una matriz), mi problema es que  no hago idea del cómo hacer para que al ingresar yo una ubicación este barco se agregue ocupando el tamaño de barco que haya escogido el jugador.

A: Con este código puedes ingresar en una sola entrada las coordenadas, cuando lo ejecutes e ingreses las coordenadas, la entrada debe tener el siguiente orden para que funcione: fila columna espacio fila columna espacio fila columna espacio... así sucesivamente, un ejemplo de como tiene que ser: d3 d4 d5 d6 pone el barco en horizontal o bien puede ser b5 c5 d5 e5 pone el barco en vertical, la cantidad de coordenadas ingresadas determinara la longitud del barco, con lo cual, si ingresas a2 (una sola coordenada) el barco tendrá una longitud de uno, si ingresas a2 b2 (dos coordenadas) el barco tendrá una longitud de dos, aclarar que el código solamente se encarga de recibir las coordenadas en una única entrada por medio de un array tipo char y convierte letras y números a valores numéricos tipo int, no crea la matriz ni pone los barcos en la matriz, puedes implementarlo en tu código fuente como una función que puede llamar tu función principal main.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//reemplaza letras por el numero correspondiente
char reemplazar(char caracter){
    switch(caracter){
        case 'a':
            return '1';
        case 'b':
            return '2';
        case 'c':
            return '3';
        case 'd':
            return '4';
        case 'e':
            return '5';
        case 'f':
            return '6';
        case 'g':
            return '7';
        case 'h':
            return '8';
        case 'i':
            return '9';
    }

    return caracter;
}

int main(void){
    const int TAM = 17;
    char entrada[TAM];
    char fentrada[TAM];
    int i = 0, j = 0, cantCoo = 1;
    char *token;

    //captura de caracteres en array 'entrada' tipo char
    printf("Ingrese coordenadas: ");
    fgets(entrada,TAM,stdin);
    fflush(stdin);

    //reemplazar salto de linea por fin de cadena, debido a que se utilizo fgets para captura de caracteres
    while(entrada[i] != '\n') i++;
    entrada[i] = '\0';

    //crear formato que debera tener la secuencia de caracteres ingresados, para que strtok pueda hacer tokens con las comas
    for(i = 0; i < TAM-1; i++){
        if(i % 2 == 0){
            fentrada[i] = '-';
        }else{
            fentrada[i] = ',';
        }
    }

    //aplicar formato, guardando el formato resultante en 'fentrada'
    for(i = 0; entrada[i] != '\0'; i++){
        if(entrada[i] != ' '){
            fentrada[j] = entrada[i];
            fentrada[j] = reemplazar(fentrada[j]);
            j+=2;
        }
    }
    fentrada[--j] = '\0';

    //contar cantidad de numeros ingresados
    for(i = 0; fentrada[i] != '\0'; i++){
        if(fentrada[i] == ',') cantCoo++;
    }

    //crear array 'coordenadas' de tipo int, de longitud igual a los numeros ingresadas
    int coordenadas[cantCoo];
    i = 0;

    //convertir caracteres a numeros tipo int guardandolo en array 'coordenadas'
    coordenadas[i] = atoi(token = strtok(fentrada,","));
    while(token != NULL){
        coordenadas[++i] = atoi(token = strtok(NULL,","));
    }

    /*
    a partir de aqui las coordenadas estan listas para usar en el tablero
    recordar que en el array los numeros quedan: fila columna fila columna fila columna fila columna
    tal como se muestra recorriendo el array con los valores ya convertidos a int
    */

    for(i = 0; i < cantCoo; i++){
        if(i % 2 == 0){
            printf("fila   : %d\n",coordenadas[i]);
        }else{
            printf("columna: %d\n\n",coordenadas[i]);
        }
    }

    return 0;
}


text:
Q: Encode WELCOME using RSA encryption I am stuck on a problem using RSA encryption. We are encoding the message WELCOME.
$W= 23$
$E= 5$
$L= 12$
$C= 3$
$O= 15$
$M= 13$
$E= 5$
$n =77$ $\text{and}$ $e =31$
I've come up with a couple that are the same values as they were before encoding. Here's an example of $W$ and my approach to each letter.
$23^1\pmod{77}=23$
$23^2\pmod{77}=67$
$23^4\pmod{77}=23$
$23^8\pmod{77}=67$
$23^{16}\pmod{77}=23$
After which I multiply the values: $23*67*23*67*23=54617663$
$54617663/77 = 709320.2987$
$54617663-(77*709320)=23$
Is $23$ the correct encoded value? I've done a few others and had $L$ and $C$ end up with the same values as well. What am I doing wrong?

A: You are nont soing anything wring in the calculation. It is just that the modulus and exponent are suboptimal for cryptographic purposes.
While it is clear that $n=7\cdot 11$ must be composed of very small primes if one wants such an exercise to be feesible for manual calculation. But as direct consequence we'd have an immediate problem with the relatively many message numbers that fail to be coprime to the modulus, such as $G=7$, or $K=11$, or $N=14$ - which just happen not to be among the input.
But apart from this, also the exponent $e=31$ is not good. Note that for primes $p$ we have $x^p\equiv x\pmod p$ ("little Fermat"), and likewise $x^{k\cdot (p-1)+1}\equiv x\pmod p$, specifically $x^{5\cdot 6+1}\equiv x\pmod 7$ and $x^{3\cdot10+1}\equiv x\pmod{11}$. By the Chinese Remainde Theorem we conclude $x^{31}\equiv x\pmod {77}$, so your encryption is just a fancy way of sending cleartext.


text:
Q: Vertex Invariants for a 2-regular Graph If i have a graph in this form (adjacency matrix):
0 0 1 0 0 0 1
0 0 0 1 0 1 0
1 0 0 1 0 0 0
0 1 1 0 0 0 0
0 0 0 0 0 1 1
0 1 0 0 1 0 0
1 0 0 0 1 0 0
This is a 2-regular graph with 7 vertices. What are examples of vertex invariants? Usually i would look at the degrees of each vertex, but they are all the same in this case.

A: 2-regular (simple) graphs on n vertices are determined (up to isomorphism) by the partition of n induced by the size of its connected components.  This is because connected components of 2-regular graphs must be cycles.
Conversely, given a partition $d_1,d_2,\ldots,d_k$ of n into parts of size at least 3 (you can't have cycles of length 1 or 2, which would induce loops and multiedges) then you can construct a 2-regular graph consisting of a $d_i$-cycle for each $d_i$.
In the above case, the partition is 7 (since the graph is a 7-cycle).
0 0 1 0 0 0 1
0 0 0 1 0 1 0
1 0 0 1 0 0 0
0 1 1 0 0 0 0
0 0 0 0 0 1 1
0 1 0 0 1 0 0
1 0 0 0 1 0 0

There exist an automorphism of the graph that maps vertex u to vertex v provided u and v both belong to cycles of the same length.  To illustrate, you can fix everything outside of the components containing u and v, then

*

*if u and v are in the same cycle, just rotate the cycle, or otherwise,

*swap the cycles containing u and v, then rotate each appropriately.


text:
Q: Arial font for text in Android I want to show text in Arial font. But Arial font is not available in android system fonts. I don't want to use arial ttf file in my application. Is there any other way to apply text with Arial font.

A: Download Arial font and in assets create folder name with "fonts" and save font at there
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/arial.ttf");
TextView tv = (TextView) findViewById(R.id.CustomFontText);
tv.setTypeface(tf);

A: If the font is not available in the android system, then you have to use the font file to apply that particular font say arial to your textView. May I know why you are not willing to use the font file to apply as it gives the same functionality.
Sample usage for using the font file is:
Typeface tfArial = Typeface.createFromAsset(getAssets(), "arial.ttf");
TextView tv = null;
// find the textview id from layout or create dynamically
tv.setTypeface(tfArial);

EDIT:
You need to put the font file arial.ttf in your asset folder.

A: You can create your custom font just adding the .ttf file in "fonts" folder inside "res":

The xml files contain this:
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:font="@font/nunito_extrabold"
        android:fontStyle="normal"
        android:fontWeight="400" />
</font-family>

And that's all! You can use this font in every TextView just adding android:fontFamily property.
  <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/font_semibold"
        android:text="@string/custom_font"        />

A: You can add google font family from android studio by going to

*

*xml design

*add font family then there is limitem font family so click on

*more font family ( this is google font you can choose either add font or downloadable font)

*add font then click ok then the font will be added in your font list and you can use like default font.

A: Consider using Calligraphy to have any custom font in your Android application.
You will not need to add code in each TextView to apply a font. Simply initialise at application startup and you're good to go.

A: Create a TextView from Java Code or XML like this
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:textSize="15sp"
android:textColor="@color/tabs_default_color"
android:gravity="center"
android:layout_height="match_parent"
/>

Make sure to keep the id as it is here because the TabLayout check for this ID if you use custom textview
Then from code inflate this layout and set the custom Typeface on that textview and add this custom view to the tab
for (int i = 0; i < tabLayout.getTabCount(); i++) {
    //noinspection ConstantConditions
 TextView tv=(TextView)LayoutInflater.from(this).inflate(R.layout.custom_tab,null)
 tv.setTypeface(Typeface);
 tabLayout.getTabAt(i).setCustomView(tv);

}


text:
Q: javascript: how do I fix a 'not a function' error in an anonymous function? I converted a simple javascript function into one that uses a prototype.  Now a call in an anonymous function is getting the "not a function" error.
From some researching, I see the value of 'this' may not always be what you think it is when an anonymous function is used.
So, how do I fix this problem?
Here's the cut-down code to show the problem.

var chart;

chart = function Chart(){
    var xScale;
}

chart.prototype = {

  method1 : function() {
    this.xScale = d3.time.scale();
  }

  method2 : function () {

    this.xScale(0);  // No "not a function error here"

    // but I get the "not a function" error below when I call this.xScale(d.date)

    var overlay = d3.svg.area()
      .x(function (d) { return this.xScale(d.date); })
      .y0(0)
      .y1(height);
  }
}

A: Within the call to d3.svg.area().x(), this is, most likely, referring to the area object. If you want to use your function(d){}, it is easiest to just create another variable referring to your current object outside of this call:
method2 : function () {
    this.xScale(0);  // No "not a function error here"

    // store the current this here
    var thisChart = this;

    var overlay = d3.svg.area()
      .x(function (d) { return thisChart.xScale(d.date); })
      .y0(0)
      .y1(height);
}

By the way, as t.niese suggests, it's not a good idea to rely on method1 begin called before method2, to ensure that scaleX is defined.


text:
Q: Macbook 3,1 (2007 White Model) works slow and lags For the past year my Macbook has be getting slower, lauder and lags constantly...
The lags range from switching spaces to changing a language or even typing an input.
It almost never craches, but it does seem like his age is catching up to him...
I have tried formatting it completely already. I bought it with Leopard, and went through Snow Leopard to Lion. It got this way before the Lion installation (which I hoped would help), and now after completely reformatting my into Lion, it took only a few days for it to come back to this condition.
What can I do to make my Mac work right again?


text:
Q: Poi Formula evaluation Error I am using poi-3.8-20120326.jar and Excel 2007, trying to collect all the cell value in one list.
I am using formula for date increment operation. For example: =(i2+3) for k2 cell.
While evaluating this formula through my java code returns #VALUE! (i2 is a date cell.)

A: Without source it's hard to guess what's wrong, but I think that are two things that you may forget.
1) FormulaEvaluator
2) DataFormatter
Take a look at example.
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;

public class CellReader {

    private Workbook workbook;
    private DataFormatter formatter;
    private FormulaEvaluator evaluator;

    private void openWorkbook(String file) throws FileNotFoundException,
            IOException, InvalidFormatException {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);

            workbook = WorkbookFactory.create(fis);
            evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            formatter = new DataFormatter(true);
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
    }

    private void printXLSX() {
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;
        int lastRowNum;
        int lastCellNum;
        sheet = workbook.getSheetAt(0);

        lastRowNum = sheet.getLastRowNum();
        for (int j = 0; j <= lastRowNum; j++) {
            row = sheet.getRow(j);
            if (row == null) {
                continue;
            }
            lastCellNum = row.getLastCellNum();
            for (int k = 0; k <= lastCellNum; k++) {
                cell = row.getCell(k);
                if (cell == null) {
                    continue;
                }
                if (cell.getCellType() != Cell.CELL_TYPE_FORMULA) {
                    System.out.println(formatter.formatCellValue(cell));
                } else {
                    System.out.println(formatter.formatCellValue(cell,evaluator));
                }
            }

        }
    }

    public static void main(String[] args) {
        CellReader converter = null;
        try {
            converter = new CellReader();
            converter.openWorkbook("a.xlsx");
            converter.printXLSX();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}


text:
Q: Adding photo to OrgChart (smartart layout 98) This is so simple question that I am quite embarrassed to ask. I would like to add photo to org chart in PowerPoint. I am using SmartArtLayout(98), this is the kind of orgchart with a slot for image. I have tried reach this slot following IntelliSense suggestion but it led me nowhere.
I have been trying to google for any object model for this specific shape but I am unable to find anything. Could you help? I guess it must be something after:
ActivePresentation.Slides(1).Shapes(1).SmartArt.Nodes(1).

but what?
I have tried even to draw org chart in Excel and record a macro, however, inserting a photo were not recorded.

A: I think as per here:
SmartArtNode.Shapes.Item(1).Fill.UserPicture "c:\somepath\picture.jpg"
E.g.
With QNode.Shapes.Item(1).Fill
    .Visible = msoTrue
    .UserPicture "c:\somepath\picture.jpg"
    .TextureTile = msoFalse
End With

I think you need to do some fiddling the following idea does show the image only in the slot
Option Explicit

Sub test()

Dim oSALayout As SmartArtLayout
Dim myNode As SmartArtNode
Dim oShp As Shape

Set oSALayout = Application.SmartArtLayouts(98)

ActivePresentation.Slides(1).Shapes(3).SmartArt.Layout = oSALayout

Set oShp = ActivePresentation.Slides(1).Shapes(3)

Set myNode = oShp.SmartArt.AllNodes.Add

With myNode.Shapes(2).Fill

    .UserPicture "C:\Users\User\Desktop\XmasTree.jpg"

End With

End Sub


text:
Q: Text output for mutually exclusive radio buttons R Shiny Overall context: I am trying to build a decision tree app in shiny and have never used shiny before. I am trying to have text display when a certain radio button is selected. After trial and error I still can't get anything to display with different inputs. Below is the basic code.
library(shiny)

priceChange <- "Does it change the price?"
zpInfer1 <- "Can zero-price-change be inferred?"

ui <- fluidPage(
  radioButtons("exist", "Does it exist?",
               c("Yes" = "existYes",
                 "No" = "existNo"),
               textOutput("a")
  )

)

server <-   function(input, output){
  output$a <- renderText({
    existAnswer <- switch(input$exist,
                    existYes = priceChange,
                    existNo = zpInfer1)

  })
}

shinyApp(ui, server)

A: As @Phil said, this seems to be a simple syntax error. This one should work :
library(shiny)

priceChange <- "Does it change the price?"
zpInfer1 <- "Can zero-price-change be inferred?"

ui <- fluidPage(
  radioButtons("exist", "Does it exist?",
               c("Yes" = "existYes",
                 "No" = "existNo")),
               textOutput("a")

)

server <-   function(input, output){
  output$a <- renderText({
    existAnswer <- switch(input$exist,
                          existYes = priceChange,
                          existNo = zpInfer1)

  })
}

shinyApp(ui, server)


text:
Q: If HTML5 aims to reduce the need for external plugins, how can different audio/video codecs work? I've noticed that one of HTML5's goals is to reduce the need for external plugins — Flash, for example. Considering that browsers would need external plugins to support many formats of video and audio as well, does that goal make sense?
Would the browsers be supposed to maintain the codecs without any external library? Would the codecs be embedded? Or is the main reason to avoid closed solutions like Flash?

A: I think the reason behind it is to open up as much of the web to as many devices as possible.  External browser plugins prohibit this.  I also think there's a general agreement among the browser developers and development community that we need to have easy, cross-platform, in-browser video & audio playing.  It's no longer something that fringe sites are doing, it is a business necessity.
Will there be external browser plugins for playing video?  Absolutely.  But, a lot of video streaming services that are using Flash can start using HTML5 and open up their reach to more people.  Particularly people on mobile devices.  Which, let's face it,  right now, regardless of your device of choice chokes hardcore on Flash.  Mobile data and technology is the new in thing.  There's a lot of money to be made in streaming video reliably over a strained network.
For example, the US government's streaming service of Congressional committee meetings currently runs Flash.  This is a good example, in my opinion, of an existing video solution using Flash that should convert to HTML5.  Or a system where Flash is a fallback solution.
This is a very contentious issue though.  It is as much about opinion as it is fact...in my opinion.

A: Depends which standards group you ask.
WHATWG
The stated goal of the HTML5 being coordinated by the WHATWG (Web Hypertext Applications Technology Working Group) is "Web Applications". The draft "living" standard covers a wide range of technologies beyond HTML itself.

The WHATWG, while open to any participants, is largely a Google initiative that started at a time where the W3C wasn't doing much with HTML5. Other prominent members are Apple, Opera and Mozilla. Notably absent - Microsoft. Given that group it seems clear to me that the "unofficial" goal of HTML5 is to enable products like Google Docs and make it harder for MS to monopolise web applications.
Officially:

The Web Hypertext Application Technology Working Group (WHATWG) is a growing community
  of people interested in evolving the
  Web. It focuses primarily on the
  development of HTML and APIs needed
  for Web applications.
The WHATWG was founded by individuals
  of Apple, the Mozilla Foundation, and
  Opera Software in 2004, after a W3C
  workshop. Apple, Mozilla and Opera
  were becoming increasingly concerned
  about the W3C's direction with XHTML,
  lack of interest in HTML and apparent
  disregard for the needs of real-world
  authors. So, in response, these
  organisations set out with a mission
  to address these concerns and the Web
  Hypertext Application Technology
  Working Group was born.

W3C
If you asked the W3C though the primary goal of HTML5 would probably be "interoperability, accessability and openness" or something like that. Despite the claims of a lack of interest made by WHATWG the w3c has their own HTML5 working group and is currently making a last call to ratify a standard by 2014.
Officially:

The World Wide Web Consortium (W3C) is
  an international consortium where
  Member organizations, a full-time
  staff, and the public work together to
  develop Web standards. W3C primarily
  pursues its mission through the
  creation of Web standards and
  guidelines designed to ensure
  long-term growth for the Web. Over 325
  organizations are Members of the
  Consortium. W3C is jointly run by the
  MIT Computer Science and Artificial
  Intelligence Laboratory (MIT CSAIL) in
  the USA, the European Research
  Consortium for Informatics and
  Mathematics (ERCIM) headquartered in
  France and Keio University in Japan,
  and has additional Offices worldwide.

A: Yes, that is one of the criticisms of HTML5 is that it requires collaboration among browser technologies.
Google Chrome is already embedding many popular codecs.
The main reason is not to avoid closed solutions like the Flash Player (flex is open source, the player is not), the main reason is to create one open standard for development.
More info on their goals here:
http://www.w3.org/html/wiki/FAQs

A:
Would the browsers be supposed to maintain the codecs without any external library? Would the codecs be embedded?

It's up to the browsers what libraries they use, but yup, they're expected to bundle whatever libraries or codecs they need to handle audio and video so that the user doesn't have to install anything (like with images).
They're not required to support any possible video format that authors might want to use though. (Just like they're not required to display PhotoShop image files.)
There was a lot of discussion around choosing one video format for all browsers to implement (see http://lists.whatwg.org/htdig.cgi/whatwg-whatwg.org/2009-June/020620.html), but they couldn't agree on one. (Standards aren't perfect.) Hence the HTML5 spec doesn't mandate a particular format. But all browsers now support at least one video format natively, i.e. without the need for third-party plugins.

is the main reason to avoid closed solutions like Flash?

Possibly, although Opera and Microsoft are involved in the HTML5 standardisation effort, and their entire browsers are closed source. Bear in mind that web standards get made mostly by companies that make browsers — it's not like there's a completely independent standards body  with a bias towards open-source that invents HTML5 and tells browser-makers what to do.
I believe Firefox refused to support H.264 because it's not open-source, but equally Apple and Microsoft refused to support Ogg Theora because they thought the patent situation around it was too uncertain.


text:
Q: Can we refer angular 2 files from CDN instead of installing them from nodejs I have an angularjs 2 application. And I dont have nodejs installed (my company has some restrictions about software and it will take them for them to install it).
Can we refer all the angular files from CDN, instead of NPM it from nodejs.
Do we really need nodejs/npm for angularjs 2 to work ?

A: Yes you can. This is how plunkr works. See system.config.js and index.html of this plunk
Node and npm are there to ease the development to bring basic dependencies.
You can work without them with angular2 in JS ( for TS you need tsc installation)


text:
Q: Creating Strongly typed view showing big list in View data class  When I am creating Strongly Typed View I get lots of Classes in View Data Drop down. Classes like Automapper, ninject, Interface..., latebound... Due this its very hard to find my project classes. Is there any way to restrict dropdown to only display my project classes?
Hope you understand my problem.

A: Thanks for the report. There's currently no way to customize which types appear in that dialog. In the future we might improve things by providing searching, smarter filtering, etc, but this will not happen for MVC 3 RTM.


text:
Q: storing values in variable and print them using PHP Is it possible to do something like this? I'm new to this so don't know!
//row 1 in mysql array
$var = "hello";
$id = 1;

//row 2 in mysql array
$var = "bye";
$id = 2;

//Closing while loop

//Is the following possible?
echo $var1; //outputs "hello"
echo $var2; //outputs "bye"

A: Not like you want, you can use an array though:
$var[1] = "hello";
$var[2] = "bye";

echo $var[1];
echo $var[2];

A: You mention MySQL. So a more complete example of what you want to achieve would be:
$var = array();
$id  = array();
while ($row = mysql_fetch_assoc($result)) {
    $var[] = $row['text']; // don't know how the column is named
    $id[]  = $row['id'];
}

echo $row[0]; // hello
echo $row[1]; // bye

With a looping variable i:
$var = array();
$i = 1;
while ($row = mysql_fetch_assoc($result)) {
    $var[$i] = $row['text']; // don't know how the column is named
    $i++;
}

echo $row[1]; // hello
echo $row[2]; // bye

A: I would do so
$id = 1;
$var[$id] = "hello";
$id = 2;
$var[$id] = "bye";
echo $var['1'];
echo $var['2'];
// or
echo $var[$id];

A: // Define them both as arrays
$var = array();
$id = array();

// In your loop
$var[] = "hello";
$id[] = 1;

// Next iteration
$var[] = "bye";
$id[] = 2;

// Printing them out
echo $var[0]; // prints out "hello"
echo $var[1]; // prints out "bye"

Using arrays^^
Alternatively:
$rows = array();

// In your loop
$rows[] = array("id" => 1, "var" => "hello");

// Next iteration
$rows[] = array("id" => 2, "var" => "bye");

// Print them out
echo $rows[0]["var"]; // Prints hello
echo $rows[1]["var"]; // Prints bye


text:
Q: overflow-y: hidden on window height > x px not working in IE7 I am doing it like this but it doesn't seems to work in ie7
if($(window).height() > 700){
            $('body').css({'overflow-y':'hidden'});

        }else{
             $('body').css({'overflow-y':'visible','height':'700px'});

        }

it does work in all other browsers
any idea why?

A: "It is a well-known bug in IE6 and IE7. To solve it, you need to add position:relative to the container. Since in your case body is the container, I'd suggest you add a div directly under the body and give it position:relative. It should solve your problem."
See if this helps
IE6 + IE7 CSS problem with overflow: hidden; - position: relative; combo


text:
Q: How to input integer number in Swing? I have code
    NumberFormat format = NumberFormat.getIntegerInstance();
    format.setGroupingUsed(false);

    JFormattedTextField jtf = new JFormattedTextField(format);

    jtf.setValue(new Integer(0));
    jtf.setColumns(10);

but when I input characters in text field they stay printed until i switch to another text field. I need to forbid characters input totally, i mean when character is inputted i need to delete at the moment or make somehow for character to not even appear for processing by listener if that is possible and also not to appear in text field ofcourse. I mean only characters which are digits must appear.

A: I found a solution in possible duplicates for that question
Restricting JTextField input to Integers
    NumberFormat format = NumberFormat.getIntegerInstance();
    format.setGroupingUsed(false);

    NumberFormatter numberFormatter = new NumberFormatter(format);
    numberFormatter.setValueClass(Long.class);
    numberFormatter.setAllowsInvalid(false); //this is the key

    JFormattedTextField jFormattedTextField = new JFormattedTextField(numberFormatter);

A: It has been some time since I have worked on Swing, but I think you can
create your own Document and set it on the JTextField.
Then in the document object you can control which characters are accepted and rejected as the user types them in.
Here is an example setting a filter on a document:
Restricting JTextField input to Integers

A: I would use a JSpinner configured with a JSpinnerNumberModel.  This is specifically designed for integer input, and also gives the benefit of up/down arrow buttons for changing with the mouse.


text:
Q: Why my firebase "onAuthStateChanged" don't clear from useEffect Hook? I am getting this error from console 'Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.'
This is my function:
useEffect(() => {
    let isMounted = true;
    const onSubscribe = () => {
      auth.onAuthStateChanged((userAuth) => {
        if (userAuth && isMounted) {
          dispatch(
            login({
              email: userAuth.email,
              uid: userAuth.uid,
              displayName: userAuth.displayName,
              photoUrl: userAuth.photoURL,
            })
          );
        } else if (!userAuth && isMounted) {
          dispatch(logout());
        }
      });
    };
    onSubscribe();
    return () => {
      isMounted = false;
    };
  }, []);

I tried this way too
  useEffect(() => {;
    const onSubscribe = () => {
      auth.onAuthStateChanged((userAuth) => {
        if (userAuth) {
          dispatch(
            login({
              email: userAuth.email,
              uid: userAuth.uid,
              displayName: userAuth.displayName,
              photoUrl: userAuth.photoURL,
            })
          );
        } else if (!userAuth) {
          dispatch(logout());
        }
      });
    };
    onSubscribe();
    return () => {
      onSubscribe()
    };
  }, []);

A: Can you try it like this:

useEffect(() => {
    const unsubscribe =  auth.onAuthStateChanged((userAuth) => {
        if (userAuth && isMounted) {
          dispatch(
            login({
              email: userAuth.email,
              uid: userAuth.uid,
              displayName: userAuth.displayName,
              photoUrl: userAuth.photoURL,
            })
          );
        } else if (!userAuth && isMounted) {
          dispatch(logout());
        }
      });

    return unsubscribe;
  }, []);


text:
Q: Updating a subset of apps in a marathon group When using the v2/groups API to update a subset of applications in a group, how does one specify the configuration for those apps that are unchanged? Does the update request have to include the full original configuration for the unchanged app, or does one simply have to include its id to indicate it is still part of the group but with configuration unchanged?

A: You can either

*

*use PUT on the group and include the unchanged configuration as well. Marathon will detect which apps are changed and only redeploy changed applications.

*use PUT on the app endpoint to only change one of the apps in isolation.


text:
Q: Matlab :Error in Matrix dimensions I am interested in modelling the modified Shape analysis for which i have written a function which interpolates the Experimental values and also the curve which fits approximately the interpolated data
When i compute interpolation i am obtaining Matrix mismatch error, please kindly review it and let me know my My mistake
function [c_i,c_f,c_e] = M_shape_analysis(t,S,a1,a2,td,tmax,alpha,Be,p,q,r,k_el,k1,k2,k3)
%Modified Shape_analysis and estimating K3
%  Interpolation of measured Data points

c_i = zeros(size(t));

ind = (t > td) & (t < tmax);
c_i(ind) = S *(1 - exp(-alpha*t(ind)));
%c_t(ind)= (A_max*K_1*(t(ind)/(k2+k3)-(td*(k2+k3)/(k2+k3).^2)-(td/(k2+k3) -(td*(k2+k3)/(k2+k3).^2))*exp(-(k2+k3)*(t(ind)-td)))+(0.5*K_2*(t(ind)-td).^2));

ind = (t >= tmax);

a3 =(S *(1 - exp(-alpha*t(ind))) -(a1+a2));
c_i(ind) = a1*exp(-p * (t(ind) - tmax))+ a2*exp(-q * (t(ind) - tmax)) + a3*exp(-r * (t(ind) - tmax));
%c_t(ind) =((K_1*(A/(k2+k3-B))*(exp(B*(t(ind)-tmax))- exp(-(k2+k3)*(t(ind)-tmax)))+(K_2*(A/B)*(1+exp(B*(t(ind)-tmax))))));

%ft = fittype('Input_function(t, a1, a2, a3, b1, b2, b3, td, tmax)', 'independent', 't');

%fo = fit(t, c, ft,'StartPoint', [20000, 20000, 20000, 0.01, 0.01, 0.01, 10, 30],'Lower', [0, 0, 0, 0, 0, 0, 0, 0]);

%plot(t,c_t);
hold all;
subplot(2, 2, 2);
plot(t, c_i,'x');
axis([0 50 -2000 80000]);
xlabel time ;
ylabel concentration ;

%--------------------------------------------------------------------------------------------------------------------------
   % Fitting the measured Data

ind = (t > td) & (t < tmax);

c_f(ind)= conv(((t(ind) - td) ./ (tmax - td) * (a1 + a2 + a3)),(k1*exp(-(k2+k3)*t(ind)+((k1*k3)/(k2+k3-k_el)))),'same');

ind = (t >= tmax);

c_f(ind) = conv((a1 * exp(-b1 * (t(ind) - tmax))+ a2 * exp(-b2 * (t(ind) - tmax))) + a3 * exp(-b3 * (t(ind) - tmax)),(k1*exp(-(k2+k3)*t(ind)+((k1*k3)/(k2+k3-k_el)))),'same');

hold all;
subplot(2, 2,4);
plot(t, c_f);
axis([0 50 -2000 80000]);
xlabel time ;
ylabel concentration ;

%plot(ts, Input_function(ts, fo.a1, fo.a2, fo.a3, fo.b1, fo.b2, fo.b3, fo.td, fo.tmax));

%--------------------------------------------------------------------------------------------------------------------------
   % Plotting K3 Estimate : Fitted curve

  DV_free= k1/(k2+k3);

  ind = (t >= tmax);
   c_e(ind) = DV_free* exp(-Be*t(ind));

subplot(2, 2, 6);
plot(t, c_e);

axis([0 50 -2000 80000]);
xlabel time ;
ylabel concentration ;

end

Following is the error that i am obtaining
Error using  *
Inner matrix dimensions must agree.

Error in M_shape_analysis (line 17)
c_i(ind) = a1*exp(-p * (t(ind) - tmax))+ a2*exp(-q * (t(ind) - tmax)) + a3*exp(-r *
(t(ind) - tmax));

Kindly let me know where i have mistaken in my modelling

A: I cannot point out where the exact error is because I am unaware of dimensions of your input arguments. The error is due to the fact that you are using * operator when either:

*

*You want to perform matrix multiplication when the dimensions of the two matrices being multiplied are not in agreement. For example, one has to be a mxn and the other has to be a nxk matrix. I am assuming you are aware of this.

*You want to perform element-wise multiplication and not matrix multiplication. If that is the case, then you have to use .* operator.  If you want to multiply scalar with a vector (or matrix), you can use either operator.
I believe point no. 2 is the cause of the error.
Read times vs. mtimes i.e. (.* vs *).


text:
Q: Escape JavaScript quotes in EL in a JSF component attribute I have an onclick event that depends on the state of a variable. So I need to do something like
onclick="#{object.isEnabled ? 'ch.my.js_method('#{object.property}'); return false;' : 'return false;'"

The problem is, that I can't use ' inside of the onclick. How can I escape the quotes inside of the EL?

A: You can escape them with \ or \\, but rules differ per EL implementation, because it isn't clear cut in EL spec (Oracle's EL impl needs single backslash, but Apache needs double backslash). And you need the += operator to string-concatenate the EL expression.
<x:someComponent onclick="#{object.isEnabled ? 'ch.my.js_method(\'' += object.property += '\'); return false;' : 'return false;'}" />

Safest bet is to just create an alias with help of <c:set>.
E.g.
<c:set var="js_method" value="ch.my.js_method('#{object.property}'); return false;" />
<x:someComponent onclick="#{object.isEnabled ? js_method : 'return false;'}" />

You've only still a potential problem if #{object.property} can contain JS-special characters which can in turn cause invalid JS output, such as single quotes or newlines. Head to the second link below for the solution to that.
See also:

*

*How to concatenate Strings in EL expression?

*How do I pass JSF managed bean properties to a JavaScript function?

A: I found another solution: just invert the condition and add the event afterwards. This way the quotes around the JS method are not needed:
onclick="#{object.isEnabled == 'false' ? 'return false;' : ''} ch.my.js_method('#{object.property}'); return false;"


text:
Q: How to turn function into .prototype? Problem
I have created a function that breaks an array into sentences within an array.
But, at the moment, I can only do one array at a time. The objects name will be created created dynamically.
Is there anyway to convert the create_Sentences function into a .prototype.
This way, the create_Sentences function is dynamic.

sentences = {
  load: [],
  all: [
    "If you're visiting this page, you're likely here because you're searching for a random sentence. Sometimes a random word just isn't enough, and that is where the random sentence generator comes into play. By inputting the desired number, you can make a list of as many random sentences as you want or need. Producing random sentences can be helpful in a number of different ways."
  ]
}
graphic_designer = {
  logo_designer: [
    "For those writers who have writers' block, this can be an excellent way to take a step to crumbling those walls. By taking the writer away from the subject matter that is causing the block, a random sentence may allow them to see the project they're working on in a different light and perspective. Sometimes all it takes is to get that first sentence down to help break the block."
  ],
  grand_master: [
    "It can also be successfully used as a daily exercise to get writers to begin writing. Being shown a random sentence and using it to complete a paragraph each day can be an excellent way to begin any writing session."
  ],
  hello: [
    "Random sentences can also spur creativity in other types of projects being done. If you are trying to come up with a new concept, a new idea or a new product, a random sentence may help you find unique qualities you may not have considered. Trying to incorporate the sentence into your project can help you look at it in different and unexpected ways than you would normally on your own."
  ]
}

function create_Sentences() {
  a = /([.?!])\s+([a-zA-Z]|[$\-])/g
  b = "$1" + "newSentence newSentence" + "$2"
  c = "newSentence newSentence"
  modifiedText = sentences.all[0].replace(a, b)
  sentences.all = modifiedText.split(c)
}
create_Sentences()

document.write("
" + JSON.stringify(sentences, null, 2) + "
");
document.write("
" + JSON.stringify(graphic_designer, null, 2) + "
");

What I've tried
I've tried to execute something along these lines multiple times.
Yet it keeps failing.

sentences = {
  load: [],
  all: [
    "If you're visiting this page, you're likely here because you're searching for a random sentence. Sometimes a random word just isn't enough, and that is where the random sentence generator comes into play. By inputting the desired number, you can make a list of as many random sentences as you want or need. Producing random sentences can be helpful in a number of different ways."
  ]
}
graphic_designer = {
  logo_designer: [
    "For those writers who have writers' block, this can be an excellent way to take a step to crumbling those walls. By taking the writer away from the subject matter that is causing the block, a random sentence may allow them to see the project they're working on in a different light and perspective. Sometimes all it takes is to get that first sentence down to help break the block."
  ],
  grand_master: [
    "It can also be successfully used as a daily exercise to get writers to begin writing. Being shown a random sentence and using it to complete a paragraph each day can be an excellent way to begin any writing session."
  ],
  hello: [
    "Random sentences can also spur creativity in other types of projects being done. If you are trying to come up with a new concept, a new idea or a new product, a random sentence may help you find unique qualities you may not have considered. Trying to incorporate the sentence into your project can help you look at it in different and unexpected ways than you would normally on your own."
  ]
}

String.prototype.create_Sentences = function() {
  a = /([.?!])\s+([a-zA-Z]|[$\-])/g
  b = "$1" + "newSentence newSentence" + "$2"
  c = "newSentence newSentence"
  modifiedText = this[0].replace(a, b)
  this = modifiedText.split(c)
}

sentences.all.create_Sentences()
graphic_designer.logo_designer.create_Sentences()
graphic_designer.grand_master.create_Sentences()
graphic_designer.hello.create_Sentences()

document.write("
" + JSON.stringify(sentences, null, 2) + "
");
document.write("
" + JSON.stringify(graphic_designer, null, 2) + "
");

A: sentences is an object, you need to add function in object prototype.
Example:

sentences = {
  load: [],
  all: [
    "If you're visiting this page, you're likely here because you're searching for a random sentence. Sometimes a random word just isn't enough, and that is where the random sentence generator comes into play. By inputting the desired number, you can make a list of as many random sentences as you want or need. Producing random sentences can be helpful in a number of different ways."
  ]
}
graphic_designer = {
  logo_designer: [
    "For those writers who have writers' block, this can be an excellent way to take a step to crumbling those walls. By taking the writer away from the subject matter that is causing the block, a random sentence may allow them to see the project they're working on in a different light and perspective. Sometimes all it takes is to get that first sentence down to help break the block."
  ],
  grand_master: [
    "It can also be successfully used as a daily exercise to get writers to begin writing. Being shown a random sentence and using it to complete a paragraph each day can be an excellent way to begin any writing session."
  ],
  hello: [
    "Random sentences can also spur creativity in other types of projects being done. If you are trying to come up with a new concept, a new idea or a new product, a random sentence may help you find unique qualities you may not have considered. Trying to incorporate the sentence into your project can help you look at it in different and unexpected ways than you would normally on your own."
  ]
}

Object.prototype.createSentences = function createSentences() {
  var a = /([.?!])\s+([a-zA-Z]|[$\-])/g;
  var b = "$1" + "newSentence newSentence" + "$2";
  var c = "newSentence newSentence";
  modifiedText = this.all[0].replace(a, b);
  return modifiedText.split(c)
}
document.write("
" + JSON.stringify(sentences.createSentences(), null, 2) + "
");

PS: comment if any questions.
If you want in String prototype, need to send sentences.all[0].
Example Snippet :

sentences = {
  load: [],
  all: [
    "If you're visiting this page, you're likely here because you're searching for a random sentence. Sometimes a random word just isn't enough, and that is where the random sentence generator comes into play. By inputting the desired number, you can make a list of as many random sentences as you want or need. Producing random sentences can be helpful in a number of different ways."
  ]
}
graphic_designer = {
  logo_designer: [
    "For those writers who have writers' block, this can be an excellent way to take a step to crumbling those walls. By taking the writer away from the subject matter that is causing the block, a random sentence may allow them to see the project they're working on in a different light and perspective. Sometimes all it takes is to get that first sentence down to help break the block."
  ],
  grand_master: [
    "It can also be successfully used as a daily exercise to get writers to begin writing. Being shown a random sentence and using it to complete a paragraph each day can be an excellent way to begin any writing session."
  ],
  hello: [
    "Random sentences can also spur creativity in other types of projects being done. If you are trying to come up with a new concept, a new idea or a new product, a random sentence may help you find unique qualities you may not have considered. Trying to incorporate the sentence into your project can help you look at it in different and unexpected ways than you would normally on your own."
  ]
}

String.prototype.createSentences = function createSentences() {
  var a = /([.?!])\s+([a-zA-Z]|[$\-])/g;
  var b = "$1" + "newSentence newSentence" + "$2";
  var c = "newSentence newSentence";
  modifiedText = this.replace(a, b);
  return modifiedText.split(c)
}
document.write("
" + JSON.stringify(sentences.all[0].createSentences(), null, 2) + "
");

A: There's actually two problems here. The basic one is that
sentences.all

is an array, not a string, so you can't call your create_sentences() function against it. You could try
sentences.all.forEach( s => s.create_sentences );

...or you could make create_sentences() into a function on the Array prototype.
The other issue is that the create_sentences() function is trying to alter a string object in place, which isn't actually possible because javascript strings are immutable. So when you do
this = modifiedText.split(c);

...it doesn't make any sense, because this can't be reassigned. What you're trying to do is make a change to a string object, but all you can do is create a modified copy. So I'd do
return modifiedText.split(c);

and call it with
var newSentence = oldSentence.create_sentences();

A: The reason is that you're modifying the String prototype after you've created the Strings you want to work on. Modifying a prototype only affects objects that are created after you do the modification (because object creation basically involves copying the prototype). So do your String.prototype.create_Sentences stuff first, and it should all work fine.


text:
Q: Ajax No Access-Control-Allow-Origin using type 'HEAD' I ran into this problem when using this solution to check if the image is valid.
However I get a

No Access-Control-Allow-Origin error

, and I have no access to the image server.
Any help will be appreciate!

A: The problem lies within JS policy not to allow cross-origin (or to put it simple - cross-domain) requests to prevent intrusions etc. If the server does not allow cross-origin requests (using specific headers in communication), you won't be able to get your image even if it exists.
This and this should enlighten you a bit.


text:
Q: Amazon MWS Report API always change the request reports to status 'CANCELLED' I want to use the Amazon MWS Report API and I am using this http://docs.developer.amazonservices.com/en_US/reports/Reports_Overview.html.
I create successfully Request report, but when I check the report with GetReportRequestList call my request has 'CANCELLED' status.
Is there a way to find why the report request are cancelled?
Any help would be appreciated.

A: I think the answer might be here: Do not request FBA reports more frequently than they are generated
The same thing happened to me years ago and it was because I was testing with the scratchpad and sending too many requests in a short amount of time.


text:
Q: VB 2013: Enabling Aero on borderless form I am looking for a way to add the Aero functions of Windows back into a bordlerless windows form in Visual Basic 2013. I have coded a custom component for the titlebar to allow be to set my own background/design for it, as well as the minimize, maximize, and close buttons. I am having issues, however, finding a way to make the Windows Aero properties come back, such as:

*

*dragging the to the top or sides of the screen to change it's size

*animations upon resizing/minimizing/maximizing

I am making a custom looking form, such as that found in Google Chrome and Visual Studios. The Aero functionality is my only issue. Does anyone happen to know how to add it to a borderless form in Visual Basic 2013?

A: Partial answer that might help:
Without the form borders, the only way I was able to get the resize portion to work was to use panels on all sides use the mouse events to control actions.  The panels were transparent, but the mouse enter event would facilitate changing the cursor event as well.
'**************************************************
    'MouseDown = User clicks the button
    'MouseMove = User is holding down the left mouse button and moves the mouse.  Simulates top of a regular form
    'MouseUp = User releases the mouse button
    '**************************************************
    Private Sub Panel1_MouseDown(sender As Object, e As MouseEventArgs) Handles Panel1.MouseDown
        If e.Button = Windows.Forms.MouseButtons.Left Then
            drag = True
            mouse_x = Windows.Forms.Cursor.Position.X - Me.Left
            mouse_y = Windows.Forms.Cursor.Position.Y - Me.Top
        End If
    End Sub
    Private Sub Panel1_MouseMove(sender As Object, e As MouseEventArgs) Handles Panel1.MouseMove
        If drag Then
            Me.Top = Windows.Forms.Cursor.Position.Y - mouse_y
            Me.Left = Windows.Forms.Cursor.Position.X - mouse_x
        End If
    End Sub
    Private Sub Panel1_MouseUp(sender As Object, e As MouseEventArgs) Handles Panel1.MouseUp
        drag = False
    End Sub


text:
Q: Magento 2.x PHP memory_limit requirements I noticed that Magento 2.1 manual recommends memory_limit=2G in php.ini.  That is a crazy amount of memory, isn't that memory allowed per HTTP request?  I doubt there is any hosting provider that provides that amount of memory for PHP scripts, and certainly makes Magento not viable for shared hosting.
Is that perhaps an amount for setup and migration?  Is that amount really needed for production?
I also found in the documentation:
Set the PHP memory limit.
Our detailed recommendations are:
Compiling code or deploying static assets, 756M
Installing and updating Magento components from Magento Marketplace, 2G
Testing, 2G

It doesn't mention production recommendations. What is recommended for production?

A: As the documentation snippet you found explains, 2G is the memory limit to cover all possible use cases. Some operations (particularly command-line operations like setup, testing, and compilation) can take a substantial amount of memory depending on the size and complexity of your installation.
Some things to note:

*

*memory_limit is the maximum amount of memory a given PHP request is allowed to take before it will be terminated. It is not the total amount of memory each request will take. In practice, most front-facing requests will take far less memory (probably 60 MB or less for most CMS pages, categories, products), with some outliers (checkout) taking several times more depending on integrations, customization, etc.

*Some servers allow you to set different memory limits for web requests versus the command line. If so, you should have a CLI limit of 2G, and a web limit of 768M or less.

*Magento itself tries to enforce a default 768M limit across-the-board, via rules in .htaccess and pub/.htaccess: php_value memory_limit 756M, and in .user.ini: memory_limit = 756M

*The 'technology stack requirements' page you probably saw regarding 2 GB minimum is talking about total system memory, not PHP memory limit. If you try running Magento2 on a virtual private server with less than 2 GB of RAM (including swap), you are going to have a bad time.

*A dedicated environment will always be better than shared hosting, but Magento2 does work on shared hosting. Magento worked extensively with some common hosting providers including GoDaddy to make one-click installations a reality. There are also Magento-specialized hosts like Nexcess that provide a higher level of shared service for a few dollars more.


text:
Q: Null Values in Subquery I have  subquery where CompletedDate have Null Values i need to add tht null values my Output with not null values .
       select * from Crew c
 where

 a.CrewDate > '2016/12/22 00:00:00'
   and ActionTypeID = 20
 ---  and objectid = 73658
  AND CrewDate IN (SELECT MAX(CrewDate) FROM Crew cc WHERE c.ObjectID =
  cc.ObjectID
   AND cc.crewTypeID = 20
    )
 **AND A.CompletedDate IN  (SELECT MAX(CompletedDate)   FROM crew cc WHERE
 c.ObjectID = cc.ObjectID
AND AA.ActionTypeID = 20**
 )
   order by ObjectID

oBJECTid     CompletedDate               Createddate
1445209     2017-01-04 09:36:30          2016-12-22 00:00:03
3145514     2017-01-30 15:43:02          2016-12-22 00:00:03
2778154     NULL                         2016-12-22 00:00:03
3025853     2017-01-30 15:43:02          2016-12-22 00:00:03
2342785     2017-03-03 12:02:17          2016-12-22 00:00:03
3113524     NULL                         2016-12-22 08:04:58
3198917     2017-08-16 07:38:29          2016-12-22 08:06:08
1245218     NULL                         2016-12-22 08:12:20
3433585     NULL                         2016-12-22 08:14:35

at the moment my query taking out Null values but i need null values in output

A: If I understand correctly your issue, then you need to use LEFT JOIN sub-query instead of IN sub-query
Please review next SQL code:
SELECT
    c.ObjectID,
    cc.MaxCrewDate,
    cd.MaxCompletedDate
FROM Crew c
LEFT JOIN
(
    SELECT
        cc.ObjectID
        MAX(cc.CrewDate) AS MaxCrewDate
    FROM Crew cc
    WHERE cc.crewTypeID = 20
    GROUP BY cc.ObjectID
) AS cc ON cc.ObjectID = c.ObjectID
LEFT JOIN
(
    SELECT
        cd.ObjectID,
        MAX(CompletedDate) AS MaxCompletedDate
    FROM Crew cd
    WHERE cd.ActionTypeID = 20
    GROUP BY cd.ObjectID
) AS cd ON cd.ObjectID = c.ObjectID


text:
Q: illegal operation on a directory, open Using this answer, with mkdirp, I want to create a directory and save files inside. Inside of plates those folders will be created and reuse if present.
const fs = require('fs')
const mkdirp = require('mkdirp')

// Decode image then save to local storage
const decodeBase64Image = (string, plateNumber) => {
  let regex = /^data:.+\/(.+);base64,(.*)$/
  let matches = string.match(regex)
  let ext = matches[1]
  let data = matches[2]
  let buffer = new Buffer(data, 'base64') // I cant use Buffer.alloc()

  let pathForImages = `plates/${plateNumber}`

  saveImagesToPath(pathForImages, ext, buffer)
}

const saveImagesToPath = (pathForImages, ext, buffer) => {
  mkdirp(pathForImages, function (err) {

    fs.writeFileSync(pathForImages, 'data.' + ext, buffer)

  })
}

let string = "data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/<SHORTEN>w=="

// Performing it all
decodeBase64Image(string, 'HGT5KU')

Error message:
fs.js:651
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^

Error: EISDIR: illegal operation on a directory, open 'plates/HGT5KU'

Basically, create a sub-folder for "plates" with the name of the plate numbers  and save data inside that folder: plates/HGT5KU/foo.png others: plates/GFTYU7/bar.jpg

A: You're telling fs.writeFileSync to write to the directory, not to a file within the directory:
mkdirp(pathForImages, function (err) {
  fs.writeFileSync(pathForImages, 'data.' + ext, buffer)
// ----------------^^^^^^^^^^^^
})

Of course that's going to fail. You need to add a filename to the path:
mkdirp(pathForImages, function (err) {
  const filename = /*...create appropriate filename...*/;
  fs.writeFileSync(pathForImages + "/" + filename, 'data.' + ext, buffer)
})

Side notes:

*

*It's not generally good practice to ignore errors. mkdirp can fail, you need to check err.

*Since mkdirp is asynchronous, using a synchronous call within it is pointless and unnecessarily ties up the JavaScript thread. Just use writeFile. In general, avoid xyzSync functions without a really good reason to use them.

*Proabably best to test for errors from writeFileSync/writeFile, too. :-)

A: Please use the file name in the path along with the file data.
Ex:
const fullPath = path.join('c/d', 'somefilename');
fs.writeFile(fullPath, file.data);


text:
Q: Theorem 2.4.5 of Hormander's book Hi I was trying to understand Theoerem 2.4.5 of Hormander's book "An Introduction to Complex Analysis in Several Variables". It shows the existence and uniqueness of power series expansion of any holomorphic function in a connect Reinhardt domain containing the origin. However I don't have a big picture of how to prove it, like why we construct $\Omega_\epsilon$. Below are some of my questions so far:

*

*how to show $\Omega_\epsilon$ is open? I was trying to use definition and inverse triangle inequality to prove it but it was unsuccessful.

*Why do we need the component of $\Omega_\epsilon$, denoted by $\Omega_\epsilon^\prime$. Furthermore, why we need to note that $\Omega = \cup_{\epsilon > 0} \Omega_\epsilon^\prime$ and then when $z \in \Omega_\epsilon^\prime$, we define a such integral, called $g(z)$?

*How to show $g(z)$ is holomorphic in $\Omega_\epsilon$? I know if we can show it, then we can apply the principle of analytic continuation to derive $f = g$.
Any help will be appreciated!

A: A Reinhardt domain $D$ is a region that can be characterized  by its schematic diagram in absolute space (the space of absolute values of the coordinate entries). For example, in two complex variables, if $D$ is Reinhardt, then $(z_1, z_2)\in D \iff (|z_1|,|z_2|)\in D $ Consequently, to visualize $D$  we first sketch the diagram in absolute space comprising  all ordered pairs of non-negative real values $ (r_1, r_2)$ in $D$.  Denote this absolute region in the first quadrant of the real plane $[0,\infty] \times [0, \infty]$ by $|D|$.
For each pair of positive such radii  in $|D|$ , a point pair $p=(r_1, r_2)$, we can construct a  multivariable Cauchy integral formula $I(p)$ that we suspect  ought to properly represent a given analytic function  $f(z)$ inside the associated poly-disk region $R(p)= \{(z_1, z_2) :|z_1|<r_1, |z_2|<r_2\}$.  To prove this representation $I(p)$ for $f(z)$ is actually independent of $p \in |D|$, we use two ideas: (i) under a small perturbation to nearby point $p'\in|D|$ the integral representation $I(p')$ agrees with that of $I(p)$ on the intersection of the two associated poly-disks $R(p)\cap R(p')$ (a region that contains the origin).  (Hormander uses dilations to perturb $p$ to $p'$. Thus one dilated poly-disk is a subregion of the other.) Also (ii) note that if we deform the point $p$ to be sufficiently near the origin we are indeed recovering $f(z)$.
Suggestion.Try drawing an open region $|D|$  in absolute space that worms around in the plane  starting from an open nbd of the origin to see how the global property is pieced together from local information.
(Broadly speaking this has the flavor of the typical path deformation principle in one complex variable for passing from local to global uniqueness of a representation of an analytic function.)


text:
Q: How to Save Shared Preference Value in ClearData Application?[Android] In clear Data Android, Shared Preference is clear. I don't want it clear.

A: If you clear the app data, shared preferences will also be cleared, you have to store in your database or cloud.

A: there is a trick for that, it is not a normal way but works:
<application android:label="MyApp" android:icon="@drawable/icon"
                 android:manageSpaceActivity=".ActivityOfMyChoice">

by adding this line to your manifest instead of "Clear Data" button for "Manage Space" which launches ActivityOfMyChoice will be shown, it calls your activity and the Activity and you can finish your activity there like this:
public class ActivityOfMyChoice extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        finish();

    }
}

for me, this method worked!
let me know about the result
for more info, if you want to save your data even after "clear data" you might use the database to save your data and save your database in a file out of your application place in the device.


text:
Q: Use a custom function as argument to Ecto order_by I have a function distance/2 which calculates the Levenshtein Distance between two strings.
I would like to use this as an argument for order_by/3 (documentation), so that the result be ordered by Levenshtein distance to a term, as I am trying to implement a rudimentary autocomplete.
Currently, I have something like:
Api.Repo.all(from p in Api.Product, select: p.name, order_by: distance(p.name, ^term), where: p.company_id == ^company_id)

however this errors, stating that:
'distance(p.name ^term)' is not a valid query expression.
I have also tried moving the ^ to before the function like so:
Api.Repo.all(from p in Api.Product, select: p.name, order_by: ^distance(p.name, term), where: p.company_id == ^company_id)

however then I get a complaint that p/0 is undefined.
Is there a way to use my function as an argument to order_by/3?

A: You cannot call an Elixir function from within a query like that. You'll either have to use a function that your database allows in queries or do the sorting after fetching all data into Elixir. The second method can be done like this:
products =
  Api.Repo.all(from p in Api.Product, select: p.name, where: p.company_id == ^company_id)
  |> Enum.sort_by(&distance(&1, term))


text:
Q: How to create/modify the controller class generated by pylons? Say I wanted to add some imports to the file generated when I run:
paster controller controllern_name

Is this possible?

A: I assume you want to modify the pylons templates -- in this case controller.py_tmpl. It's best to create your own set of templates based on the ones from pylons, and then use them when starting a new project.


text:
Q: How to create modal forms in ASP.NET? At the moment,  I have a form in its own view in an ASP MVC application.
@model MyPortal.ViewModels.NewStudentViewModel
@{
    ViewBag.Title = "NewStudent";
    Layout = "~/Views/Shared/_LayoutStaff.cshtml";
}

New Student

@using (Html.BeginForm("CreateStudent", "Staff"))
{

    @Html.LabelFor(s => s.Student.Id)
    @Html.TextBoxFor(s => s.Student.Id, new { @class = "form-control" })
    @Html.ValidationMessageFor(s => s.Student.Id)

        @Html.LabelFor(s => s.Student.FirstName)
        @Html.TextBoxFor(s => s.Student.FirstName, new { @class = "form-control" })
        @Html.ValidationMessageFor(s => s.Student.FirstName)

        @Html.LabelFor(s => s.Student.LastName)
        @Html.TextBoxFor(s => s.Student.LastName, new { @class = "form-control" })

        @Html.LabelFor(s => s.Student.YearGroup)
        @Html.DropDownListFor(s => s.Student.YearGroup, new SelectList(Model.YearGroups,"Id","Name"),"" ,new { @class = "form-control" })

        @Html.LabelFor(s => s.Student.RegGroup)
        @Html.DropDownListFor(s => s.Student.RegGroup, new SelectList(Model.RegGroups,"Id","Name"),"" ,new { @class = "form-control" })

        @Html.LabelFor(s => s.Student.FourMId)
        @Html.TextBoxFor(s => s.Student.FourMId, new { @class = "form-control" })

    @Html.HiddenFor(s => s.Student.AccountBalance, new {Value = 0.00})
    @Html.AntiForgeryToken()
    <button type="submit" class="btn btn-primary">Save</button>
}

@section scripts
{
    @Scripts.Render("~/bundles/jqueryval")
}

However, I would like to render this form in a Bootstrap modal above the Students table (in the Students view).
I have an API under api/students, and I'm guessing I need to use AJAX in order to submit the form.
The modal form should then close upon submission without refreshing the page (with the new student appearing in the DataTable).
UPDATE:
I understand how to create modals in the View, however, I'm not sure how to build a form correctly using AJAX (as the form will need a new Student object each time).

A: You should change the form to Ajax as Ajax.BeginForm() - see https://www.c-sharpcorner.com/UploadFile/0c1bb2/ajax-beginform-in-Asp-Net-mvc-5/
This way - you can use events like "OnComplete" to do after form POST logic such as hiding the modal etc (not always necessary but helpful)
Create your modal as:

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

          @Html.RenderAction("Your Student GET action method", "Controller")

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

use a hyperlink or a button to load the modal:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

Since you already have data-toggle and data-target as attributes in button tag - you won't need any additional script.

There are other ways to load/upload modal content. If you do not wish to prerender modal body with students Create view... you can use jQyery .get to retrieve the view from your controller's action method. Something like:
$('button').on('click', function() {
    $.get(url).done(function(res) {
        $('.modal-body').html(res); // this will append View html to Modal body div.
        $('#myModal').modal('show'); // this will trigger show event.
    });
})

Alternatively, you can also code the view load part in modal event:
$('#myModal').on('show.bs.modal', function (e) {
   $.get(url).done(function(res) {
        $('.modal-body').html(res);
    });
})


text:
Q: Linux Bash script to read samba config I'm trying to create a bash script that will read the samba config, loop through the different "sections" and act if a variable is set
Here is an example config:
[global]
    workgroup = METRAN
    encrypt passwords = yes
    wins support = yes
    log level = 1
    max log size = 1000
    read only = no
[homes]
    browsable = no
    map archive = yes
[printers]
    path = /var/tmp
    printable = yes
    min print space = 2000
[music]
    browsable = yes
    read only = yes
    path = /usr/local/samba/tmp
[pictures]
    browsable = yes
    read only = yes
    path = /usr/local/samba/tmp
    force user = www-data

Here is kinda what I want to do (I know this syntax a real language, but it should give you the idea:
#!/bin/sh
#
CONFIG='/etc/samba/smb.conf'
sections = magicto $CONFIG    #array of sections
foreach $sections as $sectionname       #loop through the sections
  if $sectionname != ("homes" or "global" or "printers")
    if $force_user is-set
       do something with $sectionname and with $force_user
    endif
    else
       do something with $sectionname
    endelse
  endif
endforeach

A: This will read each section and get key,value pair.
#!/bin/bash
CONFIG='/etc/samba/smb.conf'
for i in homes music; do
    echo "$i"
    sed -n '/\['$i'\]/,/\[/{/^\[.*$/!p}' $CONFIG | while read -r line; do
        printf "%-15s : %s\n" "${line%?=*}" "${line#*=?}"
    done
done

Output
homes
browsable  : no
map archive : yes
music
browsable  : yes
read only  : yes
path       : /usr/local/samba/tmp

Explanation

*

*sed -n '/\['$i'\]/,/\[/{/^\[.*$/!p}'
1) /\['$i'\]/,/\[/ Matches the section name between [] until the next [
2) {/^\[.*$/!p} Matches the start of line ^ followed by [ and zero or more characters .* until end of line $ and if matches don't print !p

*${line%?=*} Trim string from the end (right) until first = and any char ?

*${line#*=?} Trim string from the start (left) until first = and any char ?

A: Using Perl:
use strict;
use warnings;

sub read_conf {
  my $conf_filename = shift;
  my $section;
  my %config;
  open my $cfile, "<", $conf_filename or die ("open '$conf_filename': $!");
  while (<$cfile>) {
    chomp;
    if (/^\[([^]]+)]/) {
      $section = $1;
    } else {
      my ($k, $v) = split (/\s*=\s*/);
      $k =~ s/^\s*//;
      $config{$section}{$k} = $v;
    }
  }
  close $cfile;
  return \%config;
}

sub main {
  my $conf_filename = '/etc/samba/smb.conf';
  my $conf = read_conf($conf_filename);
  foreach my $section (grep { !/homes/ and !/global/ and !/printers/} keys %$conf) {
    print "do something with: $section\n";
    foreach my $key (keys %{$conf->{$section}}) {
      my $val = $conf->{$section}{$key};
      print "$key is $val in $section\n";
    }
  }
}

main;

A: If you're comfortable with Perl, you might look at Config::Std
http://metacpan.org/pod/Config::Std
Compliments of this question: How can I find all matches to a regular expression in Perl?


text:
Q: RESIZING REPORTS IN OBIEE 12C I am new to OBIEE but I have had cosiderable experience working with oracle reports. I loved the dynamism of oracle reports because I could play with the page heights and width as I wished. However, I have run into an obstacle with OBIEE in that the items are squeezed to fit the width of the report depending on the layout chosen. Is there a way to bypass the default size ?

A: First of all if you're using OBIEE then you're using analyses,not reports. If you're really using report and want something reminiscent of Oracle Reports it's rather BI Publisher. Its a separate tool and technology but it comes integrated with OBIEE. That said OBIEE is analytics. BI Publisher is pixel-perfect reporting. Huge difference.


text:
Q: 'QuerySet' object has no attribute 'images' I want to retrieve a list of information belonging to a certain field in a database. But , I am getting 'QuerySet' object has no attribute 'images'error.
models.py
class Business(models.Model):
    business_name = models.CharField(max_length=50)
    business_location = models.CharField(max_length=200)
    business_description = models.TextField()

    def __str__(self):
        return self.business_name

 class BusinessImage(models.Model):
    business = models.ForeignKey(Business, related_name='images', on_delete =models.CASCADE)
    image = models.ImageField()

views.py
def get_data1(request, *args, **kwargs):
    b= Business.objects.filter(business_name="some-name")
    image_list = b.images.all()
    c = {'image_list': image_list}
    return render(request, "index.html", c)

This error got solved using this code but not seeing anything in template:
views.py
def get_data1(request, *args, **kwargs):
b= BusinessImage.objects.filter(business__business_name="some-name")
image_list = b.values_list('image',flat = True)
c = {'image_list': image_list}
return render(request, "index.html", c)

index.html
{% for i in image_list %}

{% endfor %}

A: For your case you need to use values_list:
b= Business.objects.filter(business_name="some-name")
image_list = b.values_list(
    'images',
     flat=True
).distinct(
    'images',
)

in your template,
{% for i in image_list %}

{% endfor %}

Or you can fetch your images directly:
b= Business.objects.filter(business_name="some-name")
image_list = b.values_list(
    'images__image',
     flat=True
).distinct(
    'images__image',
)

in your template,
{% for i in image_list %}

{% endfor %}

A: filter will return you query set you have to use for loop for this. And It is image not images please fix this like this.
def get_data1(request, *args, **kwargs):
b= BusinessImage.objects.filter(business__business_name="some-name")
image_list = b.values_list('image',flat = True)
c = {'image_list': image_list}
return render(request, "index.html", c)

after updating the question-
b= BusinessImage.objects.filter(business__business_name="some-name")
return render(request, "index.html", b)

in index.html
{% for bb in b %}

{% endfor %}


text:
Q: Обьявление переменных в функции в SQL Server Добрый день.
Создал функцию, в ней обьявляю переменную, но возникает ошибка синтаксиса, в чем я не прав:
USE [MYTABLE]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[func] (@users nvarchar(4))
RETURNS TABLE AS
    DECLARE @i int;
RETURN (SELECT * FROM MYTABLE.dbo.users WHERE users = @users)
GO

A: Че-то мне кажется, что не хватает

AS BEGIN
...
END

Да и еще чего-то

UPD1:
Если вам надо программно наполнять таблицу, то надо делать как-то так:

CREATE FUNCTION dbo.fn_FindReports (@InEmpID INTEGER)
RETURNS @retFindReports TABLE
(
    EmployeeID int primary key NOT NULL,
    Name nvarchar(255) NOT NULL,
)
AS
BEGIN
... операции по заполению временной таблицы @retFindReports
/* и НЕ ЗАБЫТЬ*/
  RETURN
END;
GO

A: Пока писал ответ куда-то делось ошибочное AS в
DECLARE @i AS int;

:-)
Впрочем, проблема кода в том, что есть два вида табличнозначных UDF. И нужно следовать либо одному синтаксическому правилу, либо другому, но не их смеси.
A: Возвращаемый парвметр может быть должен иметь опцую OUTPUT


text:
Q: React.js: How to show base64 image with ImageField of react-admin How to show base64 image with ImageField of react-admin?
I used following code but it is not work:
import * as React from "react";
import { List, Datagrid, TextField, EmailField, UrlField ,ImageField} from 'react-admin';

export const RequestList = props => (
    <List {...props} >

        <Datagrid  >

           <TextField source="id" />

           <ImageField  source={`data:image/png;base64,myBase64Img`}  />

        </Datagrid>
    </List>
);

Thanks for reading everyone!

A: You've used ImageField incorrectly. The source property of ImageField refers to a key in a record, and this behaves like a pointer in C.
In the following example, the record is { id: 123, url: 'cat.png', title: 'meow' }.
ImageField will lookup a value in the record by key url and use that value cat.png for the src of the .
source
import { ImageField, TextField } from "react-admin";
import data from "./data";

<ImageField record={data} source="url" title="title" />
// data = { id: 123, url: 'cat.png', title: 'meow' }

output html after rendering

This demo shows a cat with ImageField in the page.
ImageField demo

A: I just throw the base64 string directly in the src field of a img tag instead of using ImageField. Somewhat like this


text:
Q: Figuring out when $f(x) = \sin(x^2)$ is increasing and decreasing Regarding the function $f(x) = \sin(x^2)$, I'm supposed to figure out when it is increasing/decreasing.
So far, I've found the derivative to be $f'(x) = 2x\cos(x^2)$.
So long as I can solve the inequality $\cos(x^2) > 0$ I can figure the rest out, but this is where I'm stuck.
I've narrowed it down to $-\frac\pi2 < x^2 < \frac\pi2$ meaning $x^2 < \frac\pi2 \pm n2\pi, \ \ n\in \mathbb N$
Then I get $x < \pm \sqrt{\frac\pi2 \pm n2\pi}$
Am I on the right track here? I can't seem to find a path from here.

A: You're on the right track.
The "points that matter" in partitioning the increasing/decreasing intervals are the points for which $f'(x) = 0$.  This happens when either $2x = 0$ or $\cos(x^2) = 0$.
The function is increasing when $f'(x) > 0$, and decreasing when $f'(x) < 0$.
Consider each part of the derivative separately.
The linear part of the derivative, $2x$, is positive when $x > 0$, and negative when $x < 0$.
The cosine function part of the derivative, $\cos(x^2)$, is positive when its argument is on one the open intervals
$$(2 \pi n - \pi / 2, 2 \pi n + \pi / 2), n \in \mathbb{Z},$$
and negative when it's on one the open intervals
$$(2 \pi n + \pi / 2, 2 \pi n + 3\pi / 2), n \in \mathbb{Z}.$$
The next steps would involve looking at when the product of these two parts changes sign.  Those points would define your increasing/decreasing intervals.


text:
Q: Not able to do ssh(without asking passowrd) to remote System using Authentication Keys Hello Friends.
                I am using Rhel 5.4 on System1 and centos 5.4 on System2. I am able to do SSH from A1 user of System1 to A2 User of System2 by simple method.Now i want that i generates Keys for both user A1 & A2. I generated keys succesfully.

IP of System1 - 200.0.0.1
IP of System2 - 200.0.0.2

[A1@System1 ~]$ssh-keygen -t dsa       - Generated succesfully
[A2@System2 ~]$ssh-keygen -t dsa       - Generated succesfully
[A1@System1 ~]$scp -p .ssh/id_dsa.pub A2@200.0.0.2:.ssh/authorized_keys2  - Successfully Uploaded
[A2@System2 ~]$chmod 600 .ssh/authorized_keys2
[A1@System1 ~]$ssh A2@200.0.0.2   - Logined successfully without asking any password Done.

Now I want that User B1 of System1 should also be able to do ssh by same manner to A2 user of System2.I am not doing any changes in A2 user of System2.
[B1@System1 ~]$ssh-keygen -t dsa       - Generated succesfully
[B1@System1 ~]$scp -p .ssh/id_dsa.pub A2@200.0.0.2:.ssh/authorized_keys5  - Successfully Uploaded
[A2@System2 ~]$chmod 600 .ssh/authorized_keys5
[B1@System1 ~]$ssh A2@200.0.0.2      - Now it is asking Passowrd for A2 user of System2. This is problem

Why it is asking password when i am trying to do ssh from B1@System1 to A2@System2. I have done same steps where is the gap. Stiil i am able to do ssh from A1@System1 to A2@System2 without asking password.
Kindly suggest me and point out where i am wrong

A: use ssh-copy-id command instead of scp, it will set  the correct files at the correct places with the correct permissions to enable passwordless login

A: You can not just use any name for the authorized_keys file. The use of authorized_keys2 is deprecated in SSH v2.
Just use one file for both accounts and append the public key of the 2nd. Don't overwrite the file and you should be able to ssh from two different accounts/machines to the same account.


text:
Q: asp.net mvc usercontrol viewdata i have user control, which i render on several views. i want to show viewdata in the usercontrol, but viewdata must be filled in controller method, so i need to fill viewdata  on each controller method of each view, where i render usercontrol.
is there any simple solutions?

A: Have a controller for that control like
MenuController
with an action method
RenderMenu()
{
    **do your work to get the data here and preferrably strong type it**
    return PartialView("NameOfYourAscxFile", yourObject);
}

If you name your control RenderMenu.ascx, you can just do
RenderMenu()
{
    **do your work to get the data here and preferrably strong type it**
    return PartialView(yourObject);
}

Or, maybe it would make more sense to name it Menu.ascx and have a method Menu like this
Menu()
{
    **do your work to get the data here and preferrably strong type it**
    Menu myMenuObject = Repository.GetMenu(...);
    return PartialView(myMenuObject);
}

Your Menu.ascx start would look like this
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<mynamespace.Menu>" %>

To use it in a View you do it like this:
<% Html.RenderAction("Menu", "Menu"); %>

HTH


text:
Q: PHP getting str_replace to work with a GET request? So, Jessica was kind enough to help me last time.
<?php
$string = 'hi+';
if(strpos($string, '+') !== false){
$string = str_replace('+', 'test', $string);
}
echo $string;
?>

Would basically work, however changing $string to a GET request like $string = $_GET['s']; and testing that would not take the + as user input (would just be blank). How would I fix this? Would it work with POST?

A: When in a GET parameter, the + gets urlencoded as %2B. When grabbing it from the query string, you need to urldecode it.:
$string = urldecode($_GET['s']);

Example

A: And if your url's aren't properly encoded, you can force encoding and you get desired result.
Something like that should work:
<?php

$string = urlencode($_GET['s']);
if(strpos($string, '+') !== false){
  $string = str_replace('+', 'test', $string);
}

echo $string;

But i say: the correct way is decoding the encoded URL, not doing reverse (encoding to get the raw URL from already decoded one.)


text:
Q: Hibernate org.hibernate.MappingException: Unknown entity runtime error I am trying to persist data with Hibernate and I have encountered the following exception during runtime.
Entity Class
import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name="FINANCES_USER")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="USER_ID")
private Long userId;

@Column(name="FIRST_NAME")
private String firstName;

@Column(name="LAST_NAME")
private String lastName;

@Column(name="BIRHT_DATE", nullable = false)
private Date birthDate;

@Column(name = "EMAIL_ADDRESS")
private String emailAddress;

@Column(name = "LAST_UPDATED_DATE")
private Date lastUpdatedDate;

@Column(name = "LAST_UPDATED_BY")
private String lastUpdatedBy;

@Column(name = "CREATED_DATE", updatable = false)
private Date createdDate;

@Column(name = "CREATED_BY",updatable = false)
private String createdBy;

This is the hibernate.cfg.xml:
<hibernate-configuration>

<session-factory>

    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/ifinances</property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <mapping class="com.codenogo.data.entities.User"/>

</session-factory>

This is my main:
    public class Application {

    public static void main(String[] args){

        Session session = HibernateUtil.getSessionFactory().openSession();
        session.getTransaction().begin();

        User user = new User();
        user.setBirthDate(new Date());
        user.setCreatedDate(new Date());
        user.setCreatedBy("Arnold");
        user.setEmailAddress("argo@mail.com");
        user.setFirstName("Arod");
        user.setLastName("Nogo");
        user.setLastUpdatedBy("Arno");
        user.setLastUpdatedDate(new Date());

        session.save(user);

        session.getTransaction().commit();
        session.close();
    }
}

I have imported javax.persistence.* in the Entity class. I am not able to persist the data to my database despite having mapped the entity class in the xml config file. I get this exception:
org.hibernate.MappingException: Unknown entity: com.codenogo.data.entities.User.
Any help around this?

A: Try to remove this line : <mapping class="com.codenogo.data.entities.User"/> from your hibernate.cfg.xml file because you are using Annotations to map your entity not the xml mapping mode


text:
Q: Want to add 3 Strings to an Array in Javascript with a button I'm new to programming. Right now I'm trying to add a few strings that are given in a form in HTML to an array thats stored inside a Jscript. The relevant code:
<input type="text" id="fName" placeholder="Vorname" />
<input type="text" id="fNachname" placeholder="Nachname" />
<input type="email" id="fEmail"  placeholder="E-Mail" />
<button id="formSubmit" > Absenden </button>

And here the jscript:
document.getElementById("formSubmit").addEventListener("click", Person);

function Person(vorname, name, email) {
    this.name = name;
    this.vorname = vorname;
    this.email = email;
}

var Personen = [
    new Person(document.getElementById("fName"), document.getElementById("fNachname"), document.getElementById("fEmail")  )

]
document.getElementById("formSubmit").addEventListener("click", console.log(Personen));

But right now, it does not show in the console when I give the array a person. It simply gives me the code that is stored inside the Personen variable. How can I resolve this?

A: You should do it in as an object and not as function
var Personen = new Array();
Personen.push({name : document.getElementById("fName"),vorname :document.getElementById("fNachname"),email : document.getElementById("fEmail")  })

A:

function Person(vorname, name, email) {
    this.name = name;
    this.vorname = vorname;
    this.email = email;
}

var Personen = [];
var addPerson = function() {
    Personen.push(new Person(document.getElementById("fName").value, document.getElementById("fNachname").value, document.getElementById("fEmail").value  ));
    console.log( Personen);
}

document.getElementById("formSubmit").addEventListener("click", addPerson);
    <body class='home'>
        <input type="text" id="fName" placeholder="Vorname" />
        <input type="text" id="fNachname" placeholder="Nachname" />
        <input type="email" id="fEmail"  placeholder="E-Mail" />
        <button id="formSubmit" > Absenden </button>
    </body>

function Person(vorname, name, email) {
    this.name = name;
    this.vorname = vorname;
    this.email = email;
}

var Personen = [];
var addPerson = function() {
    Personen.push(new Person(document.getElementById("fName").value, document.getElementById("fNachname").value, document.getElementById("fEmail").value  ));
    console.log( Personen);
}

document.getElementById("formSubmit").addEventListener("click", addPerson);

this should add a person when you submit


text:
Q: Alternate of quoteInto in zend framework? I am using this query in api
if (isset($json['version'])) {
        $client_cache_version =  @$json['version'];

        $version_sql = $db->quoteInto("SELECT max(messageVersion) as version FROM messageTable");
        $version_results = $db->fetchAll($version_sql);

        $version_array = $version_results['0'];

        $max_version = $version_array['version'];

        if($max_version > $client_cache_version){

            $sql = $db->quoteInto("SELECT * FROM messageTable");
            $results = $db->fetchAll($sql);

            $count = array(
                'count' => sizeof($results)
            );

all code working fine but problem in
$version_sql = $db->quoteInto("SELECT max(messageVersion) as version FROM messageTable");

when i try to check this code on curl I got this error
Warning: Missing argument 2 for Zend_Db_Adapter_Abstract::quoteInto()

I know in the case of Using quoteInto() multiple arguments are reguired but i have not an multiple argument right now so what i can do ?

A: From the Zend API on Db_Adapter_Pdo_Mysql::quoteInto():
The placeholder is a question-mark; all placeholders will be replaced with the quoted value. For example:
$text = "WHERE date < ?";
$date = "2005-01-02";
$safe = $sql->quoteInto($text, $date);
// $safe = "WHERE date < '2005-01-02'"

--

Parameters
Name   Type     Description
$text  string   The text with a placeholder.
$value mixed    The value to quote.
$type  string   OPTIONAL SQL datatype
$count integer OPTIONAL count of placeholders to replace

Returns
Type    Description
string  An SQL-safe quoted value placed into the original text.

Note that the value is REQUIRED. You shouldn't be using this method if you're not binding any params.


text:
Q: Cypress how to use api key in put/post request? I am trying to use AWS API and its API-key in POST/PUT call in Cypress, couldn't find enough details, can someone please help?

A: There are few options you can try, Here is one :
cy.intercept('POST', '/users*', (req) => {
  req.headers['x-api-key'] = 'bearer my-bearer-auth-token'
}).as('addAuthHeader')

Refer Offical Link here:
https://docs.cypress.io/guides/guides/network-requests#Assertions

A: I was able to resovle it syntax is: authorization : key + value no quotes –

A: You can use cy.request. Although not outlined in the docs, it accepts an object:
cy.request({
  method: 'POST',
  url: 'https://jsonplaceholder.cypress.io/',
  headers: { 'x-api-key': 'APIKEY' },
}).then((res) => {
  // use the response with response.body
});


text:
Q: How to stretch horizontal lines in header on left side (as on right side)? \documentclass[10pt,times,a4paper]{letter}
\usepackage{graphicx}
\usepackage{fancyhdr}
\usepackage{booktabs, tabularx, colortbl, xcolor}
\usepackage[left=0.8in,right=0.8in,top=0.8in,bottom=0.7in,headsep=0.1in]{geometry}
\usepackage{lipsum}
\fancypagestyle{empty}{
\fancyhf{}
\fancyhead{}
\renewcommand{\headrulewidth}{0pt} % <-----To change the thickness of header
\vspace*{-40pt} %<----To adjust the vertical position of Header  0.47\paperwidth
\begin{tabularx}{0.87\paperwidth}{X}
    \arrayrulecolor{lightgray}  % choose color
    \midrule[0.045in] \par
    \midrule[0.045in]\par
    \midrule[0.045in]\par
    \midrule[0.045in]\par
    \midrule[0.045in]
\end{tabularx}
}
\makeatletter
\address{
}
\begin{document}
\begin{letter}{}
    \pagenumbering{gobble}
\opening{}
\vspace{20pt}
\lipsum[1-1]
\vspace{10pt}
I will be thankful for your kind consideration.
\vspace{80pt}
Sincerely and Kind Regards,\newline
\raisebox{0pt}[200pt][0pt]

\end{letter}%
\end{document}%

A: Is this what you want?
\documentclass[10pt,times,a4paper]{letter}
\usepackage{graphicx}
\usepackage{booktabs, tabularx}
\usepackage[table]{xcolor}
\usepackage[hmargin=0.8in, top=0.8in, bottom=0.7in, headsep=0.1in, showframe]{geometry}
\usepackage{lipsum}
\usepackage{fancyhdr}
\fancypagestyle{empty}{%
\fancyhf{}%
\renewcommand{\headrulewidth}{0pt}%
 \chead{\renewcommand{\arraystretch}{0.02}%
\raisebox{7pt}[0pt][0pt]{\makebox[\textwidth]{%
 \begin{tabularx}{0.87\paperwidth}{X}
 \arrayrulecolor{lightgray} % choose color
 \midrule[0.045in] \\
 \midrule[0.045in]\\
 \midrule[0.045in]\\
 \midrule[0.045in]
 \end{tabularx}}}%
 }}%

\address{
}

\begin{document}

\begin{letter}{}
    \pagenumbering{gobble}
\opening{}
\vspace{20pt}

\lipsum[1-1]
\vspace{10pt}
I will be thankful for your kind consideration.
\vspace{80pt}
Sincerely and Kind Regards,\newline
\raisebox{0pt}[200pt][0pt]

\end{letter}%

\end{document}%

A: I found it's solution by using the following code.
\documentclass[10pt,times,a4paper]{letter}
\usepackage{graphicx}
\usepackage{fancyhdr}
\usepackage{booktabs, tabularx, colortbl, xcolor}
\usepackage[left=0.8in,right=0.8in,top=0.8in,bottom=0.7in,headsep=0.1in]{geometry}
\usepackage{lipsum}
\usepackage{chngpage}
\fancypagestyle{empty}{
\fancyhf{}
\fancyhead{}
\renewcommand{\headrulewidth}{0pt} % <-----To change the thickness of header
\vspace*{-40pt} %<----To adjust the vertical position of Header  0.47\paperwidth
\begin{adjustwidth}{-0.9in}{-0.1in}% adjust the L and R margins by 1 inch
\begin{tabularx}{1.3\paperwidth}{X}
    \arrayrulecolor{lightgray}  % choose color
    \midrule[0.045in] \par
    \midrule[0.045in]\par
    \midrule[0.045in]\par
    \midrule[0.045in]\par
    \midrule[0.045in]
\end{tabularx}
\end{adjustwidth}
}
\makeatletter
\address{
}
\begin{document}
\begin{letter}{}
    \pagenumbering{gobble}
\opening{}
\vspace{20pt}
\lipsum[1-1]
\vspace{10pt}
I will be thankful for your kind consideration.
\vspace{80pt}
Sincerely and Kind Regards,\newline
\raisebox{0pt}[200pt][0pt]

\end{letter}%
\end{document}%