text:
Q: Using libgrib2c in c++ application, linker error "Undefined reference to..." EDIT: If you're going to be doing things with GRIB files I would recommend the GDAL library which is backed by the Open Source Geospatial Foundation. You will save yourself a lot of headache :)
I'm using Qt creator in Ubuntu creating a c++ app.  I am attempting to use an external lib, libgrib2c.a, that has a header grib2.h.  Everything compiles, but when it tries to link I get the error:

undefined reference to 'seekgb(_IO_FILE*, long, long, long*, long*)

I have tried wrapping the header file with:
extern "C"{
#include "grib2.h"
}

But it didn't fix anything so I figured that was not my problem. In the .pro file I have the line:
include($${ROOT}/Shared/common/commonLibs.pri)

and in commonLibs.pri I have:
INCLUDEPATH+=$${ROOT}/external_libs/g2clib/include
LIBS+=-L$${ROOT}/external_libs/g2clib/lib
LIBS+=-lgrib2c

I am not encountering an error finding the library.  If I do a nm command on the libgrib2c.a I get:
nm libgrib2c.a | grep seekgb
seekgb.o:
00000000 T seekgb

And when I run qmake with the additional argument of LIBS+=-Wl,--verbose I can find the lib file in the output:
attempt to open /usr/lib/libgrib2c.so failed
attempt to open /usr/lib/libgrib2c.a failed
attempt to open /mnt/sdb1/ESMF/App/ESMF_App/../external_libs/linux/qwt_6.0.2/lib/libgrib2c.so failed
attempt to open /mnt/sdb1/ESMF/App/ESMF_App/../external_libs/linux/qwt_6.0.2/lib/libgrib2c.a failed
attempt to open ..//Shared/Config/lib/libgrib2c.so failed
attempt to open ..//Shared/Config/lib/libgrib2c.a failed
attempt to open ..//external_libs/libssh2/lib/libgrib2c.so failed
attempt to open ..//external_libs/libssh2/lib/libgrib2c.a failed
attempt to open ..//external_libs/openssl/lib/libgrib2c.so failed
attempt to open ..//external_libs/openssl/lib/libgrib2c.a failed
attempt to open ..//external_libs/g2clib/lib/libgrib2c.so failed
attempt to open ..//external_libs/g2clib/lib/libgrib2c.a succeeded

Although it doesn't show any of the .o files in the library is this because it is a c library in my c++ app?
in the .cpp file that I am trying to use the library I have:
#include "gribreader.h"
#include <stdio.h>
#include <stdlib.h>
#include <external_libs/g2clib/include/grib2.h>
#include <Shared/logging/Logger.hpp>

//------------------------------------------------------------------------------
/// Opens a GRIB file from disk.
///
/// This function opens the grib file and searches through it for how many GRIB
/// messages are contained as well as their starting locations.
///
/// \param a_filePath. The path to the file to be opened.
/// \return True if successful, false if not.
//------------------------------------------------------------------------------
bool GRIBReader::OpenGRIB(std::string a_filePath)
{
  LOG(notification)<<"Attempting to open grib file: "<< a_filePath;
  if(isOpen())
  {
    CloseGRIB();
  }
  m_filePath = a_filePath;
  m_filePtr = fopen(a_filePath.c_str(), "r");

  if(m_filePtr == NULL)
  {
    LOG(error)<<"Unable to open file: " << a_filePath;
    return false;
  }
  LOG(notification)<<"Successfully opened GRIB file";

  g2int currentMessageSize(1);
  g2int seekPosition(0);
  g2int lengthToBeginningOfGrib(0);
  g2int seekLength(32000);
  int i(0);
  int iterationLimit(300);
  m_GRIBMessageLocations.clear();
  m_GRIBMessageSizes.clear();
  while(i < iterationLimit)
  {
    seekgb(m_filePtr, seekPosition, seekLength,
           &lengthToBeginningOfGrib, &currentMessageSize);
    if(currentMessageSize != 0)
    {
      LOG(verbose) << "Adding GRIB message location " << lengthToBeginningOfGrib
                   << " with length " << currentMessageSize;
      m_GRIBMessageLocations.push_back(lengthToBeginningOfGrib);
      m_GRIBMessageSizes.push_back(currentMessageSize);

      seekPosition = lengthToBeginningOfGrib + currentMessageSize;
      LOG(verbose) << "GRIB seek position moved to " << seekPosition;
    }
    else
    {
      LOG(notification)<<"End of GRIB file found, after "<< i
                      << " GRIB messages.";
      break;
    }
  }
  if(i >= iterationLimit)
  {
    LOG(warning) << "The iteration limit of " << iterationLimit
                 << "was reached while searching for GRIB messages";
  }
  return true;
}

And the header grib2.h is as follows:
#ifndef _grib2_H
#define _grib2_H
#include<stdio.h>

#define G2_VERSION "g2clib-1.4.0"
#ifdef __64BIT__
typedef int g2int;
typedef unsigned int g2intu;
#else
typedef long g2int;
typedef unsigned long g2intu;
#endif
typedef float g2float;

struct gtemplate {
   g2int type;           /* 3=Grid Defintion Template.                       */
                         /* 4=Product Defintion Template.                    */
                         /* 5=Data Representation Template.                  */
   g2int num;            /* template number.                                 */
   g2int maplen;         /* number of entries in the static part             */
                         /*                    of the template.              */
   g2int *map;           /* num of octets of each entry in the               */
                         /*         static part of the template.             */
   g2int needext;        /* indicates whether or not the template needs      */
                         /*     to be extended.                              */
   g2int extlen;         /* number of entries in the template extension.     */
   g2int *ext;           /* num of octets of each entry in the extension     */
                         /*                      part of the template.       */
};

typedef struct gtemplate gtemplate;

struct gribfield {
   g2int   version,discipline;
   g2int   *idsect;
   g2int   idsectlen;
   unsigned char *local;
   g2int   locallen;
   g2int   ifldnum;
   g2int   griddef,ngrdpts;
   g2int   numoct_opt,interp_opt,num_opt;
   g2int   *list_opt;
   g2int   igdtnum,igdtlen;
   g2int   *igdtmpl;
   g2int   ipdtnum,ipdtlen;
   g2int   *ipdtmpl;
   g2int   num_coord;
   g2float *coord_list;
   g2int   ndpts,idrtnum,idrtlen;
   g2int   *idrtmpl;
   g2int   unpacked;
   g2int   expanded;
   g2int   ibmap;
   g2int   *bmap;
   g2float *fld;
};

typedef struct gribfield gribfield;

/*  Prototypes for unpacking API  */
void seekgb(FILE *,g2int ,g2int ,g2int *,g2int *);
g2int g2_info(unsigned char *,g2int *,g2int *,g2int *,g2int *);
g2int g2_getfld(unsigned char *,g2int ,g2int ,g2int ,gribfield **);
void g2_free(gribfield *);

/*  Prototypes for packing API  */
g2int g2_create(unsigned char *,g2int *,g2int *);
g2int g2_addlocal(unsigned char *,unsigned char *,g2int );
g2int g2_addgrid(unsigned char *,g2int *,g2int *,g2int *,g2int );
g2int g2_addfield(unsigned char *,g2int ,g2int *,
                       g2float *,g2int ,g2int ,g2int *,
                       g2float *,g2int ,g2int ,g2int *);
g2int g2_gribend(unsigned char *);

/*  Prototypes for supporting routines  */
extern double int_power(double, g2int );
extern void mkieee(g2float *,g2int *,g2int);
void rdieee(g2int *,g2float *,g2int );
extern gtemplate *getpdstemplate(g2int);
extern gtemplate *extpdstemplate(g2int,g2int *);
extern gtemplate *getdrstemplate(g2int);
extern gtemplate *extdrstemplate(g2int,g2int *);
extern gtemplate *getgridtemplate(g2int);
extern gtemplate *extgridtemplate(g2int,g2int *);
extern void simpack(g2float *,g2int,g2int *,unsigned char *,g2int *);
extern void compack(g2float *,g2int,g2int,g2int *,unsigned char *,g2int *);
void misspack(g2float *,g2int ,g2int ,g2int *, unsigned char *, g2int *);
void gbit(unsigned char *,g2int *,g2int ,g2int );
void sbit(unsigned char *,g2int *,g2int ,g2int );
void gbits(unsigned char *,g2int *,g2int ,g2int ,g2int ,g2int );
void sbits(unsigned char *,g2int *,g2int ,g2int ,g2int ,g2int );

int pack_gp(g2int *, g2int *, g2int *,
            g2int *, g2int *, g2int *, g2int *, g2int *,
            g2int *, g2int *, g2int *, g2int *,
            g2int *, g2int *, g2int *, g2int *, g2int *,
            g2int *, g2int *, g2int *);

#endif  /*  _grib2_H  */

I have been scratching my head for two days on this. If anyone has an idea on what to do or can point me in some sort of direction, I'm stumped.  Also, if you have any comments on how I can improve this post I'd love to hear them, kinda new at this posting thing.  Usually I'm able to find an answer in the vast stores of knowledge already contained on the web.

A: Try specifying external C linkage explicitly by putting the following near the top of the header file:
#ifdef __cplusplus
extern "C" {
#endif

and this near the bottom:
#ifdef __cplusplus
}
#endif


text:
Q: Why data.table is taking too much time to execute a specific part of script in r (Reproducible Example given)? I am having some issues with extremely slow processing of few lines of my script as given below .I guess apply & customised function are slowing down the performance
Any suggestions to expedite this script/calculation ??
One can use these tables and check the code
dt1=data.table(location_id=rep("abc",52),report_date=c(rep("2020-04-22",24),rep("2020-04-23",24),rep("2020-04-24",4)),hour=c(rep(c(0:23),2),0,1,2,3),hr_visitors=c(20:67,345,236,123,67))

dt2=dt1[, date_hour := as.POSIXct(paste0(report_date,hour), format = "%Y-%m-%d %H")]

Part 1
Creating timestamp column using date and hour observations
Sys.time()
"2020-09-30 06:22:55 GMT"

dt2=copy(dt1)[, date_hour := as.POSIXct(paste0(report_date,hour),
format = "%Y-%m-%d %H")]

Sys.time()
"2020-09-30 06:31:51 GMT"

Part 2
Applying function model on a bigger data set
stl_model_outlier<-function(xyz){
model=ts(xyz,frequency=24)
f=stl(model,"periodic",robust = TRUE)
result=data.table(row_id=which(f$weights<1e-8))%>%mutate(outlier="Yes")
return(list(result))
}

Sys.time()
"2020-09-30 06:41:51 GMT"

results1<-dt2[,lapply(.SD, stp_model_outlier), by = location_id, .SDcols = "hr_visitors"]

Sys.time()
"2020-09-30 06:54:51 GMT"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calling SOAP service returns a 500 error when using marshalSendAndReceive I am using Spring Boot and Java  11.
I am trying to write a SOP client to invoke the following web service.  The service provider has provided a tool to test the it, and from here you can see it is working as expected.

Results - returns a 200:

I  use the provided WSDL to generate the stubs successfully, and then write the following Java Client using the generated ObjectFactory:
String PROCON_SOAP_ACCESS_URL = "http://********/ProCONWS/WebService_PCSOrderEntry.asmx";

