text:
Q: How to handle MaxUploadSizeExceededException MaxUploadSizeExceededException exception appears when I upload a file whose size exceeds the maximum allowed. I want to show an error message when this exception appears (like a validation error message). How can I handle this exception to do something like this in Spring 3?
Thanks.

A: Thanks for solving this Steve. I banged around trying to solve for several hours.
The key is to have the controller implement HandlerExceptionResolver and add the resolveException method.
--Bob

A: Use controller advice
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ModelAndView handleMaxUploadException(MaxUploadSizeExceededException e, HttpServletRequest request, HttpServletResponse response){
        ModelAndView mav = new ModelAndView();
        boolean isJson = request.getRequestURL().toString().contains(".json");
        if (isJson) {
            mav.setView(new MappingJacksonJsonView());
            mav.addObject("result", "nok");
        }
        else mav.setViewName("uploadError");
        return mav;
    }
}

A: This is an old question so I'm adding it for the future people (including future me) who are struggling to get this working with Spring Boot 2.
At first you need to configure the spring application (in properties file):
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

If you're using embedded Tomcat (and most likely you are, as it comes as standard) it's also important to configure Tomcat not to cancel the request with large body
server.tomcat.max-swallow-size=-1

or at least set it to relatively big size
server.tomcat.max-swallow-size=100MB

If you will not set maxSwallowSize for Tomcat, you might waste lots of hours debugging why the error is handled but browser gets no response - that's because without this configuration Tomcat will cancel the request, and even though you'll see in the logs that application is handling the error, the browser already received cancellation of request from Tomcat and isn't listening for the response anymore.
And to handle the MaxUploadSizeExceededException you can add ControllerAdvice with ExceptionHandler.
Here's a quick example in Kotlin that simply sets a flash attribute with an error and redirects to some page:
@ControllerAdvice
class FileSizeExceptionAdvice {
    @ExceptionHandler(MaxUploadSizeExceededException::class)
    fun handleFileSizeException(
        e: MaxUploadSizeExceededException,
        redirectAttributes: RedirectAttributes
    ): String {
        redirectAttributes.addFlashAttribute("error", "File is too big")
        return "redirect:/"
    }
}

NOTE: if you want to handle MaxUploadSizeExceededException with ExceptionHandler directly in your controller class, you should configure following property:
spring.servlet.multipart.resolve-lazily=true

otherwise that exception will be triggered before the request is mapped to controller.

A: I finally figured out a solution that works using a HandlerExceptionResolver.
Add multipart resolver to your Spring config:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

   <property name="maxUploadSize" value="1000"/>
</bean>

Model  - UploadedFile.java:
package com.mypkg.models;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class UploadedFile
{
    private String title;

    private CommonsMultipartFile fileData;

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public CommonsMultipartFile getFileData()
    {
        return fileData;
    }

    public void setFileData(CommonsMultipartFile fileData)
    {
        this.fileData = fileData;
    }

}

View  - /upload.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

        <title>Test File Upload</title>

Select a file to upload

        <c:if test="${not empty errors}">

${errors}.

        </c:if>
        <form:form modelAttribute="uploadedFile" method="post" enctype="multipart/form-data" name="uploadedFileform" id="uploadedFileform">

                    Title:
                    <form:input id="title" path="title" cssClass="areaInput" size="30" maxlength="128"/>

                    File:
                    <form:input id="fileData" path="fileData" type="file" />

                    <input type="submit" value="Upload File" />

        </form:form>

Controller  - FileUploadController.java:
    package com.mypkg.controllers;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.mypkg.models.UploadedFile;

@Controller
public class FileUploadController  implements HandlerExceptionResolver
{
    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String getUploadForm(Model model)
    {
        model.addAttribute("uploadedFile", new UploadedFile());
        return "/upload";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String create(UploadedFile uploadedFile, BindingResult result)
    {
        // Do something with the file
        System.out.println("#########  File Uploaded with Title: " + uploadedFile.getTitle());
        System.out.println("#########  Creating local file: /var/test-file-upload/" + uploadedFile.getFileData().getOriginalFilename());

        try
        {

            InputStream in = uploadedFile.getFileData().getInputStream();
            FileOutputStream f = new FileOutputStream(
                    "/var/test-file-upload/" + uploadedFile.getFileData().getOriginalFilename());
            int ch = 0;
            while ((ch = in.read()) != -1)
            {
                f.write(ch);
            }
            f.flush();
            f.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        return "redirect:/";
    }

    /*** Trap Exceptions during the upload and show errors back in view form ***/
    public ModelAndView resolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception exception)
    {
        Map<String, Object> model = new HashMap<String, Object>();
        if (exception instanceof MaxUploadSizeExceededException)
        {
            model.put("errors", exception.getMessage());
        } else
        {
            model.put("errors", "Unexpected error: " + exception.getMessage());
        }
        model.put("uploadedFile", new UploadedFile());
        return new ModelAndView("/upload", model);
    }

}

========================================================================

A: if using ajax,need to response json,can response json in resolveException method
@Override
  public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) {
    ModelAndView view = new ModelAndView();
    view.setView(new MappingJacksonJsonView());
    APIResponseData apiResponseData = new APIResponseData();

    if (ex instanceof MaxUploadSizeExceededException) {
      apiResponseData.markFail("error message");
      view.addObject(apiResponseData);
      return view;
    }
    return null;
  }


text:
Q: VBA Coding in Excel I am very new to VBA Coding. I have two sheets in excel .
Sheet 1 - Columns include CTC ,TCC (A1,B1)
          Rows contain the ctc and tcc details (A2,B2)
Sheet 2 - Rows include CTC and TCC. It's in this page that TCC Calculated.
          B1 has CTC taken from first row of sheet1.Then calculations are done to calculate TCC in B3.
Requirement :
For calculating TCC ,we need to paste the first CTC in sheet 1 to sheet 2 CTC Column.The result obtained has TCC should appear on sheet 1 under TCC Column.
This is the code I tried :
Sub Button1_Click()

    Dim value1 As Integer
    Dim value2 As Integer

    For i = 1 To 6

        value1 = ThisWorkbook.Sheets(1).Range("Ai").Value

        Sheet2.Range("B1") = value1

        Sheet1.Cells(B, i) = ThisWorkbook.Sheets(2).Range("B3").Value

    Next i
End Sub

A: I feel that this code is what you want.
Let me know if it's different that what you expected.
Sub Button1_Click()
    Dim value1 As Integer
    Dim value2 As Integer
    For i = 1 To 6
        value1 = ThisWorkbook.Sheets(1).Range("A" & i).Value ' we can't make Range("Ai").Value
        Sheet2.Range("B1").Value = value1
        Sheet1.Cells(i, Range("B1").Column).Value = Sheet2.Range("B3").Value 'Cells(row, columns), that is the correct format for cells
    Next i
End Sub

A: It sounds like you want the following code:
Sub Button1_Click()
    Dim i As Long
    For i = 1 To 6
        ThisWorkbook.WorkSheets("Sheet 2").Range("B1").Value = ThisWorkbook.WorkSheets("Sheet 1").Cells(i, "A").Value
        ThisWorkbook.WorkSheets("Sheet 1").Cells(i, "B").Value = ThisWorkbook.WorkSheets("Sheet 2").Range("B3").Value
    Next i
End Sub

I've used sheet names of "Sheet 1" and "Sheet 2", as that is what you have in your question.  Those should be changed if your sheets are actually called "Sheet1" and "Sheet2".

It's hard to know how close you were without knowing which CodeName your sheets were using, and which order they appeared in the workbook.  But your use of a Range("Ai") was definitely wrong - it needs to be Range("A" & i) or Cells(i, "A") (or Cells(i, 1)).

Updated to process all values in column A of worksheet "Sheet 1":
Sub Button1_Click()
    Dim i As Long
    With ThisWorkbook.WorkSheets("Sheet 1")
        For i = 1 To .Cells(.Rows.Count, "A").End(xlUp).Row
            'Check so that we only process non-empty cells
            '(just in case there is an empty cell part-way through the data)
            If Not IsEmpty(.Cells(i, "A").Value) Then
                ThisWorkbook.WorkSheets("Sheet 2").Range("B1").Value = .Cells(i, "A").Value
                .Cells(i, "B").Value = ThisWorkbook.WorkSheets("Sheet 2").Range("B3").Value
            End If
        Next i
    End With
End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to measure AC current using ACS712 and interface with ESP32? Actually, I want to measure the AC current using ACS712 connect with ESP32 module.
I know this module only works under 3.3v. So, I used voltage divider circuit and step down 5v to 3.3v which is being come from the acs712 20A (You may consider any of your 5A/20A/30A chip). I also tested the "ACS712.h" Arduino library. Still, I do not get proper current which I compared with 2 multimeters. Maybe I need to change in hardware side means place op. amp in between circuit. So, Help me to resolve my issue.
Thank's in advance.

A: I think your statement about stepping down from 5v to 3.3v is confusing but it looks like your issue is solely with the output of the ACS712 AC current sensor which nominally outputs 0V-5V to a microcontroller ADC corresponding to a range of -20A to 20A through the sense inputs of the ACS712.
In a normal setup with ACS712 providing your current reading to a 0-5V ADC (on an Arduino), you'd expect a current of 0A to correspond to a voltage of 2.5V at the microcontroller ADC input.
The issue here is that the ESP32 ADC inputs only go up to 3.3V and would give an incorrect maxed out reading for anything over about 6.4A:
((3.3 - 2.5V) / 0.125 V/A) = 6.4A

So, if you only need to read less than 6.4A you could theoretically use the ACS712 as is shown in any example circuit for the arduino setup without any kind of extra op-amp, buffer or voltage divider.
The other alternative is if you need readings higher than +6.4A but you only care about polarity going in one direction you can reverse the polarity of your inputs through the current sensor so that instead of a range of -20A to +6.4 you get -6.4A to +20A.
The result would be that your 0A still reads 2.5V but 10A reads 1.25V to your ESP32, 20A reads 0V to your ESP32, etc.. then within your microcontroller code you just invert the sign of your reading.
Depending on specific issues of porting that arduino sample code to the ESP you may run into issues with the ESP ADC input trying to automatically rescale itself from the expected 0V to 5V on the arduino down to the ESP32 0V to 3.3V range but if you can read the raw voltages coming into the ESP32 you should be able to do a simple linear conversion yourself:
Input V to your ESP32 ADC = (Sensed A * 0.125 V/A) + 2.5

E.g.:
      5V = ( 20 * 0.125 V/A) + 2.5
    2.5V = (  0 * 0.125 V/A) + 2.5
      0V = (-20 * 0.125 V/A) + 2.5

In other words (Input V to ADC - 2.5 ) / 0.125 = Sensed Current at ACS712 and then flip polarity/sign of the output as needed.
Note: You don't want to get yourself into a situation where you may accidentally damage a 3.3V ADC by providing a 5V input but the ESP32 seems to be fairly tolerant of the 3.3->5V overvoltage on the inputs and our intent is to not actually get close to that by providing anything from -6.4A to -20A after reversing the polarity of your ACS712 inputs.

A: As mentioned, you've used a resistor divider (R1 and R2) to level down the voltage, but did you check the datasheet for the burden resistor?
So the resistor divider between Vout and the ground should have an equivalent resistance greater than or equal to the burden resistor
( R1 + R2 ≥ Rb )

