text:
Q: Spring Beginner - No such field error I am new to spring. I am developing one sample project using spring. I am getting the following exception when I provide a value in Beans.xml. Please provide solution.
Beans.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="helloWorld" class="com.dhr.spring.beans.HelloWorld">
       <property  name="message"  value="d" />
   </bean>

</beans>

HelloWorld.java:
public class HelloWorld {
     private String message;

       public void setMessage(String message){
          this.message  = message;
       }

       public void getMessage(){
          System.out.println("Your Message : " + message);
       }
}

MainApp:
 public class MainApp {
     public static void main(String[] args) {
          ApplicationContext context =
                 new ClassPathXmlApplicationContext("Beans.xml");

          HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

          obj.getMessage();
       }
}

Exception:
Caused by: java.lang.NoSuchFieldError: NULL
    at org.springframework.expression.TypedValue.<clinit>(TypedValue.java:31)
    at org.springframework.expression.spel.support.StandardEvaluationContext.setRootObject(StandardEvaluationContext.java:85)
    at org.springframework.expression.spel.support.StandardEvaluationContext.<init>(StandardEvaluationContext.java:74)
    at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:124)
    at org.springframework.beans.factory.support.AbstractBeanFactory.evaluateBeanDefinitionString(AbstractBeanFactory.java:1299)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.evaluate(BeanDefinitionValueResolver.java:210)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:182)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1360)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    ... 11 more

A: Welcome! To the ambiguous world of Spring! Where stack traces are long and documentation is short convoluted.
I have seen this error several times and, at least for me, it usually has to do with dependency inconsistencies.
I see that you just posted you are not using Maven. I can almost assure you that that is the problem. You really SHOULD be using Maven. The amount of work it will save you is monumental.
Edit: To make this post more answer-like: You are getting the error due to dependency inconsistencies. You are manually putting Spring JAR files into your dependency tree which is not recommended.
Either 1) Use Maven to handle dependency management (recommended) or 2) Ensure that all your JAR files utilize non-conflicting and coherent dependency trees.
For instance, you are using org.springframework.expression-3.0.3.RELEASE which is not part of the 3.1.x group. So, replace the jar file with org.springframework.expression-3.1.0-RELEASE


text:
Q: OGR to read from Oracle, and then write a CSV I need to read an Oracle (not Spatial) table with OGR.
I have no problem with ogrinfo. I use this command:

ogrinfo -ro OCI:user/password -sql "select * from HR.EMPLOYEES"

I have this kind of output:
OGRFeature(select * from HR.EMPLOYEES):106
  EMPLOYEE_ID (Integer) = 206
  FIRST_NAME (String) = William
  LAST_NAME (String) = Gietz
  EMAIL (String) = WGIETZ
  PHONE_NUMBER (String) = 515.123.8181
  JOB_ID (String) = AC_ACCOUNT
  SALARY (Real) =  8300.00
  COMMISSION_PCT (Real) = (null)
  MANAGER_ID (Integer) = 205
  DEPARTMENT_ID (Integer) = 110

Now I would like to export (in example) in CSV format, using OGR. This is the command:

ogr2ogr -f "CSV" test.csv OCI:"user/password" -sql "select * from HR.EMPLOYEES"

I have this errors:
ERROR 4: Failed to create test.csv\select * from HR.EMPLOYEES.csv:
Invalid argument
ERROR 1: Terminating translation prematurely after failed
translation from sql statement.

I'm not able to find the syntax error.
What's wrong?
I'm using GDAL/OGR 1.9 and Oracle 11g for windows.

A: try adding -nlt NONE, in case it's a table without geometries

A: I suppose the -sql parameter should be positioned before the destination file:
ogr2ogr -f "CSV" -sql "select * from HR.EMPLOYEES" test.csv OCI:"user/password"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Highcharts graph width exceed div I am trying to make a graph fill the whole width of the parent div. When the page is loaded the width of the graph exceeds the width of the div.
I know there are similar topics targetting this problem, but I haven't find a working solution yet.
I have tried setting the width: 100% !important; on .highcharts-container but it just chops of the graph. I am using this bootstrap template: https://wrapbootstrap.com/theme/sing-web-angular-dashboard-WB0J6BJ85
I think the problem has something to do with the sidebar. When the sidebar is full width, the chart exceeds the div, but when it is collapsed the chart fills up the div perfectly. When I open the console in chrome the chart resizes perfect.
Here are some pictures and the code of the chart and html.
http://imgur.com/a/iLDM0
graph:


text:
Q: How would I create this background effect? What would you call the effect applied to the backgrounds in the Giygas fight of Earthbound, and the battle backgrounds in Mother 3? This is what I'm talking about.
http://www.youtube.com/watch?v=tcaErqaoWek
http://www.youtube.com/watch?v=ubVnmeTRqhg
Now anyone know how I could go about this without using animated images, or using openGL?

A: These are also called demo effects. They are used on demoscene events, beside games.
Check out this effect collection.

A: it's just a textured quad, with sin and cos applied to the texture coordinates


text:
Q: How can I find the value of this limit $$\lim _{ { x }\to { 0 } }{ \frac { \sin x-\arctan x }{  {x }^{ 2 }\log(1+x) } }$$
this log is natural logarithm

A: Using Series Expansion
$$\frac{\sin x-\arctan x}{x^2\log(1+x)}$$
$$=\frac{x-\frac {x^3}{3!}+O(x^5)-\{x-\frac {x^3}3++O(x^5)\}}{x^3}\cdot\frac1{\frac{\ln(1+x)}x}$$
$$=\frac{x^3(\frac13-\frac16)+O(x^5)}{x^3}\cdot\frac1{\frac{\ln(1+x)}x}$$
$$=\{\frac16+O(x^2)\}\cdot\frac1{\frac{\ln(1+x)}x}\text{ if }x\ne0$$
If $x\to0,x\ne0$


text:
Q: Failed to fetch in Excel Office Web Script I'm getting a Line 15: Failed to fetch error without further details.
This is my script in Excel Web.
async function main(workbook: ExcelScript.Workbook) {
    let sheet = workbook.getActiveWorksheet();
    const company:string  = String(sheet.getRange("C4").getValue());
  const id: string = String(sheet.getRange("C5").getValue());

  sheet.getRange('D4').setValue(await getairequest(company, id));
  sheet.getRange('D5').setValue(Date());

}

async function getairequest(company: string, id: string): Promise <string>{
  const link = encodeURI('{CUSTOM LINK}/' + company + '/' + id);

  console.log(link);
  const response = await fetch(link);

  const { data }: { data: JSONData } = await response.json();

  //const json: JSONData = await response.json();
  console.log(JSON.stringify(data));

  return data.text;

}

interface JSONData {
  text: string;
  index: number;
  logprobs: string;
  finish_reason: string;
}

The response of the link is the following:
{"text":"individual text result","index":0,"logprobs":null,"finish_reason":"stop"},

Script will be executed directly in Excel Online (Not via Power Automate), I'm able to modify the response of the Custom Link, due to the fact that this is an internal tool.
Fetch the JSON and put the answer into a cell in Excel.


text:
Q: Setting up virtual box to connect to database server on host machine I have installed Ubuntu inside virtual box installed in a Windows 7 host machine.
I'm currently developing a web application both in windows 7 and ubuntu (in the virtual box), the problem is, I always have outdated database content in ubuntu.
Code for both OS is easily updated, I could just pull fresh code from the repository for both the windows app and the one in ubuntu, but restoring database everytime data is inserted takes some time (DB size approx 9GB).
Is there a way to have the web application in Ubuntu virtual machine run by it's own application server (Apache) to point to the database server (Postgres) in Windows host running at port 5432.
The purpose is that whether I develop something in ubuntu or in windows, I can always have updated database content for both.


text:
Q: Calculate amplitude of a signal after application FFT I'm using Arduino Due and sensor for noise and I applied FFT library to extract frequency and it's working  perfectly. But I don't know how to calculate the amplitudes and print them on console?
Here is the code:
#include "arduinoFFT.h"

#define SAMPLES 32
#define SAMPLING_FREQUENCY 1000

arduinoFFT FFT = arduinoFFT();

unsigned int sampling_period_us;
unsigned long microseconds;

double vReal[SAMPLES];
double vImag[SAMPLES];

void setup() {
    Serial.begin(9600);

    sampling_period_us = round(1000000*(1.0/SAMPLING_FREQUENCY));
}

void loop() {

    /*SAMPLING*/
    for(int i=0; i<SAMPLES; i++)
    {
        microseconds = micros();

        vReal[i] = analogRead(0);
        vImag[i] = 0;

        while(micros() < (microseconds + sampling_period_us)){
        }
    }

    /*FFT*/
    FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
    FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD);
    FFT.ComplexToMagnitude(vReal, vImag, SAMPLES);
    double peak = FFT.MajorPeak(vReal, SAMPLES, SAMPLING_FREQUENCY);

    Serial.println(peak);

    for(int i=0; i<(SAMPLES/2); i++)
    {

        Serial.print((i * 1.0 * SAMPLING_FREQUENCY) / SAMPLES, 1);
        Serial.print(" ");
        //Serial.println(vReal[i], 1);    //View only this line in serial plotter to visualize the bins
    }

    delay(1000);
    while(1);
}

A: The serial plotter does not have a number of sample to plot functionality.
If you want to view the amplitudes for each window correctly, you will need to use the following code
for(int i=0; i<(SAMPLES/2); i++)
{
//  Serial.print((i * 1.0 * SAMPLING_FREQUENCY) / SAMPLES, 1);
    for(int i=0; i<20; i++)//Adjust the 20 to make space between each samples.
        Serial.print(0);
    Serial.print(vReal[i]);
}

And then adjust the size of the serial plotter to fit your window.
I hope this helps.


text:
Q: How can I popViewController to rootViewController? Let me specific. I have three XIBs. From the first XIB i used pushViewController and got into the second. From the button click in second XIB i got into the third. The thing is, On the click of Cancel button in third ViewController I have to go the first XIB. How is this possible? I am stuck there. Help me please. I used the navigationController to push the viewControllers. I have already used the popToRootViewController: but it popped only to the second XIB.

A: use this
[self.navigationController popToRootViewController:YES];


text: Q: Why do we use friend function in overloading operator <>>? I have a question about overloading operator <>. I read some C++ books and I do not understand that why do we use friend function for overloading operator <> instead of defining it as a member function of the class.


text:
Q: Normal Spaces in topology? If $\prod X_{\alpha}$ is normal then is $X_{\alpha}$ normal too? I would guess it's not? But I have no idea of how to prove it. Is there any proof to prove the claim or a counterexample otherwise?

A: If $X=\prod_{\alpha\in A}X_\alpha$ is normal, then each factor $X_\alpha$ must be normal as well. Fix $\alpha\in A$, and let $H$ and $K$ be disjoint closed subsets of $X_\alpha$. Then $\pi_\alpha^{-1}[H]$ and $\pi_\alpha^{-1}[K]$ are disjoint closed subsets of $X$, where $\pi_\alpha:X\to X_\alpha$ is the usual projection map. $X$ is normal, so there are disjoint open sets $U$ and $V$ in $X$ such that $\pi_\alpha^{-1}[H]\subseteq H$ and $\pi_\alpha^{-1}[K]\subseteq V$. Let $x=\langle x_\beta:\beta\in A\rangle$ be any point of $X$, and let $$Y=\big\{\langle y_\beta:\beta\in A\rangle\in X:y_\beta=x_\beta\text{ for all }\beta\in A\setminus\{\alpha\}\big\}\;.$$
Let $h=\pi_\alpha\upharpoonright Y$, the restriction of the $\alpha$-th projection map to $Y$; then $h$ is a homeomorphism, and $h[U\cap Y]$ and $h[V\cap Y]$ are disjoint open subsets of $X_\alpha$ such that $H\subseteq h[U\cap Y]$ and $K\subseteq h[V\cap Y]$.