public CalculateMD5Response calculateMD5(final String userName) {
    String msg = null;
    String parameters = null;
    try {
        // request
        ObjectFactory objectFactory = new ObjectFactory();
        CalculateMD5 request = objectFactory.createCalculateMD5();
        request.setUser("pcscord");
        request.setTimestamp(DateUtil.dateToString(new Date(), "yyyyMMdd HHmmss"));
        request.setSecretWord("********");
        parameters = URLEncoder.encode("user="+request.getUser()+"&timestamp="+request.getTimestamp()+"&Secret_word="+request.getSecretWord(), "UTF-8");

        PROCON_SOAP_ACCESS_URL = PROCON_SOAP_ACCESS_URL + "/calculate_MD5";//?"+parameters;

        // call the SOAP service
        logger.info("About to call Procon SOAP Service: " + PROCON_SOAP_ACCESS_URL + ".");
        JAXBElement<String> jaxbElementPayload = objectFactory.createString(parameters);
        Object response = getWebServiceTemplate().marshalSendAndReceive(PROCON_SOAP_ACCESS_URL, jaxbElementPayload);
        logger.info("Called Procon SOAP service. Response: " + response);
    } catch (Exception e) {
        msg = "FAILURE: There was an error calling the Procon SOAP service. Exception: "+e.getMessage()+". URL: "+PROCON_SOAP_ACCESS_URL+" and PARAMETERS: "+parameters+".";
        logger.error(msg);
    }
    return null;
}

This however returns a 500 error:
Internal Server Error [500]

As far as I understand, the getWebServiceTemplate().marshalSendAndReceive should perform a SOAP POST request with the  given URL and payload.
Am I using the generated stubs incorrectly? Is the URLEncoder.encode incorrectly formatting the payload?  Any feedback appreciated.

A: Check names of elements. It's possible add @XmlRootElement("<ElementName>").


text:
Q: Modal Immediately Closes Problem: I am having an issue where when the user clicks on the modal "Privacy Notice" on the footer. Every time the user clicks on it, it immediately closes the modals. I have compared the files with what I have done before and it is the same.
I have checked if I had both bootstrap.js and bootstrap.min.js and I just only have the min js file. I have checked if I am calling the modal's twice and I am not.
The following is the path of the site: regalmed. I unfortunately do not have access to the files but based on comparing the test site with the Privacy Notice in the footer, they look the same.
Any suggestions would be helpful.

A: Bootstrap is being double loaded which is causing your problem. It's loaded from the cdn in the <head> and then again near the bottom of the body from:
http://www.regalmed.com/Regal-en-us/includes/themes/MuraBootstrap3/assets/bootstrap/js/bootstrap.min.js


text:
Q: How to draw 2D circle in irrlicht Is there a way to draw a simple circle with given radius and center point in irrlicht?