I don't know why they have not mentioned the resistor in the typical application diagram.

A: Some suggestions.

*

*Use only a pure sine wave signal when testing and calibrating an AC measurement system. As a general rule do not use arbitrary wave forms like triangle, square, powered/spinning motors, aperiodic signals, etc. for testing / calibration purposes.

*Ensure your ADC sampling rate (samples per second) is high enough, ensure your circuit grounds are connected together, and use circuit and software designs that minimize ADC ghosting.

*When measuring AC signals with a multimeter, know that the multimeter indicates RMS values and not peak or peak-to-peak values. If your software measures the peak current value \$i_p\$ or the peak-to-peak current value \$i_{p-p}\$, then your software must convert that value to RMS before checking whether your system and the multimeter are yielding the same measurement value.
$$
i_{RMS} = \frac {i_{p}}{\sqrt{2}} = \frac {i_{p-p}}{2\sqrt{2}}
$$

*Digital multimeters (DMM) are usually one of two types: average responding, RMS indicating; or, RMS responding, RMS indicating (a.k.a., true RMS).  An average responding DMM requires a purely sinusoidal input signal when measuring AC volts or AC current; non-sinusoidal waveforms produce incorrect RMS indications on the meter's display and therefore should not be measured.  An RMS responding DMM, also known as a true RMS DMM, indicates the correct RMS value of any AC waveform as long as the AC signal does not contain harmonics that exceed the meter's rated maximum measurement frequency. For example, if the meter can measure AC signals up to 300 kHz, then the arbitrary shaped AC signal must not contain harmonics exceeding 300 kHz.See also: What is true-RMS? (Fluke); What is the difference between a multimeter with RMS and one with True RMS? (EE.SE).

*You'll probably need to use one or more calibration constants in your software calculations to fine tune your measurement system. For example, you might need to add a DC offset (a bias adjustment) \$k_1\$ and a scaling factor (gain or sensitivity adjustment) \$k_2\$.
$$
i_{corrected}=k_2 \cdot i_{measured} + k_1
$$

*The easiest way to determine calibration factors like k1 and k2 is to generate a calibration table that maps applied current vs measured current values, and then use the curve fitting tools in MATLAB or Excel or whatever to determine these constants.
+---------+----------+
| Applied | Measured |
| Current | Current  |
| (A_RMS) | (A_RMS)  |
+---------+----------+
|   1.0   |          |
|   2.0   |          |
|   3.0   |          |
|   ...   |          |
+---------+----------+
Applied = Measured by the DMM (the reference standard)
Measured = Measured by your system (the device under test, or DUT)

A: Actually the issue is with ESP32 module as it has an inbuilt Hall effect sensor  and ACS712 is also based on Hall effect. thus this is causing the incorrect result. I'm also having this problem and not able to resolve it.
you can check the same code with NodeMCU, it will give you the desired result .

A: I would try running the sensor on 5volt, and use a (10k)resistor between sensor out and analogue in.
No current would be 2.5volt, so ~75% on the A/D scale.
With the 20A version of the ACS712 you probably won't have any clipping.
Larger currents will clip the top of the sine wave.
You could try reading only the negative half of the sinewave in software.
original answer here:
https://forum.arduino.cc/t/using-acs712-on-3-3v-mcu-without-level-shifting/334026


text:
Q: run() is never called by Thread.start() method I have written a small multithreading program.
public class NewThread implements Runnable {
    Thread t;

    public NewThread() {
        t = new Thread(this, "Thread created by Thread Class.");
        System.out.println("Created by constuctor:"+ t);
        t.start(); // This will call run, because t has context as this
    }

    @Override
    public void run() {
        System.out.println("run() method called.");
    }

    public static void main(String[] args) {
        new NewThread();
    }
}

This is how the book says to write it. However, I never get the run() method called statement in the console. Thus, it seems run() is never called. How can this be true?
Edit: Yes, it is bad practice to start a Thread from constructor, but that is not affecting the question. (I am getting so many down votes for that)

A:
run() is never called by Thread.start() method

You code actually works on my system but that it doesn't work on your's, demonstrates that you have a classic race condition.
Inside of main(), the NewThread is constructed but the Java language says that it can reorder operations so that the operations in a constructor can happen after the constructor finishes.  So it is possible that main() might finish before the NewThread has actually been started which can result in the JVM shutting down without running the thread.
Because of instruction reordering, you should never have a thread auto-start itself inside of the constructor.  See: Why not to start a thread in the constructor? How to terminate?
You should instead do:
public NewThread() {
    t = new Thread(this, "Thread created by Thread Class.");
    System.out.println("Created by constuctor:" + t);
    // don't start here
}
public void start() {
    // start in another method
    t.start();
}
public void run() {
    System.out.println("run() method called.");
}
...

public static void main(String[] args) {
    NewThread nt = new NewThread();
    nt.start();
}

Since the NewThread has the same daemon status as your main thread (which is non-daemon) the JVM will not shutdown until nt.run() completes.


text:
Q: Yet another SQL on Pandas DFs question. Help me end these once and for all I frequently pull data from different databases into pandas dataframes, do some processing, and then eventually hit a processing step that I would strongly prefer to write in SQL (often involving joins across DFs). I figured I'd write a quick function which would:

*

*accept an arbitrary sql query and set of relevant dataframes

*write the dataframes to a tmp sqlite3 db

*execute the SQL query in sqlite3 and return results as a dataframe

The function I came up with looks like this:
def SQL_on_DFs(query:str, dfs=[]) -> pd.DataFrame:
    """convenience function to write sql on arbitrary DFs
        ...execute in a temp sqlite db and return results as DF
    """
    # validation - every item in dfs list must be a dataframe
    assert [isinstance(x, pd.DataFrame) for x in dfs].all()

    # if no temp.db exists here, sqlite3 will create one
    sql3conn = sqlite3.connect("temp.db")

    # write dfs to sqlite3 db to perform sql query on them there
    for df in dfs:
        df.to_sql(sql3conn)

    result = pd.read_sql_query(query, sql3conn)
    return result

# TEST
df_ab = pd.DataFrame({"a": [1,2,3], "b": [2,2,2]})
df_ac = pd.DataFrame({"a": [1,2,3], "c": [3,3,3]})
df_abc = pd.DataFrame({"a": [1,2,3], "b": [2,2,2], "c": [3,3,3]})

q = "select ab.*, ac.c from df_ab ab left join df_ac ac on ab.a = ac.a"
assert SQL_on_DFs(q, [df_ab, df_ac]).equals(df_abc)

Super useful, super easy. Right?! Wrong! Don't you feel like a sucker. Definitely you and not me.
df.to_sql(sql3conn) throws an error. It says it's missing 1 required positional argument: 'con', but we've passed a con. What it's missing is the other required positional parameter, name of the table to write to sqlite3 as. So I need a way to get that the "name" of df_ab should be "df_ab", and the "name" of df_ac should be "df_ac".
Now I know what you're thinking: Max Power, why don't you just change your second function parameter from dfs = [df_ab, df_ac], to [(df_ab, "df_ab"), (df_ac, "df_ac")]?
Please don't make me do that. This is supposed to be a convenience function and that looks inconvenient

A: Ok I have an answer, and this method doesn't even require the DFs as a param at all. It parses their names from the SQL statement and then grabs the corresponding objects. This answer satisfies the following:

*

*have: some Pandas DataFrames lying around

*want: a function that accepts a SQL query referencing them as if they were SQL tables, executes the SQL query and returns the result as a DataFrame

...
Given this setup (imports and helper function)...
import pandas as pd
import sqlite3
from sql_metadata import Parser
from inspect import currentframe

def get_dfs_from_caller_scope(df_names: list[str]) -> dict[str, pd.DataFrame]:
    """Given a list of DF names, this returns a dict mapping df-name to df from original* scope

    *'original scope' in this function context meaning the caller's caller's scope
     """
    vars_in_orig_scope = currentframe().f_back.f_back.f_locals

    dfs_map = {}
    for k,v in vars_in_orig_scope.items():
        if k in df_names and isinstance(v, pd.DataFrame):
            dfs_map[k] = v

    return dfs_map

This function now does what I want:
def SQL_on_DFs(query:str)->pd.DataFrame:
    """convenience function to write sql on arbitrary DFs
        ...execute in a temp sqlite db and return results as DF
    """
    # get table-names referenced by query, which should correspond to dataframes in caller's scope
    tablenames = Parser(query).tables

    # get a mapping of those tablenames in query to the actual corresponding DataFrame objects from caller's scope
    tablenames_and_assoc_dfs = get_dfs_from_caller_scope(tablenames)

    # if no temp.db exists here, sqlite3 will create one
    sql3conn = sqlite3.connect("temp.db")

    # write dfs to sqlite3 db to perform sql query on them there
    for df_name,df in tablenames_and_assoc_dfs.items():
        df.to_sql(df_name, sql3conn, index=False, if_exists='replace')

    result = pd.read_sql_query(query, sql3conn)
    return result

TEST:
df_ab = pd.DataFrame({"a": [1,2,3], "b": [2,2,2]})
df_ac = pd.DataFrame({"a": [1,2,3], "c": [3,3,3]})
df_abc = pd.DataFrame({"a": [1,2,3], "b": [2,2,2], "c": [3,3,3]})

q = "select ab.*, ac.c from df_ab ab left join df_ac ac on ab.a = ac.a"
assert SQL_on_DFs(q).equals(df_abc)  # Passes


text:
Q: got SIGSEGV while calling 'require ("lsqlite3")' with lua 5.1.5 I had built lua 5.1.5 and lsqlite3-0.8.1. all of them run well on my RedHat Linux.
and then I ported them to my MIPS development board. lua and other modules (such as luafilesystem, md5, cgilua and wsapi) run well. but lsqlite3 does not work.
when I execute require("lsqlite3") in lua command line, it returns error messages in below:
lua
Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio

require("lsqlite3")
  do_page_fault() #2: sending SIGSEGV to lua for invalid read access from
  00000000 (epc == 00000000, ra == 2ac36144)
  Segmentation fault

can any one give me any help to fix it? Thanks!
I got few progress in solving this problem, I rebuilt the LUA with gcc compile option '-Wl,-E' and rebuilt lsqlite3 later. I executed require ("lsqlite3") in lua command line, and it didnt print any message. I continued running some other database operation commands and found them all been successfully executed. As it seemed the problem had been solved, I should be very happy about it.
but another more strange problem raised.
If I put sentence require("lsqlite3") into a file, and then execute the file in this way:

lua file

it still printed  error messages like this:

do_page_fault() #2: sending SIGSEGV to lua for invalid read access from
  2ada054c (epc == 2ada054c, ra == 2abdceac)

If I put more database operation sentences into a file, and then run this file by lua. Lua can give correct result of query operation and insert values to table correctly, but always print error messages showed above.
If I run sentences in the file one by one in lua command line interface, it never print this error message.
It seems to give the error message when executing the 'require' function. But if I put require("lfs") into a file and run this file by lua, it never print error message.
I am confused that whait is the difference between the lua command line execution and lua script.

A: There are three places in lsqlite3.c where sqlite_int64 is used (never long long directly). When you build sqlite3 some type will be used for 64 bit integers; lsqlite3 will use the same type by including sqlite3.h for the definition of the type.