text:
Q: Python vectorization, how to get all index for every row with numpy I'm having a hard time trying to solve this problem, the main issue is I'm running a simulation, so for lops are mainly forbidden, I have a numpy array NxN, in this case mine is about (10000x20).
stoploss = 19.9 # condition to apply
monte_carlo_simulation(20,1.08,10000,20) #which gives me that 10000x20 np array
mask_trues = np.where(np.any((simulation <= stoploss) == True, axis=1)) # boolean mask

I need some code to make a new vector of len(10000) which returns an array with all the positions for every row, lets suppose:
function([[False,True,True],[False,False,True]])
output = [[1,2],[2]]

Again, the main problem resides in not using loops.

A: Simply this:
list(map(np.where, my_array))

performance comparison against Kasrâmvd's solution:
def f(a):
    return list(map(np.where, a))

def g(a):
    x, y = np.where(a)
    return np.split(y, np.where(np.diff(x) != 0)[0] + 1)

a = np.random.randint(2, size=(10000,20))

%timeit f(a)
%timeit g(a)

7.66 ms ± 38.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
13.3 ms ± 188 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

A: For completeness I'll demonstrate a sparse matrix approach:
In [57]: A = np.array([[False,True,True],[False,False,True]])
In [58]: A
Out[58]:
array([[False,  True,  True],
       [False, False,  True]])
In [59]: M = sparse.lil_matrix(A)
In [60]: M
Out[60]:
<2x3 sparse matrix of type '<class 'numpy.bool_'>'
    with 3 stored elements in LInked List format>
In [61]: M.data
Out[61]: array([list([True, True]), list([True])], dtype=object)
In [62]: M.rows
Out[62]: array([list([1, 2]), list([2])], dtype=object)

And to make a large sparse one:
In [63]: BM = sparse.random(10000,20,.05, 'lil')
In [64]: BM
Out[64]:
<10000x20 sparse matrix of type '<class 'numpy.float64'>'
    with 10000 stored elements in LInked List format>
In [65]: BM.rows
Out[65]:
array([list([3]), list([]), list([6, 15]), ..., list([]), list([11]),
       list([])], dtype=object)

Rough time tests:
In [66]: arr = BM.A
In [67]: timeit sparse.lil_matrix(arr)
19.5 ms ± 421 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [68]: timeit list(map(np.where,arr))
11 ms ± 55.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [69]: %%timeit
    ...: x,y = np.where(arr)
    ...: np.split(y, np.where(np.diff(x) != 0)[0] + 1)
    ...:
13.8 ms ± 24.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Generating a csr sparse format matrix is faster:
In [70]: timeit sparse.csr_matrix(arr)
2.68 ms ± 120 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [71]: Mr = sparse.csr_matrix(arr)
In [72]: Mr.indices
Out[72]: array([ 3,  6, 15, ...,  8, 16, 11], dtype=int32)
In [73]: Mr.indptr
Out[73]: array([    0,     1,     1, ...,  9999, 10000, 10000], dtype=int32)
In [74]: np.where(arr)[1]
Out[74]: array([ 3,  6, 15, ...,  8, 16, 11])

It's indices is just like the column where, while the indptr is like the split indices.

A: Here is one way using np.split() and np.diff():
x, y = np.where(boolean_array)
np.split(y, np.where(np.diff(x) != 0)[0] + 1)

Demo:
In [12]: a = np.array([[False,True,True],[False,False,True]])

In [13]: x, y = np.where(a)

In [14]: np.split(y, np.where(np.diff(x) != 0)[0] + 1)
Out[14]: [array([1, 2]), array([2])]


text:
Q: Douglas-Peucker point count tolerance I am trying to implement Douglas-Peucker Algorithm with point count tolerance. I mean that i specifies that i want 50% compression. I found this algorithm on this page http://psimpl.sourceforge.net/douglas-peucker.html under Douglas-Peucker N. But i am not sure how this algorithm is working. Is there any implementation of this in java or some good specification about this version of algorithm?
What i dont understand from psimpl explanation is what will happend after we choose fist point into simplification? We will broke the edge into two new edges and rank all points and choose best point from both edges?

A: DP searches the polyline for the farthest vertex from the baseline. If this vertex is farther than the tolerance, the polyline is split there and the procedure applied recursively.
Unfortunately, there is no relation between this distance and the number of points to keep. Usually the "compression" is better than 50%, so you may try to continue the recursion deeper. But achieving a good balance of point density looks challenging.

A: Combine the Douglas-peucker algorithm with iteration, and consider the remained points as a judge criteria.
Here is my algorithm, array 'points' stores the points of the trajectory.Integer 'd' is the threshold.
public static Point[] divi(Point[] points,double d)
    {
    System.out.println("threshold"+d);
    System.out.println("the nth divi iteration");
    int i = 0;
    Point[] p1 = new Point[points.length];
    for (i = 0;i<points.length;i++)
        p1[i] = points[i];
    compress(p1, 0,p1.length - 1,d); //first compression
    int size = 0;
    for (Point p : p1)    //trajectory after compression
        if(p != null)
        size ++;
    System.out.println("size of points"+size);
    if(size<=200 && size>=100)
        return p1;
    else if(size>200)
        return divi(p1,d + d/2.0);
    else
        return divi(points,d/2.0);
   }
public static void compress(Point[] points,int m, int n,double D)
   {
        System.out.println("threshold"+D);
        System.out.println("startIndex"+m);
        System.out.println("endIndex"+n);

        while (points[m] == null)
            m ++;

        Point from = points[m];
        while(points[n] == null)
            n--;

        Point to = points[n];

        double A = (from.x() - to.x()) /(from.y() - to.y());
        /** -
         * 由起始点和终止点构成的直线方程一般式的系数
         */
        double B = -1;

        double C = from.x() - A *from.y();
        double d = 0;
        double dmax = 0;
        if (n == m + 1)
            return;
       List<Double> distance = new ArrayList<Double>();
       for (int i = m + 1; i < n; i++) {
        if (points[i] ==null)
        {
            distance.add(0.0);
            continue;
        }
        else
        {
         Point p = points[i];
       d = Math.abs(A * (p.y()) + B * (p.x()) + C)  / Math.sqrt(Math.pow(A, 2) + Math.pow(B, 2));
       distance.add(d);
        }
        }
        dmax= Collections.max(distance);

        if (dmax < D)
            for(int i = n-1;i > m;i--)
                 points[i] = null;
        else
           {
            int  middle = distance.indexOf(dmax) + m + 1;

            compress(points,m, middle,D);

            compress(points,middle, n,D);

           }
    }


text:
Q: How can I select records in MySQL when a foreign key doesn't return anything? SELECT videos.id, videos.game_id, videos.xbox360, videos.ps3, videos.pc,
  videos.wii, videos.other, videos.thumbnail, videos.vid_info, videos.sdvid,
  videos.hdvid, UNIX_TIMESTAMP( videos.date_added ) , game_data.name,
  AVG( video_ratings.rating )
FROM videos, game_data, video_ratings
WHERE videos.game_id = game_data.id
  AND videos.id = video_ratings.video_id
GROUP BY videos.id, video_ratings.video_id
ORDER BY videos.date_added DESC LIMIT 10;

I am running this query to extract data from three tables video_ratings, game_data, videos...
Now the problem I'm facing is the result only shows the videos that have been rated (or are in table video_ratings) because of AND videos.id = video_ratings.video_id...
Is there any way that I can select the data for all videos and the result shows AVG(video_ratings.rating) as null if ratings for those videos is not present in the video_ratings table (or say none of the videos have been rated so the result must show 10 rows with AVG(video_ratings.rating) column as null ) ...
Thanks