A: You can use driver->draw2DPolygon() method.
Simply pass vertexCount to be high enough for your size of shape (the smaller circle on the screen, the lower value you can pass and it won't be noticeable that it has edges).


text:
Q: How to convert file format ascii text to ascii english text in UNIX I have two files file1 and file2.
file1 format is ascii text.
file2 format is ascii english text.
When I import the data into a table file1 successfully inserted,
but file2 is not imported getting error like format error.
How to convert ascii text to ascii english text?
Give me the command.....
How to convert file format ascii text to ascii english text in UNIX?
Can anyone please tell me?


text:
Q: How to concat query results? I've got data like this:
A          | B
-----------------------
Date       | Data
30/06/2015 | 1.2
01/07/2015 | 2
01/07/2015 | 3
02/07/2015 | 2
02/07/2015 | 3

And I write a simple query like this:
=query(A:B; "select YEAR(A) || ' ' || month(A), SUM(B)
    group by YEAR(A), month(A)")

But I've got a "Value Error", so I write this
=query(A:B; "select YEAR(A), MONTH(A), SUM(B)
    group by YEAR(A), month(A)")

And it work well, but, how can I concat two values in one cell ?
I though of this:
=QUERY(Journal!A:B;"select A, SUM(B)
    group by A
    format A 'yyyy-MM'")

But the format operation is done AFTER the group by so it's like the group by never was.
Any idea ?
[Solution]
=query({Arrayformula(text(Foo!A:A; "yyyy-MM")) \Foo!B:B}; "select Col1, sum(Col2) group by Col1"; -1)

Because my local is "french" I've to use the '\' in the Arrrayformula and ; instead of ','...

A: Use the ampersand (&) to concatenate in arrayformula:
=ArrayFormula(if(len(A:A), year(A:A)&" "&month(A2:A),))

or if you don't want the space between year and month:
=ArrayFormula(if(len(A:A), year(A:A)&month(A2:A),))

EDIT:
If you want to query and sum, try:
=query({Arrayformula(text(Journal!A:A, "yyyy-MM")),Journal!B:B}, "select Col1, sum(Col2) where Col2 is not null group by Col1", 0)

or in locale that use semi-colons as argument separators:
=query({Arrayformula(text(Journal!A:A; "yyyy-MM"))\Journal!B:B}; "select Col1, sum(Col2) where Col2 is not null group by Col1"; 0)

Example spreadsheet


text:
Q: POST to two locations using AJAX On a web page I have a button that does a POST to a server that I don't have anything to do with. When someone clicks the button, I need to update some data on my (another) server so that when the user is eventually redirected back, the correct info will be displayed. Is this something that AJAX can do?
Many thanks,
TA

A: Sure.
With Jquery, it will be something like that:
 var url1 = $.post("url1", {...});
 var url2 = $.post("url2", {...});

 $.when(url1, url2).then(function() {
      // Action when the two posts are back
 });

You can also act upon just one of the urls if the other one is not important.


text:
Q: JComponent global method GET doesn't work in Total.js Flow components I have a problem in Total.js Flow using inside a component the client-side method GET to retrieve value of JComponent ( in my case textbox or input ).
I have tried from Componentator and actually works, but inside my Total.js Flow ( version 6, but the 5 version has the same problem ) it return undefined. Someone know any solution or better way to retrieve for example on button click the value inside the input box?

@(URL)

 <button onclick="getUrl()">Try</button>     // this call an example function that call the "console.log"

console.log(GET('url'));    // return undefined

A: Flow uses jComponent scopes in the form settings.NAME_OF_COMPONENT.path. So you can use GET('settings.name_of_component.url') or you can use a direct call like console.log(settings.name_of_component.url).


text:
Q: Given $A, B\in R^{n\times n}$ diagonal matrices, there exist $p,q \in R[x]$ and $X\in R^{n\times n}$ such that $A = p(X),B=q(X)$
(1) We are given $A,B \in R^{n\times n}$ diagonal matrices of n rows and n columns with real values.
Show that there are $X \in R^{n\times n}$ and polynomials $q$ and $p$ such that:
$$q(X)=B \text{ and }p(X)=A$$

What I've tried doing:
I've tried a different combinations of X and p,q, for example:
If we say that $X=A$ and we define $q(X) = X-A+B$ and $p(X)=X$ we indeed solve the problem
BUT those p and q are not polynomials, because if i use a scalar as an input for those polynomials instead of a matrix, it doesn't work. There is no scalar version of the matrix A (Unlike for example the unit matrix, which the scalar version of which is 1) So that isn't the way to solve the question

(2) Is this correct for any 2 matrices or just for diagonal matrices? Hint: What basic difference is there between the polynomial ring and the matrix ring?

(Haven't started working on this yet cause didn't solve question 1, but it probably involves that the matrix multiplication isnt commutative)

A: Hint:
$$X=\begin{pmatrix}x_1&&\\&\ddots&\\&&x_n\end{pmatrix}$$
$$P(X)=\begin{pmatrix}P(x_1)&&\\&\ddots&\\&&P(x_n)\end{pmatrix}$$

A: Hints:

*

*Lagrange interpolation would be useful if $X$ is a diagonal matrix with distinct diagonal entries.

*The polynomial ring over $\mathbb{R}$ is commutative, but the matrix ring is not. So, $p(X)$ always commutes with $q(X)$ but ...

Remarks:
(a) Note that in question 1, a solution $(p,q,X)$ exists not only because $A$ and $B$ are diagonal matrices, but also because the underlying field ($\mathbb{R}$) is infinite. There can be no feasible solution if the field is finite. For instance, consider $A=\operatorname{diag}(1,0,0)$ and $B=\operatorname{diag}(0,1,0)$ over $GF(2)$. There are only $512$ choices of $X$ and eight choices of each of $p(X)$ and $q(X)$. One can perform a brute-force search to verify that none of these choices solve the set of equations $p(X)=A,\,q(X)=B$.
(b) The wording of the question may lead one to (wrongly) believe that two commuting matrices $A$ and $B$ can always be written as polynomials of some matrix $X$. However, in the previous remark, we have already seen that this is not the case even if $A$ and $B$ are diagonal matrices. For more in-depth discussions, see MSE/326293 and MO/34314.


text:
Q: Photoshop - Auto align images into a grid Is there a script/plugin/action available that will automatically align several images into a grid style layout e.g. wookmark ?
I am desperately in need of something to automate this, as a weekly project I have to arrange about 40 thumbnails into a PSD.

A: Using JavaScript...
You can define a selection using an array of coordinate points like so:
var x = 0;
var y = 0;
var w = thumbnailDoc.width; // width of thumbnail document
var h = thumbnailDoc.height; // height of thumbnail document

var sel = [ // Define a rectangle of coordinate points
    [x, y], // moving clockwise from top-left corner of rectangle
    [x + w, y],
    [x + w, y + h],
    [x, y + h],
    [x, y] //back to start
];

var doc = app.documents.add(200, 200, 72) // create new document (width, height, resolution)

doc.selection.select(sel); // make a selection using the array of coordinates
doc.paste(true) // paste the contents of the clipboard
                // pass in the boolean 'true' to make it paste into the selection

So all you have to do is loop through all the pictures, resize them to thumbnails if you haven't already, copy to the clipboard, then paste into the selection on the working document. Increment your x,y coordinates as you go and you're strolling.


text:
Q: The method '[]' was called on null, but it's not null That title error is pointed on this line:
Text('${intData['summary']['intrested']}')

I want to display here data from backend, but I don't know how to accomplish that I am getting this error, but this is not null.
Here is my code:

var intData;

Future<Map> loadMyFriends(String eventId) async {

    var request = await EndPoints.interest(eventId, userId);
    print(request.body);
    intData = jsonDecode(request.body)['data'] as Map;
    return jsonDecode(request.body)['data'];
  }

@override
  void initState() {
    super.initState();
    userId = widget.userId;
    loadMyFriends(widget.partyMap['id']).then((value) => print('$intData'));
  }

@override
  void didUpdateWidget(SquareBoxMovableBuilder oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.partyMap != oldWidget.partyMap) {
      loadMyFriends(widget.partyMap['id']);
      print(intData);
    }
  }

and here are console prints what intData contains:
//print(request.body) in loadMyFriends function
{"data":{"intrested":null,"participate":null,"summary":{"intrested":0,"participate":0},"friends":{"list":[],"sum":0}}}

//print(intData) in initState
{intrested: null, participate: null, summary: {intrested: 0, participate: 0}, friends: {list: [], sum: 0}}

//print(intData) in didUpdateWidget
{intrested: null, participate: null, summary: {intrested: 0, participate: 0}, friends: {list: [], sum: 0}}

I tried to do this with FutureBuilder but I had same result.
How to fix it or how to do it?
How to display data downloaded from backend every time when I open this widget?

A: While the loadMyFriends is a future method and it will take some time to get data and after getting data you need to call setState((){}) to update the UI. You can try on
Future<Map> loadMyFriends(String eventId) async {

    var request = await EndPoints.interest(eventId, userId);
    print(request.body);
    intData = jsonDecode(request.body)['data'] as Map;
    setState((){}); //here
    return jsonDecode(request.body)['data'];
  }


text:
Q: Java Stream - Combine filter and collect ColumnFamily column = tokens.getColumnFamilies().stream()
    .filter(family -> family.getName().equals("this_family"))
    .findAny()
    .get();

Map<String, String> tokenized = column.getColumns().stream()
    .collect(Collectors.toMap(
        Column::getQualifier,
        Column::getValue
    ));

Is there a way I can combine these two streams into one? I am using the first stream to filter and find on my nested list, and using the second stream to create a map based on the result of the stream. I am wondering if there's a way I could have done this using a single stream.
Something like this
Map<String, String> tokenized = tokens.getColumnFamilies().stream()
    .filter(family -> family.getName().equals("this_family"))
    .collect(Collectors.toMap(
        //
    ));

A: You can use flatMap to get nested Stream and flatten the structure:
Map<String, String> tokenized = tokens.getColumnFamilies().stream()
    .filter(family -> family.getName().equals("this_family"))
    .limit(1)  // equivalent of findAny
    .flatMap(cf -> cf.getColumns().stream())
    .collect(Collectors.toMap(
        Column::getQualifier,
        Column::getValue
    ));

A: Use Optional#map() and combine
Map<String, String> tokenized = tokens.getColumnFamilies().stream()
                    .filter(family -> family.getName().equals("this_family"))
                    .findAny()
                    .map(cf -> cf.getColumns().stream()).get()
                    .collect(Collectors.toMap(Column::getQualifier, Column::getValue));


text:
Q: How to number gathered equations using single number I want to number gathered equations, but single number for several equations. Following is the code I've used. But it results numbering both equations. I want to equations to be justified, not right aligned.  Spilt and align environment right align the equations. Is there any way to do this?
\begin{gather}
\eta_{c1} P_{pv}(k) + \eta_{c2} P_{bat}(k) \leq P_{conG,rate} \\\
P_{grid} + P_{load} \geq -P_{conG,rate}
\end{gather}

A: After \ you can put \nonumber this way you can avoid having both equations numbered

A: As said by Good Luck, you can add \nonumber at the end of the line before \\.
A problem I encountered was that when adding a \label{label_name} the Eq.~\ref{label_name} showed as (for example) Eq.2.5 instead of Eq.2. I've managed to sort this by moving the \label{label_name} to the row below \begin{gather}. So for example my code would look like this:
\begin{gather}
\label{labe_name}
e=\sum_{n=0}^{\infty}{\frac{1}{n!}}\\
\begin{aligned}
&\textit{\small Where:}\nonumber\\
&\textit{\small $1^{st}$ line and more explanations to fill the line} \nonumber\\
&\textit{\small $2^{nd}$ line}\nonumber\\
&\textit{\small ext \dots}\nonumber\\
\end{aligned}
\end{gather}

Make sure to have this packages:
\usepackage{amsmath,amssymb}

A: Here is a cleaner solution than using \nonumber.  Using gathered or aligned environments inside an equation environment groups the equations and assigns one number to them.  This is recommended by the amsmath user guide.
\documentclass{article}

\usepackage{amsmath}

\begin{document}

\begin{equation}
    \begin{gathered}
        \eta_{c1} P_{pv}(k) + \eta_{c2} P_{bat}(k) \leq P_{conG,rate}
        \\
        P_{grid} + P_{load} \geq -P_{conG,rate}
    \end{gathered}
\end{equation}

\begin{equation}
    \begin{aligned}
        \eta_{c1} P_{pv}(k) + \eta_{c2} P_{bat}(k) &\leq P_{conG,rate}
        \\
        P_{grid} + P_{load} &\geq -P_{conG,rate}
    \end{aligned}
\end{equation}

\end{document}


text:
Q: Show total Minute Utilization for An hour in PowerBI report I am trying to do log(ssrs execution log) analysis is powerbi. Requirement here is to show how many minutes utilized for a particular hour based on the request start & end time. Below is example for 4 requests Start & end time with expected result.
1st request 12:00 AM - 12:15 AM
2nd request 12:05 AM - 12:10 AM
3rd request 12:40 AM - 12:42 AM
4th request 12:41 AM - 12:48 AM
So total minute utilization for 12 AM hour should be 15mins(as first two requests overlap with each other) + 8mins (as last two also overlap for some mins) = 23 mins of total utilization at 12 AM.
Any help will be greatly appreciated.

A: I'd recommend splitting up the hour into 60 minutes and counting how many of the minutes are within the time frame of one of the requests.
Something like this logic for a calculated column:
Utilization =
VAR CurrentHour = HOUR ( Requests[Start] )
VAR Minutes =
    GENERATESERIES (
        TIME ( CurrentHour, 0, 0 ),
        TIME ( CurrentHour + 1, 0, 0 ),
        TIME ( 0, 1, 0 )
    ) /*This generates a column named [Value] with 61 rows
        starting from the beginning of the hour.*/
RETURN
    SUMX (
        Minutes,
        IF (
            COUNTROWS (
                FILTER (
                    Requests,
                    HOUR ( Requests[Start] ) = CurrentHour
                        && Requests[Start] < [Value]
                        && Requests[End]   > [Value]
                )
            ) > 0,
            1,
            0
        )
    )


text:
Q: How do I make an image slider with list items generated from an array I am trying to make an  fade-in-out slider show. Here is the sliding show code with static html code:
var slider = document.getElementById("slider");
var slideArray = slider.getElementsByTagName("li");
var slideMax = slideArray.length - 1;
var curSlideNo = 0;
var nextSlideNo =null;
var fadeStart = false;
var curSlideLevel = 1;
var nextSlideLevel = 0;

for (i = 0; i <= slideMax; i++) {
    if (i === curSlideNo) changeOpacity(slideArray[i], 1);
    else changeOpacity(slideArray[i], 0);
}

function startSlide(dir)
{
    if (fadeStart === true) return;
    if( dir === "prev" )
    {
        nextSlideNo = curSlideNo - 1;
        if ( nextSlideNo < 0 ) nextSlideNo = slideMax;
    }
    else if( dir === "next" )
    {
        nextSlideNo = curSlideNo + 1;
        if ( nextSlideNo > slideMax ) nextSlideNo = 0;
    }
    else
    {
        fadeStart = false;
        return;
    }
    fadeStart = true;
    changeOpacity(slideArray[curSlideNo], curSlideLevel);
    changeOpacity(slideArray[nextSlideNo], nextSlideLevel);
    fadeInOutAction(dir);
}

function fadeInOutAction(dir)
{
    curSlideLevel = curSlideLevel - 0.1;
    nextSlideLevel = nextSlideLevel + 0.1;
    if( curSlideLevel <= 0 )
    {
        changeOpacity(slideArray[curSlideNo], 0);
        changeOpacity(slideArray[nextSlideNo], 1);
        if(dir === "prev")
        {
            curSlideNo = curSlideNo - 1;
            if (curSlideNo < 0) curSlideNo = slideMax;
        }
        else
        {
            curSlideNo = curSlideNo + 1;
            if (curSlideNo > slideMax) curSlideNo = 0;
        }
        curSlideLevel = 1;
        nextSlideLevel = 0;
        fadeStart = false;
        return;
    }
    changeOpacity(slideArray[curSlideNo], curSlideLevel);
    changeOpacity(slideArray[nextSlideNo], nextSlideLevel);
    setTimeout(function () {
        fadeInOutAction(dir);
    }, 100);
}

function changeOpacity(obj,level)
{
    obj.style.opacity = level;
    obj.style.MozOpacity = level;
    obj.style.KhtmlOpacity = level;
    obj.style.MsFilter = "'progid:DXImageTransform.Microsoft.Alpha(Opacity=" + (level * 100) + ")'";
    obj.style.filter = "alpha(opacity=" + (level * 100) + ");";
}

var autoslider = setInterval( function(){startSlide('next');}, 1000);
autoslider;

actually, this code worked properly when html code was like that

but images from server can be changed or added.
so, I thought making it dynamic would be better.
this is added code
if(xhr.readyState===XMLHttpRequest.DONE){
        if(xhr.status===200){
            var test=xhr.response.replace(/["]/g,'');
            test= test.substring(1,test.length-1);
            let test2=test.split(",");
            alert(test2);

            let lis=document.createElement("li");

            for(var i=0; i<test2.length; ++i){
                let imgNode=document.createElement("img");
                imgNode.setAttribute("src", url+test2[i]);
                lis.appendChild(imgNode);
            }
            document.getElementById("slider").appendChild(lis);

        }else{
            alert(`:'(`);
        }
    }

but this time, it doesn't work.
no sliding show but the images are listed vertically.
how could I make this sliding show? What should I edit?


text:
Q: Neighbors have three children. Given three independent observations of boy, what is the probability that they have 3 boys? I would really appreciate some help on this one. I'm completely lost. I have no idea why my method doesnt work.

"Your new neighbors have three children. If you are told about three
  independent observations of a boy, what is the probability that they
  have three boys?"

I solve it by saying that our sample space is $S = \{bbb,ggg,bgb,bbg,ggb,gbg,gbb,bgg\}$.
If we then introduce the event $A_i = \{$observation i of boy$\}$ and call the event $B=\{bbb\}$
then $P(A_i)=7/8 $ for $i=1,2,3$ and the events $A_i$ are independent according to the problem text. Furthermore, clearly $P(B) = 1/8$.
We now want to calculate the probability
$P(B|A_1 \cap A_2 \cap A_3)$ which is (because of total law of probability/Bayes formula) equal to
$\frac{P(B)P(A_1 \cap A_2 \cap A_3 | B)}{P(A_1 \cap A_2 \cap A_3)}$
Now, $P(A_1 \cap A_2 \cap A_3) = P(A_1)P(A_2)P(A_3)$ because of their independence, and I argue that $P(A_1 \cap A_2 \cap A_3 | B) = 1$ because the probability of observing a boy three times given that there only is three boys should be one hundred percent.
This simplifies to
$\frac{8^2}{7^3}$
which is clearly wrong. The answer should be 1/2, but i have no idea how to come up with that.
What am I doing wrong?
Thanks!

A: The probability of three observations of boys and zero girls is not $\frac18$ but higher at $\frac14$.  Indeed the probability of a million observations of boys and zero girls would still be marginally above $\frac18$ rather than $\frac1{2^{1000000}}$.
One way of presenting the calculation based on your $S$ could be $$\frac{\frac18 1^3 }{\frac18 1^3+ \frac18 0^3 +\frac18 \left(\frac23\right)^3+\frac18 \left(\frac23\right)^3+\frac18 \left(\frac13\right)^3 +\frac18 \left(\frac23\right)^3+\frac18 \left(\frac13\right)^3+\frac18 \left(\frac13\right)^3} =\frac12$$

A: Since you are asked to give a probability given observations, you need to chose a prior distribution and then update it using Bayes rule, as you suggested. Let say you decide that each child has a probability 1/2 to be a boy, independently of the other children's sex (you could refine this prior, it is generally a bit more than 1/2). You have four events $\{A_0,A_1,A_2,A_3\}$ where $A_i$ is the event that your neighbor has $i$ boys. Before your observation, your prior distribution of probability is, by counting the number of outcomes, $P(A_0)=P(A_3)=1/8$ and $P(A_1)=P(A_2)=3/8$. Let us call $O$ the event "3 independent observations of a child gave me 3 times a boy". You have $P(O|A_3)=1$, $P(O|A_2)=(2/3)^3$, $P(O|A_1)=(1/3)^3$ and $P(O|A_0)=0$ (you can compute them using Bernouilli distributions).
We conclude with Bayes rule
$$
P(A_3|O) = \frac{P(O|A_3)P(A_3)}{\sum_i P(O|A_i)P(A_i)} = \frac{1\cdot 1/8}{1\cdot 1/8 + (2/3)^3\cdot 3/8 + (1/3)^3\cdot 3/8 + 0 \cdot 1/8} =  1/2.
$$

A: We can restate the question as follows.  Suppose there are $3$ balls in an urn, and each ball is either black or white with equal probability.  We draw one ball from the urn at random, observe the color, and replace it in the urn.  Given that after $3$ draws we observed a black ball each time, what is the probability that the urn contains no white balls?
Let the number of white balls in the urn be the random variable $X$.  Then before any data is observed, $X$ is presumed to follow a binomial distribution with parameters $n = 3$ and $p = 1/2$.  Let $Y$ represent the number of white balls drawn out of $3$ independent trials with replacement.  Then we have $$\Pr[X = 0 \mid Y = 0] = \frac{\Pr[Y = 0 \mid X = 0]\Pr[X = 0]}{\Pr[Y = 0]}$$ by Bayes theorem.  Since the prior distribution of $X$ is binomial, we have $$\Pr[X = 0] = \binom{3}{0}(1/2)^0 (1 - 1/2)^{3-0} = \frac{1}{8}.$$  Given that there are no white balls, $\Pr[Y = 0 \mid X = 0] = 1$--we cannot draw a white ball if there is none in the urn.  The only remaining quantity to be determined is the unconditional probability of $Y = 0$, which by the law of total probability is simply $$\Pr[Y = 0] = \sum_{x=0}^3 \Pr[Y = 0 \mid X = x]\Pr[X = x].$$  We can already compute the first term of this sum, since it is just the numerator in the desired probability.  But the other conditional probabilities when $X \in \{1, 2\}$ require more thought.  Specifically, the conditional distribution of $Y \mid X = x$ is binomial with parameters $n = 3$ and $p = x/3$.  That $n = 3$ is obvious; $Y$ comprises the sum of the number of white balls obtained from three independent draws with replacement from the urn.  The probability of observing a white ball in any single draw is determined by the number of white balls in the urn, which is $x$:  so if $x = 0$, all balls are black and $p = 0$, reflecting the impossibility of drawing a white ball.  If $x = 1$, then $p = 1/3$ reflects a $1/3$ chance of drawing a white ball.  Thus $$\Pr[Y = y \mid X = x]\Pr[X = x] = \binom{3}{y}(x/3)^y (1 - x/3)^{3-y} \cdot \binom{3}{x} (1/2)^x (1 - 1/2)^{3-x} = \frac{1}{216} \binom{3}{x}\binom{3}{y} x^y (3-x)^{3-y}.$$
With this in mind, we compute $$\Pr[Y = 0] = \frac{1}{216} \sum_{x=0}^3 \binom{3}{0} \binom{3}{x} x^0 (3-x)^3 = \frac{54}{216} = \frac{1}{4}.$$  It follows that $$\Pr[X = 0 \mid Y = 0] = \frac{1/8}{1/4} = \frac{1}{2}.$$
From here, the sophisticated student can easily generalize to the case where we are given $n$ balls in the urn, each with a prior probability $p$ of being white, and $m$ iid draws from the urn, in which $y$ are observed white.  Then the posterior distribution of the number of white balls is $$\Pr[X = x \mid Y = y] = \frac{\Pr[Y = y \mid X = x]\Pr[X = x]}{\Pr[Y = y]} = \frac{\binom{m}{y} (x/n)^y (1 - x/n)^{m-y} \binom{n}{x} p^x (1-p)^{n-x}}{\sum_{k=0}^n \binom{m}{y} (k/n)^y (1 - k/n)^{m-y} \binom{n}{k} p^k (1-p)^{n-k}}.$$


text:
Q: Broken laptop screen in win7 installation broken laptop screen in middle of win7 installation, will not boot straight to external monitor.
How can I restore? Or install?
Lenovo g560

A: The stripes you describe being on screen could be a number of things:

*

*The LCD Panel of the screen could be damaged

*The connector for the LCD panel to the laptop's internal video card has come loose and needs to be reseated

*The laptop's internal video card has become damaged.

Typically, one would press the Fn key and the key with the monitor icon in it to switch to the external monitor. If you are unable to do this, I would believe that the internal laptop video card is damaged. As with any piece of electronics falling to the ground, it is possible that more than one component was damaged in the fall (like the keyboard or motherboard), so it is difficult to propose a fix without knowing exactly which component it damaged.


text:
Q: Javascript:Dates comparison <script>
  dfrom = datefrom.split("/");
    dto = dateto.split("/");

     //Checking Year Part;
     if(parseInt(dfrom[2]) > parseInt(dto[2])){
      alert("DateFrom Cannot greater than DateTo");
      return false;
     }
     if((parseInt(dfrom[1]) > parseInt(dto[1])) && parseInt(dfrom[2]) == parseInt(dto[2])){
      alert("DateFrom Cannot greater than DateTo");
      return false;
     }
     if(parseInt(dfrom[0]) > parseInt(dto[0]) && (parseInt(dfrom[1]) == parseInt(dto[1])) &&    parseInt(dfrom[2]) == parseInt(dto[2])){
      alert("DateFrom Cannot greater than DateTo");
      return false;
     }
</script>

This is my script code to compare dates and is working fine but when I check 07/04/2013 and 08/04/2013, it shows "DateFrom Cannot greater than DateTo" and only these dates are showing wrong result. Is any error in my script or something else?
Any help would be highly appreciable.

A: try this
dfrom = datefrom.split("/");
dto = dateto.split("/");

var x=new Date();
x.setFullYear(dfrom [2],dfrom [1]-1,dfrom [0]);

 var y=new Date();
y.setFullYear(dto [2],dto [1]-1,dto [0]);

if (x>y)
  {
  alert("X is big ");
  }
else
  {
  alert("Y is big");
  }

see here

A: When interpreting the parseInt function's arguments, older browsers will use the octal radix (base-8 numbering system) as default when the string begins with "0" (e.g., '07', '08'). As of ECMAScript 5, the default is the decimal radix (10) (i.e., this is tricky, but at least now it is depreciated).
In other words, there is a chance that if you pass strings ("01") or numbers (01) that begin with 0 to parseInt without specifying the second parameter (radix, which means what numbering system), they will be interpreted as having radix 8. This means 07 === 7 and 08 probably has undefined behavior (0, "", undefined, who knows?).
To be safe, always set your radix in the second parameter to parseInt when dealing with dates (I know I do), for example parseInt(x, 10) for regular base 10.
By the way, leading numbers with 0 indicates the octal radix other languages, so it is a good to get rid of them when converting strings to numbers.
Good luck!

A: The easiest way to compare date strings is to turn them into date objects and compare those, so if your date strings are in the format d/m/y. you can do:
// s in format d/m/y
// e.g. 15/3/2013 or 15/03/2013
function toDate(s) {
  var s = s.split('/');
  return new Date(s[2], --s[1], s[0]);
}

var d0 = '3/3/2013';
var d1 = '15/3/2013';

// Compare dates
alert( toDate(d0) < toDate(d1) );  // true

alert( toDate(d1) < toDate(d0) );  // false

When used in a comparison or arithmetic operation, Date objects are coerced to a number that is their time value.


text:
Q: Сгруппировать картинки по тегу Мне приходит массив объектов, к примеру:
0: {type: "gif", id: "BZ9K1QrgcJr20", url: "https://giphy.com/gifs/dog-puppy-BZ9K1QrgcJr20", imageTag: "dog", …}
1: {type: "gif", id: "E5EUmJssOooGk", url: "https://giphy.com/gifs/cat-E5EUmJssOooGk", imageTag:"cat" …}

С помощью groupBy из lodash я их сгруппировал по imageTag, чтобы можно было выводить картинки по введённому тэгу:
{dog: Array(1), cat: Array(1)}

Суть в том, что мне нужно выводить картинки группами, то есть, если тег = "dog", то все картинки с таким тегом выводятся вместе, затем группа картинок с другим тегом и тд.
Мне непонятно, как именно реализовать вывод по группам.

A: Рекомендую воспользоваться Array.reduce

let array = [
  {type: "gif", id: "BZ9K1QrgcJr20", url: "https://giphy.com/gifs/dog-puppy-BZ9K1QrgcJr20", imageTag: "dog"},
  {type: "gif", id: "E5EUmJssOooGk", url: "https://giphy.com/gifs/cat-E5EUmJssOooGk", imageTag:"cat"},
  {type: "gif", id: "BZ9K1QrgcJr201", url: "https://giphy.com/gifs/dog-puppy-BZ9K1QrgcJr201", imageTag: "dog"},
  {type: "gif", id: "E5EUmJssOooGk1", url: "https://giphy.com/gifs/cat-E5EUmJssOooGk1", imageTag:"cat"}
];

let result = array.reduce((acc, item) => {
  if(acc[item.imageTag]) {
    acc[item.imageTag].push(item);
  } else {
    acc[item.imageTag] = [item];
  }
 return acc;
}, {});

console.log(result);

A: Вытащить все теги массива уникально, используйте Set():

let data = [{type: "gif", id: "BZ9K1QrgcJr20", url: "https://giphy.com/gifs/dog-puppy-BZ9K1QrgcJr20", imageTag: "dog",},
{type: "gif", id: "E5EUmJssOooGk", url: "https://giphy.com/gifs/cat-E5EUmJssOooGk", imageTag:"cat"},
{type: "gif", id: "BZ9K1QrgcJr20", url: "https://giphy.com/gifs/dog-puppy-BZ9K1QrgcJr20", imageTag: "dog"},
{type: "gif", id: "E5EUmJssOooGk", url: "https://giphy.com/gifs/cat-E5EUmJssOooGk", imageTag:"cat"}
];

console.log([... new Set(data.map(a=>a.imageTag))]);

Если вам надо сгруппировать объекты массива по тегу, используйте .sort():

let data = [{type: "gif", id: "BZ9K1QrgcJr20", url: "https://giphy.com/gifs/dog-puppy-BZ9K1QrgcJr20", imageTag: "dog",},
{type: "gif", id: "E5EUmJssOooGk", url: "https://giphy.com/gifs/cat-E5EUmJssOooGk", imageTag:"cat"},
{type: "gif", id: "BZ9K1QrgcJr20", url: "https://giphy.com/gifs/dog-puppy-BZ9K1QrgcJr20", imageTag: "dog"},
{type: "gif", id: "E5EUmJssOooGk", url: "https://giphy.com/gifs/cat-E5EUmJssOooGk", imageTag:"cat"}
].sort((a,b)=>a.imageTag>b.imageTag?1:a.imageTag<b.imageTag?-1:0);

console.log(data);

Если вам нужно отфильтровать массив объектов по тегу, используйте .filter():

let data = [{type: "gif", id: "BZ9K1QrgcJr20", url: "https://giphy.com/gifs/dog-puppy-BZ9K1QrgcJr20", imageTag: "dog",},
{type: "gif", id: "E5EUmJssOooGk", url: "https://giphy.com/gifs/cat-E5EUmJssOooGk", imageTag:"cat"},
{type: "gif", id: "BZ9K1QrgcJr20", url: "https://giphy.com/gifs/dog-puppy-BZ9K1QrgcJr20", imageTag: "dog"},
{type: "gif", id: "E5EUmJssOooGk", url: "https://giphy.com/gifs/cat-E5EUmJssOooGk", imageTag:"cat"}
].filter(a=>a.imageTag=='cat');

console.log(data);

Можно использовать и .reduce(), если вы понимаете как он работает:

let data = [{type: "gif", id: "BZ9K1QrgcJr20", url: "https://giphy.com/gifs/dog-puppy-BZ9K1QrgcJr20", imageTag: "dog",},
{type: "gif", id: "E5EUmJssOooGk", url: "https://giphy.com/gifs/cat-E5EUmJssOooGk", imageTag:"cat"},
{type: "gif", id: "BZ9K1QrgcJr20", url: "https://giphy.com/gifs/dog-puppy-BZ9K1QrgcJr20", imageTag: "dog"},
{type: "gif", id: "E5EUmJssOooGk", url: "https://giphy.com/gifs/cat-E5EUmJssOooGk", imageTag:"cat"}
]

console.log(data.reduce((r,v)=>((r[v.imageTag]||(r[v.imageTag]=[])).push(v),r),{}));

A:

let oldArr = {
      0: {type: "gif", id: "BZ9K1QrgcJr20", url: "https://giphy.com/gifs/dog-puppy-BZ9K1QrgcJr20", imageTag: "dog"},
      1: {type: "gif", id: "E5EUmJssOooGk", url: "https://giphy.com/gifs/cat-E5EUmJssOooGk", imageTag: "cat"}
    }, newArr = {};

for(let i = 0; i < Object.keys(oldArr).length; i++) {
  if(!newArr[oldArr[i]['imageTag']]) newArr[oldArr[i]['imageTag']] = [];
  newArr[oldArr[i]['imageTag']].push(oldArr[i]);
}

console.info(newArr);


text:
Q: How find Bitcoin transaction by the time inclusion in the block? There are many services that provide the ability to find a transaction by its id. For example, such as https://blockexplorer.com/tx/8987fa849d822dbb0e593d9d1b750550efe510b02885239b3d7f318cfd219a07
But, how do I get the transactions that were included in the blocks, not by their ID but by on-time? For example, I need get all transactions that were included in the block "Nov 7, 2015 12:24:07 PM"
Which way I get this transactoins?

A: you can get the block using unix timestamp(you can convert any time you want into this)
using blockr.io api
http://btc.blockr.io/api/v1/block/info/first?after=(timestamp)
it will give you the block hash and some other info that you can use to find the trasactions in the block
hope this helps!


text:
Q: Reading material on hosting MSHTML.DLL directly (not WebBrowser)? Can anyone suggest good reading material on hosting MSHTML.DLL/Trident directly (not SHDOCVW.DLL/WebBrowser)? I want to use it for GUI elements, sometimes major ones, in C++. I need HTML rendering, JavaScript with extra host-provided DOM methods and properties, events.
My impression is that WebBrowser just adds an extra layer providing nothing I need, and more than that, things I'll have to work to disable: cross-page navigation, history, UI, context menus, registry dependencies, generic Active Document hosting, downloading, etc.
All the articles I find talk about the WebBrowser control, even if calling it MSHTML in many cases. The Microsoft documentation makes it difficult to understand what's MSHTML and what's WebBrowser; for example, "Other MSHTML Interfaces" lists IWebBrowser2, which is not part of MSHTML.DLL, among other things.

A: MSHTML is an Active Document server. WebBrowser and Internet Explorer are Active Document hosts. If you want to host MSHTML directly, you get to implement all your own Active Document hosting interfaces, e.g. IOleDocumentSite or IOleInPlaceFrame (this is on top of regular OLE hosting interfaces, that might be provided by your framework of choice).
In addition, MSHTML requires its host to implement ITargetContainer and ITargetFrame. These are poorly documented.
Besides, as you probably already know, MSHTML doesn't support navigation. You have to download (or otherwise obtain) HTML content and feed it to the object.
For these reasons, it is difficult to host MSHTML directly, except in certain limited scenarios (e.g. as a UI-less HTML parser, see WalkAll sample). This is why there is so little information and so few samples on the topic. Most of the time, it's not worth the trouble. Just host a WebBrowser control, navigate it to about:blank, grab the MSHTML instance it hosts with IWebBrowser2::get_Document, and do whatever you want with it.


text:
Q: how to add back Ubuntu 22 GUI login session I run this command on my ubuntu 22 "sudo apt-get purge libelf-dev", then it removed lots of packages. but after that, my network is disconnected, I tried to re-connect the WIFI, but I cannot open the network configure. so I reboot the PC.
After all, I only can see the tty1 terminal login, I tried many repair/recovery, all of them don't fix this. now the problem is that I cannot connect to wifi.  if I cannot connect to wifi, then I can re-install the GUI.
do you know what is missed? how can add GUI login back in the case there is no internet???
thanks.


text:
Q: How to add images webservice? I have a web-service which accepts image data.Anyone guide me how do I sent image file which I have captured from my phone to the services on a button click?. I searched the smartface docs and also the website I got an idea of uploading to a Web-client but didn't find anything of how to upload data to SOAP services.
Thanks.

A: I don't know what kind of data does your webservice except.
If you are using capture function of camare, you will be able to reach the path of photo.
http://www.smartface.io/developer/guides/device/camera-usage-2/#capture
Also, you can save the captured photo, and use it by the name you gived.
http://www.smartface.io/developer/guides/device/camera-usage-2/#save
If these documents don't help, can you share the url of service in order for me to check it?


text:
Q: js using object literals for var replacement for the longest time now i've used object literals to replace multiple var statements within my code. here's a typical example:
(function(){
  var replaceVars = {};
  function x(){
    replaceVars.num=886;
}
  function y(){
    x();
    replaceVars.cal = replaceVars.num*99;
    return replaceVars.cal;
  }
})();

so my question is: is there anything wrong with this? i mean the up sides i can see are that: 1) there is only one var statement within the whole of my code. 2) within the closure all children can access it(which means replaceVars properties become global within the scope of the closure. it's like making a global-like child object (the closure) within the true global object(the window)  3) i can pre-define properties that are ready to go immediately:

var replaceVars={
          something1:"some value",
          something2:"some other value"
      }

so can anyone think of any downsides to my way of doing things?

A: I don't think there's anything wrong with using a container object. Though, I'd make a habit with it of declaring the variables needed for the related code:
var replaceVars = {
    num: null,
    cal: null
};

But, then again, this works as well:
(function () {
  var num, cal;

  function x(){
    num = 886;
  }

  function y(){
    x();
    cal = num * 99;
    return cal;
  }
})();

A: I'm not sure what you're trying to do, but if you just want to hide objects within another object and, for example, make them accessible via methods only, I would do it like this:
var objects = (function() {
  var x = 42;
  var y = 12;

  var container = {};
  container.getX = function getX() {
    return x;
  }
  container.getY = function getY() {
    return y;
  }
  container.getSum = function getSum() {
    return x + y;
  }

  return container;
})();

That's a lot easier to read, in my opinion.


text:
Q: How to set sequence for exact consecutive elements of csv string? I have a string csv containing PORTCODE and latitude longitude of location. I use these values to plot the marker on google map.
Eg csv string:
ANC|61.2181:149.9003,
ANC|61.2181:149.9003,
TLK|62.3209:150.1066,
DNL|63.1148:151.1926,
DNL|63.1148:151.1926,
DNL|63.1148:151.1926,
TLK|62.3209:150.1066,
TLK|62.3209:150.1066,
ALE|60.9543:149.1599

i want to autonumber SIMILAR PORTCODE sequence separated with pipe symbol '|' for the PORTCODE which are EXACT Consecutive next element.
Required out put:
ANC|61.2181:149.9003:1|2,
TLK|62.3209:150.1066:3,
DNL|63.1148:151.1926:4|5|6,
TLK|62.3209:150.1066:7|8,
ALE|60.9543:149.1599:9

Any solution using jquery/javascript/c# ?

A: There's probably a neater/shorter way to do this, but here's the first second way that came to mind using JavaScript:

var input = "ANC|61.2181:149.9003,\nANC|61.2181:149.9003,\nTLK|62.3209:150.1066,\nDNL|63.1148:151.1926,\nDNL|63.1148:151.1926,\nDNL|63.1148:151.1926,\nTLK|62.3209:150.1066,\nTLK|62.3209:150.1066,\nALE|60.9543:149.1599";

var output = input.split(",\n").reduce(function(p,c,i,a) {
  if (i === 1) p += ":1";
  return p + (c === a[i-1] ? "|" : ",\n" + c + ":") + (i+1);
});

console.log(output);

I've assumed each line ends with a single \n character, but obviously you can adjust for \r or whatever.
Further reading:

*

*the string .split() method

*the array .reduce() method

A: You can make something like that.

 var csv = 'ANC|61.2181:149.9003,\nANC|61.2181:149.9003,\nTLK|62.3209:150.1066,\nDNL|63.1148:151.1926,\nDNL|63.1148:151.1926,\nDNL|63.1148:151.1926,\nTLK|62.3209:150.1066,\nTLK|62.3209:150.1066,\nALE|60.9543:149.1599'.split(',\n');

//count entry :

var results = [];
var j = -1;
var previous = "";
for (i = 0; i < csv.length; i++) {
  if (previous === csv[i]) {
    results [j] += '|' + (i+1);
  } else {
    j += 1;
    previous = csv[i];
    results [j] = csv[i] + ':' + (i+1);
  }
}

//And reforme your csv
console.log(results.join(',\n'));

Further reading:

*

*the string .split() method

*the array .join() method

A: here is C# way to do,
public string[] data = { "ANC|61.2181:149.9003", "ANC|61.2181:149.9003", "TLK|62.3209:150.1066", "DNL|63.1148:151.1926", "DNL|63.1148:151.1926", "TLK|62.3209:150.1066", "TLK|62.3209:150.1066", "ALE|60.9543:149.1599", "DNL|63.1148:151.1926" };

int counter = 0;
var output = data.Select(x => new Tuple<string, int>(x, counter++))
           .GroupBy(x => x.Item1)
           .Select(h => h.Key + ":"+ string.Join("|", h.Select(x => x.Item2)));

output would be ANC|61.2181:149.9003:0|1,TLK|62.3209:150.1066:2|5|6,DNL|63.1148:151.1926:3|4|8,ALE|60.9543:149.1599:7


text:
Q: If an index is ensured on the opposite direction of a `sort()`, will it be used? I was wondering if say, sort(a:-1) would use an index ensured on a but in the opposite direction (ie: a:1).
I am guessing this is true for a single key index, but I just wanted to be sure since I can't find the information in the MongoDB documentation.

A: For sorting by using single field indexes, order of keys doesn't matter because MongoDB can traverse the index in either direction.
You can verify that by by using the explain command:
db.coll.find().sort({a: 1}).explain();

The relevant part of the output is (you should check the docs for the other fields in the output):
"cursor" : "BtreeCursor a_-1 reverse"

The reverse part means that MongoDB traversed the index in the reverse order.
However, if you're using compound indexes for sorting, the sort order matters.
For example, take the following compound index:
db.coll.ensureIndex({a: 1, b: -1});

This index can support these sorting operations:
db.coll.find().sort({a: 1, b: -1});
db.coll.find().sort({a: -1, b: 1});

But this index can't support this sorting operation:
db.coll.find().sort({a: 1, b: 1});

For more info about sorting, you should check the documentation.


text:
Q: Is $x_1\cdot x_2\cdots x_n$ proper notation? In a textbook I recently saw the notation
$$x_1\cdot x_2\cdots x_n$$
which was intended to mean $\prod\limits_{i=1}^nx_i$.
This is unappealing to me because for example one wouldn't write
$$x_1+x_2\cdots x_n,$$
but rather
$$x_1+x_2+\dots+x_n.$$
On the other hand, there does not seem to be a good alternative since neither of the following look right -
$$x_1\cdot x_2\cdot\dots\cdot x_n$$
$$x_1\cdot x_2\cdot\ldots\cdot x_n$$
This leads to the question:

Is $x_1\cdot x_2\cdots x_n$ the proper notation despite being inconsistent, or is there some other accepted way of using dots in conjunction with \cdot?

A: From the $\mathrm{\TeX book}$ (Chapter 18: Fine Points of Mathematics Typing, pg. 172):

In general, it is best to use \cdots between $+$ and $-$ and $\times$ signs, and also between $=$ signs or $\leq$ signs or $\subset$ signs or other similar relations. Low dots are used between commas, and when things are juxtaposed with no signs between them at all.

For example:

*

*$x_1+\cdots+x_n$$\qquad x_1+\cdots+x_n$

*$x_1=\cdots=x_n=0$$\qquad x_1=\cdots=x_n=0$

*$A_1\times\cdots\times A_n$$\qquad A_1\times\cdots\times A_n$

*$f(x_1,\ldots,x_n)$$\qquad f(x_1,\ldots,x_n)$

*$x_1x_2\ldots x_n$$\qquad x_1x_2\ldots x_n$

*$(1-x)(1-x^2)\ldots(1-x^n)$$\qquad (1-x)(1-x^2)\ldots(1-x^n)$

*$n(n-1)\ldots(1)$$\qquad n(n-1)\ldots(1)$

More typography: This is getting dangerously close to being more appropriate for TeX.SE, but here you have it: There's an important special case in which \ldots and \cdots don't give the correct spacing, namely when they appear at the very end of a formula, or when they appear just before a closing delimiter like `)'. In such situations an extra thin space is needed. For example, consider sentences like these:

*

*Prove that $(1-x)^{-1}=1+x+x^2+\cdots\,$.

*Clearly $a_i<b_i$ for $i=1$,$~2$, $\ldots\,$,$~n$.

*The coefficients $c_0$,$~c_1$, $\ldots$,$~c_n$ are positive.

To get the first sentence (I personally had to modify a couple of things above because they did not render as needed, but what follows is what Knuth describes in his book), the author typed
Prove that $(1-x)^{-1}=1+x+x^2+\cdots\,$.

Without the \, the period would have come too close to the \cdots. Similarly, the second sentence was typed thus:
Clearly $a_i<b_i$ for $i=1$,~2, $\ldots\,$,~$n$.

Notice the use of ties, which prevent bad line breaks. Here is an exercise from Knuth:

Exercise: B. C. Dull tried to take a shortcut by typing the second example this way:

Clearly $a_i<b_i$ for~$i=1, 2, \ldots, n$.

What's so bad about that?

Knuth's answer:

Explanation: The commas belong to the sentence, not to the formula; his decision to put them into math mode meant that ${\rm\TeX}$ didn't put large enough spaces after them. Also, his formula `$i=1,2,\ldots,n$' allows no breaks between lines, except after the $=$, so he's risking overfull box problems. But suppose the sentence had been more terse: $$\text{Clearly $a_i<b_i\quad(i=1,2,\ldots,n)$.}$$ Then his idea would be basically correct:

Clearly $a_i<b_i$ \ ($i=1,2,\ldots,n$).

My own thoughts: I have noticed Knuth's great consistency in notational conventions. For example, in TAOCP, the seventh exercise in 1.2.11.2 reads as follows:

What is the approximate value of $1^12^23^3\ldots n^n$?

It's very obvious Knuth means $\prod_{i=1}^n i^i$ here, just as your textbook has $\prod_{i=1}^nx_i$ to mean $x_1x_2\dots x_n$ as the notation they were introducing to represent multiplication.
I think everyone can agree that $x_1\cdot x_2\cdots x_n$ is absolutely hideous and should be avoided. Regardless, to a degree, I disagree with Brian M. Scott's comment about $x_1\cdot x_2\cdot\ldots\cdot x_n$ being the only "reasonable solution." For example, in David Gunderson's book Handbook of Mathematical Induction, one comes across the following exercise (screenshot to preserve authenticity):

Of course, that's not pretty at all. Having five center dots is a bit of overkill, and it looks rather horrible. In that case, I think the best solution is to do what Brian mentioned and have $1\cdot3\cdot5\cdot\ldots\cdot(2n-1)$ because you obviously can't have $135\ldots(2n-1)$, but Brian's predilection for using \ldots has been stated before, where he often uses \ldots even between $+$ signs to get $+\ldots+$ (I don't think anything is wrong about this; there is bias in that comment though).
What is truly important? That people understand what you are communicating. Of course, it is nice to typeset things very well and make correct use of notation, but I don't think it's something to get too huffy and puffy about (although I do agree $x_1\cdot x_2\cdots x_n$ is a bit disappointing). As the amazing egreg points out (and egreg, if you are reading this, please correct me if I went amiss anywhere), the notation $f : A\to B$ is not even correct--it should be $f\colon A\to B$, but the former is much more common for whatever reason.

A: You can write
$$x_1  x_2 \cdots  x_n = \prod_{i=1}^n x_i.$$
This does not work well for products whose first few terms
are literal numbers, however; in
$$1 \cdot 3 \cdot 5 \cdot 7 = \prod_{i=1}^4 (2i-1),$$
setting the numbers without any symbol for multiplication
would be simply incorrect in my opinion.
Among other alternatives already mentioned, I think I have sometimes
seen extra space inserted between the dot representing multiplication
and the dots representing ellipsis:
$$x_1 \cdot x_2 \cdot \;\cdots\; \cdot x_n = \prod_{i=1}^n x_i.$$
This way you do not have something that just looks like five dots in a row.
In that vein,
$$1 \cdot 3 \cdot 5 \cdot \;\cdots\; \cdot (2n-1) = \prod_{i=1}^n (2i-1).$$


text:
Q: To use 'to' or not to use 'to' between the verb 'is' and another verb 'What reading does is encourage comprehension and our ability to focus.'
As far as I'm concerned there's nothing wrong with this sentence. However, I'm aware that one could add 'to' before encourage. I would like to know whether any prescriptivists would say it should include 'to' or whether as a matter of style in formal English it would be better.
Thanks for any ideas on this.


text:
Q: c++ std::copy input iterator (pointers) to vector Hi I'm trying to understand why the following code does not work. I'm trying to use pointers as the input iterator type to the std::copy algorithm. fsRead.Buffer points to the beginning of the data I want to copy, and fsRead.BufferSize is size of the data that we want to copy.
// AllocateZeroPool(UINT64) takes an input size, and returns a pointer to allocated memory. (this is the existing C api)
fsRead.Buffer = static_cast<UINT8*>(AllocateZeroPool(fsRead.BufferSize));
//
// this next line populates the data into fsRead.Buffer
auto status = mFs->read_data(nullptr, &fsRead);

the type of file.data is: std::vector<UINT8>
std::copy(fsRead.Buffer, fsRead.Buffer + fsRead.BufferSize, file.data.begin());

file.data.size() is zero with the above std::copy() call.
To get the data into the vector file.data, I currently do the copy by hand:
for(auto i(0U); i < fsRead.BufferSize; ++i) {
    file.mBinaryData.emplace_back(fsRead.Buffer[i]);
}

Why does using two pointers as input iterators not seem to work?
edit: To clarify I mean that no data is actually copied into the file.mBinaryData vector.

A: With std::vector you must use a std::back_inserter. Without it the iterator will not do a push_back to copy the data, but just increment the given iterator.
std::copy(fsRead.Buffer, fsRead.Buffer + fsRead.BufferSize, std::back_inserter(file.data));

A: This fails because accessing iterators to a vector never change the size of the vector.
You can use one of the standard iterator adapters, such as back_inserter, to do this instead. That would look like this:
// Looks like you really wanted copy_n instead...
std::copy_n(fsRead.Buffer, fsRead.BufferSize, std::back_inserter(file.data));


text:
Q: Splitting the screen into half(horizontally) while using a border for TextViews (Android) I have a layout which divides the screen into two horizontally and it works correctly. But when I try to put a border (as a background image from my custom drawable folder) the second TextView does not start at the half of the page. It comes next to the first view. How can I fix?
Here is that part of my xml.
<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/border_tasks"
            android:orientation="horizontal">
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="Bekleyen                 \n Görevler \n 10"
                android:layout_weight="1"/>
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="Biten                     \n Görevler \n 90"
                android:layout_weight="1"/>

        </LinearLayout>
    </LinearLayout>

Here is the full xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/activitychart"
    android:orientation="vertical">
   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="@drawable/border_name"
       android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text ="Adı Soyadı"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Anadolu Sigorta - Eksper"
        />
   </LinearLayout>
    <com.github.mikephil.charting.charts.PieChart
        android:id="@+id/chart"
        android:background="@drawable/border_name"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:paddingLeft="@dimen/_5sdp"
        android:scaleX="1.02"
        android:scaleY="1.02"
        />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/border_tasks"
        android:orientation="horizontal">
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Bekleyen                 \n Görevler \n 10"
            android:layout_weight="1"/>
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Biten                     \n Görevler \n 90"
            android:layout_weight="1"/>

    </LinearLayout>
</LinearLayout>

And here is border tasks (values are just random, you can change them.)
The reason I use two different textviews is that I will add an additional border for each text view after adding a wider border which encapsulates both of them
border_tasks.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <corners android:radius="20dp"/>
    <size android:width="@dimen/_160sdp" android:height="@dimen/_60sdp" ></size>
    <padding android:left="10dp" android:right="@dimen/_160sdp" android:top="10dp" android:bottom="10dp"/>
    <stroke android:width="1dp" android:color="#CCCCCC"/>
</shape>

Here @dimen/_160sdp refers to 160 dp and so on. I played with the values but I could not make it work.

A: The problem is with the border_task.xml.
I changed it by removing the size tag and changing the padding to 10dp from all directions.
This generates a rounded border containing both textviews. And the text views occupy 50/50 of the space.
    <?xml version="1.0" encoding="UTF-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
        <corners android:radius="20dp"/>
        <padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
        <stroke android:width="1dp" android:color="#CCCCCC"/>
    </shape>

Hint: to separate the border of the LinearLayout from the border of the screen add a margin of 5dp to the LinearLayout.


text:
Q: How can I set this JQuery / Java Script Function to be activated on scroll? I have this function here:
  if($(".redacted").hasClass("redacted-animated")== false){
    $(".redacted").addClass("redacted-animated");
  }
}

function Uncover_Toggle(elem){
  if($(elem).hasClass("redacted-animated")== true){
    $(elem).removeClass("redacted-animated");
  }else{
    $(elem).addClass("redacted-animated");
  }
}

$(".redacted").on("click", function(event){
  Uncover_Toggle(event.target);
});

setTimeout(function(){Redact();},1000);

That along with this small piece of CSS:
.redacted {
-webkit-box-decoration-break: clone;
box-shadow: inset -1000px 0 0 var(--color-dark);
transition: box-shadow 600ms cubic-bezier(0.645, 0.045, 0.355, 1);}

Adds small "Censorship Rectangles" to an HTML Text when the class of 'redacted" is used in a  tag:

It's currently triggered by a 1000ms Timeout.
setTimeout(function(){Redact();},1000);
I want to change this script to be triggered when the user scrolls, and tried to make it work like this:
    const $body = $('body');
    const $panel = $('.redacted');

    // Change 33% earlier than scroll position so the first redactions are there when the scroll arrives.

    const scroll = $window.scrollTop() + ($window.height() / 1.8);

    $panel.each(function () {
        const $this = $(this);

        // if position is within range of this panel.
        // So position of (position of top of div <= scroll position) && (position of bottom of div > scroll position).
        // Scroll was set to 33% earlier in scroll var.
        if ($this.position().top <= scroll && $this.position().top + $this.height() > scroll) {

            // Add class to currently active scroll position
            $span.addClass(`redacted-${$(this) )}`);
        }
    });
}).scroll();