text:
Q: cross-domain iframe javascript click event (scroll up) Setup:
I have website A and B.
Website B has a scroll-up button and is iframed inside of site A.
 A and B are two different domains.
I've tried everything including window.postMessage and nothing is working.
Any help is appreciated.

A: This lib has a function to allow an iframe to scroll the parent page.
https://github.com/davidjbradshaw/iframe-resizer


text:
Q: Encrypt client connection with squid forward proxy using SSL I'm setting up a Squid forward proxy and I'm wondering if I could configure Squid in such a way that the connection from my web browser to squid is https regardless of whether the connection from squid to the destination website is http or https. In other words, I want my connection from my web browser to my forward proxy to be encrypted even though I'm just surfing normal http website through that proxy.
Can it be done?

A: Squid 3.0 has https_port configuration directive. See this configuration example on Squid Wiki for details.


text:
Q: angularjs + yeoman + ng-switch + build:minify -> assertion I am using an ng-switch in angularjs to have dynamic content in my page, dependent on the url. And I am managing my project with yeoman. Here is the code of the dynamic content generation:
html:

controller:
$scope.renderPath = $location.path().split('/');
// remove first entry because it's empty string
$scope.renderPath.shift();

This works perfectly well when running the stuff with 'yeoman server'. But if I build with 'yeoman build:minify', it doesn't work anymore afterwards. It hits an assertion:
at assertArg (http://host:8888/scripts/vendor/d10639ae.angular.js:973:11)
at Object.ngDirective.compile (http://host:8888/scripts/vendor/d10639ae.angular.js:13474:5)
at applyDirectivesToNode (http://host:8888/scripts/vendor/d10639ae.angular.js:4047:32)
at compileNodes (http://host:8888/scripts/vendor/d10639ae.angular.js:3794:14)
at compileNodes (http://host:8888/scripts/vendor/d10639ae.angular.js:3799:14)
at compile (http://host:8888/scripts/vendor/d10639ae.angular.js:3739:29)
at update (http://host:8888/scripts/vendor/d10639ae.angular.js:13685:22)
at $get.Scope.$broadcast.next (http://host:8888/scripts/vendor/d10639ae.angular.js:8002:24)
at Array.forEach (native)
at forEach (http://host:8888/scripts/vendor/d10639ae.angular.js:110:11)

Does someone know how to fix this? Or where I need to look to debug it?

A: If you are using dependency-injection within your scripts, make sure to use the minify-proof syntax as described here: http://docs.angularjs.org/guide/di


text:
Q: should anonymous access to the IPC share be allowed on Windows 2008 r2 During an audit the question of anonymous access to the IPC$(null sessions) share was raised. The audit lists the following as being a risk on a Windows 2008r2 file server:
C:\>net use \\fileserver\ipc$ "" /user:""
The command completed successfully.
I've confirmed that the following settings are configured
Computer Configuration\Windows Settings\Security Settings\Local Policies\Security Options\
 Network access: Allow anonymous SID/Name translation = disabled
 Network access: Do not allow anonymous enumeration of SAM accounts =enabled
 Network access: Do not allow anonymous enumeration of SAM accounts and shares =enabled
 Network access: Let Everyone permissions apply to anonymous users=disabled
 Network access: Named Pipes that can be accessed anonymously= <blank>
 Network access: Shares that can be accessed anonymously= <blank>
and that anonymous enumeration(shares, users, etc..) does not work, but I've been told that if the above command completes successfully then the risk remains and we need to correct it. I'm at a loss as to what other settings would fix this and do not want to script the deletion of the share. Are there any other settings that need to be set? Should these setting cause the anonymous connection to fail? Is there anything else I might have missed?

A: Change the registry value:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\LSA\
    RestrictAnonymous = 2

Or, if you'd rather do it via Group Policy:
Network access: Restrict anonymous access to Named Pipes and Shares = Enabled.
Also you want to make sure that
Network access: Let Everyone permissions apply to anonymous users
is set to Disabled. This corresponds to the registry entry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\LSA\
    EveryoneIncludesAnonymous = 0

A: Check the latest guidance in the SCM for your OS.  According to the baseline for 2k8r2 SP2, restrict anonymous access to named pipes and share should be enabled.  You should be setting this via group policy, and should probably audit your security baseline with the tool as well.


text:
Q: Minimise winform without blocking Outlook functionality I am working on a vsto plugin in which I've created a Form(WinForm) that has fields for long text that user has to copy from previous mails. Now, the issue i am facing is, whenever I minimise the winform, the whole Outlook gets minimised. And when I try to open the outlook application from taskbar, it goes to form again.
Is there a way where user can minimise the Form and work on outlook application independently?
For example, he/she might need to scroll through few mails to get some values of field in the winform more than one time, so they minimise the form, fetch the long text, then open the form again and paste it.

A: Create a task pane instead of a floating window - see https://learn.microsoft.com/en-us/visualstudio/vsto/custom-task-panes?view=vs-2022&tabs=csharp


text:
Q: Index and charge deficiency I'm currently trying to understand this paper [1], in which the authors give a rigorous proof of the Laughlin's charge pump argument for the quantum hall effect.
In Lemma 4.4, it proves that if $u:\mathbb{C}\backslash 0\to\mathbb{S}^1\subseteq \mathbb{C}$ has winding number $N(u)$, e.g., $re^{i\theta} \mapsto e^{i\theta}$, then
$$
\int_{\mathbb{R}^2}dx \left(1-\frac{u(x-a)}{u(x-b)} \right) \left(1-\frac{u(x-b)}{u(x-c)} \right)\left(1-\frac{u(x-c)}{u(x-a)} \right) = 2\pi i N(U) \text{Area}(a,b,c)
$$
where $a,b,c\in \mathbb{R}^2$ and $\text{Area}(a,b,c)=a\wedge b +b\wedge c +c\wedge a$  (e.g., $a\wedge b = a_1b_2-a_2 b_1$).
For the moment, let us not care about the details of convergence and consider a sufficiently large disc $D$ which contains $a,b,c$ so that the integral over $\mathbb{R}^2$ is replaced by over $D$. Then the author shows that
$$
(\partial_{a_1} \partial_{b_2} - \partial_{a_2} \partial_{b_1})C(a,b,c)= 2i \Im\int_{\partial D} \bar{u}(x-a)du(x-b) = 4\pi iN(u)
$$
Up to this point, I understand the calculations. The author then claims that these are the only non-vanishing second derivative (except for cyclic permutations) and $C(a,b,c)$ can be reconstructed if we integrate the above equation twice.
There are 2 things that I don't quite understand.

*

*Why do the other second derivatives (e.g. $\partial_{a_1} \partial_{a_2} C =0$) vanish?

*Accepting that the other second derivatives indeed vanish, how can $C(a,b,c)$ be reconstructed by integrating twice?

[1] Avron, J.E., Seiler, R. & Simon, B. Charge deficiency, charge transport and comparison of dimensions. Commun.Math. Phys. 159, 399–422 (1994).


text:
Q: Getting null value from 'document.getElementById()' I have following confirmation box on review.xhtml page:
<p:confirmDialog message="#{msgs['com.yob.dpg.customerReview.invalid.invoiceDate.message']}" width="400" header="#{msgs['portaal.popup.window.confirmation.title']}" closable="false" widgetVar="invoiceDateConfirmation" showEffect="bounce" hideEffect="explode" severity="alert">
            <p:commandButton value="#{msgs['portaal.popup.window.cancel']}" onclick="invoiceDateConfirmation.hide()" oncomplete="documentWiz.back(); setFocusToInvoiceNumber()" />
            <p:spacer width="5"/>
            <p:commandButton value="#{msgs['common.ok.button']}" update="messages,@form,headerForm:todoCountMenu,welcomeMessage" onclick="invoiceDateConfirmation.hide()" />
</p:confirmDialog>

and .js is on documentPreview.xhtml page:
function setFocusToInvoiceNumber(){
    document.getElementById("invoiceNumber").focus();
}

input text code on which I want to set focus is on 'documentPreview.xhtml':
<p:inputText  style="color:#4d4d4f; width:280px !important; margin-top: -3px;" id="invoiceNumber" value="#{customerReviewLazyDataModel.customerReviewVO.transactionheaderVO.invoiceNumber}" required="true" requiredMessage="#{msgs['com.yob.dpg.customerReview.mandatory.invoiceNumber']}"/>

My problem is that when I click on cancel button of confirmation box, an exception is thrown on browser that 'document.getElementById() is null'
Can any one give me solution for this problem.

A: Because the component id in JSF is not the same as the HTML DOM object ID, you can see this when you check the component id in the generated HTML file.
Check this blog post (JSF: working with component identifiers (id/clientId)) by McDowell

A: try adding prependId=false attribute to your form. this will keep the ids of all its children when JSF will generate the html.

A: Check out the rendered html in your browser. The id of the input element is probably something like "form1:invoiceNumber" instead of simply invoiceNumber. This is because JSF prepends all the parent NamingContainer id's to a component upon rendering to html.
In order to resolve this, you could turn off the prepend id feature like @sergui suggested, but that could have some adverse effect (namely, duplicate id's if composite components are reused multiple times on the same page). Another option is to store the "clientId" (the part that JSF prepends) in javascript.
To do so, add init(String clientId) function to the js file, then call it using an inline script from the JSF facelet
<h:outputScript>init('#{component.clientId}')</h:outputScript>

You'd then have to prepend invoiceNumber with clientId, but only after escaping the delimiter that JSF uses (:).


text:
Q: Assign value to column in matlab In matlab if
a = zeros(1,2); b= ones(2,1) then it is wrong a+b;
but X=zeros(2,2), X(:,1)=a works well, why?

A: Good question. The exact answer can be found on the Matlab site, right near the bottom of the page:

Indexing on Assignment When assigning values from one matrix to
  another matrix, you can use any of the styles of indexing covered in
  this section. Matrix assignment statements also have the following
  requirement.
In the assignment A(J,K,...) = B(M,N,…), subscripts J, K, M, N, etc.
  may be scalar, vector, or array, provided that all of the following
  are true:

*

*The number of subscripts specified for B, not including trailing
  subscripts equal to 1, does not exceed ndims(B).

*The number of
  nonscalar subscripts specified for A equals the number of nonscalar
  subscripts specified for B. For example,  A(5, 1:4, 1, 2) = B(5:8) is
  valid because both sides of the equation use one nonscalar subscript.

*The order and length of all nonscalar subscripts specified for A
  matches the order and length of nonscalar subscripts specified for B.
  For example,  A(1:4, 3, 3:9) = B(5:8, 1:7) is valid because both sides
  of the equation (ignoring the one scalar subscript 3) use a 4-element
  subscript followed by a 7-element subscript.

When you look at your example, it follows the last point in the above: although you are assigning to X(:,2) which is a 2x1 column vector, and the right hand side is a 1x2 row vector, the rule "order and length of all non scalar subscripts specified for A matches the order and length of non scalar subscripts specified for B".
Note that the same is not true when you want to add two matrices - in that case, they actually need to be of exactly the same shape (so you can't add a 2x1 and a 1x2 matrix, even though both have two elements).

A: With "X(:,1)=b", you are asking MATLAB to copy the values of the column vector b to the first column of X. b has two rows, and so does X. So the value assignment works.
As for "a+b", matrix-matrix addition requires exact match of dimensions.


text:
Q: .NET Core CLR debugger VSDBG halts the application when attaching to a remote process in a Windows Docker container I have a .NET Core application running in a Windows Docker container that I want to attach Visual Studio Code to. When I do attach to the remote process, it seem the process freezes and if I disconnect the debugger, the container shuts down without any errors.
File launch.json:
{
    "name": ".NET Core Remote Attach",
    "type": "coreclr",
    "request": "attach",
    "pipeTransport": {
        "pipeProgram": "powershell",
        "pipeArgs": ["docker exec -i --privileged amazing_johnson" ],
        "pipeCwd": "${workspaceRoot}",
        "debuggerPath": "c:\\coreclr-debug\\vsdbg.exe"
    },
    "processId": "1736"
},

Results in the Debug Output Console:
Starting: "powershell" "docker exec -i --privileged amazing_johnson" "c:\coreclr-debug\vsdbg.exe --interpreter=vscode"

After attaching the debugger to the remote process, when I try to visit the site, it just hangs. Visual Studio Code lists the threads and displays some JSON in the terminal, but nothing happens. Disconnecting from it shuts down the container. Why is this happening?

A: It might be related to this GitHub issue:
Visual Studio Code hangs on breakpoint when attached to a remote debugger on a Windows Docker container #31070


text:
Q: How to develop a https:// area using mvc2 and IIS 6 on your local machine General question to experienced developers:
I want to develop a secure an area on my local machine which I will then roll up to the remote server.
I am using IIS 6 with MVC2 on VS 2008.
I understand that the SSL provider will only issue a certificate to a given domain, which while I find this logical, cannot figure out how to build locally.
How do you guys do it?

A: Its a oddly long and tedious process, but you can create your own certificate and install it on your machine and then use it to develop with SSL running locally.
Michele Leroux Bustamante has the steps listed on several places online, this is just one:
http://www.devproconnections.com/article/security-development/working-with-certificates.aspx


text:
Q: How to populate the datatable from json object with key and value as columns Normally for populating the Jquery datatable we need to give Json Array (Array of json object) to datatable and map each field with one column. But I have one json object and I want to show all the key in one column and its associated value in next colmn in same row.
For e.g. Sample json :-
 {
"first-name": "Tom",
"last-name": "Hanks",
"Designation": "Developer"
 }

Output table :-
             Key          Value

            first-name    Tom
            last-name     Hanks
            Designation  Developer

Number of these key and values may vary in future.
One simple way is that I can traverse on object and convert it into array of objects having two attributes and use to populate table.
But I was wondering if there is any other direct way.

A: This seems to be working for your example data:
var data = {
    "first-name": "Tom",
    "last-name": "Hanks",
    "Designation": "Developer"
};
var table = $('#example').DataTable({
    "columns": [
        {
            "data": "key",
            "title": "Key"
        },
        {
            "data": "value",
            "title": "Value"
        }
    ]
});
for(var key in data) {
    if(data.hasOwnProperty(key)) {
        table.row.add({
            "key": key,
            "value": data[key]
        });
    }
}
table.draw();

There is probably a more elegant solution but as a back of an envelope thing it seems to work well - should probably be done using a call back I reckon though. You can see it working here.
This is a much smaller method using a callback:
var data = {
    "first-name": "Tom",
    "last-name": "Hanks",
    "Designation": "Developer"
};
var table = $('#example').DataTable({
    "columns": [{
        "data": "key",
        "title": "Key"
    },{
        "data": "value",
        "title": "Value"
    }],
    "initComplete": function() {
        this.api().rows.add(JSON.stringify(data).slice(2, -2).split('","').map((c)=>({
            "key": c.split('":"')[0],
            "value": c.split('":"')[1]
        }))).draw();
    }
});


text:
Q: R Transpose A column into a Binary Row I have a single data column that looks like this for "one record"
There can be hundreds if not thousands of records where each record has a different ID but many different attributes ColName2
I want to transpose the table so it looks like table 2
Is this possible in R. It is possible in Rapid-miner but i would like to implement it in R
What I have Table 1

*

*ID   ColName2

*1A   Item1

*1A   Item2

*1A   Item3

*1A   Item4

*2A   Item5

What I want - Table 2

*

*ID Item1 Item2 Item3 Item4 Item 5

*1A 1     1     1     1     0

*2A 0     0     0     0     1

Thanks

A: You can use reshape2 for this, for example:
> df <- data.frame(ID = c(rep("1A", 4), "2A"), ColName = 1:5)
> df
#  ID ColName
#1 1A       1
#2 1A       2
#3 1A       3
#4 1A       4
#5 2A       5

library(reshape2)

> df2 <- dcast(df, ID ~ ColName, fun.aggregate = any, value.var = "ColName")

The result of this reshapeing is:
  ID     1     2     3     4     5
1 1A  TRUE  TRUE  TRUE  TRUE FALSE
2 2A FALSE FALSE FALSE FALSE  TRUE

So you have logical values (TRUE where you want 1 and FALSE where you want 0). Since you can convert logical values to numeric, where TRUE == 1 and FALSE == 0, you just need to convert all columns (except the first) to numeric. To do this, you can use lapply on the data.frame except the first column (indicated by df2[-1]) and apply the function as.numeric to each of the other columns:
> df2[-1] <- lapply(df2[-1], as.numeric)
> df2
#  ID 1 2 3 4 5
#1 1A 1 1 1 1 0
#2 2A 0 0 0 0 1

lapply is often quite useful if you want to apply a function to all columns of a data.frame or all elements in a list. For some more information check out ?lapply and this question.


text:
Q: Saving pictures in the a MySQL DB vs saving it as file I know this question was asked in various ways here, but none of the answer is conclusive.
I have a system which among other things updates a website gallery.
I can both "upload" the file to the website (and save a copy at the system - needed) or just save it in the DB and save the space (and another upload). If I go with the files I would need to "notify" the webpage of every change (picture delete, add or change) instead of just making the change in the DB.
So:

*

*If we are talking about a standard website with a  picture gallery, is it best to save the pictures as pictures or in the DB?

*If the webpage is very visited or very large, does it makes any difference?

Is the difference that significant? Or just go with the convenient way?
Although I presented my case I would like also to have a "more in general" answer, what is the "good" approach when talking about saving files.
Thanks in advance for clarifying it,
Michel.

A: Only put structured data in a DB. Images are files and should be kept on a files system. The performance of the DB will degrade more and more as the number of pictures / users grows. Instead create an image object which you can use to track the image location and meta data.

A: I have had the same problem with you in a previous project of mine.
I decided to go with only storing the path of the image in my database (which is just a string) and save the image in the file system, not in the DB.
This is the best practice in many ways.
It keeps your DB small, getting a large amount of rows is faster and DB back ups are significantly smaller.
Just put the images in a file and save the path in the DB so you can retrieve it later.


text:
Q: How to better position Next/Back button in shiny glide, in order to eliminate large white space? The Shinyglide package is just what I need, using a carousel for grouped radio buttons giving the user many choices for data parsing.
However, the "Next" (and "Back") button occupies a large white space. I'd like to shift the button in line with the glide row (see image at bottom). Does anyone know how to do this? Is there a CSS trick? Reading through the Glide manual, the only choices are "top" and "bottom".
If moving the Next/Back button isn't possible, a secondary option is to insert (a somewhat superfluous) line of text but in line with the Next/Back buttons, to at least cover up the annoyingly large white space.
The actual panel this is for has much more information presented than in this example, so I'm trying to make the page as clean as possible.
Please see image at bottom that better explains what I'm trying to do.
Reproducible example:
library(dplyr)
library(DT)
library(shiny)
library(shinyglide)

ui <-
  fluidPage(
    fluidRow(div(style = "margin-top:15px"),
      strong("Input choices shown in row below, click ´Next´ to see more choices:"),
        column(12, glide(
           height = "25",
           controls_position = "top",
           screen(
             div(style = "margin-top:10px"),
             wellPanel(
               radioButtons(inputId = 'group1',
                 label = NULL,
                 choiceNames = c('By period','By MOA'),
                 choiceValues = c('Period','MOA'),
                 selected = 'Period',
                 inline = TRUE
                 ),
               style = "padding-top: 12px; padding-bottom: 0px;"
               )
          ),
          screen(
            div(style = "margin-top:10px"),
            wellPanel(
              radioButtons(inputId = 'group2',
                label = NULL,
                choiceNames = c('Exclude CT','Include CT'),
                choiceValues = c('Exclude','Include'),
                selected = 'Exclude',
                inline = TRUE
                ),
             style = "padding-top: 12px; padding-bottom: 0px;"
             )
          )
         )
        )
      ),
    DTOutput("plants")
  )

server <- function(input, output, session) {
  output$plants <- renderDT({iris %>% datatable(rownames = FALSE)})
}

shinyApp(ui, server)

A: You could use a custom control element with custom_controls, and then have it hover over the displayed screen on the top right with a container set to absolute positioning. Setting a limited width for the container will ensure that the back button won't fly too far out.
Something along these lines:
glide(custom_controls = div(class = "glide-controls", glideControls()), ...)

# Somewhere in the UI
tags$style(
  ".glide-controls { position: absolute; top: 18px; right: 15px; width: 160px; }"
)

Just make sure to also set controls_position = "bottom" so that the controls hover over the screen content, rather than under it.
A minimal example app:
library(shiny)
library(shinyglide)

ui <- fixedPage(
  h3("Simple shinyglide app"),
  tags$style(
    ".glide-controls { position: absolute; top: 18px; right: 15px; width: 160px; }"
  ),
  glide(
    custom_controls = div(class = "glide-controls", glideControls()),
    screen(wellPanel(p("First screen."))),
    screen(wellPanel(p("Second screen.")))
  )
)

server <- function(input, output, session) {}

shinyApp(ui, server)


text:
Q: How to find high power numbers modulo How can I find high power number modulo number. What If I have to do it with the calculator or if the calculator is not allowed in exam.
For example:
$174^{55} \pmod {221} \equiv 47$

A: Some of the useful tools to do this are

*

*Fermat's little theorem (special case of below)

*Euler's totient theorem (general case of above)

*Repeated squaring, i.e., $a \equiv b \pmod{n} \implies a^n \equiv b^n \pmod{n}$. You can do this more efficiently by exponentiation by squaring.

*Aryabhatta's remainder theorem
For the specific problem, note that $221 = 13 \times 17$. From Fermat's little theorem, we have
$$174^{12} \equiv 1\pmod{13} \text{ and }174^{16} \equiv 1\pmod{17}$$
Hence,
$$174^{48} \equiv 1 \pmod{13} \text{ and }174^{48} \equiv 1 \pmod{17}$$
Further,
$$174 \equiv 5\pmod{13} \implies 174^2 \equiv -1\pmod{13} \implies 174^7  \equiv 8\pmod{13}$$
$$174 \equiv 4\pmod{17} \implies 174^2 \equiv -1\pmod{17} \implies 174^7  \equiv 13\pmod{17}$$
This gives us that
$$174^{55} \equiv 8 \pmod{13} \text{ and }174^{55} \equiv 13 \pmod{17}$$
Now use Aryabhatta's remainder theorem to conclude that $$174^{55} \equiv 47 \pmod{221}$$

A: I'll add an example of fast exponentiation at it can be programmed on a hand-held calculator.
A pseudo-code is this:
Input: $a, n, k, m$: integers;
Output: $P=a^n\mod m$
$k:=n$; $P:=1$;
Repeat
If $k$ is odd then $P:= P*a\,$; endif
$a:=a^2$; $k:=\Bigl\lfloor\dfrac k2\Bigr\rfloor$
until $k=1$.
Here is a example with $a=174$, $n=55$, $m=211$ (which is prime):
$$\begin{array}{rrcr}
n&P&&a^k\\
\hline
55&174&\times&103\\
27&198&\times&59\\
13&77&&105\\
6&77&\times&53\\
3&72&\times&66\\
1&\color{red}{110}\\
\hline
\end{array}$$


text:
Q: Javascript: Catch and prevent duplicate row entry in HTML table I currently have two tables on my page, I can now add records from table 1 to table 2 but I want to add condition that will check if that new record is already exist on my table2. Here is my tables:

                    ID Number
                    Name

                        ID Number
                        Name
                        Action

Here's my javascript to add the new record and need validation here to avoid duplicate using id as its unique value:
function AddRecord(that, id, name) {

        var table = document.getElementById("table2");

        var row = table.insertRow(1);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);

        cell1.innerHTML = id;
        cell2.innerHTML = name;

Any suggestions/comments TIA.

A: This could be achieved by:

*

*first iterating the tr row elements of table2 where, for each iteration

*you check the innerHTML value of td cell elements on the current row to see if they match your input arguments and,

*if a match is detected, early exit from the AddRecord() function via a return statement

There are many few ways this can be implemented. One option is to use the querySelector() method to extract the tr elements for iteration, and the specific td elements for comparison as follows:

function AddRecord(that, id, name) {

  var table = document.getElementById("table2");

  /*
  Extract and iterate rows from tbody of table2
  */
  for(const tr of table.querySelectorAll("tbody tr")) {

    /*
    Extract first and second cell from this row
    */
    const td0 = tr.querySelector("td:nth-child(1)");
    const td1 = tr.querySelector("td:nth-child(2)");

    /*
    If this row has missing cells, skip it
    */
    if(!td0 || !td1) {
      continue;
    }

    /*
    Check if cells of existing tr row contain same contents
    as input arguments. Note also the use of == rather than
    the use of === to allow type coercion when comparing
    number id with string id.
    */
    if ((td0.innerHTML == id) && (td1.innerHTML == name)) {

      console.log(`Match found for ${id} and ${name}. Insert rejected`);
      return;
    }
  }

  var row = table.insertRow(1);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);

  cell1.innerHTML = id;
  cell2.innerHTML = name;
}

AddRecord('', 1, 'bob')
AddRecord('', 2, 'jon')
AddRecord('', 1, 'bob') // Should fail to insert
AddRecord('', 3, 'jon')
AddRecord('', 2, 'jon') // Should fail to insert

          ID Number
          Name
          Action

Hope this helps!

A: I have a function attached to a click event to add a row into a table, part of its implementation is this:
    var cartTotal = $('#cart_total').val();
    var cartDiscount = $('#cart_discount').val();
    var cartType = $('input[name="cart_type"]:checked').val();
    var cartTypeLabel = (
        cartType == 0 ? 'percentage' : 'fixed amount'
    );
    var duplicatedRow = false;

    $('#discount_rules_table tr').each(function (index, tr) {
        //if it is not the header row
        if(index!==0) {
            var tds = $(tr).find("td");
            if(duplicatedRow){
                return;
            } else {
                duplicatedRow = (
                    tds[0].innerHTML == cartTotal
                    && tds[1].innerHTML == cartDiscount
                    && tds[2].innerHTML.toLowerCase() == cartTypeLabel.toLowerCase()
                );
            }
        }
    });

    if(duplicatedRow) {
        return;
    }
    //...

With above code, I can avoid duplicated rows.


text:
Q: In shapeless, have two lists such that one contains typeclasses of the other In shapeless I'm trying to write a function such that takes two HLists l1 and l2 of arbitrary length which exhibit the following properties:

*

*Length of l1 and l2 are the same.

*l2 contains the exact types of l1, wrapped in a constant outer type constructor.

So, if l1 was
1 :: 1.2 :: "hello" :: HNil`

l2 could be
Ordering[Int] :: Ordering[Double] :: Ordering[String] :: HNil

Using UnaryTCConstraint and LengthAux lets me constrain the lengths and require a static outer constructor for l2, however having them conform has become a problem.
Any ideas on how I could go about it?

A: Mapped provides precisely this constraint without the additional need for Length. From the documentation:

Type class witnessing that the result of wrapping each element of
  HList L in type constructor F is Out.

Here's how it looks in 1.2.4:
import shapeless._

def foo[L1 <: HList, L2 <: HList](l1: L1, l2: L2)(implicit
  ev: MappedAux[L1, Ordering, L2]
) = ()

val l1 = 1 :: 1.2 :: "hello" :: HNil
val l2 = Ordering[Int] :: Ordering[Double] :: Ordering[String] :: HNil
val l3 = Ordering[Int] :: Ordering[Double] :: Ordering[Char] :: HNil

And then:
scala> foo(l1, l2)

scala> foo(l1, l3)
<console>:17: error: could not find implicit value for parameter ev: ...

As expected. For 2.0 just add a shapeless.ops.hlist._ import and replace MappedAux with Mapped.Aux and you're ready to go.


text:
Q: MySql and creating Foreign keys     -- MySQL Script generated by MySQL Workbench
-- Sun Apr  2 17:50:54 2017
-- Model: New Model    Version: 1.0
-- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

-- -----------------------------------------------------
-- Schema SintalDB
-- -----------------------------------------------------

-- -----------------------------------------------------
-- Schema SintalDB
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `SintalDB` DEFAULT CHARACTER SET utf8 COLLATE utf8_slovenian_ci ;
USE `SintalDB` ;

-- -----------------------------------------------------
-- Table `SintalDB`.`User`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`User` (
  `PK_User` INT NOT NULL,
  `Name` VARCHAR(15) NOT NULL,
  `Surname` VARCHAR(25) NOT NULL,
  `Phone_Nr` VARCHAR(13) NOT NULL,
  `Email` VARCHAR(90) NOT NULL,
  `Car_Reg_Nr` VARCHAR(10) NULL,
  `Username` VARCHAR(20) NOT NULL,
  `Password` VARCHAR(20) NOT NULL,
  `Servis_Input_Rights` TINYINT(1) NOT NULL,
  `Servis_Output_Rights` TINYINT(1) NOT NULL,
  `Servis_Delete_Rights` TINYINT(1) NOT NULL,
  `Admin_Rights` TINYINT(1) NOT NULL,
  PRIMARY KEY (`PK_User`))
ENGINE = InnoDB
AUTO_INCREMENT = 1
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

-- -----------------------------------------------------
-- Table `SintalDB`.`City`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`City` (
  `PK_City` INT NOT NULL,
  `Name` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`PK_City`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

-- -----------------------------------------------------
-- Table `SintalDB`.`Company`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`Company` (
  `PK_Company` INT NOT NULL,
  `Name` VARCHAR(25) NOT NULL,
  `Address` VARCHAR(45) NOT NULL,
  `Address_Nr` VARCHAR(4) NOT NULL,
  `FK_City` INT NOT NULL,
  PRIMARY KEY (`PK_Company`),
  INDEX `FK_City_Company_fkn_idx` (`FK_City` ASC),
  CONSTRAINT `FK_City_Company_fkn`
    FOREIGN KEY (`FK_City`)
    REFERENCES `SintalDB`.`City` (`PK_City`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

-- -----------------------------------------------------
-- Table `SintalDB`.`Facility`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`Facility` (
  `PK_Facility_AD` VARCHAR(6) NOT NULL,
  `Name` VARCHAR(60) NOT NULL,
  `Address` VARCHAR(45) NOT NULL,
  `Address_Nr` VARCHAR(4) NOT NULL,
  `FK_City` INT NOT NULL,
  `FK_Company_Affiliation` INT NOT NULL,
  PRIMARY KEY (`PK_Facility_AD`),
  INDEX `FK_City_Facility_fkn_idx` (`FK_City` ASC),
  INDEX `FK_Company_Affiliation_Facility_fkn_idx` (`FK_Company_Affiliation` ASC),
  CONSTRAINT `FK_City_Facility_fkn`
    FOREIGN KEY (`FK_City`)
    REFERENCES `SintalDB`.`City` (`PK_City`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_Company_Affiliation_Facility_fkn`
    FOREIGN KEY (`FK_Company_Affiliation`)
    REFERENCES `SintalDB`.`Company` (`PK_Company`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

-- -----------------------------------------------------
-- Table `SintalDB`.`Servis`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`Servis` (
  `PK_Servis_Nr` VARCHAR(11) NOT NULL,
  `FK_Facility_AD` VARCHAR(6) NOT NULL,
  `Description` VARCHAR(255) NOT NULL,
  `Date_Recived` DATETIME NOT NULL,
  `FK_User_Commited` INT NULL,
  `Date_Commited` DATETIME NULL,
  `FK_User_Done` INT NULL,
  `Date_Done` DATETIME NULL,
  PRIMARY KEY (`PK_Servis_Nr`),
  INDEX `FK_User_Servis_fkn_idx` (`FK_User_Commited` ASC, `FK_User_Done` ASC),
  INDEX `FK_Facility_Servis_fkn_idx` (`FK_Facility_AD` ASC),
  CONSTRAINT `FK_User_Servis_fkn`
    FOREIGN KEY (`FK_User_Commited` , `FK_User_Done`)
    REFERENCES `SintalDB`.`User` (`PK_User` , `PK_User`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_Facility_Servis_fkn`
    FOREIGN KEY (`FK_Facility_AD`)
    REFERENCES `SintalDB`.`Facility` (`PK_Facility_AD`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

-- -----------------------------------------------------
-- Table `SintalDB`.`ServisNote`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`ServisNote` (
  `PK_ServisNote` INT NOT NULL,
  `Note` VARCHAR(255) NOT NULL,
  `FK_User_Note` INT NOT NULL,
  `Date_Created` DATETIME NOT NULL,
  `FK_Servis_Nr` VARCHAR(11) NOT NULL,
  PRIMARY KEY (`PK_ServisNote`),
  INDEX `FK_Servis_ServisNote_fkn_idx` (`FK_Servis_Nr` ASC),
  INDEX `FK_User_ServisNote_fkn_idx` (`FK_User_Note` ASC),
  CONSTRAINT `FK_Servis_ServisNote_fkn`
    FOREIGN KEY (`FK_Servis_Nr`)
    REFERENCES `SintalDB`.`Servis` (`PK_Servis_Nr`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_User_ServisNote_fkn`
    FOREIGN KEY (`FK_User_Note`)
    REFERENCES `SintalDB`.`User` (`PK_User`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

this is my sql file and I get error after i run sql file
Error Code: 1215. Cannot add foreign key constraint

17:52:08  CREATE TABLE IF NOT EXISTS SintalDB.Servis (
PK_Servis_Nr VARCHAR(11) NOT NULL,   FK_Facility_AD VARCHAR(6) NOT
  NULL,   Description VARCHAR(255) NOT NULL,   Date_Recived DATETIME
  NOT NULL,   FK_User_Commited INT NULL,   Date_Commited DATETIME
  NULL,   FK_User_Done INT NULL,   Date_Done DATETIME NULL,
  PRIMARY KEY (PK_Servis_Nr),   INDEX FK_User_Servis_fkn_idx
  (FK_User_Commited ASC, FK_User_Done ASC),   INDEX
  FK_Facility_Servis_fkn_idx (FK_Facility_AD ASC),   CONSTRAINT
  FK_User_Servis_fkn     FOREIGN KEY (FK_User_Commited ,
  FK_User_Done)     REFERENCES SintalDB.User (PK_User ,
  PK_User)     ON DELETE NO ACTION     ON UPDATE NO ACTION,
  CONSTRAINT FK_Facility_Servis_fkn     FOREIGN KEY (FK_Facility_AD)
  REFERENCES SintalDB.Facility (PK_Facility_AD)     ON DELETE NO
  ACTION     ON UPDATE NO ACTION) ENGINE = InnoDB DEFAULT CHARACTER SET
  = utf8 COLLATE = utf8_slovenian_ci    Error Code: 1215. Cannot add foreign key constraint 0.063 sec

A: Check this: Adding foreign key on multiple columns
I think you must add two foreign key for made reference to the same column.
You can replace your code for this and test.
-- -----------------------------------------------------
-- Table `SintalDB`.`Servis`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`Servis` (
  `PK_Servis_Nr` VARCHAR(11) NOT NULL,
  `FK_Facility_AD` VARCHAR(6) NOT NULL,
  `Description` VARCHAR(255) NOT NULL,
  `Date_Recived` DATETIME NOT NULL,
  `FK_User_Commited` INT NULL,
  `Date_Commited` DATETIME NULL,
  `FK_User_Done` INT NULL,
  `Date_Done` DATETIME NULL,
  PRIMARY KEY (`PK_Servis_Nr`),
  INDEX `FK_User_Servis_fkn_idx` (`FK_User_Commited` ASC, `FK_User_Done` ASC),
  INDEX `FK_Facility_Servis_fkn_idx` (`FK_Facility_AD` ASC),
  CONSTRAINT `FK_User_Servis_fkn`
    FOREIGN KEY (`FK_User_Commited`)
    REFERENCES `SintalDB`.`User` (`PK_User` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_User_Servis_2_fkn`
    FOREIGN KEY (`FK_User_Done`)
    REFERENCES `SintalDB`.`User` (`PK_User`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_Facility_Servis_fkn`
    FOREIGN KEY (`FK_Facility_AD`)
    REFERENCES `SintalDB`.`Facility` (`PK_Facility_AD`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;


text:
Q: 3D to 2D projection I'm trying to write a game in Java (Processing, actually) with some cool 3D effects.
I have a choice of two 3D renderers, but neither have the quality or flexibility of the default renderer. I was thinking that if I could get a function to proje
So say I have a set of coordinates (x, y, z) floating in 3D space. How would I get where on the 2D screen that point should be drawn (perspective)?
Just to clarify, I need only the bare minimum (not taking the position of the camera into account, I can get that effect just by offsetting the points) - I'm not re-writing OpenGL.
And yes, I see that there are many other questions on this - but none of them seem to really have a definitive answer.

A: Here is your bare minimum.
column = X*focal/Z + width/2
row = -Y*focal/Z  + height/2

The notation is:
X, Y, Z are 3D coordinates in distance units such as mm or meters;
focal is a focal length of the camera in pixels (focal= 500 for VGA resolution is a reasonable choice since it will generate a field of view about 60 deg; if you have a larger image size scale your focal length proportionally); note that physically focal~1cm << Z, which simplifies formulas presented in the previous answer.
height and width are the dimensions of the image or sensor in pixels;
row, column - are image pixels coordinates (note: row starts on top and goes down, while Y goes up). This is a standard set of coordinate systems centered on camera center (for X, Y, Z) and on the upper-left image corner (for row, column, see green lines).

You don't need to use OpenGL indeed since these formulas are easy to implement. But there will be some side-effects such as whenever your object has several surfaces they won't display correctly since you have no way to simulate occlusions. Thus you can add a depth buffer which is a simple 2D array with float Z values that keeps track which pixels are closer and which are further; if there is an attempt to write more than once at the same projected location, the closer pixel always wins. Good luck.

A: Look into Pin hole camera model
http://en.wikipedia.org/wiki/Pinhole_camera_model
ProjectedX = WorldX * D / ( D + worldZ )
ProjectedY = WorldY * D / ( D + worldZ )
where D is the distance between the projection plane and eye


text:
Q: Rails include page How would I include a page from the public folder in one of my views? I want to include a single header like I do in PHP so when I make a change it affects all the other pages. (It is for multiple views)

A: For the most part, the only web pages in the public folder will be purely static (custom 404 pages, FAQ, etc).  If you have a piece of static HTML that you'd like to be displayed in a lot of pages, a partial is what you're looking for.
A partial doesn't have to be tied to a controller.  You can create the sub-directory:
/views/static

and fill it with a whole bunch of partials, so you would have:
/views/static/_my_first_partial.html.erb
/views/static/_my_second_partial.html.erb

and anywhere you want those fragments, you can do:
render :partial => "static/my_first_partial"

and voila, you're done!

A: I'm pretty new to rails, but I guess for such task you would use Layouts:
Layouts and Rendering


text:
Q: Get total price and quantity of items sold with price changes I have these tables:

*

*items ( pk:id | Name )

*priceChanges( pk:id | fk:item_id | price | fromDate | toDate )

*request( pk:id | deliveryDate)

*requested_category( pk:id | assigned_quantity | fk:item_id | fk:request_id )

The PriceChanges table keep track of the price's change of every item.
I want to get the items sold between two dates with the total income (price*quantity) for ech item, while the quantity is the total count of ths item sold with the same price in the period (without the item's price change).
That means that whenever the price for a change i get a new row with the total count of items sold with the new price.
Here is an exemple of the desired output :

id      Name      sold    price     total
------  -------   -----   ------    ------
8P01    51645A    3       1,20      3,60
8P01    51645A    1       2,82      2,82
8P01    51645A    5       2,50      12,50

i have tried this SQL command, but i can't stop getting too many duplicated row :
SELECT
i.id,
i.name,
sum(rc.assigned_quantity) AS assigned_quantity,
pc.price,
pc.price * sum(rc.assigned_quantity) as total
FROM requested_category rc
LEFT JOIN items i ON rc.item_id = i.id
LEFT JOIN request r ON rc.request_id = r.id
LEFT JOIN priceChanges pc ON pc.item_id = i.id
WHERE
r.delivery_date BETWEEN 'startDate' AND 'endDate'
GROUP BY i.id, i.name, pc.price

the result that i get:

id      Name      sold    price     total
------  -------   -----   ------    ------
8P01    51645A    3       1,20      3,60
8P01    51645A    1       1,20      1,20
8P01    51645A    5       1,20      6,00
8P01    51645A    3       2,82      7,86
8P01    51645A    1       2,82      2,82
8P01    51645A    5       2,82      12,10
8P01    51645A    3       2,50      7,50
8P01    51645A    1       2,50      2,50
8P01    51645A    5       2,50      12,50

I tried as requested in comments below the follow query:
SELECT i.id, i.name, rc.assigned_quantity, pc.price
FROM requested_category rc
LEFT JOIN items i ON rc.item_id = i.id
LEFT JOIN request r ON rc.request_id = r.id
LEFT JOIN priceChanges pc ON pc.item_id = i.id
WHERE r.delivery_date BETWEEN 'startDate' AND 'endDate'

I get this result:

 id     name   assigned_quantity    price
8P01    51645A 1                    1.20
8P01    51645A 1                    2.82
8P01    51645A 1                    2.50
8P01    51645A 3                    1.20
8P01    51645A 3                    2.82
8P01    51645A 3                    2.50
8P01    51645A 5                    1.20
8P01    51645A 5                    2.82
8P01    51645A 5                    2.50

Thank you

A: I came back with the solution I used.
In my application, I use Symfony Framewok and Doctine Framework to handle the database.
i'm not a DBAdmin, but I think that this solution can be achieved by database triggers as well. In this case, I chose the applicatif approach because I used Top-Down design.
The business logic behind the need is trying to get the store output reporting (items*price per period) knowing that the price is fixed at the item's importation time.
I used the Entity Listener that watches for any change in items price. Whenever there is a change, I log the (price, quantity, start date,end date)
And when the reported is generated, I simply match the period with items price change and multiply it with the quantity that is logged in the same database entry.
Hope I helped someone.


text:
Q: What technologies of Spring Framework do we use for creating real Enterprise applications? I am new to Java EE (rather enterprise application development) and initially i started off with EJB. After a while, and based on some research i decided to learn (and eventually to work) using Spring Framework.
I now spent almost 2 months in learning Spring framework (using materials in internet and some books) and i have fair understanding of Core Spring (Like DI, AOP etc.). I have worked on a full scale enterprise application (bug fixing project) for 2-3 months and in that project we used: EJB 3.x along with other technologies.
Using Spring Framework, it has MVC support (web-applications). I am having difficulty in understanding for some of the things as to how it is done using Spring Framework, which i have listed below and it would help me if you spare your valuable time to share your inputs:
1) Full-blown Enterprise applications typically use Application servers (like JBOSS or alike), it is possible to have a spring application which is deployed in Apache tomcat  only and in terms of functionality equal to full-blown Java EE application?
2) I read Spring framework simplifies the work which is achieved by EJB (in a typical Java EE application) and without using Application server, if this is true, then the above point should be true? Is my understanding correct here?
3) Like Business is implemented in EJBs (mainly in Session EJBs), what is the equivalent we have in Spring?
And finally, for writing a complex real time Enterprise application, what spring technologies / sub-project are needed to learn?

A: Fist of all, Spring is not a Java EE  application server.  Spring is only a framework which allows 3 things basically: dependency injection, proxies and Java EE abstractions.
1) Tomcat is not a Full Java EE Compliant Server and you cannot "complete" server with Spring.
2) Spring can simplify Java EE Clients development without an Application Client environment, for example using the SimpleRemoteStatelessSessionProxyFactoryBean to access EJB clients.
3) Spring supports exporting beans for communication in a client-server architecture, using Hessian or Burlap exporter for example.
Last, I've never used any realtime library.

A: Wow, the answer to this question could lead to multiple books and several flame wars, but I try myself to keep it civil.
1) Yes and no. A short comparison of Spring and Java EE
Short: As long as you are not afraid of using parts of the Java EE stack like JPA or JSF (if you need those), and you don't need real JTA transaction handling against multiple datasources and you don't need any other advanced stuff from Java EE, Spring + ORM Framework + Webframework on Tomcat is as powerful as Java EE  on an full-blown Application Server.
To break things up a little:

*

*Springs Core DI container is on par with the different CDI implementations

*Springs own persistence framework (Spring JDBC) is less powerfull than the JPA Standard, however you easily can use any even a container managed JPA

*Springs MVC framework is more a low-level framework than the JSF standard, however you can easily use that one as well

*Springs MVC framework is also well suited for REST apps, about on the same level as the JAX-RS standard

So you can mix and match it as you like, one of the good things about Spring is, that is has nearly no "vendor tie in" regarding third party libraries, and no one forces you to use a part that you don't need or don't like.
2) It has been true up until the more recent Java EE standards, however nowadays with CDI, I'd say Java EE has caught up and developing Java EE Apps is as simple.
3) A simple singleton bean. Probably with a Transactional annotation.

A:
1) Full-blown Enterprise applications typically use Application
  servers (like JBOSS or alike), it is possible to have a spring
  application which is deployed in Apache tomcat only and in terms of
  functionality equal to full-blown Java EE application?

Correct, Jboss, Weblogic, Websphere are some of the most widely used application servers in the market. These servers are required if you need EJB (Session Beans, Entity Beans, Message Driven Beans), Messaging, RMI and other middleware support. Remember Tomcat, Jetty etc (http://java-source.net/open-source/web-servers) are webservers. So you have to decide if you need a App server or a Webserver completely based on your business requirement

2) I read Spring framework simplifies the work which is achieved by
  EJB (in a typical Java EE application) and without using Application
  server, if this is true, then the above point should be true? Is my
  understanding correct here?

Nothing is easy in this world ;). Spring supports Transaction Management, Persistance, Security and other features that were only available for EJB's. Moreover Spring provides other benefits like AOP, DI etc.

3) Like Business is implemented in EJBs (mainly in Session EJBs), what
  is the equivalent we have in Spring?

You have @Service in Spring. The class containing your business code can be specifically annotated with @Service or generally with @Component


text:
Q: Why tensor flow could not load csv I just installed tensor flow using pip and I try to run the following tutorial:
https://www.tensorflow.org/versions/r0.11/tutorials/tflearn/index.html
# Data sets
IRIS_TRAINING = "iris_training.csv"
IRIS_TEST = "iris_test.csv"

# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING,
                                                       target_dtype=np.int)
test_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TEST,
                                                   target_dtype=np.int)

But I have error:
    training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING,
AttributeError: 'module' object has no attribute 'load_csv'

I read some answer saying that I need to use pandas dataframe? But shouldn't everything just works as in the tutorial? That is so strange! I should not be the only one facing this issue right?
Here's the whole code as in the tutorial:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
import numpy as np

# Data sets
IRIS_TRAINING = "iris_training.csv"
IRIS_TEST = "iris_test.csv"

# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING,
                                                       target_dtype=np.int)
test_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TEST,
                                                   target_dtype=np.int)

# Specify that all features have real-value data
feature_columns = [tf.contrib.layers.real_valued_column("", dimension=4)]

# Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
                                            hidden_units=[10, 20, 10],
                                            n_classes=3,
                                            model_dir="/tmp/iris_model")

# Fit model.
classifier.fit(x=training_set.data,
               y=training_set.target,
               steps=2000)

# Evaluate accuracy.
accuracy_score = classifier.evaluate(x=test_set.data,
                                     y=test_set.target)["accuracy"]
print('Accuracy: {0:f}'.format(accuracy_score))

# Classify two new flower samples.
new_samples = np.array(
    [[6.4, 3.2, 4.5, 1.5], [5.8, 3.1, 5.0, 1.7]], dtype=float)
y = classifier.predict(new_samples)
print('Predictions: {}'.format(str(y)))

A: The function tf.contrib.learn.datasets.base.load_csv() was removed in TensorFlow release 0.11. Depending on whether the file has a header or not (and the Iris dataset does have a header), the replacement functions are:

*

*tf.contrib.learn.datasets.base.load_csv_with_header()

*tf.contrib.learn.datasets.base.load_csv_without_header()

A: since my version is 11... They removed load_csv in 11 without changing the tutorial... I have to run version 0.10.0rc0 just to run the tutorial.

A: The library urllib have removed the method urlopen(), you should import urllib.request, then use the method urllib.request.urlopen().


text:
Q: Exception parsing json with System.Text.Json.Serialization My sample code is very simple:
using System.Text.Json.Serialization;
using Newtonsoft.Json;

public class C {
  public C(string PracticeName) { this.PracticeName = PracticeName; }
  public string PracticeName;
}

var x = new C("1");
var json = JsonConvert.SerializeObject(x); // returns "{\"PracticeName\":\"1\"}"

var x1 = JsonConvert.DeserializeObject<C>(json); // correctly builds a C

var x2 = System.Text.Json.Serialization.JsonSerializer.Parse<C>(json);

the last line raises:

Exception thrown: 'System.NullReferenceException' in System.Text.Json.dll
  Object reference not set to an instance of an object.

What am I doing wrong ?
(Note this is on latest .NET Core 3 preview 5 with latest System.Text.Json 4.6.0-preview6.19259.10)
Adding a parameterless constructor prevents the exception however I don't want/need a parameterless constructor and Json.Net parses fine without it.
Is there a way to make System.Text.Json parse using the given constructor like Json.Net does ?

A: PracticeName needs to be a property, not a field. Try that w/ the parameterless constructor.
I developed a quick console program class. The class C1 is converted via the Newtonsoft.Json package. The class C2 is parsed via the System.Text.Json package.
using Newtonsoft.Json;

namespace TestJsonParse
{
    class Program
    {
        static void Main(string[] args)
        {
            var c1 = new C1("1");
            var json1 = JsonConvert.SerializeObject(c1); // returns "{\"PracticeName\":\"1\"}"
            var x1 = JsonConvert.DeserializeObject<C1>(json1); // correctly builds a C1

            var c2 = new C2();
            string json2 = "{\"PracticeName\":\"1\"}";
            var x2 = System.Text.Json.Serialization.JsonSerializer.Parse<C2>(json2); // correctly builds a C2
        }

        class C1
        {
            public C1(string PracticeName) { this.PracticeName = PracticeName; }
            public string PracticeName;
        }

        class C2
        {
            public C2() { }
            public string PracticeName { get; set; }
        }
    }
}

A: In it's current state, JSON Support in .NET Core 3.0 is still not finished, and it seems only a parameterless constructor is supported. It might be, that that feature will be added in future.
One workaround option  would be to make a parameterless constructor for your serialized model, when you want to use the new Json API from the .net framework. Probably we shouldn't use constructors for plain datatransfer objects at all, hence I see it as option, not as a workaround.
If you search for a way, on how to migrate from an older version to .net core 3.0, or use Newtonsoft.Json anyway, this is documented here:
MVC:
Install Microsoft.AspNetCore.Mvc.NewtonsoftJson package, and register it to your services:
services.AddMvc().AddNewtonsoftJson();

SignalR:
Install Microsoft.AspNetCore.SignalR.Protocols.NewtonsoftJson package
//Client
new HubConnectionBuilder()
.WithUrl("/chatHub")
.AddNewtonsoftJsonProtocol(...)
.Build();

//Server
services.AddSignalR().AddNewtonsoftJsonProtocol(...);

That way you should* be able to use Json.NET Features in .Net Core 3.0
*I don't have installed it, so I can not test it

A: Json Support with System.Text.Json.Serialization is quite unstable. It is better to use NewtonSoft.Json as it is more stable and almost everyone uses that. If running a console app then from the folder in your terminal do
You are not required to specify the version though. If using visual studio then use Nuget package manager to install Newtonsoft.json.
To read json from a file for example data.json
{
  "Name":"Logan",
  "Age": 30
  "Books": ["Infinity War", "End Game"]
}

Specify your properties example
class Person
{
  public string Name{get; set;}
  public int Age{get; set;}
  public IList<string> Books{get; set;}
}

then from the class you wish to access the json data do the following
string fileContent = System.IO.File.ReadAllText(@"./data.json");
Person person = Newtonsoft.Json.JsonConverter.DeserializeObject<Person>(fileContent);

test it
Console.WriteLine($"Hi {person.Name} you are {person.Age} today read {person.Books[0]}");

For more info go to https://www.newtonsoft.com/json/help/html/DeserializeObject.htm


text:
Q: Prove that $A$ and $B$ are nilpotent - proof checking
Let $A$ and $B$ be $n \times n$ matrices with real entries and $c_1, c_2, \dots ,c_{n+1}$ distinct real numbers such that $A+c_1B, A+c_2B \dots, A+c_{n+1}B$ are nilpotent matrices. Prove that $A$ and $B$ are nilpotent.

Is my proof alright? This is my approach:
For $k$ chosen arbitrarily from $\{1,2, \dots, n\}$ define the polynomial :
$ P_k(x) = \operatorname{tr}[ (A+xB)^k]$.
Suppose that $P_k$ is not constant taking the value $0$.
$A+c_iB \text{ is nilpotent} \iff tr[ (A+c_iB)^k ] = 0 \forall k \in \mathbb{N}^* \text{ and } \forall i \in \{1,2,\dots, n+1\} \Rightarrow P_k(c_1) = P_k(c_2) = \cdots = P_k(c_{n+1}) = 0 \Rightarrow$
$$\operatorname{deg} P_k \geq n+1.$$
However the elements of $(A+xB)^k$ are polynomials in $x$ of degree at most $k$. So $$ \operatorname{deg} P_k \leq k. $$
But from these two statements $k \geq n+1$ which is a contradiction because we chose $ k \leq n$. So $P_k(x) = 0 \forall x \in \mathbb{R} $. That means that all of its coefficients are $0$. But, because $(A+xB)^k = x^k B^k + \dots + A^k$, the leading coefficient of $P_k$ is $\operatorname{tr} (B^k)$ and the constant term is $\operatorname{tr} (A^k) \Rightarrow \operatorname{tr} (A^k) = \operatorname{tr} (B^k) = 0 \forall k \in \mathbb\{1,2 \dots n\} \Rightarrow $ $$ A \text{ and } B \text{ are nilpotent} $$

A: Consider $(A+xB)^n$. This is a matrix where each element is a polynomial of degree at most $n$ in $x$. Furthermore, each of these polynomials is zero for $x=c_i, 1\le i \le n+1.$
Therefore each element is zero for all $x$. The value $x=0$ shows that $A$ is nilpotent.
Then $(B+xA)^n$ is zero for all non-zero $x$ and therefore zero for all $x$. Hence $B$ is also nilpotent.

A: Your proof is correct, but I would say that it is a bit difficult to follow at some points. Here's an edit of your proof that I would find easier to read.
Note that a matrix $M$ is nilpotent if and only if we have $\operatorname{tr}(M^k) = 0$ for $k = 1,\dots,n$. With that in mind: for $k = 1,2,\dots,n,$ define the polynomial $P_k(x) = \operatorname{tr}[ (A+xB)^k]$. Fix any such $k$.
Suppose that $P_k$ is not identitcally $0$. We note that because $A + c_i B$ is nilpotent for $i = 1,\dots,n+1$, we must have $P_k(c_i) = 0$ for all such $i$.  This means that $P_k(x)$ is a polynomial with degree $k \leq n$ with $n+1$ zeros.  However, if $P_k$ is not identitcally zero, then this is impossible.
So $P_k(x)$ is identitcally zero. That means that all of its coefficients are $0$. But, because $(A+xB)^k = x^k B^k + \dots + A^k$, the leading coefficient of $P_k$ is $\operatorname{tr} (B^k)$ and the constant term is $\operatorname{tr} (A^k).$ So, $\operatorname{tr} (A^k) = \operatorname{tr} (B^k) = 0$ for $k = 1,\dots,n$.
This implies that $A$ and $B$ are nilpotent, which was the desired conclusion.


text:
Q: Meteor Helpers - DOM Manipulation // Works
var counter = 0;
    var myInterval = Meteor.setInterval(function(){
      counter++;
      var time = moment().hour(0).minute(0).second(counter).format('HH:mm:ss');
      console.log(time);
    }, 1000);

// Inside Helper - Does Not Work

Template.clockRunner.helpers({
  start: function () {
    var counter = 0;
    var time = moment().hour(0).minute(0).second(counter).format('HH:mm:ss');
    var myInterval = Meteor.setInterval(function(){
      counter++
    }, 1000);
    return time;
  },
})

The first version console logs the time in increments of 1 second. The Helper version displays "00:00:00" in the DOM, but does not increment, if I console log the time in helper it logs "00:00:00" every second.
I'm not sure if I'm misunderstanding the reactive nature of helpers or if I'm not seeing a minor mistake. Thanks in advance!

A: a helper is meant to provide data to a Blaze template; it won't get called unless invoked from a template.
that said, you should think of a helper as something that only provides data, it shouldn't "do anything." as a template renders, and as reactive data is processed, a helper may get called several times in unexpected ways.
i reckon you want your timer to be started in the onRendered() method; that is called once as a template is put on the screen. (there's a corresponding method that's called when the template is taken off the screen, so the timer can be stopped).
once your timer is started, you can write timer data to a reactive variable, and then a helper that returns a formatted version of that timer data. because it's in a reactive var, that will ensure your helper is re-invoked each time the timer ticks.
the last part is simply ensuring the Blaze template references the helper.


text:
Q: How can I correlate events in a masstransit state machine without using a Guid? I have defined the following state machine in Masstransit:
public class OrderStateMachine : MassTransitStateMachine<OrderState>
{
    public OrderStateMachine()
    {
        InstanceState(x => x.Status);

        Event(() => OrderCreated, x => x.CorrelateBy(order => order.OrderCode, ctx => ctx.Message.OrderCode).SelectId(ctx => NewId.NextGuid()));

        //How should I select an id for these events?
        Event(() => OrderProvisioned, x => x.CorrelateBy(order => order.OrderCode, ctx => ctx.Message.OrderCode));
        Event(() => OrderInvoiced, x => x.CorrelateBy(order => order.OrderCode, ctx => ctx.Message.OrderCode));

        State(() => Created);
        State(() => Finished);

        CompositeEvent(() => OrderFinished, order => order.CompositeStatus, OrderProvisioned, OrderInvoiced);

        Initially(
            When(OrderCreated)
                .Then(context => Console.WriteLine("Order created"))
                .TransitionTo(Created));

        During(Created,
            When(OrderFinished)
                .Then(context => Console.WriteLine("Order finished"))
                .TransitionTo(Finished)
                .Finalize());

    }

    public State Created { get; set; }
    public State Finished { get; set; }

    public Event<OrderCreated> OrderCreated { get; set; }
    public Event<OrderProvisioned> OrderProvisioned { get; set; }
    public Event<OrderInvoiced> OrderInvoiced { get; set; }
    public Event OrderFinished { get; set; }

}

public class OrderState : SagaStateMachineInstance
{
    public Guid CorrelationId { get; set; }

    public string OrderCode { get; set; }
    public string Status { get; set; }
    public CompositeEventStatus CompositeStatus { get; set; }

}

public class OrderCreated
{
    public string OrderCode { get; set; }

    public OrderCreated(string orderCode)
    {
        OrderCode = orderCode;
    }
}

public class OrderInvoiced
{
    public string OrderCode { get; set; }

    public OrderInvoiced(string orderCode)
    {
        OrderCode = orderCode;
    }

}

public class OrderProvisioned
{
    public string OrderCode { get; set; }

    public OrderProvisioned(string orderCode)
    {
        OrderCode = orderCode;
    }
}

How can I correlate the OrderProvisoned and the OrderInvoiced event to the same OrderState instance as the initial OrderCreated event without sending Guids in my events and only use the ordercode property to correlate them?
If I run this example, I never get the OrderFinished event if both OrderProvisioned and OrderInvoiced are sent, but if I add Guids to the events and correlate them based on that Guid it is executed correctly.

A: I solved it, apparently you must explicitly set the custom correlationid on the statemachine instance, I would expect that masstransit would do that for me.
So this is the adapted code for the initial state:
            Initially(
            When(OrderCreated)
                .Then(context => context.Instance.OrderCode = context.Data.OrderCode)
                .Then(context => Console.WriteLine("Order created"))
                .TransitionTo(Created));

Also using a saga factory works, but I would think that you could drop the selectid logic as the saga factory overrules this, but than I get an exception.
        Event(() => OrderCreated,
            x =>
            {
                x.CorrelateBy(order => order.OrderCode, ctx => ctx.Message.OrderCode);
                x.InsertOnInitial = true;
                x.SetSagaFactory(context => new OrderState
                {
                    CorrelationId = NewId.NextGuid(),
                    OrderCode = context.Message.OrderCode
                });
                x.SelectId(context => NewId.NextGuid());
            });

A: Is there a broken unit test that would be usable to see if this behavior is not working? From the edited code above, that seems to be how I would expect it to be correlated - using the OrderCode. That's how the shopping cart example works as well.
The SelectId() function is only needed for an event that initiates the state machine, since that is where the CorrelationId is assigned. If it isn't used by the other events, there is no need to "select" it since the Query (the orderCode) would do the correlation.
That's how the shopping cart example works in the sample:
https://github.com/MassTransit/Sample-ShoppingWeb/blob/master/src/CartTracking/ShoppingCartStateMachine.cs#L15
In your example above:
Event(() => OrderCreated, x => x.CorrelateBy(order => order.OrderCode, ctx => ctx.Message.OrderCode).SelectId(ctx => NewId.NextGuid()));

Event(() => OrderProvisioned, x => x.CorrelateBy(order => order.OrderCode, ctx => ctx.Message.OrderCode));
Event(() => OrderInvoiced, x => x.CorrelateBy(order => order.OrderCode, ctx => ctx.Message.OrderCode));

This is exactly how I would configure it, and it seems like you're on the right track.


text:
Q: How to get the filed data form json file? This code are successful to get the "version" and "shapes" data. (for i in data.get("shapes"):)
but when i swtch "shapes" to  the "label" ,the problme come
TypeError: 'NoneType' object is not iterable
Thanks help.
{
  "version": "4.5.7",
  "flags": {},
  "shapes": [
  {
    "label": "2",
    "points": [
      [
        602.8,
        590.2
      ],
      [
        610.3,
        642.0
      ]
    ]
  }
],
"imagePath": "ladybug_13451176_20200410_141545_ColorProcessed_000497_Cam0_20059_026-2678.png",
"imageWidth": 1024
}

import json
import jsonpath
import io

with open("B123.json", mode="r") as dict:
  data = json.load(dict)
  for i in data.get("shapes"):
    print(i,end="")

A: data is of type dict. Calling dict.get() would either return the value (if present) or None (if not present).
So if your data varies and might have no defined "shapes", don't just iterate over it as you could be iterating on a None object. So replace this:
for i in data.get("shapes"):

Instead, put a check first.
if "shapes" in data:
    for i in data.get("shapes"):

Or better yet maximize the or operation which continues to the next if the previous has a false value.
for i in data.get("shapes") or []:

A: Because "shape" is a list of dict, you cabiterate it. But label is inside shapes dict, you can't just replace "shapes" by "label", also when you will have obtained the contents of label, you still won't be able to iterate it because the value of key label is not a list or dict


text:
Q: java unit test with selenium getting nullpointer exception for @inject function I am trying to unit test Sign On method in selenium. My Sign On method is injecting other pages which is taking webdriver in turn.
SignOn.java
import ...

@PageObject
public class SignOn {

@Inject
BasePage basepage

public void signOn(driver,user,password){
    basepage.clickhamburgermenu() #This line is not instantiated when
    unit testing but works fine when just running this file.

}
BasePage.java
import ...

public class BasePage {

Map<String, String> data;
WebDriver driver;

@Inject
public BasePage(WebDriver driver) {
    this.driver = driver;
    PageFactory.initElements(driver, this);
}

public void clickHamburgerMenu() {
    if(driver.findElements(By.cssSelector(hamburgerMenu)).size() > 0)
    {
        WebElement burgerMenu = driver.findElement(By.cssSelector(hamburgerMenu));
        if(burgerMenu.isDisplayed()){burgerMenu.click();}
    }
}

SignOntest.java
import ...

public class signOnTest{

@BeforeMethod
public void setUp() {
    webDriver = new ChromeDriver();
signOn = new SignOn();
}

@Test
public void testSignOn() {
    webDriver.get("www.facebook.com");
    SignOn.SignOn(webDriver,"user","password");
    }

}

Here, I wanna unit test sign-on method but it fails on basepage initiation. I am not that pro in dependency injection. Anything helps.


text:
Q: How to make a certain View in MVC not inherit _Layout.cshtml? I'm using ASP.NET MVC5, razor syntax.  I need a specific "Create" view to NOT inherit the _Layout.cshtml Shared View.
Basically, in this particular View, I don't want any of the _Layout.cshtml features like the navigation menu, footer, etc.

A: Use.
@{
    Layout = null
}

In whatever .cshtml file you don't want to inherit the _layout.cshtml

A: It inherits Layout because of your _ViewStart.cshtml file. Look at your ViewStart and delete related line. Then if you want to use Layout in your page you have to specify your Layout in each page.


text:
Q: using OR in an argument to a method How can I include multiple terms as a single arguments to a method?
For example:
method is declared as follows:
 public void showSchedules(String day, String AMPM);

I want to call something like
showSchedules ("Monday" || "Tuesday", AM);

but the operators cannot be applied to java lang String.
Any tips?

A: What you are suggesting is not possible. The || operator in Java is a logical (boolean) operator. It evaluates the boolean expressions on either side (if necessary) and returns a boolean value. So your suggestion will never work since the expressions on each side are Strings and not booleans.
You have three options here:

*

*Pass each argument individually into the method, or if you don't know how many there will be pass them in an array or some other collection.

showSchedules("Monday", "Tuesday", AM) {...}
or
showSchedules(new String[] {"Monday", "Tuesday"}, AM) {...}

*Call the method twice, passing in one argument each time and then deal with the results in the calling method.

*Invert the order of params and use varargs:
showSchedules(String AmPm, String... days) {...}

A: No. You cannot do that in passing arguments. However you can only control the functionality.
For ex
public void showSchedules(String day, String AMPM) {
    if (day.equals("Monday") ||  day.equals("Tuesday") ) {
       //TODO
    }

  }

A: You can totally do that with an varargs, like so:
day will be an array of strings and you can pass as many as you want
public void showSchedules(String AMPM, String... day) {
    // you'll have to iterate through them here
    for(String d:day)
{
  switch(d)
    {
        case "Monday":
        break;
        case "Tuesday":
        break;
    }
}

}


text:
Q: If clause with "? :"
Possible Duplicate:
Nullable types and the ternary operator: why is `? 10 : null` forbidden?

I want to assign a value or null value to x (which is a nullable integer) according to a case (you can see below)
int? x;
x = stackoverflow.ToString() != "" ? int.Parse(stackoverflow.ToString()) : null;

But it gives below error.
Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'

Why?

A: Cast the int to a nullable int.
x = stackoverflow.ToString() != "" ?
       (int?)int.Parse(stackoverflow.ToString()) : null;

A: try this:
x = stackoverflow.ToString() != "" ? int.Parse(stackoverflow.ToString()) : (int?) null;

and see if that works. I didn't test it since I don't know what stackoverflow is supposed to be