A: Yeah, just use a left outer inner instead of an inner join (which is what you're doing). I'd also suggest you use the JOIN syntax instead. It's far clearer:
SELECT v.id, v.game_id, v.xbox360, v.ps3, v.pc, v.wii,
v.other, v.thumbnail, v.vid_info, v.sdvid, v.hdvid,
UNIX_TIMESTAMP(v.date_added), gd.name, AVG(vg.rating)
FROM videos v
LEFT JOIN game_data gd ON gd.id = v.game_id
LEFT JOIN video_ratings vr ON v.id = vr.video_id
GROUP BY videos.id, video_ratings.video_id
ORDER BY videos.date_added DESC LIMIT 10


text:
Q: Fish selection question - combination and permutation, elementary set Case: Suppose there are two 100-fish tanks, and one fish is to be chosen from each tank.
Question 1: Assuming that the order in which the fish are chosen is irrelevant (That is, all that matters is which two fish are chosen, not which is chosen first), there are $C_{200}^2=19,900$ ways to make the selection.
Question 2: If the order is important, there are  $P_{200}^2=39,800$ ways to make the selection.
Please let me know if my answers are correct.
Thank you so much!

A: Your first answer is wrong, because you have specified that each fish comes from a different tank.  So, there are $(100)^2$ possibilities.  Your answer would be correct if you were allowed to choose both fish from the same tank.
Regardless of whether the fish are or are not allowed to come from the same tank, whatever the appropriate answer is, the appropriate answer to part $2$ will be $2$ times the previous answer.  That is because there are two ways of ordering the fish.


text:
Q: Subclassing an Edit control with SHAutoComplete applied I'm new, so sorry if the question isn't posed exactly as you're get used to.
I inevitably need to subclass an Edit control for which SHAutoComplete() has been called like this:
// initialization
if FAILED( CoInitialize(NULL) ) exit(1);
// creation of an Edit control
HWND hEdit=CreateWindow( WC_EDIT, ... );
// calling SHAutoComplete - I essentially understand this as a subclassing behind the scenes
SHAutoComplete( hEdit , SHACF_AUTOSUGGEST_FORCE_ON|SHACF_FILESYSTEM );
// subclassing an Edit box for which SHAutoComplete has been called
WNDPROC autoCompleteWndProc=SubclassWindow( hEdit , __myNewWndProc__ ); // using macro

Suppose the __myNewWndProc__ function looks like a classic window procedure:
LRESULT CALLBACK __myNewWndProc__(HWND hEdit, UINT msg, WPARAM wParam, LPARAM lParam){
    // handle subclass-specific messages
    switch (msg){ ... }
    // handle SHAutoComplete-specific messages
    return autoCompleteWndProc(hEdit,msg,wParam,lParam); // <-- here's the problem (read further)
}

The problem is, it doesn't work.  The application crashes with error:

Process returned -1073741819 (0xC0000005)" (access violation)

pointing the problem at line marked in the above listing.
The question is what am I doing wrong?
(I've experienced the same problem when subclassing from ComboBoxEx, but I managed to work around it, but can't find any trick with the SHAutoComplete() problem.)

A: SubclassWindow() is a wrapper for SetWindowLongPtr():
#define     SubclassWindow(hwnd, lpfn)       \
              ((WNDPROC)SetWindowLongPtr((hwnd), GWLP_WNDPROC, (LPARAM)(WNDPROC)(lpfn)))

When you use that type of subclassing, you MUST use CallWindowProc() to call the previous window procedure when needed, DO NOT call the procedure directly:
LRESULT CALLBACK __myNewWndProc__(HWND hEdit, UINT msg, WPARAM wParam, LPARAM lParam)
{
    //...
    // handle SHAutoComplete-specific messages
    return CallWindowProc(autoCompleteWndProc,hEdit,msg,wParam,lParam);
}

The reason for that is stated in the documentation:
SetWindowLongPtr function

Calling SetWindowLongPtr with the GWLP_WNDPROC index creates a subclass of the window class used to create the window. An application can subclass a system class, but should not subclass a window class created by another process. The SetWindowLongPtr function creates the window subclass by changing the window procedure associated with a particular window class, causing the system to call the new window procedure instead of the previous one. An application must pass any messages not processed by the new window procedure to the previous window procedure by calling CallWindowProc. This allows the application to create a chain of window procedures.

CallWindowProc function:

lpPrevWndFunc [in]
  Type: WNDPROC
The previous window procedure. If this value is obtained by calling the GetWindowLong function with the nIndex parameter set to GWL_WNDPROC or DWL_DLGPROC, it is actually either the address of a window or dialog box procedure, or a special internal value meaningful only to CallWindowProc.

You are probably running into the latter case, which will crash trying to call something that is not directly callable.
With that said, you should not be using SetWindowLongPtr() to subclass.  Use SetWindowSubClass() instead.  Read the following articles for more details:
Subclassing Controls
Safer subclassing


text:
Q: Need help on how to convert this select to a DELETE statement: I need help as to how to convert this select to a delete statement.
SELECT stud_term_sum_div.id_num,
     stud_term_sum_div.hrs_enrolled,
     stud_term_sum_div.transaction_sts,
     student_crs_hist.crs_cde,
     student_crs_hist.transaction_sts
  FROM stud_term_sum_div,
     student_crs_hist
 WHERE ( stud_term_sum_div.yr_cde = student_crs_hist.yr_cde ) and
     ( stud_term_sum_div.trm_cde = student_crs_hist.trm_cde ) and
     ( stud_term_sum_div.id_num = student_crs_hist.id_num ) and
     ( ( stud_term_sum_div.yr_cde = '2013' ) AND
     ( stud_term_sum_div.trm_cde = 'FA' ) AND
     ( stud_term_sum_div.hrs_enrolled >= 3.00 ) AND
     ( student_crs_hist.transaction_sts = 'D' ) )

A: The most straight-forward conversion is below:
DELETE * FROM stud_term_sum_div
WHERE ( stud_term_sum_div.yr_cde = student_crs_hist.yr_cde ) and
 ( stud_term_sum_div.trm_cde = student_crs_hist.trm_cde ) and
 ( stud_term_sum_div.id_num = student_crs_hist.id_num ) and
 ( ( stud_term_sum_div.yr_cde = '2013' ) AND
 ( stud_term_sum_div.trm_cde = 'FA' ) AND
 ( stud_term_sum_div.hrs_enrolled >= 3.00 ) AND
 ( student_crs_hist.transaction_sts = 'D' ) )

BUT, before you go executing that, please check that the WHERE clause really contains the conditions to be used for deletion. Note that this SQL statement will delete the entire row (a/k/a record) when the attributes in the WHERE clause satisfy the stated conditions.
If you only want to remove the data from the attributes (as opposed to the entire record), you'd need to use an SQL UPDATE statement instead. The (simplified) syntax for that is as follows:
UPDATE <table_name>
SET <attribute1> = <value1>
[, SET <attribute_n> = <value_n>...]
WHERE <conditions on which the record should be updated>

Doing a search on Bing, google, <insert your favorite search engine here> for "SQL DELETE" or "SQL UPDATE" should get you all the information you need (e.g. MSDN, for one).


text:
Q: The use of pivot data to calculate a column I have a PIVOT
SELECT         txtSchoolID, intSubjectID, txtPreName, txtSurname, txtForm, [636] AS Effort, [637] AS Focus, [638] AS Participation, [639] AS Groupwork, [640] AS Rigour, [641] AS Curiosity, [642] AS Initiative,
                [643] AS SelfOrganisation, [644] as Perserverance

FROM         (SELECT  txtSchoolID, intSubjectID, intGradeTransposeValue, intGradeID, txtForm, txtPreName, txtSurname FROM VwReportsManagementAcademicReports
                WHERE (intReportCycleID = 142) AND (intReportProgress = 1)) p
PIVOT
(AVG        (intGradeTransposeValue)
FOR intGradeID IN ([636], [637], [638], [639], [640], [641], [642], [643], [644] )
) AS pvt

I need to now use values from my pivot to produce additional columns. I want to create a column called FocusLH and populate it with a value based on a calculation. The calculation is - if the result of Effort+Focus=2 then assign the value 5 in FocusLH, if the result is 3 assigns the value 4 etc etc
Is this possible?

A: I was putting the CASE statement in the wrong place and needed to use the intGradeID's instead of the alias. This works now
SELECT         txtSchoolID, intSubjectID, txtPreName, txtSurname, txtForm, [636] AS Effort, [637] AS Focus, [638] AS Participation, [639] AS Groupwork, [640] AS Rigour, [641] AS Curiosity, [642] AS Initiative,
                [643] AS SelfOrganisation, [644] as Perserverance,
        CASE WHEN [636] + [637] = 2 THEN 5
        WHEN [636] + [637] =3 THEN 4
        WHEN [636] + [637] =4 THEN 3
        WHEN [636] + [637] =5 THEN 2
        ELSE NULL END AS FocusLH
FROM         (SELECT  txtSchoolID, intSubjectID, intGradeTransposeValue, intGradeID, txtForm, txtPreName, txtSurname
                FROM VwReportsManagementAcademicReports
                WHERE (intReportCycleID = 142) AND (intReportProgress = 1)) p
PIVOT
(MAX        (intGradeTransposeValue)
FOR intGradeID IN ([636], [637], [638], [639], [640], [641], [642], [643], [644] )
) AS pvt


text:
Q: Magento: How to override vendor/magento/module-quote/Model/Quote.php? How to override vendor/magento/module-quote/Model/Quote.php in Magento2.
Any help would be appreciated.

A: You can use preference to override the whole class
you below type of code in your module's etc/di.xml
if only want to use for front-end then etc/frontend/di.xml or if only for admin then etc/adminhtml/di.xml
<preference for="Magento\Quote\Model\Quote" type="Vendor\Custommodule\Rewrite\Magento\Quote\Model\Quote"/>

or if you only want to modify the reference class public method then best to use plugin and add below code in your module's etc/di.xml
<type name="Magento\Quote\Model\Quote">
    <plugin disabled="false" name="Vendor_Custommodule_Plugin_Magento_Quote_Model_Quote" sortOrder="10" type="Vendor\Custommodule\Plugin\Magento\Quote\Model\Quote"/>
</type>

and in your plugin class use below type of code and use after method to modify the result of reference class method(or before plugin if you only want to modify the input arguments of reference method)
<?php

namespace Vendor\Custommodule\Plugin\Magento\Quote\Model;

class Quote
{

    public function afterIsVirtual(
        \Magento\Quote\Model\Quote $subject,
        $result
    ) {
        //Your plugin code
        return $result;
    }
}


text:
Q: What's this PHP snippet doing? $from = 'no-reply@'.htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8');

Especially what's ENT_COMPAT for?
Anyone knows?

A: htmlspecialchars encodes all characters than can be encoded as entities. This is especially important for angle brackets and ampersands. ENT_COMPAT will leave single quotes in place and only convert double quotes. 'UTF-8' will treat the input as UTF-8 encoded (instead of the default iso-latin1 encoding).
In this case, the htmlspecialchars makes only sense if the mail address will be put into a "mailto:" href attribute. Normal server names don't have characters that must be encoded, so I'm not sure if htmlspecialchars is needed.

A: forming a email address, quite stupid way
For the answer to the question Especially what's ENT_COMPAT for? you can browse PHP documentation for the htmlspecialchars, because it's this function's parameter

A: Creating a valid looking email semi-auotmatic. The email username is 'no-reply' and the domain is whatever the servers hostname is. With a 'no-reply' the recipient usually does not reply to these emails.
ENT_COMPAT is explained here:
http://php.net/manual/en/function.htmlspecialchars.php


text:
Q: How to add event listeners on endpoint Earlier we could add event listener to endpoints using -
this.instance = newInstance({
      container: this.wrapper.nativeElement,
});

_addEndpoints(
    id: string,
    sourceAnchors: Array<AnchorSpec>,
    targetAnchors: Array<AnchorSpec>
  ) {
    const endpointDOMEl = document.getElementById(`endpoint_${id}`);
    for (let i = 0; i < sourceAnchors.length; i++) {
      const sourceUUID = id + sourceAnchors[i];
      const endpoint = this.instance.addEndpoint(
        endpointDOMEl,
        this.sourceEndpoint,
        {
          anchor: sourceAnchors[i],
          uuid: sourceUUID,
        }
      );

      this.addListenersForEndpoint(endpoint, endpointDOMEl, null);
    }
}
addListenersForEndpoint() {
 endpoint.canvas.removeEventListener('mouseover', addHoverListener);
 endpoint.canvas.removeEventListener('mouseout', removeHoverListener);
 endpoint.canvas.addEventListener('mouseover', addHoverListener.bind(null, endpoint, domCircleEl, labelId));
 endpoint.canvas.addEventListener('mouseout', removeHoverListener.bind(null, endpoint, domCircleEl, labelId));
}

But, in 5.x i can't see the canvas property anymore. What alternative can i use to achieve the same?

A: You should bind to the endpoint mouseover and mouseout events:
https://docs.jsplumbtoolkit.com/community/lib/events
instance.bind(EVENT_ENDPOINT_MOUSEOVER, (e:Endpoint) => {

..

})


text:
Q: Adding Error Messages to If Then Statements I have an issue with VBA code that I would like to get help with.
I have a code with 3 If-Then Statements. IF TextBox5 = 0; TextBox5 = 1; and TextBox5 > 1
I need to insert an error msg but I don't know what would be the correct location for each of the If-Then Statements.
Error msg: "The Leg Doesn't Exist. Please Check The Traveller And Try Again."
Private Sub TextBox5_AfterUpdate()

On Error Resume Next
If TextBox5.Value = 0 And Not IsEmpty(TextBox5.Value) Then

   Set MyRange = ActiveWorkbook.Worksheets("Raw Data").Range("Table_Query_from_Visual654[base_id]")

   For Each c In MyRange
       If c.Value Like UCase(TextBox4.Value) Then
          If Sheet1.Cells(c.Row, 4) = TextBox5.Value Then
            TextBox13.Value = Sheet1.Cells(c.Row, 5)
            TextBox14.Value = Sheet1.Cells(c.Row, 6)
          End If
        End If
   Next
End If

If TextBox5.Value = 1 And Not IsEmpty(TextBox5.Value) Then

   Set MyRange = ActiveWorkbook.Worksheets("Raw Data").Range("Table_Query_from_Visual654[base_id]")

   For Each c In MyRange
      If c.Value Like UCase(TextBox4.Value) Then
         If Sheet1.Cells(c.Row, 4) = 0 Then         ' Set it to 0 if 1 is enetered into TextBox5
            TextBox13.Value = Sheet1.Cells(c.Row, 5)
            TextBox14.Value = Sheet1.Cells(c.Row, 6)
         End If
      End If
   Next
End If

If TextBox5.Value > 1 And Not IsEmpty(TextBox5.Value) Then

   Set MyRange = ActiveWorkbook.Worksheets("Raw Data").Range("Table_Query_from_Visual654[base_id]")

   For Each c In MyRange
      If c.Value Like UCase(TextBox4.Value) Then
         If Sheet1.Cells(c.Row, 4) = TextBox5.Value Then
            TextBox13.Value = Sheet1.Cells(c.Row, 9)
          Else
          TextBox14.Value = ""
          End If
      End If

   Next