But did not succeed - can someone point me to my mistake in triggering the script on scroll?


text:
Q: Is it possible to replace / or . in a string with __ in a macro? I want to convert a string with / or . into an auto-generated variable name. So I need convert / or . into something acceptable by variable naming, such as __.
It's easy to do it with a function. But with macro, is it possible?
#define ROUTE(path, impl) \
char * k##path##_route = "{"#path":\""#impl"\"}"; // compilation failure for path like /usr/abc or ./abc

I can use impl to name the variable, but since multiple paths may map to the same impl, the compiler will complain about duplication for different paths with the same impl.

A:
But with macro, is it possible?

No. It is not possible to replace characters of an argument using the standard preprocessor.

acceptable by variable naming, such as __

__ is not an acceptable variable name because it is reserved to the implementation. As are all identifiers that contain consecutive underscores in C++.


text:
Q: Classification from a string of numbers and letters I have a database full of items and I've been tasked with classifying them (they could be books, stationary etc). The options are to either go through 100k records manually and figure out what they are or to automate the task.
The codes for each type of item follow some kind of pattern, and so I'm hoping to use machine learning to solve this (I do not want to use regular expressions). Though I'm quite good at python, my ml knowledge only goes as far as random forests and logistic regression.
Is this at all possible? The data looks like this:

Item          code          type
1       4S2BDANC5L3247151   book
2       1N4AL3AP1JC236284   book
3       3R4BTTGC3L3237430   book
4       KNMAT2MT1KP546287   book
5       97806773062273208   pen
6       07356196706378892   Pen
7       97807345361169253   pen
8       01008130715194136   chair
9       01076305063010CCE44 chair
etc

I'm happy to look up and learn whatever is necessary, I just don't know where to start
Thanks!

A: I understood that you have 100k example. You can use RNN, LSTM or Attention based deep learning methods because the pattern of codes can be tracked by that models. Also machine learning models can solve that problem. In the end, your problem includes specific type of patterns for different classes. Therefore, you can separate that classes.
1) You need to start with finding embedding to represent your codes. I guess you can use ascii codes of numbers and letters. Also to make all vectors be the same length, use padding. Then you can normalize them to put in between 0-1.
2) Then my advise is to start with SVM with one-vs-all strategy to make multi-class classification. After that you can try XGBoost, which is a powerful ml model. Or you can start with more basic ml models. Idea behind that, start from basic and goes to complicated models.
3) If ml models are not enough for that task, start with basic RNN models.
I don't know about your data distribution among classes and also number of classes. If it is balanced and each class have enough data I guess you can easily automate that task.


text:
Q: How to change meta tag image dynamically in reactjs for sharing of link on Facebook, WhatsApp or any platform I need to display the image for a link when sharing on Facebook, WhatsApp or any platform.
It worked when added in index.html but I need to add the image in component because the image is dynamic. I tried with react-meta-tag but did not work, Please help me.
return (

      <MetaTags>
        <title>title app.js</title>
        <meta property="og:site_name" content="The Rock Photo Studio" />
        <meta property="og:title" content="The Rock Photo Studio in Florida" />
        <meta
          property="og:description"
          content="The best photo studio for your events"
        />
        <meta
          property="og:image"
          content="https://thewedpostamit.s3.ap-southeast-1.amazonaws.com/1584017948002WK2_4905.jpg"
        />
        <meta property="og:type" content="website" />
        <meta property="og:image:type" content="image/jpg" />
        <meta property="og:image:width" content="300" />
        <meta property="og:image:height" content="300" />
        <meta
          property="og:url"
          content="https://thewedpost.com/stories/varsha-and-ram-from-college-sweethearts-to-happily-ever-after"
        />
      </MetaTags>

        Test Title{" "}

        Published by - Test User | 8 minute read

  );