End If
Worksheets("Cost Analysis").Range("B1").Value = UCase(TextBox5.Value)

Call TextBox6_AfterUpdate
Call TextBox9_data

End Sub


text:
Q: How do I configure Postfix to not accept messages for invalid recipients? As with all mail servers, mine frequently receives spam for invalid recipient addresses.
What configuration values will force Postfix to immediately reject these messages? Furthermore, if Postfix is rejecting them and tries to bounce them back to the origin, how do I force Postfix not to bother deferring the bounce message if it isn't immediately accepted by the origin?

A: Set the following options in the /etc/postfix/main.cf
bounce_queue_lifetime = 0
local_recipient_maps = unix:passwd.byname $alias_maps

If you are using virtual domain/users you should use virtual_mailbox_maps instead


text:
Q: Convert 'embedded' XML doc into CDATA output in XSLT (1.0) Given an input XML document like this:
<?xml version="1.0" encoding="utf-8"?>
<title> This contains an 'embedded' HTML document </title>
<document>

<title>HTML DOC</title>

Hello World

</document>
</root>

How I can extract that 'inner' HTML document; render it as CDATA and include in my output document ?
So the output document will be an HTML document; which contains a text-box showing the elements as text (so it will be displaying the 'source-view' of the inner document).
I have tried this:
<xsl:template match="document">
<xsl:value-of select="*"/>
</xsl:template>

But this only renders the Text Nodes.
I have tried this:
<xsl:template match="document">
<![CDATA[
<xsl:value-of select="*"/>
]]>
</xsl:template>

But this escapes the actual XSLT and I get:
<xsl:value-of select="*"/>

I have tried this:
<xsl:output method="xml" indent="yes" cdata-section-elements="document"/>
[...]
<xsl:template match="document">
<document>
<xsl:value-of select="*"/>
</document>
</xsl:template>

This does insert a CDATA section, but the output still contains just text (stripped elements):
<?xml version="1.0" encoding="UTF-8"?>

      <title>My doc</title>

Title: This contains an 'embedded' HTML document

      <document><![CDATA[
                                                HTML DOC

                                                                Hello World

                                ]]></document>

A: There are two confusions you need to clear up here.
First, you probably want xsl:copy-of rather than xsl:value-of.  The latter returns the string value of an element, the former returns a copy of the element.
Second, the cdata-section-elements attribute on xsl:output affects the serialization of text nodes, but not of elements and attributes. One way to get what you want would be to serialize the HTML yourself, along the lines of the following (not tested):
<xsl:template match="document/descendant::*">
  <xsl:value-of select="concat('<', name())"/>

  <xsl:text>></xsl:text>
  <xsl:apply-templates/>
  <xsl:value-of select="concat('</', name(), '>')"/>
</xsl:template>

But the quicker way would be something like the following solution (squeamish readers, stop reading now), pointed out to me by my friend Tommie Usdin.  Drop the cdata-section-elements attribute from xsl:output and replace your template for the document element with:
<xsl:template match="document">
  <document>
    <xsl:text disable-output-escaping="yes"><![CDATA[</xsl:text>
    <xsl:copy-of select="./html"/>
    <xsl:text disable-output-escaping="yes">]]></xsl:text>
  </document>
</xsl:template>


text:
Q: Kubernetes dashboard doesn't show the consumed CPU and memory by pods I successfully connected to the Kubernetes dashboard and I can see all of my deployment, statefulsets, pods, and etc. But the Graphs which determined the amount of CPU and memory using by pods, do not exist.
All the pods :
kube-system   coredns-576cbf47c7-cj8qv                1/1     Running   33         67d
kube-system   coredns-576cbf47c7-qh9hm                1/1     Running   34         67d
kube-system   etcd-master                             1/1     Running   15         67d
kube-system   heapster-684777c4cb-qt6f5               1/1     Running   0          134m
kube-system   kube-apiserver-master                   1/1     Running   23         67d
kube-system   kube-controller-manager-master          1/1     Running   15         67d
kube-system   kube-proxy-bs5k9                        1/1     Running   13         67d
kube-system   kube-proxy-fjp8b                        1/1     Running   13         67d
kube-system   kube-scheduler-master                   1/1     Running   15         67d
kube-system   kubernetes-dashboard-77fd78f978-cnhsc   1/1     Running   0          71m
kube-system   metrics-server-5cbbc84f8c-vz77c         1/1     Running   0          71m
kube-system   monitoring-influxdb-5c5bf4949d-jqr9d    1/1     Running   0          133m
kube-system   weave-net-fl972                         2/2     Running   77         67d
kube-system   weave-net-gh96b                         2/2     Running   34         67d

There are log from dashboard pod :
2018/12/16 08:43:54 Starting overwatch
2018/12/16 08:43:54 Using in-cluster config to connect to apiserver
2018/12/16 08:43:54 Using service account token for csrf signing
2018/12/16 08:43:54 No request provided. Skipping authorization
2018/12/16 08:43:54 Successful initial request to the apiserver, version: v1.12.1
2018/12/16 08:43:54 Generating JWE encryption key
2018/12/16 08:43:54 New synchronizer has been registered: kubernetes-dashboard-key-holder-kube-system. Starting
2018/12/16 08:43:54 Starting secret synchronizer for kubernetes-dashboard-key-holder in namespace kube-system
2018/12/16 08:43:55 Initializing JWE encryption key from synchronized object
2018/12/16 08:43:55 Creating in-cluster Heapster client
2018/12/16 08:43:55 Successful request to heapster
2018/12/16 08:43:55 Auto-generating certificates
2018/12/16 08:43:55 Successfully created certificates
2018/12/16 08:43:55 Serving securely on HTTPS port: 8443
2018/12/16 08:44:19 Getting application global configuration
2018/12/16 08:44:19 Application configuration {"serverTime":1544949859551}
2018/12/16 08:44:20 [2018-12-16T08:44:20Z] Incoming HTTP/2.0 GET /api/v1/settings/global request from 10.32.0.1:53200: {}
2018/12/16 08:44:20 [2018-12-16T08:44:20Z] Outcoming response to 10.32.0.1:53200 with 200 status code
2018/12/16 08:44:20 [2018-12-16T08:44:20Z] Incoming HTTP/2.0 GET /api/v1/login/status request from 10.32.0.1:53200: {}
2018/12/16 08:44:20 [2018-12-16T08:44:20Z] Outcoming response to 10.32.0.1:53200 with 200 status code
2018/12/16 08:44:20 [2018-12-16T08:44:20Z] Incoming HTTP/2.0 GET /api/v1/systembanner request from 10.32.0.1:53200: {}
2018/12/16 08:44:20 [2018-12-16T08:44:20Z] Outcoming response to 10.32.0.1:53200 with 200 status code
2018/12/16 08:44:20 [2018-12-16T08:44:20Z] Incoming HTTP/2.0 GET /api/v1/login/status request from 10.32.0.1:53200: {}
2018/12/16 08:44:20 [2018-12-16T08:44:20Z] Outcoming response to 10.32.0.1:53200 with 200 status code
2018/12/16 08:44:20 [2018-12-16T08:44:20Z] Incoming HTTP/2.0 GET /api/v1/rbac/status request from 10.32.0.1:53200: {}
2018/12/16 08:44:20 [2018-12-16T08:44:20Z] Outcoming response to 10.32.0.1:53200 with 200 status code
2018/12/16 08:44:20 [2018-12-16T08:44:20Z] Incoming HTTP/2.0 GET /api/v1/csrftoken/token request from 10.32.0.1:53200: {}
2018/12/16 08:44:20 [2018-12-16T08:44:20Z] Outcoming response to 10.32.0.1:53200 with 200 status code
2018/12/16 08:44:20 [2018-12-16T08:44:20Z] Incoming HTTP/2.0 POST /api/v1/token/refresh request from 10.32.0.1:53200: { contents hidden }
2018/12/16 08:44:20 [2018-12-16T08:44:20Z] Outcoming response to 10.32.0.1:53200 with 200 status code
2018/12/16 08:44:20 [2018-12-16T08:44:20Z] Incoming HTTP/2.0 GET /api/v1/overview/default?filterBy=&itemsPerPage=10&name=&page=1&sortBy=d,creationTimestamp request from 10.32.0.1:53200: {}
2018/12/16 08:44:20 Getting config category
2018/12/16 08:44:20 Getting discovery and load balancing category
2018/12/16 08:44:20 Getting lists of all workloads
2018/12/16 08:44:20 No metric client provided. Skipping metrics.
2018/12/16 08:44:20 No metric client provided. Skipping metrics.
2018/12/16 08:44:20 No metric client provided. Skipping metrics.
2018/12/16 08:44:20 No metric client provided. Skipping metrics.
2018/12/16 08:44:20 No metric client provided. Skipping metrics.
2018/12/16 08:44:20 No metric client provided. Skipping metrics.
2018/12/16 08:44:20 No metric client provided. Skipping metrics.
2018/12/16 08:44:20 Getting pod metrics
2018/12/16 08:44:20 [2018-12-16T08:44:20Z] Outcoming response to 10.32.0.1:53200 with 200 status code
2018/12/16 08:44:24 Getting application global configuration
2018/12/16 08:44:24 Application configuration {"serverTime":1544949864040}

Which says :
Creating in-cluster Heapster client
Successful request to heapster

So the heapster correctly connected to kubernetes dashboard.
I use kubeadm version=v1.12.1.
And also when I do kubectl top node in the master node to get the cpu and memory usage it shows the amount of cpu and memory that was used.
When I want to access the heapster via teminal like :
curl -L http://heapster-pod-ip:heapster-service-port/api/v1/model/metrics/

and it returns :
curl: (7) Failed to connect to 10.40.0.63 port 80: Connection refused

The metric-service pod's log :
I1216 12:05:24.783577       1 serving.go:273] Generated self-signed cert (apiserver.local.config/certificates/apiserver.crt, apiserver.local.config/certificates/apiserver.key)
[restful] 2018/12/16 12:05:25 log.go:33: [restful/swagger] listing is available at https://:443/swaggerapi
[restful] 2018/12/16 12:05:25 log.go:33: [restful/swagger] https://:443/swaggerui/ is mapped to folder /swagger-ui/
I1216 12:05:25.802972       1 serve.go:96] Serving securely on [::]:44

3
Any idea?

A: Heapster has been retired and you may need to modify your heapster installation by following the steps here.

A: Quote from README.MD of Kubernetes Dashboard:

Heapster has to be running in the cluster for the metrics and graphs
  to be available. Read more about it in Integrations guide.

In order to see graphs, you need to deploy
grafana.yaml heapster.yaml influxdb.yaml and heapster-rbac.yaml
Then run
kubectl delete -f https://raw.githubusercontent.com/kubernetes/dashboard/master/src/deploy/recommended/kubernetes-dashboard.yaml
kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/master/src/deploy/recommended/kubernetes-dashboard.yaml

You will able to see graphs for pods and deployments.
I hope it will be useful

A: This is an open issue that is not resolved yet as of this post.
https://github.com/kubernetes/dashboard/issues/4145

We are aware, we have a couple of issues with metrics that are not
  fixed yet. We will work on them.


text:
Q: Открытие activity в отдельном окне Как сделать что бы новая activity открывалась не по верх другой, а как бы в новом окне, т.е чтобы при нажатии на кнопку последних программ пользователь видел и новую активити и ее родителя? Например в приложении почта mail.ru когда нажимаешь на итем новое сообщение, ты можешь что то написать(но не отправлять), затем вернуться в основное приложение и что то сделать там, а потом снова продолжить писать текст сообщения, к тому же можно так делать много раз и в истории программ будет много этих активити с новыми сообщениями