A: It seems like you need server side rendering to make crawlers(fb, tw, etc...) see your open graph tags. Dynamically adding on client side does not work. Crawlers can see only static html.


text:
Q: Make particular column of datagrid a combobox when AutoGenerateColumns="True" I know this has been asked before but I still can't get it to work
I am just testing things because I m new so I'm not using MVVM.
I have a datagrid bound to an Observable Collection of entities
The data binding works fine but I want to make one column a ComboBox on edit mode
Which i achieved but i couldn't not bind that column , to the specific property of the entity.
Here's my Datagrid xaml :
        <DataGrid x:Name="dataGrid1"   IsSynchronizedWithCurrentItem="false"  ItemsSource="{Binding}"  RowHeaderWidth="0"  HorizontalScrollBarVisibility="Disabled"  HorizontalAlignment="Left" Margin="50.752,160.516,0,0" VerticalAlignment="Top" Height="Auto"  MaxHeight="200"  Width="395.429" RenderTransformOrigin="0.5,0.5" Background="#FFCFCFCF"  ColumnWidth="*" HorizontalGridLinesBrush="Black" VerticalGridLinesBrush="Black" RowBackground="#FFCFCFCF" AreRowDetailsFrozen="True" Style="{DynamicResource DataGridStyle2}" CellEditEnding="dataGrid1_CellEditEnding" CurrentCellChanged="dataGrid1_CurrentCellChanged" Grid.Column="1" Opacity="0" SelectionChanged="dataGrid1_SelectionChanged" AutoGeneratingColumn="dataGrid1_AutoGeneratingColumn" >
        <DataGrid.CellStyle>
            <Style TargetType="DataGridCell">
                <Setter Property="Block.TextAlignment" Value="Center"/>
                <Setter Property="Template" Value="{DynamicResource DataGridCellControlTemplate1}"/>
            </Style>
        </DataGrid.CellStyle>
        <DataGrid.Effect>
            <DropShadowEffect BlurRadius="20"/>
        </DataGrid.Effect>
        <DataGrid.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform/>
                <TranslateTransform/>
            </TransformGroup>
        </DataGrid.RenderTransform>
        <DataGrid.ColumnHeaderStyle>
            <Style TargetType="{x:Type DataGridColumnHeader}">
                <Setter Property="Background" Value="{StaticResource PrimaryBrush}"/>
                <Setter Property="Foreground" Value="{DynamicResource PrimaryFont}" />
                <Setter Property="HorizontalContentAlignment" Value="Center" />
            </Style>
        </DataGrid.ColumnHeaderStyle>
        <DataGrid.Columns >

            <DataGridTemplateColumn x:Name="champ_delete" d:IsHidden="True" >
                <DataGridTemplateColumn.CellTemplate >
                    <DataTemplate>
                        <Button x:Name="delete" Content="Button" Width="30" Height="30" Style="{DynamicResource ButtonStyle12}" Click="supprime_Click"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

        </DataGrid.Columns>

    </DataGrid>