A: UPD: Может кому то будет полезно. Только api>21(android 5.0)
intent.addFlags(FLAG_ACTIVITY_NEW_DOCUMENT); // что бы активити запустилась в новом окне
// если нужно что бы каждый раз активити была в новом окне, то еще и:
intent.addFlags(FLAG_ACTIVITY_MULTIPLE_TASK); // каждый запуск в новом окне

Можно так же прописать для Activity эти параметры в манифесте, подробнее developer.android.com/guide/components/activities/recents.html


text:
Q: NSUrlConnection doesnt seem to be working, I'm trying to use googletts converted and seem to be running into trouble.  I think I made the class correctly in terms of structure.  But I dont think the NSURLConnection is returning any useful data.  Can someone please help me check if its working and if not why?
In the connectiondidfinishloading section I am checking download length
NSLog(@"hmmmm %lu", (unsigned long)[downloadedData length])
which is returning 0.  Thats why I think its not working.
The goal is to have the app speak what is downloaded
Thanks!!!
I just have a button in my view controller that launches everything
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import "RJGoogleTTS.h"

@interface ViewController : UIViewController <CLLocationManagerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *userLabel;
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) CLGeocoder *geoCoder;

@property (strong, nonatomic) RJGoogleTTS *googleTTS;

- (IBAction)geoCodeLocation:(id)sender;

- (IBAction)rjGoogleButton:(id)sender;
@end

here is the implementation file
- (IBAction)rjGoogleButton:(id)sender {

    googleTTS = [[RJGoogleTTS alloc]init];

    [googleTTS convertTextToSpeech:@"How are you today user?"];

}

RJGoogleTTS.h
#import <Foundation/Foundation.h>

@protocol RJGoogleTTSDelegate <NSObject>

@required
- (void)receivedAudio:(NSMutableData *)data;
- (void)sentAudioRequest;

@end

@interface RJGoogleTTS : NSObject {
    id <RJGoogleTTSDelegate> delegate;
    NSMutableData *downloadedData;
}

@property (nonatomic, retain) id <RJGoogleTTSDelegate> delegate;
@property (nonatomic, retain) NSMutableData *downloadedData;

- (void)convertTextToSpeech:(NSString *)searchString;

@end

.m
#import "RJGoogleTTS.h"
#import <AVFoundation/AVFoundation.h>

@implementation RJGoogleTTS
@synthesize delegate, downloadedData;

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }

    return self;
}

- (void)convertTextToSpeech:(NSString *)searchString {
    NSString *search = [NSString stringWithFormat:@"http://translate.google.com/translate_tts?q=%@", searchString];
    search = [search stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    NSLog(@"Search: %@", search);
    self.downloadedData = [[NSMutableData alloc] initWithLength:0];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:search]];
    [request setValue:@"Mozilla/5.0" forHTTPHeaderField:@"User-Agent"];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    [delegate sentAudioRequest];

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"did you receive response user");
    [self.downloadedData setLength:0];

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSLog(@"did you receive data user");
    [self.downloadedData appendData:data];

//    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]initWithData:downloadedData error:nil];
//    [audioPlayer play];

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Failure");
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSLog(@"it worked user!!!");
    [delegate receivedAudio:self.downloadedData];
    NSLog(@"hmmmm %d", [self.downloadedData length]);

//    NSString *txt = [[NSString alloc] initWithData:downloadedData encoding: NSASCIIStringEncoding];
//    NSLog(@"%@hello",txt);

}

@end

A: Remember that this is happening asynchronously.  You set the size of downloadedData to 0 after your call the NSURLConnection.
Move:
self.downloadedData = [[NSMutableData alloc] initWithLength:0];
before your call to NSURLConnection.

A: There's nothing wrong with your NSURLConnection methods. Your search string is wrong. It should be:
NSString *search = [NSString stringWithFormat:@"http://translate.google.com/translate_tts?tl=en&q=%@",searchString];

A: You didn't start the URLConnection. Change [[NSURLConnection alloc] initWithRequest:request delegate:self]; like this [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];


text:
Q: jQuery to submit textarea with enter key I have this simple sctipt
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
    $(function(){
         $("#message").keypress(function(e){
            var code = (e.keyCode ? e.keyCode : e.which);
            if (code == 13){
                  $("#query").submit();
            }
          });
    });
</script>

and this html:
<div id="textarea">
    <form name="query" class="form1" id="query" action="query.py" method="post">
        <textarea rows="2" name="message" id="message" class="message" placeholder="RM911 Chat" cols="26"></textarea>
        <input type="submit" id="submit" name="submit1" value="a"/>
    </form>
</div>

if input's id is "submit" nothing works, if it's id is something else - it works... But the whole project uses "submit" id for submit buttons, and I don't want to rename it (because of CSS). Is there anything I can do?

A: Here you go, this submits the form (by triggering the submit button) when the enter key is pressed; and lets you create a new line when you hold Control and press Enter.
$(function(){
    function getCaret(el) {
        if (el.selectionStart) {
            return el.selectionStart;
        } else if (document.selection) {
            el.focus();

            var r = document.selection.createRange();
            if (r == null) {
                return 0;
            }

            var re = el.createTextRange(),
                rc = re.duplicate();
            re.moveToBookmark(r.getBookmark());
            rc.setEndPoint('EndToStart', re);

            return rc.text.length;
        }
        return 0;
    }
    $("#message").keyup(function(e){
        if ((e.keyCode == 13 || e.keyCode == 10) && e.ctrlKey) {
            var content = $(this).val();
            var caret = getCaret(this);
            $(this).val(content.substring(0,caret)+
                        "\n"+content.substring(caret,content.length));
            e.stopPropagation();
        } else if (e.keyCode == 13 || e.keyCode == 10){
            $("#submit").click();
        }
    });
});

Here's a Demo
Credit to TheSuperTramp for the getCaret and original keyup code for the Ctrl+Enter solution.

A: Try this, in your script,
$("#submit").trigger('click');

Full Code,
$(function () {
    $("#message").keypress(function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        //alert(code);
        if (code == 13) {
            $("#submit").trigger('click');
            return true;
        }
    });
});

Demo


text:
Q: Convert Blob to Image in Go I'm trying to create an mbtiles server in Go. The file follows the mbtiles spec.
The tile_data field is a BLOB and i'm trying to query the database and get the corresponding images (stored as blob types).
So far the queries are OK but i'm getting corrupted tile_data results.
I'm not sure how to map a SQLite BLOB to a proper Go data structure.
So far i tried using var tileData []byte without success following this github gombtiles sample. The return value gets me an array of only 4 bytes which i suspect is kinda true since when i see the BLOB as Text type in a SQLite GUI it gets me 4 characters too (something like ÿØÿà)
To summarize:
The tile_data is a BLOB (storing an image) and i can't get a proper conversion to a Go var.
How can i convert a BLOB to Image in Go ?
UPDATE:
The ÿØÿà characters are 0xFF 0xD8 0xFF 0xE0 which are indeed the start of the JPEG file. I'm using the same MBTile file that i use in an iOS app through the Mapbox iOS SDK, so the file isn't corrupted and i can actually see the BLOB images using a SQLite GUI. The MBTiles spec says that the field is a BLOB type, and indeed, that's the field type that i'm using.
Again, the database is fine, is the same one used by an external iOS app. I can even query other data with success.
For context this is my isolated code.
func TilesHandler(w http.ResponseWriter, r *http.Request) {

  db, _ := sql.Open("sqlite3", "./mapSource.mbtiles")
  defer db.Close()

  rows, _ := db.Query("SELECT tile_data FROM tiles WHERE zoom_level = 10 AND tile_column = 309 AND tile_row = 569")
  defer rows.Close()

  var tileData []byte
  for rows.Next() {
    rows.Scan(&tileData)
  }

  w.Write(tileData)
}

The zoom and coordinates are hardcoded for simplicity. tiledata is returning the mentioned 4 bytes.
UPDATE 2:
Here is the output of one specific record of the tiles table. Notice that the tile_data field is a BLOB and at the bottom the GUI shows that 4 characters. That are the exact one that i'm receiving in the []byte array at my Go code.
So my question is: I have this BLOB image file in my database which is a jpeg image. How i read it and show it as an image in my web page ? I want to read that BLOB and return an image in my http request.
Tiles row sample:

Tiles fields types

A: This was a bug in the sqlite3 driver. It wasn't handling strings that contain NUL characters properly. It is now fixed.
Also the data have not been inserted correctly into the database. The datatype for them is TEXT and not BLOB as required by the schema. You can see this in the sqlite shell with: SELECT typeof(tile_data) FROM tiles;. 1


text:
Q: splitting data in a table column for search I was working with a simple mysql table in php when I came across this problem and I am wondering if there is a solution to this.
The table holds a username and his locations in a comma separated format.
 id|user|locations
------------------
 1 |abc | A, B, C
------------------
 2 |xyz | P, Q, R

I was wondering if there was any way to write a mysql query so that it would return me a user who has location as A.
Basically if one of the values among the comma separated values match, the record should be returned.
I know it is a better way to store them as separate records, but I was just curious if such a retrieval is possible.
Thanks in advance.

A: Ideally, you should consider normalizing the data so you are not storing the comma separated list.
But if you cannot alter the table structure, MySQL has a FIND_IN_SET() function that can be used to return the rows that match the value you want:
select id, user, locations
from yourtable
where find_in_set('A', locations)

See SQL Fiddle with Demo

A: We think
the following query may help you -
SELECT * FROM table WHERE column REGEXP  '(^|,)A($|,)'
You can have a useful link in -
How to query comma delimited field of table to see if number is within the field


text:
Q: How can Perl's Getopt::Long discover arguments with mandatory parameter missing? In one of my scripts I use the Getopt::Long library. At the beginning of the program I make a call:
&GetOptions ('help', 'debug', 'user=s' => \$GetUser);

The first two arguments are simple: I discover their existance by checking $opt_help and $opt_debug respectively. However the third argument is tricky, because I need to distinguish between no option at all ($GetUser is undefined, which is ok for me), using "--user" alone ($GetUser is also undefined, but this time I want to display an error message) and "--user FooBar" (where the $GetUser receives 'FooBar', which I can use in further processing).
How can I distinguish between using no "--user" option and using it alone, without a username?

A: You are looking for : instead of =, so 'user:s' => \$GetUser. From Options with values

Using a colon : instead of the equals sign indicates that the option value is optional.  In this case, if no suitable value is supplied, string valued options get an empty string '' assigned, while numeric options are set to 0