And here is my MainWindow.xaml.cs code
/// <summary>
/// Interaction logic for MENU.xaml
/// </summary>
public partial class MENU : UserControl, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public MENU()
    {
        this.InitializeComponent();

        SContext = new Entities();

        ObsCollection = new ObservableCollection<PERFCONTENEUR>(SContext.PERFCONTENEUR.ToList());

        DataContext = this;
        dataGrid1.ItemsSource = ObsCollection;
    }

    public BindingList<PERFCONTENEUR> Ji { get; set; }
    public ObservableCollection<PERFCONTENEUR> ObsCollection { get; set; }

    public Entities SContext;

    private void dataGrid1_AutoGeneratingColumn(object sender, System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs e)
    {

      if (e.PropertyName == "CLIENT")
        {
          var cb = new DataGridComboBoxColumn();

          e.Column.Header = "clients";
          cb.ItemsSource = (DataContext as ObservableCollection<PERFCONTENEUR>).ToList(); // I think the problem is here

          cb.SelectedValueBinding = new Binding("CLIENT");
          e.Column = cb;
         }
    }
  }

A: please refer below implementation.
<DataGrid  ItemsSource="{Binding Persons}" AutoGeneratingColumn="DataGrid_AutoGeneratingColumn"/>
 public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new ViewModel();
    }

    private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        if (e.PropertyName == "FirstName")
        {
            DataGridComboBoxColumn cboclm = new DataGridComboBoxColumn();
            cboclm.Header = "First Name";
            cboclm.ItemsSource = (DataContext as ViewModel).Names;
            cboclm.SelectedValueBinding = new Binding("FirstName");
            e.Column = cboclm;
        }
    }
}
 class ViewModel
{
    private ObservableCollection<Person> persons = new ObservableCollection<Person>();

    public ObservableCollection<Person> Persons
    {
        get { return persons; }
        set { persons = value; }
    }

    private ObservableCollection<string> names = new ObservableCollection<string>();

    public ObservableCollection<string> Names
    {
        get { return names; }
        set { names = value; }
    }

    public ViewModel()
    {
        Person p = new Person();
        persons.Add(p);
        Names.Add("Test1");
        Names.Add("Test2");
    }

}

class Person
{
    private string firstName;

    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }

}


text:
Q: how to use fluentmigrator with SQL CLR i was wandering if fluentmigrator has any feature to auto update a clr in sql. Is sql clr assemblies something that should be migrated separately?
Thanks in advance


text:
Q: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException Previously, I could successfully send request to a web service and receive response but it now returns the following exception. Based on other answers I need to renew the certificate but I need to know why I am receiving this exception now. The other issue is that, I could find the address of my java_home but I can not renew the certificate.
Exception:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: timestamp check failed

Code
URI uri = new URI("https", "xml.example.com", "/service/ServiceRequest.do",
                           "serverName=www.example.com&xml="
                           ...
                           +" ", null);

            URL page = uri.toURL();
            HttpsURLConnection conn = (HttpsURLConnection) page.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();

A: The problem is that you are trying to talk to a server whose SSL Certificate has expired.  The reason you are getting the exception is because the Java SSL code is checking the certificate chain, and has noticed the problem.  A SSL certificate that has expired is not trustworthy ... and is not trusted by the default certificate validator.

I can not renew the certificate ...

Renewing the certificate is up to the owner of the website.  If that is not you, then there is nothing you can do ... apart from bypassing validation of the certificate, which is bad for SSL connection security.


text:
Q: Using htaccess to redirect to certain extension I want to know how to use .htaccess to redirect a certain path to a certain extension. To be more clear, I want to redirect something like this:
http://www.example.com/api/some/page

To this:
http://www.example.com/some/page.json

I understand that I could just do this using the router that is supplied by CakePHP, however, how would this be done with a .htaccess file?

A: To handle this rewrite, you may use this rule just below RewriteEngine On:
RewriteEngine On

RewriteRule ^api/(?!.+\.json$)(.+)$ $1.json [L,NC]

*

*(?!.+\.json$) is a negative lookahead that skips matching URIs that end with .json (to avoid a rewrite loop)

*Pattern ^api/(?!.+\.json$)(.+)$ matches URIs that start with /api/ and captures part after /api in $1

*$1.json in target adds .json at the end of matched part

*Flags: L is for Last and NC is Ignore case


text:
Q: stuck booting into broken Bootcamp (Win 7) volume. any ideas on how to get back to OS X? I've got a 10.11.6 (El Capitan) tower with separate drives for OS X and Windows 7 via Bootcamp, which I also use via Parallels. I went to shut down the Win 7 VM via Parallels yesterday and it wanted to 'finish' installing a bunch of Windows Updates. I let it run for hours and it was still stuck on 1 of 32(ish) so I reluctantly killed it. After this it was failing to boot up again, so I figured I'd reboot the entire machine into Win 7 to fix it... big mistake apparently.
The automatic repair options in Windows are all failing to correct the problem. Rolling back to a previous known good state fails. System restore fails. Safe mode blue screens at login. I have a Windows 7 install CD but can't get the system to boot to it and restore the OS. Tapping F8 at startup gives me some more options but restore via CD doesn't seem to be one.
The worst part is that holding the option key down at boot leaves me with a black screen so I can't select to boot back into OS X. I tried using 'X' from the list here but no dice on that either (just proceeds to fail to boot into windows again).
Would love to hear any other ideas about repairing the windows installation or getting back into OS X.

A: I pulled the windows drive and put it in a windows machine to repair it and got it booting over there, but it still wouldn't boot when put back into my Mac Pro.
I was able to get my Mac Pro to boot back into OS X by resetting NVRAM (command-option-P-R after startup sound until you hear it again). Apparently this contains boot disk preference and resetting it along with pulling the windows drive let it 'find' OS X again.
I believe the reason that OS X Recovery and holding option for the Startup Manager don't work for me is due to an aftermarket GTX 760 graphics card. It works great on successful boot, however it doesn't behave the same as the OEM card did in the EFI.


text:
Q: Custom image on facebook sharer I'm working on task of share a link on facebook. But I want to display my own static image (independent of url). With help of google and facebook, I come to know that I have to pass image path (which I want to display) in image parameter of sharer.php. But still, it displays image related to that site. I don't know that where is my mistake. If anyone know answer then please explain or suggest me link from where I can understand from beginning. Thank You.
Here is my code.
<?php
        $title = urlencode("How to Create a Custom Facebook Share Button with a Custom Counter");
        $url = urlencode("http://www.daddydesign.com/wordpress/how-to-create-a-custom-facebook-share-button-with-a-custom-counter/");
        $summary = urlencode("Learn how to create a custom Facebook 'Share' button, complete with a custom counter, for your website!");
        $image = urlencode("http://www.daddydesign.com/ClientsTemp/Tutorials/custom-iframe-share-button/images/thumbnail.jpg");
?>
<html>
        <a id="button" onClick="window.open('http://www.facebook.com/sharer.php?s=100&p[title]=<?php echo $title; ?>&p[summary]=<?php echo $summary; ?>&p[url]=<?php echo $url; ?>&&p[images][0]=<?php echo $image; ?>', 'sharer', 'toolbar=0,status=0,width=550,height=400');" target="_parent" href="javascript: void(0)">
            Click to Share
        </a>
</html>

A: Your image http://www.daddydesign.com/ClientsTemp/Tutorials/custom-iframe-share-button/images/thumbnail.jpg is the problem - it's not actually an image but takes you to a regular webpage.
You need to set a specific image which fits facebook's size  requirements, the minimum size is 200x200 pixels.


text:
Q: Sequence diverging to infiinity definition question Let $a_n$ be a real sequence
I know a definition for a sequence to diverge to infinity, that being: if for all m ∈ real numbers, exists N ∈ natural numbers :
$a_n > m , n≥N$
Is the following definition a proper definition for a real sequence to diverge to infinity as well?
For all m ∈ real numbers, exists $a_n$ ∈ real numbers :
$a_n > m $
Otherwise, I would like some clarification, please.

A: No take the sequence
$$
a_n=(-1)^nn.
$$
Under your proposed definition this sequence diverges to infinity (but it clearly does not).


text:
Q: simplecart js setting column widths I've used this site for assistance many times but never had to ask a question so finally joined...anyway, trying to set up simplecart checkout and having some trouble formatting cart output. I have my cart set to table and by default the simpleCart_items class displays the table and it's cells only as wide as they need be to fit the data. I can change this by specifying all cells(columns) as a percentage of the whole table. Unfortunately with 7 columns each only gets about 14% and this is way to much for a 1 or 2 digit quantity and not near big enough for all the characters in the item name without wrapping. What I want is a way to define a different width for each column. I have not found a way to do this even with colgroup but maybe just not doing it right. Any and all help would be appreciated!

A: Okay, so this may or may not help. This line is located in the simpleCart.js file. I changed it to something simple.
cartColumns         : [
{ view: function(item, column){
return"

"+item.get('name')+"

<button>-</button> "+item.get('quantity')+" <button>+</button>

$"+item.get('price')+"

";
},
}
],

You can change it to your own html
cartColumns         : [
{ view: function(item, column){
return" YOUR HTML HERE ";
},
}
],

It MUST all be in ONE (1) LINE or else it may not work.
here are some values that are used
image = item.get('image')
name = item.get('name')
quantity = item.get('quantity')
price = item.get('price')

you can look at all the values here
http://simplecartjs.org/documentation/displaying_cart_data
but the point is that you can make a cart and display it how you want; with you own html and css. I hope this helped.


text:
Q: Knockout rendered link, click handler issue Lets talk with code:

                    Update score

                    You  /

I have registered click handler to link 'btnPush' as:
$("#btnPush").on('click', function () {
//My code
});

Just using knockout foreach control, virtual elements and contexts, don't know what i am missing but click never get registered for this link this way. Inline Html onClick() works though:
Update score

Also, if same link is outside of ul-container (Outside of foreach binding), it works fine. Can someone suggest me please?

A: You should handle the click event with knockout. It is a bad practice use jQuery to handle the DOM when you use knockout and also it will easy if you use the ko click binding.
Check the documentation: http://knockoutjs.com/documentation/click-binding.html
*If you need run a method inside a ko foreach, and this method belongs to the VM remember to use the $parent or $root key.

    link


text:
Q: Unique Instances of NSString for empty or 1-char strings I would like to understand more about the way XCode/Objective-C handle constant strings.  I found a related question, but I would like more information.  Consider the following code:
NSString *a = [[NSString alloc] initWithUTF8String:[[_textFieldA stringValue] UTF8String]];
NSString *b = [[NSString alloc] initWithUTF8String:[[_textFieldB stringValue] UTF8String]];
NSString *c = [a copy];
NSString *d = [a mutableCopy];

Note that the textFields are just a way to set the strings at runtime ensuring that the compiler doesn't get too smart on me and build in a single instance.
If my text fields are empty, or contain a single character such as "x" or "$", then a == b == c == the same constant NSString instance.  If I instead provide "xy", then a == c != b.  d is always unique, as one might expect since it is mutable.
Now normally this wouldn't be an issue, I'm not trying to modify the contents of these strings, however, I am working on a system where I frequently use objc_setAssociatedObject.  So here now I might come accross an empty string, and then set associated object data on it, and then have another empty string and collide with the first.
I have, for the moment, solved my issue by creating mutable strings instead.
So my questions:

*

*Is this an Objective-C specification, or an XCode excentricity?

*Does anyone know how the instance is determined?  Why "x" get's one instance, but not "xy"?  I would think some internal dictionary is involved and there's no good reason to stop at 1 character.

*Is there a way to turn this off, so all empty strings are unique instances, or other suggestions?

I am using XCode 5.1.1, OSX 10.9.4, SDK 10.9.
Thank you!

A:
Is this an Objective-C specification, or an XCode excentricity?

It is just implementation detail. Not documented any where. These kind of behaviour may changed in future without notice.

Does anyone know how the instance is determined? Why "x" get's one instance, but not "xy"? I would think some internal dictionary is involved and there's no good reason to stop at 1 character.

No until someone able to access source code want to share the details with us.

Is there a way to turn this off, so all empty strings are unique instances, or other suggestions?

No way to turn it off. Don't use objc_setAssociatedObject with NSString

As @Ken Thomases said in comment

In general, it probably doesn't make sense to use objc_setAssociatedObject() with any value class.

Some other examples are NSNumber, NSData and NSValue. They are often cached and reused.


text:
Q: Why is G3 continuity only achievable between two edges? Why is G3 continuity only achievable between two edges?
For example, curve 1/2/3, 4/5/6, 7/8/9, 10/11/12 are all G3 continuous. The center surface is built with G3 constraint on edge 5/2. Since curve 1/2/3, 4/5/6 are G3 already, how come edge 8/11 can only achieve G1 tangent?
Can't I just build a function to use the first & second & third derivatives at each u/v's edge control point to compute the 3 control points adjacent to this edge control point to achieve G3 on all 4 edges?

A: The reason that the center surface cannot be built to be G3 to all 4 surfaces is because the 4 surfaces might not meet at the 4 corner points with G3 continuity. In fact, for the given condition that the curves 1/2/3, 4/5/6, 7/8/9, 10/11/12 are all G3 continuous only ensures that the 4 surfaces meet at the 4 corner points with G1 continuity.
The following is a bit more details per OP's request.
Let's denote two of the 4 surfaces as Surface A and B with coincident control points P and Q as shown in the following picture.

The normal vector of Surface A at point P is obtained by taking cross product of vector(P,P1) and vector(P,P2) and that for surface B at point Q is the cross product of vector(Q,Q1) and vector(Q,Q2). Since curve 1 and 2 are connected with G3 continuity, it means that vector(P,P1) is parallel to vector(Q,Q1). Similarly we have vector(P,P2) parallel to vector(Q,Q2). Therefore, we can conclude that surface A and B have the same unit normal vector at point P (or Q), which means the two surface meet with G1 continuity.
In order for surfaces A and B to meet with G2 at point P, 3 more control points from each surface will get involved (shown in the picture as green dots P3, P4 and P5 for surface A). All these 12 control points (6 from each surface) need to form a specific relationship in order for the two surfaces to meet with G2 continuity. The fact that curve 1/2 and 8/9 are connected with G3 continuity only affects the location of P3 and P5, and not the location of P4. Therefore, it does not ensure the two surfaces meet with G2 continuity at point A, let alone G3 continuity.


text:
Q: Using file_exists to check if image exist before echo I'm trying to let my script check if an image exist before echoing it into my table. If it doesn't exist, it should echo another image in stead. My problem is that even though the image exist, it still goes to the else factor. Can anyone spot any coding mistakes?
<?php
mysql_select_db("xxxx");
$result = mysql_query("SELECT * FROM yyyy WHERE frivillig=1 ORDER BY stilling");
while($row = mysql_fetch_array($result))
{
?>

<?php  if (file_exists($url . "ansatte" . "/" . (utf8_encode($row['etternavn'])) . "%20" . (utf8_encode($row['fornavn'])) . ".jpg")) {
echo "";
}
else {
echo "";
}
?>

As you can see, I use $url for my complete url, and the images are placed in the /ansatte/ folder.
Thanks for any help!

A: file_exists() isn't intended for checking URLs.  Your call to file_exists() should reflect a relative or absolute filesystem path instead of a URL.

A: Consider the below snippet for checking remote resources:
$path = $url . "ansatte" . "/" . (utf8_encode($row['etternavn'])) . "%20" . (utf8_encode($row['fornavn'])) . ".jpg"

$ch = curl_init($path);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, TRUE);
$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpcode < 400) { // Filter out bad request, not found, etc
 // found
} else {
 // not accessible
}

If you don't have php5-curl installed, you could also look at the following alternatives:
getimagesize
Again only certain streams are supported here, but usage is simple and it will validate the return better:
if (getimagesize($path) !== FALSE) {
  //exists
}

fopen
if (fopen($path,"r") !== FALSE) {
  // exists
}

get_headers
$headers = get_headers($path, TRUE);
if ($headers !== false && isset($headers['Content-Type']) && $headers['Content-Type'] == 'image/jpeg') {
  // exists
}

A: I'm going on a hunch here and assuming that the image file is, in fact, on the same server as the script. If so, you should be using absolute or relative paths when checking if the file exists, not a URL.
<?php

$stmt = $dbh->prepare("SELECT * FROM yyyy WHERE frivillig=1 ORDER BY stilling");
$stmt->execute();
$rows = $stmt->fetchAll();

$url = 'http://www.yoursite.com/subdir/';
$path = '/path/to/yoursite/subdir/';

foreach ($rows as $row) {
    ?>

    <?php
    if (file_exists($path . "ansatte" . "/" . (utf8_encode($row['etternavn'])) . "%20" . (utf8_encode($row['fornavn'])) . ".jpg")) {
        echo "";
    }
    else {
        echo "";
    }
}
?>

Also as @crush mentioned, you should not be using mysql_* functions. They are deprecated as of PHP 5.5. The above example uses PDO.


text:
Q: AppEngine: Getting only 1KB when uploading from an fetched URL to S3 I´m trying to upload a file which is fetched from a server. But when the fetched file is bigger than 1MB there will be only a 1KB small file saved at S3. When it´s smaller than 1MB, the file will be saved properly.
I ´ve searched and tried different ways, but none off them is working. Here is the class which is triggered by the user clicking a button.
`
class Fetch_by_button(webapp.RequestHandler):
def get(self):
    #1. fetch the file
    try:
        result = urlfetch.fetch('http://someurl.com/music.mp3') # file with 2MB
        #result = urlfetch.fetch('http://anotherurl.com/document.pdf') #file with 900KB is working
    except DownloadError:
        print("URL fetch doesnt work properly")

    #2. search datastore UserData-model by userobject to get s3 credentials
    usr = users.get_current_user()
    query = UserData.gql("WHERE account =:1", usr)
    qr = query.get()

    #3. establish connection to s3
    conn = S3Connection(qr.s3_accesskey, qr.s3_secret_accesskey)

    #4. create bucket
    ak_lowercase = str.lower(str(qr.s3_accesskey))
    individual_bucket_name = ak_lowercase + '_' + usr.nickname()
    bucket = conn.create_bucket(individual_bucket_name)

    #5. generate key and assign to already created bucket
    k = Key(bucket)

    #6. name the key by some examplary filename
    k.key = 'justsomefilename'

    #7. save the correspondent value to the created key
    k.set_contents_from_string(result.content)`

I just don´t have any clue why this happens. Something with my code, some AppEngine restrictions, anything with boto, ... Any suggestions?
Thanks in advance.

A: The maximum request size on app engine is 1mb for urlfetch.  I'm guessing your  S3Connection class uses that to do the actual transfer.
Responses can be up to 32MB, that's why the download works.