This allows you to legitimately call the program with --user and no value (with = it's an error). Then you only declare my $GetUser; and after the options are processed you can tell what happened. If it is undef it wasn't mentioned, if it is '' (empty string) it was invoked without a value and you can emit your message. This assumes that it being '' isn't of any other use in your program.
Otherwise, when you use 'user=s' and no value is given, the GetOptions reports an error by returning false and emits a descriptive message to STDERR. So you may well leave it and do
GetOptions( 'user=s' => ...)  or die "Option error\n";

and rely on the module to catch and report wrong use.  Our own message above isn't really needed as module's messages clearly describe the problem.
One other way of doing this would go along the lines of
usage(), exit  if not GetOptions('user=s' => \$GetUser, ...);

sub usage {
    # Your usage message, briefly listing options etc.
}

I'd like to add – you don't need & in front of a function call. It makes the caller's @_ visible, ignores function prototype, and does a few other similarly involved things. One common use is to get a coderef, $rc = \&fun, where it is needed. See for example this post


text:
Q: Custom extension for form I have a detail page that has two buttons:
<apex:form >
               <apex:commandButton styleclass="btn-lg btn-data" value="Vote Up"/>

               <apex:commandButton styleclass="btn-lg btn-data" value="Vote Down"/>
</apex:form>

When "Vote Up" is clicked, I want my custom field "Button" to insert a value of "Up" for that field. And the same with "Vote Down" except insert "Down" into "Button".
The detail page uses a link: <a href="/apex/Custom_Page_Detail?id={!r.id}">
to get the record information.
How would I construct an extension that assigns the button values and tie them to the record displayed?
Thanks for any help!!!


text:
Q: Export a function in NodeJS module I have a module in NodeJS which has the following definition:
var express = require('express');
var router = express.Router();

function myFunction(){
    //do some stuff
};

router.get('/url', function(req, res, callback) {
    var data = myFunction();
    res.render('index', {
        item: data
    });
});

module.exports = router;

I want it to be called in both ways:
HTTP petition:
http://localhost:3090/url

As a function in another module:
var myModule = require('myModule');
var data = myModule.myFunction();

I can access the module by HTTP in the way shown above. However, I don't know how to export myFunction to be used in another module. I have tried the following without any success:
router.myFunction = myFunction;
module.exports = router;

And:
module.exports = router;
module.exports.myFunction = myFunction;

How could I solve this problemn?
Thank you very much in advance

A: you can make these changes
use exports to expose multiple functions
exports.router = router;
exports.myFunction = myFunction;

for including them both in other file(path to myModule can vary as per your structure) you can now include them as
var routes= require('./myModule').router;
var myfunction = require('./myModule').myFunction;

A: Another way is to also sum up everything you're exporting at the end of the module - basically construct the exports object:
module.exports = {

    myFunction: myFunction,
    router: router,
    someConstant: 42,
    anotherValue: calculateThisValue()
}

At any time, module.exports is a global per-file object you get when you require that file. If you put nothing there, it'll be undefined. If you make it a function, then it'll be a function. If you make an object literal like above, you get an object. You can also export primitives, like dates, arrays, or whatever else you may think of.


text:
Q: Change whats on a page with keyboard (JS) (work with images) So I was messing around with JS, and I made something that when I press a key it displays that letter. so if I were to press A on the keyboard, KeyA appears on the page, but I was wondering if it would be possible to make a image appear when I pressed A instead. Thanks in advance <3
(also what I have is in the code snippet)

const log = document.getElementById('log');

document.addEventListener('keypress', logKey);

function logKey(e) {
  log.textContent += ` ${e.code}`;
}

  function logKey(a) {
  log.textContent += ` ${a.code}`;
}

  function logKey(a) {
  log.textContent += ` ${a.code}`;
}

  function logKey(q) {
  log.textContent += ` ${q.code}`;
}

  function logKey(w) {
  log.textContent += ` ${w.code}`;
}

  function logKey(r) {
  log.textContent += ` ${r.code}`;
}

  function logKey(t) {
  log.textContent += ` ${t.code}`;
}

  function logKey(y) {
  log.textContent += ` ${y.code}`;
}
  function logKey(u) {
  log.textContent += ` ${u.code}`;
}
  function logKey(i) {
  log.textContent += ` ${i.code}`;
}
  function logKey(o) {
  log.textContent += ` ${o.code}`;
}
  function logKey(p) {
  log.textContent += ` ${p.code}`;
}
  function logKey(s) {
  log.textContent += ` ${s.code}`;
}
  function logKey(d) {
  log.textContent += ` ${d.code}`;
}
  function logKey(f) {
  log.textContent += ` ${f.code}`;
}
  function logKey(g) {
  log.textContent += ` ${g.code}`;
}

  function logKey(h) {
  log.textContent += ` ${h.code}`;
}
  function logKey(j) {
  log.textContent += ` ${j.code}`;
}

  function logKey(k) {
  log.textContent += ` ${k.code}`;
}
  function logKey(l) {
  log.textContent += ` ${l.code}`;
}
  function logKey(z) {
  log.textContent += ` ${z.code}`;
}
  function logKey(x) {
  log.textContent += ` ${x.code}`;
}
  function logKey(c) {
  log.textContent += ` ${c.code}`;
}
  function logKey(v) {
  log.textContent += ` ${v.code}`;
}
  function logKey(b) {
  log.textContent += ` ${b.code}`;
}
  function logKey(n) {
  log.textContent += ` ${n.code}`;
}
  function logKey(m) {
  log.textContent += ` ${m.code}`;
}

A: Just use a div instead of a  and append dynamically generated images to it. Also don't redeclare your function each time it is pointless. Use a switch/case instead and check for keycodes :

let div = document.getElementById("img");
window.onkeypress = function(e) {
  switch(e.code) {
    //I just did the letter A but you get the idea
    case "KeyA":
      let img = document.createElement("img");
      img.src = "https://etc.usf.edu/presentations/extras/letters/fridge_magnets/red/11/A-300.png"
      img.style = "width:70px;height:100px;"
      div.appendChild(img)
      break;
  }
}


text:
Q: QMap insertMulti vs QMap > I was looking at storing a set of values in a map, with an int as a key: -
QMap<int, QSet<QString> > setOfValues;

While reading the documentation, I noticed that QMap provides the insertMulti function, to allow inserting multiple values for the same key.
Ignoring QMultimap, since this is just a convenience wrapper around QMap::insertMulti, would there be any advantage of using the insertMulti function of QMap, rather than a map of a set, as above?


text:
Q: onchange event fires after onmousedown event I am using a jQuery and Ajax to dynamically generate the form elements.
so accordingly my code generates the elements and all working fine.
now I have an onchange event on each textbox which fires on focus out with value changed.
Also, I have a save button which has an onmousedown event to post the form data.
Code I am using:
(HTML code)

    <input type="text" class="vchange" />
    <input type="text" class="vchange" />

    Submit

Now, the problem is the mousedown event is called before the onchange event and so the data is not saved in the table.

A: You have to pass a variable for your event-function. I've called it here "event". The variable "event" presents the element, which has triggered the event. In this case the even is "onmousemove". Thus you can gain access to its content, such as the value, by using "event.target.value" for example. This event actually occures, whenever you move your mouse above this element, no matter if the mouse button is clicked or not. But since its value doesn't change, when you don't press the mousebutton or move the slider, you won't see any changes. But it triggers though. You see the changes first, when you let it show the value of the slider or do something else, which changes by every triggering of that function.
This is the solution you're searching for:
$('#myrange').on('mousemove', function(event){
    $('#labelToShow').html(event.target.value);
    $('#inputWithTypeNumber').val(event.target.value);
})

and this is a code example for you to understand how it works
var somecounter = 0;
$('#myrange').on('mousemove', function(event){
    $('#labelToShow').html(somecounter++);
});

simply create an input element of the type "range" and give it the id "myrange". Then also create a label with the id "labelToShow" and another input element of type "number" with the id "inputWithTypeNumber". Like this.
<input type="range" id="myrange" />
<input type="number" id="inputWithTypeNumber" />
Move your mouse above the slider

A: so far i understood your problem is to save the values in the textinput with ajax call before you submit the form and the mousedown event fires before the onchange then why dont you trigger the onchange inside the mousedown event manually for a workaround like below
$("#form").onchange(); or $("#form").fireEvent("onchange");
EDIT
I just thought to add the sample code so that if the OP is having problem understanding the idea i was discussing as a comment was just posted that the problem still isnt solved, what i am saying is that you can track the change for the text inputs with on change and to tackle the problem of the mousedown event to be always triggered after the onchange is to trigger the onchange inside the mousedown manually, like $('input[class="vchange"]').trigger('change'); and you have wrong selector in your code for the onchange event '.vchange input[type=text]' this wont select any element either use .vchange or 'input[class="vchange"]'. See below a demo where the form will always be submitted after sending ajax call.
But keep in mind this will trigger simultanious ajax calls for every input with class .vchange that has some value in it means it is not empty. so a better approach would be to create a separate function that collect all fields with class .vchange that has value!=='' and send one call to save them all if you have numerous fields.

$(document).ready(function() {
  $(document).on('change', 'input[class="vchange"]', function() {
    if ($(this).val() !== '') {
      console.log('ajax post back code to save textbox data in database.');
    }
  });
  $(document).on('mousedown', '.vsubmit', function() {
    $('input[class="vchange"]').trigger('change');
    console.log('submitting form');

  });
});

  <input type="text" class="vchange" />
  <input type="text" class="vchange" />

  Submit

A: Why not handle the input in the same handler you ask the user to confirm?
If you use a form-element, you can use the submit event and think about a submit button to support keyboard only input.

$(function(){

  $('#form').on('submit', function (e) {
    e.preventDefault();

    let choice=confirm("Are you sure u want to submit the form?");

    if (!choice) {
      console.info("cancel");
    } else {
      console.info("ajax post back code to save textbox data in database.");
    }
  });

  $('.vsubmit').on('click', function () {
    $("#form").submit();
  });

});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<form id="form">
  <input type="text" class="vchange"/>
  <input type="text" class="vchange"/>
  Submit
</form>


text:
Q: SwiftUI - @FocusState as condition For some reason, I wish to use @FocusState as a condition, but it doesn't work.
struct ContentView: View {
    @FocusState private var mystate: Bool
    var body: some View {
        if mystate {
            Text("Hello")
        }

        Button(action: {
            print("before: \(mystate)")
            mystate.toggle()
            print("after: \(mystate)")
        }, label: {
            Text("Click Me")
        })
    }
}

And the console output is
before: false
after: false

Can anyone please explain why the mystate isn't changed when button get tapped? Thank you!

A: So, the FocusState needs something to focus on, without it it just changes itself to false (that's why I added TextField) - and, it doesn't change right away, but after it focuses something, therefore delay is needed.
This works for me:

struct ContentView: View {
    @FocusState private var mystate: Bool
    var body: some View {
        if mystate {
            Text("Hello")
        }

        Button(action: {
            print("before: \(mystate)")
            mystate.toggle()
            DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(50)){
                print("after: \(mystate)")
            }

        }, label: {
            Text("Click Me")
        })
        TextField("myTextField", text: .constant("text")).focused($mystate)
    }
}


text:
Q: Django i18n Problems I have a Django 1.8 project that I would like to internationalize. I have added the code to do so in the application, and when I change the LANGUAGE_CODE tag, I can successfully see the other language used, but when I leave it on en-us, no other languages show up. I have changed my computer's language to the language in question (German), but calls to the site are still in English. What am I doing wrong?
Other things:

*

*USE_I18N = true

*LOCALE_PATHS works correctly (since changing the
LANGUAGE_CODE works)

*I have also tried settings the LANGUAGES attribute although I don't think I have to anyway.

EDIT: I have also confirmed that the GET call has the header: Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4, which contains de like I want. My locale folder has a folder de in it.

A: I just needed to add'django.middleware.locale.LocaleMiddleware' to my settings.py file in the MIDDLEWARE_CLASSES section. I figured if internationalization was already on that this wouldn't be necessary.


text:
Q: Safari 9 - Label click doesn't fire change event On Safari 9, changing a radio button via its label doesn't fire the alert.
Do you know the reason or a workaround?
HTML
<input id="star-1" type="radio" name="question[1]" value="1" required>

<input id="star-2" type="radio" name="question[1]" value="2" required>

JS
var inputRadio = document.querySelectorAll('input[type="radio"]');
for (var i = 0; i < inputRadio.length; i++) {
    inputRadio[i].addEventListener('change', function() {
        alert('ciao');
    });
}

A: Your code works in Safari 9:
var inputRadio = document.querySelectorAll('input[type="radio"]');
for (var i = 0; i < inputRadio.length; i++) {
  inputRadio[i].addEventListener('change', function() {
    alert('ciao');
  });
}

http://jsfiddle.net/dbmk9xL8/1/ - Here's a fiddle to prove it.
Maybe it's some CSS that mess it up?


text:
Q: wicket 9: how to test downloading a resource I have a component which allows a user to download an excel file after clicking a link.
It works and everything is fine, but I don't know how to write a test for this component.
I want to write a test to check if after pressing a link a file is sent to a client.
And so, my component looks like this
Link<Void> calculationsLink = new Link<>("calculationsLink") {
    @Override
    public void onClick() {

        AbstractResourceStreamWriter rStream =
                new AbstractResourceStreamWriter() {

                    @Override
                    public void write(OutputStream output)
                            throws IOException {
                        output.write(MyApp.class
                                .getResourceAsStream(pathToCalculations)
                                .readAllBytes());
                    }
                };

        ResourceStreamRequestHandler handler =
                new ResourceStreamRequestHandler(rStream, "calculations.xslx");
        getRequestCycle().scheduleRequestHandlerAfterCurrent(handler);
    }
};

My test is
@Test
public void calculations_file_downloaded_Successfully() {
    // then start and render the base page
    tester.startPage(HomePage.class); <-- link is located in a HomePage

    tester.clickLink("navBar:calculations", false); <-- link is clickable
    tester.getResponse();//????

    tester.assert???(?????); <-- how to assert and what to assert?
}

A: You should use tester.getLastResponse() and assert on its properties.
tester.getResponse() is the MockHttpServletResponse that will be used for the next HTTP call.
Some dummy examples:
assertEquals("application/octet-stream", tester.getLastResponse().getContentType());
assertEquals(3, tester.getLastResponse().getBinaryContent().length);
assertArrayEquals(new byte[] {1, 2, 3}, tester.getLastResponse().getBinaryContent());


text:
Q: How to use dotween to ease in out a float? The goal to tween the "Forward" value.
This is example from the dotween exmaples.
Instead moving the cube i want to change the "Forward" value between 0 and 1.
using UnityEngine;
using System.Collections;
using DG.Tweening;

public class Sequences : MonoBehaviour
{
    public Transform cube;
    public float duration = 4;
    public Animator anim;

    private valueToLerp = 0;

    IEnumerator Start()
    {
        // Start after one second delay (to ignore Unity hiccups when activating Play mode in Editor)
        yield return new WaitForSeconds(1);

        // Create a new Sequence.
        // We will set it so that the whole duration is 6
        Sequence s = DOTween.Sequence();
        // Add an horizontal relative move tween that will last the whole Sequence's duration
        anim.SetFloat("Forward", valueToLerp);
        s.Append(cube.DOMoveX(6, duration).SetRelative().SetEase(Ease.InOutQuad));
        // Insert a rotation tween which will last half the duration
        // and will loop forward and backward twice
        s.Insert(0, cube.DORotate(new Vector3(0, 45, 0), duration / 2).SetEase(Ease.InQuad).SetLoops(2, LoopType.Yoyo));
        // Add a color tween that will start at half the duration and last until the end
        s.Insert(duration / 2, cube.GetComponent<Renderer>().material.DOColor(Color.yellow, duration / 2));
        // Set the whole Sequence to loop infinitely forward and backwards
        s.SetLoops(-1, LoopType.Yoyo);
    }
}

A: You can use DoVirtual.Float, you will not need the valueToLerp variable in this method.
// anim.SetFloat("Forward", valueToLerp);

s.Append(DOVirtual.Float(0, 1f, 1f, v => anim.SetFloat("Forward", v)));

A: Also the solution (but DOVirtual.Float from another comment is better):
    var forwardTween = DOTween.To(
            () => anim.GetFloat("Forward"),
            (val) => anim.SetFloat("Forward", val),
            6,
            duration)
        .SetRelative()
        .SetEase(Ease.InOutQuad);
    s.Append(forwardTween);


text:
Q: Command line arguments as Ints in Haskell I have a Haskell program which accepts 2 or 3 Ints from the command line:
-- test.hs

main :: IO ()
main = do
    args <- fmap (read . head) getArgs
    case args of
        [x,y,a] -> doGeneration x y a
        [x,y]   -> doGeneration x y 10
        _       -> usage

However, when I run it with arguments:
$ ./test 100 200
divide: Prelude.read: no parse

Why?

A: getArgs :: IO [String] returns a list of Strings, by taking the head and then args and it will then read that item.
You however never specified to what it should read, since you use args in a case … of … clause with [x,y,a] and [x, y], it will try to read it as a list of numbers (the type of the number is specified by the doGeneration signature. This thus means that you should write it as:
$ ./test [100,200]
But I think it makes not much sense to do that, you can rewrite the parsing part to:
main :: IO ()
main = do
    args <- fmap (map read) getArgs
    case args of
        [x,y,a] -> doGeneration x y a
        [x,y]   -> doGeneration x y 10
        _       -> usage
This means that it will read every parameter individually, and construct a list with the parsed items, and then we can pattern match on the parsed parts of the program parameters. In that case we thus can still use:
$ ./test 100 200

A: Your running code is equivalent to
     ....
     case (read "100") of
         [x,y,a :: Int] -> doGeneration x y a
         [x,y   :: Int] -> doGeneration x y 10
     ....

but reading a string "100" as a list of Ints is impossible, a.k.a. "there's no parse". That's why.
The Int comes from doGeneration's signature which you haven't included. But it must be a Num since you use a and 10 interchangeably.
It's better to use more variables in your do block instead of fmap, when you learn Haskell. It lessens the cognitive load and lets you see clearer what's going on:
main :: IO ()
main = do
    args <- getArgs           -- getArgs :: IO [String]
                              -- args    ::    [String]
    let arg1 = head args      -- arg1    ::     String
        val1 = read arg1
    case val1 of
        [x,y,a] -> doGeneration x y a
        [x,y]   -> doGeneration x y 10
        _       -> usage


text:
Q: How to fix this? i cant start my first app FAILURE: Build failed with an exception.

*

*What went wrong:
Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the User Manual chapter on the daemon at https://docs.gradle.org/5.6.2/userguide/gradle_daemon.html
Process command line: C:\Program Files (x86)\Java\jdk1.8.0_231\bin\java.exe -Xmx1536M -Dfile.encoding=windows-1252 -Duser.country=IN -Duser.language=en -Duser.variant -cp C:\Users\Thashreef.gradle\wrapper\dists\gradle-5.6.2-all\9st6wgf78h16so49nn74lgtbb\gradle-5.6.2\lib\gradle-launcher-5.6.2.jar org.gradle.launcher.daemon.bootstrap.GradleDaemon 5.6.2

Please read the following process output to find out more:
Error occurred during initialization of VM
Could not reserve enough space for 1572864KB object heap

*

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

*Get more help at https://help.gradle.org
Finished with error: Gradle task assembleDebug failed with exit code 1

A: I suspect that your Java environment is causing the incompatibility of Android studio, please open the project settings in your AS and set its Java environment to the Jdk that comes with AS


text:
Q: Infinite impedance at resonance in parallel LC circuit ? does that mean it is not usable? In a parallel (tank) LC circuit, this means infinite impedance at resonance. In a series LC circuit, it means zero impedance at resonance: What does that mean?
Does this infinite impedance at resonance in the parallel LC circuit means it is not feasible to use at resonance frequency ? and vice versa for the serial circuit, does it's performance better than serial circuit at resonance ?

A: Think of a inductor and capacitor in parallel.  At DC, it's a short due to the inductor.  At infinite frequency it's a short due to the capacitor.  You'd therefore expect the impedance to be high in the middle.
It is, but there's a special case.  Inductors and capacitors aren't just frequency-variable resistors.  For one thing, the current is shifted by 90° phase from the voltage, although this phase shift is in opposite directions for inductors and capacitors.
Now think again what happens to a parallel inductor and capacitor as the frequency changes.  We already said at DC the inductor is a short, so the combination is a short too.  As the frequency starts to go up, the inductor still draws large current, and the capacitor starts to draw a small current.  The net result is that the inductance dominates, and the current lags the voltage by nearly 90°.
At the other end, with high but finite frequency, the capacitor dominates.  The current leads the voltage by nearly 90°.
There is a frequency somewhere such that the current magnitude thru the capacitor and thru the inductor are equal.  At that special frequency, the inductor current with its 90° phase lag and the capacitor current with its 90° phase lead combine to cancel each other out.  We have no current when a voltage of this frequency is applied.  That's infinite impedance.  A little off this special frequency, and the current phase is no longer 0°, and the above doesn't apply.
Real parts aren't ideal.  The capacitor and especially the inductor each have a little inevitable resistance in series with it.  This prevents the overall impedance to become truly infinite at the special frequency.  With good quality parts, it can come fairly close.
The result is a peak in the graph of impedance magnitude as a function of frequency.  The frequency of the peak is the resonant frequency.  The more ideal the parts, the sharper the peak, meaning it is tighter in frequency.
This relatively sharp peak can be exploited to filter in or out just the resonant frequency (or frequencies close to it).
A series L-C combination works similarly, except that the impedance at 0 and infinite frequency is infinite.  It has lower impedance to in-between frequencies.  At resonance, it's impedance is ideally 0.

A: Both series and parallel resonances are useful  One use of these circuits would be a band pass filter.  So for instance if I put a parallel resonance after the resistor of a Thevenin AC source, the frequencies well below resonance would be shorted by the inductor.  Above resonance the capacitor would short the signal.  At resonance the the high impedance of the circuit would let the signal through.  This same thing could be done with series resonance followed by the load resistor.  In the first case we short unwanted signals to ground.  In the second the unwanted frequencies are blocked by high reactances.  A use of this would be accepting a radio signal but blocking all others.
Neither is really better than the other.  Picking which one to use depends on the problem being solved.
Both circuits can be used at their resonant frequencies.
In practice because all components have parasitic resistance it is not possible to make a perfect resonator.  Well not at room temperature.  Some pretty cool things can probably be done at temperatures near absolute zero.
OK, as an example this filter is centered near 1MHz and with 3db frequencies of 900kHz and 1.1MHz.  For a stop band, 600kHz and 1.4MHz with a minimum of 24db was chosen.  The first thing to do is to find filter attenuation curves for the type of filter that works best for you.  Here is an example of a curve for 1db ripple Chebyshev filter;

Using this curve this filter has an f/fc of 4.  To get 24db this chart shows n=2.  Now look up the low pass prototype.  This filter uses 150 Ohm source and 50 Ohm load so it comes up to be the first line of the table.

To convert the low pass to a bandpass use the formulas in the schematic.

Here is a quick simulation to show the result;

A: With ideal (aka perfect) components, yes, you get zero or infinite impedance at resonance.
However no component is free from losses, and this makes the impedance of any resonant circuit non-zero, or non-infinite.
In practice, any resonant circuit is coupled to some other circuit, and it is often the losses from the other circuit that control how non-zero or non-infinite the overall impedance at resonance becomes.


text:
Q: How to simplify a sum with factorial? I have the following sum:
$$\sum_{n=1}^k \frac{k!}{n!(k-n)!}, \quad k=9$$
wolfram alpha
It got simplified to $2^k-1$. How can I do it with math formulas?
Thank you!

A: Use the binomial theorem, which states:
$$
\sum_{n=0}^k a^n b^{k-n} \frac{k!}{n!(k-n)!} = (a+b)^k
$$
Use $a=b=1$, that is where the $2^k$ comes from.
The -1 is because the theorem includes the term when $n=0$, whereas in your question the summation only starts at $n=1$. So you must subtract the term when $n=0$, which is $1$, hence $-1$.
So $2k-1$.

A: $$\frac{k!}{n!(k-n)!}=\binom{k}{n},\binom{k}{0}=1$$
$$\sum_{n=0}^k\binom{k}{n}=2^k$$
$$\sum_{n=1}^k \frac{k!}{n!(k-n)!}=-1+\binom{k}{0}+\sum_{n=1}^k \binom{k}{n}=-1+\sum_{n=0}^k\binom{k}{n}=-1+2^k$$


text:
Q: how to compress the width and height of the image without cropping in 500 x 500 I am able to crop the image as 500 x 500 px after uploading using php. But, the problem is the image is getting cropped if it is compressed. I want the full image to be compressed or resized in 500 x 500 without cropping. Please help. I am providing my code for reference.
function resize_image($file, $width, $height) {
    list($w, $h) = getimagesize($file);

    /* calculate new image size with ratio */
    $ratio = max($width/$w, $height/$h);
    $h = ceil($height / $ratio);
    $x = ($w - $width / $ratio) / 2;
    $w = ceil($width / $ratio);

    /* read binary data from image file */
    $imgString = file_get_contents($file);

    /* create image from string */
    $image = imagecreatefromstring($imgString);
    $tmp = imagecreatetruecolor($width, $height);
    imagecopyresampled($tmp, $image,
        0, 0,
        $x, 0,
        $width, $height,
        $w, $h);
    $ext = pathinfo($file, PATHINFO_EXTENSION);

    //$ext will be gif

    imagejpeg($tmp, $file, 100);
    return $file;

    /* cleanup memory */

    imagedestroy($image);
    imagedestroy($tmp);
}


text:
Q: DTA Recommends to CREATE STATISTICS I just ran a T-SQL query through DTA and one of the recommendations is to CREATE STATISTICS on one of the columns that is part of many of the queries in the SQL code file.
My question is, how exactly do statistics aid in performance?

A: statistics is used when query execution plan created.

Statistics for query optimization are objects that contain statistical information about the distribution of values in one or more columns of a table or indexed view. The query optimizer uses these statistics to estimate the cardinality, or number of rows, in the query result. These cardinality estimates enable the query optimizer to create a high-quality query plan. For example, the query optimizer could use cardinality estimates to choose the index seek operator instead of the more resource-intensive index scan operator, and in doing so improve query performance.

See http://msdn.microsoft.com/en-us/library/ms190397.aspx for more details.

A: If DTA recommended a single column statistic, you must have auto create stats turned off? Auto create will build stats on any column used in a predicate, automatically, so generally its a good idea to leave it switched on. Check the status of auto update for this database, which again should usually be on.
One of the best uses of DTA is for identifying missing multi-column statistics, which auto create won't build. But for single column, auto create should be taking care of them for you.


text:
Q: Why is XMLHttpRequest readystate not equal to 4? I'm learning AJAX for the first time and I'm trying to create a simple application that calculates the grade a person needs to get on their final exam based on their previous assessment results.
The user inputs their grades into the form and then using ajax I calculate the response in response.php which should then be output in the callback function in the div with ajax as its id.
For some reason the xhr.readystate property is never reaching 4 so the response is never generated. Can anybody see what I'm doing wrong?
Please bear in mind I'm only learning...
index.php
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Grade Calculator</title>

    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

    <link rel="stylesheet" href="style.css">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            Toggle navigation

          </button>
          Project name

Home

About

Contact

Bootstrap starter template

        <form action="index.php" method="get" id="gradeForm">

                What is your current Grade
                <input type="text" name="currentGrade">

                What is your target Grade
                <input type="text" name="targetGrade">

                What is your final worth?
                <input type="text" name="finalWorth">

            <button type="submit" class="btn btn-default" onclick="sendAjax()">Submit</button>
        </form>

Here is response.php
<?php

        $currentGrade = $_GET['currentGrade'];
        $targetGrade = $_GET['targetGrade'];
        $finalWorth = $_GET['finalWorth'];

        $neededMark = $currentGrade - $targetGrade;
        $neededMark = $neededMark / $finalWorth;
        $neededMark = $neededMark * 100;
        $neededMark = round($neededMark);

        if(isset($currentGrade, $targetGrade,$finalWorth)) {
            echo $neededMark;
        }

?>

A: The correct order of operations is:

*

*construct

*open

*set handler

*send

You are doing them in the order 1324, which is incorrect and therefore likely to not behave as expected.
Put things in the right order, see if that works :)
EDIT: Additionally, remove all document.write calls. They will not work with any asynchronous operation and will almost certainly break things.
EDIT EDIT: Also, <button type="submit" class="btn btn-default" onclick="sendAjax()"> - this should be type="button", otherwise your form will be submitted and it will look like it did nothing.

A: doesn't look like you are sending any parameters in your ajax request so response.php is not GETting any data...
if it were xhr.open("GET","response.php?param1=value1&param2=value2"); etc you should get something

A: Only one small change is required
In form division make  instead of submit. Because on submit the forms behaviour is different as compared to just a button click


text:
Q: Banding with alpha transparency in XNA WP7 Having some issues with smooth alpha gradients in texture files resulting in bad banding issues.
I have a 2D XNA WP7 game and I've come up with a fairly simple lighting system. I draw the areas that would be lit by the light in a separate RenderTarget2D, apply a sprite to dim the edges as you get further away from the light, then blend that final lighting image with the main image to make certain areas darker and lighter.
Here's what I've got so far:

As you can see, the banding is pretty bad. The alpha transparency is quite smooth in the source image, but whenever I draw the sprite, it gets these huge ugly steps between colors. Just to check I drew the spotlight mask straight onto the scene with normal alpha blending and I still got the banding.
Is there any way to preserve smooth alpha gradients when drawing sprites?

A:
Is there any way to preserve smooth alpha gradients when drawing sprites?

No, you cannot. WP7 phones currently use 16 bit color range system. One pixes got: 5 red bits, 5 blue, 6 green (humans see a wider spectrum of green color).

A: Found out that with Mango, apps can now specify that they support 32bpp, and it will work on devices that support it!

For XNA, put this line at the top of OnNavigatedTo:
SharedGraphicsDeviceManager.Current.PreferredBackBufferFormat = SurfaceFormat.Color;

For Silverlight add BitsPerPixel="32" to the App element in WMAppManifest.xml.


text:
Q: Keras - Normalization by different mean and std for each channel I need to add a layer of normalization to the image in the preprocess.
It needs to be an additional layer to the model (and not seperate code in python), because I later transform the keras model to mlmodel.
This is the normalization I mean:
In python (from here):
parser.add_argument('--std', type=list, default=[0.229, 0.224, 0.225],
                                help='the std used to normalize your images')
parser.add_argument('--mean', type=list, default=[0.485, 0.456, 0.406],
                                help='the mean used to normalize your images')

normalize = transforms.Normalize(std=args.std, mean=args.mean)

transformation = transforms.Compose([transforms.ToTensor()])

man_normalize = transformation(man_resize)

In Android:
@Override
  | protected void addPixelValue(int pixelValue) {
  | imgData.putFloat((((pixelValue >> 16) & 0xFF)/255f - IMAGE_MEAN[0]) / IMAGE_STD[0]);
  | imgData.putFloat((((pixelValue >> 8) & 0xFF)/255f - IMAGE_MEAN[1]) / IMAGE_STD[1]);
  | imgData.putFloat(((pixelValue & 0xFF)/255f - IMAGE_MEAN[2]) / IMAGE_STD[2]);
  | }

I thought on Lambda layer, but I am not sure how to do it efficiently and per channel.
Thanks

A: Solution with Lambda layer:
base_model = load_model(keras_model_p)
MEAN = [0.485, 0.456, 0.406]
STD = [0.229, 0.224, 0.225]
preprocess_layer = tf.keras.layers.Lambda(
    lambda x: (x - MEAN) / STD
)
model = Sequential()
model.add(tf.keras.Input(shape=(256, 192, 3))
model.add(preprocess_layer)
model.add(base_model)


text:
Q: How to plot arrays of different lengths How do you plot arrays of different lengths but extend properly on the x-axis?  The code below generates 2 data sets, the second one being shorter.  I run an interpolation over each set resampling the data with multiple samples per data point.  When I plot all of the data the data sets that are shorter don't extend to the end of the plot.  I don't want subplots, I need to overlay the data onto each other.
#!/usr/bin/env python3

from scipy import interpolate
import matplotlib.pyplot as plt
import numpy as np

num_points = 100

# Generate an array of data, interpolate, re-sample and graph
x1 = np.arange(0, num_points)
y1 = np.cos(x1)
f1 = interpolate.interp1d(x1, y1, kind='cubic')
xnew1 = np.arange(0, num_points - 1, 0.2)
ynew1 = f1(xnew1)

plt.plot(x1, y1, color='g', label='input 1')
plt.plot(x1, y1, 'o', color='g')
plt.plot(xnew1, ynew1, color='m', label='interp 1')
plt.plot(xnew1, ynew1, '+', color='m')

# Generate ana array different size of data, interpolate, re-sample and graph
x2 = np.arange(0, num_points/2)
y2 = np.sin(x2)
f2 = interpolate.interp1d(x2, y2, kind='cubic')
xnew2 = np.arange(0, (num_points/2) - 1, 0.2)
ynew2 = f2(xnew2)

plt.plot(x2, y2, color='k', label='input 2')
plt.plot(x2, y2, 'o', color='k')
plt.plot(xnew2, ynew2, color='r', label='interp 2')
plt.plot(xnew2, ynew2, '+', color='r')

plt.legend(loc='upper left')
plt.show()

A: If I am understanding correctly, this can be done by using two different axes which share the same y-axis, as outlined in this matplotlib example.
In your case you can accomplish this by making the following modifications:
from scipy import interpolate
import matplotlib.pyplot as plt
import numpy as np
num_points = 100

# Generate an array of data, interpolate, re-sample and graph
x1 = np.arange(0, num_points)
y1 = np.cos(x1)
f1 = interpolate.interp1d(x1, y1, kind='cubic')
xnew1 = np.arange(0, num_points - 1, 0.2)
ynew1 = f1(xnew1)

fig, ax1 = plt.subplots()  # Create the first axis

ax1.plot(x1, y1, color='g', label='input 1')
ax1.plot(x1, y1, 'o', color='g')
ax1.plot(xnew1, ynew1, color='m', label='interp 1')
ax1.plot(xnew1, ynew1, '+', color='m')

ax2 = ax1.twiny()          # Create a twin which shares the y-axis

# Generate an array different size of data, interpolate, re-sample and graph
x2 = np.arange(0, num_points/2)
y2 = np.sin(x2)
f2 = interpolate.interp1d(x2, y2, kind='cubic')
xnew2 = np.arange(0, (num_points/2) - 1, 0.2)
ynew2 = f2(xnew2)

ax2.plot(x2, y2, color='k', label='input 2')
ax2.plot(x2, y2, 'o', color='k')
ax2.plot(xnew2, ynew2, color='r', label='interp 2')
ax2.plot(xnew2, ynew2, '+', color='r')
plt.figlegend(loc='upper left', bbox_to_anchor=(0.065, 0.3, 0.5, 0.5))
plt.show()

This will give you something that looks like

 Edit
In order to properly display the legend you can construct one legend for all the subplots, as outlined in this demo. Note that using this method will require some manhandling of the bounding box for the legend, and there are much cleaner ways to do this than specifying a 4-tuple of floats as I have in the line
plt.figlegend(loc='upper left', bbox_to_anchor=(0.065, 0.3, 0.5, 0.5))