text:
Q: image focus calculation I'm trying to develop an image focusing algorithm for some test automation work. I've chosen to use AForge.net, since it seems like a nice mature .net friendly system.
Unfortunately, I can't seem to find information on building autofocus algorithms from scratch, so I've given it my best try:
take image. apply sobel edge detection filter, which generates a greyscale edge outline. generate a histogram and save the standard dev. move camera one step closer to subject and take another picture. if the standard dev is smaller than previous one, we're getting more in focus. otherwise, we've past the optimal distance to be taking pictures.
is there a better way?
update: HUGE flaw in this, by the way. as I get past the optimal focus point, my "image in focus" value continues growing. you'd expect a parabolic-ish function looking at distance/focus-value, but in reality you get something that's more logarithmic
update 2: okay, so I went back to this and the current method we're exploring is given a few known edges (okay, so I know exactly what the objects in the picture are), I do a manual pixel intensity comparison. as the resulting graph gets steeper, I get more in focus. I'll post code once the core algorithm gets ported from matlab into c# (yeah, matlab.. :S)
update 3: yay final update. came back to this again. the final code looks like this:
step 1: get image from the list of images (I took a hundred photos through the focused point)
step 2: find an edge for the object I'm focusing (In my case its a rectangular object that's always in the same place, so I crop a HIGH and NARROW rectangle of one edge)
step 3: get the HorizontalIntensityStatistics (Aforge.net class) for that cropped image.
step 4: get the Histogram (gray, in my case)
step 5: find the derivative of the values of the histogram
step 6: when your slope is the largest, is when you're in the most focused point.

A: It may be a bit simplistic for your needs, but I've had good results with a simple algorithm that looks at the difference to neighbouring pixels. The sum of the difference of pixels 2-away seems to be a reasonable measure of image contrast. I couldn't find the original paper by Brenner in the 70's but it is mentioned in http://www2.die.upm.es/im/papers/Autofocus.pdf
Another issue is when the image is extremely out of focus, there is very little focus information, so it's hard to tell which way is 'moving closer' or to avoid a local maximum.

A: I haven't built one myself, but my first thought would be to do a 2D DFT on a portion of the image. When out of focus, high frequencies will disappear automatically.
For a lazy prototype, You could try to compress a region of the image with JPEG (high quality), and look at the output stream size. A big file means a lot of detail, which in turn implies the image is in focus. Beware that the camera should not be too noisy, and that you can't compare file sizes across different scenes of course.

A: This might be useful. It's how camera's AF system actually works - Passive Autofocus

Contrast measurement
Contrast measurement is achieved by
  measuring contrast within a sensor
  field, through the lens. The intensity
  difference between adjacent pixels of
  the sensor naturally increases with
  correct image focus. The optical
  system can thereby be adjusted until
  the maximum contrast is detected. In
  this method, AF does not involve
  actual distance measurement at all and
  is generally slower than phase
  detection systems, especially when
  operating under dim light. As it does
  not use a separate sensor, however,
  contrast-detect autofocus can be more
  flexible (as it is implemented in
  software) and potentially more
  accurate. This is a common method in
  video cameras and consumer-level
  digital cameras that lack shutters and
  reflex mirrors. Some DSLRs (including
  Olympus E-420, Panasonic L10, Nikon
  D90, Nikon D5000, Nikon D300 in Tripod
  Mode, Canon EOS 5D Mark II, Canon EOS
  50D) use this method when focusing in
  their live-view modes. A new
  interchangeable-lens system, Micro
  Four Thirds, exclusively uses contrast
  measurement autofocus, and is said to
  offer performance comparable to phase
  detect systems.

A: You can have a look at the technique used in the NASA Curiosity Mars Rover.
The technique is described in this article
EDGETT, Kenneth S., et al. Curiosity's Mars Hand Lens Imager (MAHLI) Investigation. Space science reviews, 2012, 170.1-4: 259-317.
which is available as a PDF here.
Quoting from the article:

7.2.2 Autofocus
Autofocus is anticipated to be the primary method by which MAHLI is
  focused on Mars. The autofocus command instructs the camera to move to
  a specified starting motor count position and collect an image, move a
  specified number of steps and collect another image, and keep doing so
  until reaching a commanded total number of images, each separated by a
  specified motor count increment. Each of these images is JPEG
  compressed (Joint Photographic Experts Group; see CCITT (1993)) with
  the same compression quality factor applied. The file size of each
  compressed image is a measure of scene detail, which is in turn a
  function of focus (an in-focus image shows more detail than a blurry,
  out of focus view of the same scene). As illustrated in Fig. 23, the
  camera determines the relationship between JPEG file size and motor
  count and fits a parabola to the three neighboring maximum file sizes.
  The vertex of the parabola provides an estimate of the best focus
  motor count position. Having made this determination, MAHLI moves the
  lens focus group to the best motor position and acquires an image;
  this image is stored, the earlier images used to determine the
  autofocus position are not saved.
Autofocus can be performed over the
  entire MAHLI field of view, or it can be performed on a sub-frame that
  corresponds to the portion of the scene that includes the object(s) to
  be studied. Depending on the nature of the subject and knowledge of
  the uncertainties in robotic arm positioning of MAHLI, users might
  elect to acquire a centered autofocus sub-frame or they might select
  an off-center autofocus sub-frame if positioning knowledge is
  sufficient to determine where the sub-frame should be located. Use of
  sub-frames to perform autofocus is highly recommended because this
  usually results in the subject being in better focus than is the case
  when autofocus is applied to the full CCD; further, the resulting
  motor count position from autofocus using a sub-frame usually results
  in a more accurate determination of working distance from pixel scale.

The following is Figure 23:

This idea was suggested also in this answer: https://stackoverflow.com/a/2173259/15485

A: While the sobel is a decent choice, I would probably choose to do an edge magnitude calculation on the projections in x and y directions over several small representative regions. Another .NET friendly choices based on OpenCV is @ http://www.emgu.com/wiki/index.php/Main_Page.

A: I wonder if the standard deviation is the best choice: If the image gets sharper, the sobel filter image will contain brighter pixels at the edges, but at the same time fewer bright pixels, because the edges are getting thinner. Maybe you could try using an average of the 1% highest pixel values in the sobel image?

A: Another flavor for focus metric might be:
Grab several images and average them ( noise reduction).
Then FFT the averaged image and use the high to low frequencies energy ratio.
The higher this ration the better focus. A Matlab demo is available (excluding the averaging stage) within the demos of the toolbox :)


text:
Q: Can I use async controllers in the following scenario? I have an application in Asp.net MVC where at some point I would like to display a modal dialog to the user that would display process execution progress indicator.
The process behind the scenes does a lot of database data processing (based on existing data it generates lots of resulting records that get written back to database as well). Process may take anything from a brief moment to a very long time (depending on existing data).
Application will initiate this process asynchronously (via Ajax request) and display progress in the same manner.
The problem
I've read a bit about Async controllers where one can asynchronously start a process and will informed about the end of it but there's no progress indication and I'm not really sure how browser timeouts are handled. As far as the client goes an async request is the same as synchronous one. Client will therefore wait for response (as I understand it). the main difference being that server will execute something in async manner so it won't block other incoming requests. What I should actually do is:

*

*make a request that would start the process and respond to the client taht process has started.

*client would them periodically poll the server for process progress status getting immediate response back with percentage value (probably as JSON)

*when progress would be 100% it would mean that it ended so client would know to make a request for results.

I'm not convinced that async controllers work this way...
The thing is that I'm not really sure I understand async controllers hence am not sure which approach should I use approach this problem as just described? I see two possibilities myself:

*

*Asp.net MVC Async controllers if they can work this way

*Windows Service app that processes data on request and reports its progress - this service would be started by writing a particular record to DB using a normal controller action; that would start it and then service would be writing its progress status to DB so my Asp.net MVC app would be able to read it on client process polling requests.

A: I haven't used Asynch controllers myself in a project.  However here's a link to someone who has.
asynchronous-processing-in-asp-net-mvc-with-ajax-progress-bar
I have personally used Number 2 in a large production project.
Number 2 was a Service App running on a separate server using OpenSSH to communicate between the two servers.  We'd poll for progress periodically to update the progress bar to the clients UI via AJAX.
Additionally by separating your web server from your long running process you are separating your concerns.  You web server is not interested in writing files to disk, handling IO, etc and so shouldn't be burdended with such.
If your long running process has to be killed or fails then this wont affect your web server handling requests, and processing transactions.
Another suggestion would be for an extremely long running process is not to burden the client with waiting, give them an option to come back later to see the progress.  I.e. send them an e-mail when its done.
Or actually show them something interesting, in our case we had a signed Java Applet show exactly what their process is doing at that exact moment.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Geospatial search with timestamp using Lucene I have an assignment to find cab drivers close to a given user's location(similar to Grab/Lyft). I have the drivers' location(latitude, longitude) with timestamp. This data is pushed by their mobile to my server every 2 minutes. When a user requests a ride, I need to find the nearest driver available using the drivers' data. I'm trying to use Lucene's GeoSpatial search for this. I've used the drivers data to be indexed and search based on the latitude and longitude of the user. I'm also able to search with a given latitude/longitude combination and get the nearest driver(s) with a distance parameter. But I don't know how I can add another parameter to the search query to specify the timestamp of the driver's data as well. For e.g., I want to search for only drivers who are near a given location at a particular timestamp.
Can someone help me with this? Here's the code snippet I'm using:
package com.test.trials;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Paths;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.spatial3d.Geo3DPoint;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.document.LatLonPoint;

public class LuceneTrial {

    private IndexSearcher searcher;

    public static void main(String[] args) throws IOException {
        LuceneTrial trial = new LuceneTrial();
        trial.generateData();
        trial.search();
    }

    private void generateData() throws IOException {
        Directory dir = FSDirectory.open(Paths.get("C:/temp/Lucene"));
        Analyzer analyzer = new StandardAnalyzer();
        IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
        iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
        IndexWriter writer = new IndexWriter(dir, iwc);

        try (BufferedReader br = new BufferedReader(new FileReader(
                "C:/temp/Lucene/Drivers.csv"))) {
            String line;
            String[] fieldNames = new String[] { "Driver ID", "Latitude", "Longitude", "Time" };
            while ((line = br.readLine()) != null) {
                // process the line.
                String[] tags = line.split(",");
                Document doc = new Document();
                for (int i = 0; i < fieldNames.length; i++)
                    doc.add(new StoredField(fieldNames[i], tags[i]));

                // Add a latlon point to index
                try {
                    doc.add(new LatLonPoint("latlon", Double
                            .parseDouble(tags[1]), Double.parseDouble(tags[2])));
                    Geo3DPoint point = new Geo3DPoint("geo3d",
                            Double.parseDouble(tags[1]),
                            Double.parseDouble(tags[2]));
                    doc.add(point);
                } catch (Exception e) {
                    System.out.println("Skipped: " + line);
                }
                writer.addDocument(doc);
            }
        }
        searcher = new IndexSearcher(DirectoryReader.open(writer));
    }

    public void search() throws IOException {
        System.out
                .println("\nLatLonQuery around given point, 10km radius --------------------------------------");
        TopDocs docs = searcher.search(LatLonPoint.newDistanceQuery("latlon",
                6.9270790, 79.8612430, 10 * 1000), 20);
        for (ScoreDoc scoreDoc : docs.scoreDocs) {
            Document doc = searcher.doc(scoreDoc.doc);
            System.out.println(doc);
        }
    }

}

And Here's the sample data I'm using:
Driver ID   Latitude    Longitude   Time
1   -6.081689   145.391881  7:01:17
2   -5.207083   145.7887    8:32:40
3   -5.826789   144.295861  8:40:49
4   -6.569828   146.726242  8:57:33
5   -9.443383   147.22005   6:14:26
6   -3.583828   143.669186  8:13:35
7   61.160517   -45.425978  8:58:24
8   64.190922   -51.678064  7:42:16
9   67.016969   -50.689325  6:52:20
10  76.531203   -68.703161  6:08:21
11  65.659994   -18.072703  7:57:45
12  65.283333   -14.401389  7:32:23
13  64.295556   -15.227222  8:20:26
14  65.952328   -17.425978  8:51:34
15  66.058056   -23.135278  8:33:43
16  63.985  -22.605556  7:39:35
17  65.555833   -23.965 7:20:54
18  64.13   -21.940556  7:37:48
19  66.133333   -18.916667  6:46:36
20  63.424303   -20.278875  7:15:12
21  46.485001   -84.509445  6:14:15
22  50.056389   -97.0325    7:12:15
23  44.639721   -63.499444  6:15:31
24  51.391944   -56.083056  7:15:50
25  49.082222   -125.7725   6:52:22

Can someone show me how I can search for the drivers based on two attributes - distance and time?

A: You can use BooleanQuery to solve your use case. Here's how your search function might look like:
public void search() throws IOException {
        System.out
                .println("\nLatLonQuery around given point, 10km radius --------------------------------------");
        Query distQuery = LatLonPoint.newDistanceQuery("latlon", -6.08165, 145.8612430, dist * 1000);
        long startTime=0;//adjust according to your needs
        long endTime=Long.Max_VALUE;//adjust according to your needs
        Query timeQuery = LongPoint.newRangeQuery("timestamp", startTime, endTime);

        BooleanQuery booleanQuery = new BooleanQuery.Builder()
            .add(distQuery, Occur.MUST)
            .add(timeQuery, Occur.MUST)
            .build();
        TopDocs docs = searcher.search(booleanQuery, 20);
        for (ScoreDoc scoreDoc : docs.scoreDocs) {
            Document doc = searcher.doc(scoreDoc.doc);
            System.out.println(doc);
        }
    }


text:
Q: In golang, import cycle not allowed, is the principle really a good solution? I had ask it in github issue yesterday, and one of the contributors say that I should ask it at this site, so I just paste my question at stackoverflow.
What version of Go are you using (go version)?

$ go version
go version go1.17.1 windows/amd64

Does this issue reproduce with the latest release?
yes
What operating system and processor architecture are you using (go env)?
go env Output
$ go env

What did you do?
I write simple code to try to describe real world, but "Import cycle not allowed" will compile error. So I could only rewrite the simple code to complex code.
"Import cycle not allowed" is a right principle, but it is not a principle to makes code simple, it makes code more complex.
Is it a temporary principle or a permanent principle?
Is it designed after many consider and discuss, or only for personal preference?
I ask this question, because I think in real world, everything interacts with each other naturally.
For example, a teacher enter a classroom, many students enter a classroom, then teacher choose student a to ask, then the student b ask teacher. It is a normal simple requirement.
But in golang, the below code could not compile success, because import cycle not allowed. It is so strange.
testgo
│  main.go
│
├─classroom
│      ClassRoom.go
│
├─student
│      Student.go
│
└─teacher
        Teacher.go

// main.go
package main

import (
    "testgo/classroom"
    "testgo/student"
    "testgo/teacher"
)

func main() {
    c := &classroom.ClassRoom{}
    t := &teacher.Teacher{}
    a := &student.Student{}
    b := &student.Student{}
    t.Enter(c)
    a.Enter(c)
    b.Enter(c)
    t.Ask(a)
    b.Ask(t)
    print(c)
}

// classroom/ClassRoom.go
package classroom

import (
    "testgo/student"
    "testgo/teacher"
)

type ClassRoom struct {
    Teacher  *teacher.Teacher
    Students []*student.Student
}

func (c *ClassRoom) AddTeacher(t *teacher.Teacher) {
    c.Teacher = t
}

func (c *ClassRoom) AddStudent(s *student.Student) {
    c.Students = append(c.Students, s)
}

// teacher/Teacher.go
package teacher

import (
    "testgo/classroom"
    "testgo/student"
)

type Teacher struct {
    TeacherName string
    InClassRoom *classroom.ClassRoom
}

func (t *Teacher) Enter(c *classroom.ClassRoom) {
    c.AddTeacher(t)
    t.InClassRoom = c
}

func (t *Teacher) Ask(s *student.Student) {

}

// student/Student.go
package student

import (
    "testgo/classroom"
    "testgo/teacher"
)

type Student struct {
    StudentName string
    InClassRoom *classroom.ClassRoom
}

func (s *Student) Enter(c *classroom.ClassRoom) {
    c.AddStudent(s)
    s.InClassRoom = c
}

func (s *Student) Ask(t *teacher.Teacher) {

}

 Finally, it will compile error like below
package testgo
    imports testgo/classroom
    imports testgo/student
    imports testgo/classroom: import cycle not allowed

There are more examples.
In real world, Cat catch Rat, Rat escape from Cat. package Cat import package Rat, and package Rat import package Cat.
In real world, Animal eat Fruit, Fruit be eat by Animal. package Animal import package Fruit, and package Fruit import package Animal.
In real world, import cycle occur everywhere.
But in golang, import cycle not allowed.
What did you expect to see?
enable import cycle, just like the real world
What did you see instead?
import cycle not allowed

A: It is a permanent principle. Circular dependencies increase compile time and GO is highly focused on fast compile time.
A solution to circular dependency is introducing a new interface in a new package. This interface should have all the methods that a circular dependent struct have and accessed by other circular dependent struct.
I found a clear notes about it https://medium.com/@ishagirdhar/import-cycles-in-golang-b467f9f0c5a0

A: It is correct and well thought principal. If you understand and imbibe your use-case, you can avoid cycles. For eg:- student class should only have student related details, names, age, address etc etc. class should have things like capacity, address etc. There should be a separate class named schedule.go which would hold the mapping of class, student and teacher.


text:
Q: RabbitMq like topic exchanges with Masstransit I read the rabbitmq tutorials and really liked the Idea of topic exchanges. In my architecture I would have topics like continent.city.street. Where, as you can imagine, there are only a limited number of continents, but nearly infinite cities & streets, which both can have duplicated names (like NorthAmerica.GeorgsTown.Mainstreet, Europe.GeorgsTown.Mainstreet, Asia.NewTown.Mainstreet and Australia.NewTown.LostRoad)
Now I learned that Masstransit, a Libary I want to learn/use, does not support this kind of topics. (There are somehow supported but then I also could use a generic RabbitMq client)
So what is the best way to achieve a similar thing, as with rabbitmqs topic exchanges, but with Masstransit (over (any) MQ/rider system), in regards of performance?
Some facts which could make the difference regarding performance:

*

*Nearly no consumer is interested in a whole continent - but some are. Asia.*.*

*Continents primary goal is to make cities unique (in this fictional case).

*About ~30% of the consumers would like to subscribe to cities regardless
of continent or street. *.GeorgsTown.*

*About ~30% of the consumers would like to
know what happens on specific streets regardless the city or continent. *.*.Mainstreet

*About ~30% is watching for specific combinations like Antarctica.GeorgsTown.Mainstreet

A: MassTransit supports topic exchanges just fine, they're similar to those defined in the Direct Exchange sample, but using a topic pattern routing key instead.


text:
Q: React Native frame rate drops when passing props between screens I have noticeable drops in frame rate and screen stutters when i pass props between screens and the screen in question also depends on the passed props to render correctly. How do i optimize this behavior?
Development environment
 - React Native 53.0
 - React Navigation 1.1.2
 - React 16.2


text:
Q: How can I create family and local connections in anylogic in GIS space? I am building an agent-based model where my agent decision to move will be based partially on the location of family and on the decisions made by people in the local area.
For this, I need to create connections to represent family and those locally. any suggestion on how I may do this? or examples of where this has been done?
I want to create a network that I can easily set up on startup for about 50000 agents.

A: this is too broad a question for SOW as it is not a technical question. Might be closed soon ,do not be offended ;-) Do check the SOW help on how to ask questions: https://stackoverflow.com/help/how-to-ask
However, in the meantime, there are example models by AnyLogic that show you how to use agent connections or check my blog post for more details: https://www.benjamin-schumann.com/blog/2017/10/21/anylogic-agent-links-a-hidden-gem-for-your-connections


text:
Q: VBScript create list, split list items and trim them I'm trying to create code that would add variables to list. Then it would split all of list elements by :, returning only the second part. In the end all returned strings would be trimmed.
To give you better understanding let me show you an example:

*

*Add "a : b " and " c : d " to the list.

*Split elements so only "b " and "d " are returned.

*Trim "b " and "d ".

So far I have came up with something like this but it doesn't work and I have no idea why.
Set list = CreateObject("System.Collections.ArrayList")
list.Add "bob : kid"
list.Add "ryan : alex"
list.Add "kate : andy"
list.Add "alice : mandy"
For Each item In list
    Dim item As String
    Dim words As String() = item.Split(New Char() {":"c})
    For Each word In words
        WScript.Echo word
    Next
Next

A: Your code doesn't work because it's not valid VBScript. You have several issues:

*

*VBScript doesn't support typed variable declarations (Dim var As Type). Use Dim var if you want to explicitly define a variable. Note, however, that in VBScript defining variables is only required when you put Option Explicit at the beginning of your script.

*VBScript doesn't support combined declaration and definition of variables (Dim var = value). You need two separate statements for defining a variable and assigning a value to it. The two statements can be put in one line by separating them with a colon (Dim var : var = value), but they're still two separate statements.

*In VBScript string is a primitive data type. VBScript strings are not objects with properties. For splitting a string use the Split() function.

*Don't re-define your loop variable inside your loop.

Change your loop to something like this and it should do what you want:
For Each item In list
    Dim words : words = Split(item, ":")
    For Each word In words
        WScript.Echo Trim(word)
    Next
Next

If you want just the second element from each split item you'd do something like this:
Dim words : words = Split(item, ":")
WScript.Echo Trim(words(1))

or like this:
WScript.Echo Trim(Split(item, ":")(1))


text:
Q: How do I run django test case? I am using twisted to pass in a variable into my django environment so I have to run the twisted server. Hence when I am testing my django app I really need to run the twisted code
it runs something like this:
def wsgi_resource():
    pool = threadpool.ThreadPool()
    pool.start()
    # Allow Ctrl-C to get you out cleanly:
    reactor.addSystemEventTrigger('after', 'shutdown', pool.stop)
    wsgi_resource = wsgi.WSGIResource(reactor, pool, WSGIHandler())
    return wsgi_resource

wsgi_root = wsgi_resource()
reactor.listenTCP(DJANGO_PORT, server.Site(wsgi_root))

How do I even begin testing for this piece of code?
I have to run twisted because my views uses something like this:
blockingCallFromThread( reactor, engine.push_message, user_hexid, room_hexid, message)

to call the variable that I passed into it.

A: You can write tests with Twisted's built-in test runner, trial, assuming that you start your WSGI threadpool before each test and stop it afterwards (in setUp and tearDown).
The upcoming 11.1 release includes new documentation for doing test-driven development with Twisted using Trial.  Until that's available in the official location, here's a temporary link to a buildbot build of our the documentation.


text:
Q: Structures with dynamic memory allocation in C I need to write data into a structure where the length of the data depends on the command I want to send to a device. For that I have defined the following structure:
typedef struct {
    uint8 len;          // Command length (cmd ... crc)
    uint8 cmd;          // Command code
    uint8 data_length;  // Data length
    uint8 data[12];     // Data: max 12 Byte
    uint8 crc_h;        // CRC value MSB
    uint8 crc_l;        // CRC value LSB
}CMD_TYPE;

Note: the members cmd, *data_length* and crc that are always present, instead member data can be empty or contains up to 12 Bytes.
I have created a function that returns a initialized command according to the parameters passed to the function:
CMD_TYPE Device::get_cmd(uint8 cmd, uint8 data_len, uint8 *data)
{
    CMD_TYPE cmd;

    cmd.len = (4 + data_len) * sizeof(uint8);
    cmd.cmd = cmd;
    cmd.data_length = data_len;
    cmd.data = (uint8 *)realloc(cmd.data, data_len*sizeof(uint8));
    if(data_len > 0)    memcpy(cmd.data, data, data_len);

    add_crc16((uint8*)&cmd);

    return cmd;
}

The function get_cmd() is used like this:
uint8 cmd_code = 0x01;
uint8 data[2] = {0xAB, 0xCD};

CMD_TYPE cmd = local_device->get_cmd(cmd_code, 2, data);
retVal = local_device->send(cmd);

When I try to compile this code I get an error from the compiler for that line:
cmd.data = (uint8 *)realloc(cmd.data, data_len*sizeof(uint8));

and the compiler error is:
error: lvalue required as left operand of assignment

The aim of using realloc() is to re-size the array data or to remove it at all from my new command structure. What is wrong in my code? Is that the right way to initialize structures with dynamic memory allocation?

A: What you want is the infamous struct hack:
typedef struct
{
    uint8   len;          // Command length (cmd ... crc)
    uint8   cmd;          // Command code
    uint8   data_length;  // Data length
    uint8   crc_h;        // CRC value MSB
    uint8   crc_l;        // CRC value LSB
    uint8   data[1];      // Data: max 12 Byte
} CMD_TYPE;

The trick is to allocate enough room for all of the members of the struct up to data[], then add enough bytes for the data[] member:
CMD_TYPE * allocCmd(int dataSize)
{
    int         len;
    CMD_TYPE *  p;

    len = sizeof(CMD_TYPE) + (dataSize-1)*sizeof(uint8);
    p = (CMD_TYPE *) malloc(len);
    memset(p, 0, len);
    p->data_length = dataSize;
    return p;
}

Here, len is calculated to be the size of the struct, minus the size of the empty data member, plus however many elements dataSize specifies for the data array.
The catch is that you have to be careful never to access any elements of p->data[] beyond what is actually allocated in it (inside the struct).

A: Your CMD_TYPE.data is an array, not a pointer. Since you want it to track dynamically allocated memory, it has to be a pointer:
uint8_t * data;

Just don't forget to initialize it with malloc() (or by setting it to zero before realloc()) and to clean up after yourself
By the way, do not cast the result of malloc() and co.

A: array defined as a[..] are immutable, you can't assign anything to them. Instead you should use pointers.


text:
Q: VRML file loading issue in three.js I am trying to load vrml or wrl file using vrmlloader.js which is available in three.js library. After loading this file its showing nothing its showing only white blank page.
Content of VRML file is available here : http://jsfiddle.net/shiladittya/y0j1wn0c/
And I am read this vrml file by using below code :
            var loader = new THREE.VRMLLoader();
            loader.addEventListener( 'load', function ( event ) {
                var geometry = event.content;
                scene.add(geometry);
            } );
            loader.load( "./stl/test.WRL" );

What I missed? Any suggestion?

A: You also need to include Detector.js (available in three.js library) and jQuery (2.0 or newer version).
But, for now this is the older version of code.
Now, in the latest version of VrmlLoader.js, you have to write:
var loader = new THREE.VRMLLoader();
loader.load("./stl/test.WRL", function(object) {
    scene.add(object);
};

A: I have tried loading you example in the new VrmlParser project. It loads just fine. Could you try it there?
I must note that I had to reduce the indentation, the file should not start with a tab character (\t).
You can find the VrmlParser project here: https://github.com/bartmcleod/VrmlParser
It uses ThreeJs.


text:
Q: Failing a ant build if the Java version is 1.5 or 1.6 I have an ant build file, which first checks what is the version of JAVA in my system. the code is like this-
<target name="-private.check.java">
  <echo message="Ant java version: ${ant.java.version}" />
</target>

The output is -
-private.check.java:
 [echo] Ant java version: 1.7

Now I want to make Build Fail if the java version is less than 1.7, how can I do that?

A: <target name="checkJava">
    <fail message="Unsupported Java version: ${java.version}. Make sure that the Java version is 1.7.">
        <condition>
            <not>
                <or>
                    <contains string="${java.version}" substring="1.7" casesensitive="false" />
                    <contains string="${java.version}" substring="1.8" casesensitive="false" />
                </or>
            </not>
        </condition>
    </fail>
</target>

A: The approach I know would be to use the following:
<condition property="version1.6">
  <or>
    <equals arg1="1.5" arg2="${ant.java.version}"/>
    <equals arg1="1.6" arg2="${ant.java.version}"/>
  </or>
 </condition>

Plus you have to negate it probably.

A: I use the test below;  There's a subtle different between ${ant.java.version} (the Java version which is being used to run Ant) and ${java.version} (The Java which will be found on the PATH by forked tasks) so you may need to modify the property used according to your needs.
<fail message="ERROR: This project requires Java 7 or above; you are using ${java.version}.">
    <condition>
        <matches string="${java.version}" pattern="^1\.[0-6]"/>
    </condition>
</fail>

A: The approach taken by the Ant team itself is to verify that something that has been added in Java7 is actually present. This way you don't need to change your build file when Java9 comes out - or get surprised if people use Java 1.4.
<fail message="Java7 is required to build">
  <condition>
    <not>
      <available classname="java.nio.file.FileSystem"/>
    </not>
  </condition>
</fail>


text:
Q: Parameter array versus IEnumerable for an API I have an C# API that can take 0/1/Many paramters of same type. What should be better way to have a API defined = params versus IEnumerable<T>?

A: I would almost always use params for APIs like that, since it allows the caller to pass the arguments without having to manually construct a container for them.
This:
SomeMethod(param1, param2, param3);

is just cleaner than requiring this:
SomeMethod(new[] { param1, param2, param3 });

However, if you are specifically operating on a single sequence of items, then IEnumerable<T> is more sensible. As well, if you expect > 5 or so parameters, then an enumerable makes more sense, since at that point the calling method starts to look pretty bad.
It really comes down to the logical operation of the API, along with the number of parameters you are actually expecting.

A: Use a params array when the number of parameters is small but undefined.
Use an IEnumerable when the number of parameters is large, or is a set of same objects, as in customers or orders.


text:
Q: AWS SES save email to s3 bucket I have configured AWS SES for saving emails to AWS S3 bucket. Followed All Steps.
When i try to send verified email at first, it is saved into S3 bucket named as "AMAZON_SES_SETUP_NOTIFICATION".
It does not generate a real email file. Please help me to resolve this issue.
Thanks.
Jacob

A: From the docs

The bucket may also contain a file named AMAZON_SES_SETUP_NOTIFICATION. You can ignore or delete this file.

This file has nothing to do with the emails you receive, you can delete the file if you want. If you have done all the configurations correctly, whenever you receive an email, you should see a new file getting created in your S3 bucket.
To setup email receiving, you need to publish an MX record as well.
https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-mx-record.html
Reference:
https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-getting-started-view.html


text:
Q: how to remove an array of div's with the same id using ajax? I am echoing an array in php:
foreach ($array as $print) {

$var = $print['var'];

echo $var;

}

I have a function that removes this div if a user posts a new comment:
$("#post").remove();

However this will only remove 1 div with the id=post, I need to remove all of them, Is there a way to do this?

A: First of all, there is never a case where it makes sense to use duplicate id's on an html page. It's invalid, and no one should ever do it.
that said, you can solve this by using the attribute equals selector if you must use duplicate id's (which again, makes no sense.)
$('[id="post"]').remove();

The better solution of course would be to NOT use duplicate ID's, and instead use a selector based on whatever alternative you use.

A: So you should use class instead of id.
foreach ($array as $print) {
    $var = $print['var'];
    echo '
'.$var.'
';
}

To remove all the elements by post class
$(".post").remove();

A: As mentioned ID's need to be unique, instead use classes.

echo $var;

And then
$(".post").remove();

A: Use class instead of id.
foreach ($array as $print) {
   $var = $print['var'];
   echo "
".$var."
";
}

$(".post").remove();


text:
Q: Proving a point is interior
Let $D = \left \{ (a,b,c,d,e) : ax^4+bx^3+cx^2+dx+e=0 \text{ has a real root} \right \}$
Show that (1,2,-4,3,-2) is an interior point in $D$.

My only idea was trying to somehow use the implicit function theorem, but I can't find how.
Hints appreciated.

A: Here is a hint: is there any way you can take advantage of the structure of the polynomial, specifically with the coefficients you have been given to show that polynomials with close coefficients also have real roots?
ANSWER BELOW:

First we notice that $c = (1,2,-4,3,-2)$ is an element of $D$. To show that it's an interior point, we need to find an open ball around $c$ where each element of the ball is in $D$.
So let $B=B_{1/2}(c)$ be the open ball around $c$ of radius $1/2$. Then a point $d \in B$ may be written:
$$d = c+b = (1+b_1, 2+b_2, -4+b_3, 3+b_4, -2+b_5)$$
where $||b|| < 1/2$. Now notice that each component of $b$ can only be of magnitude less than $1/2$, so the fifth component of $d$ will always be negative. Moreover, the first component of $d$ will always be positive. Then any polynomial $d(x)$ with coefficient vector $d$ will have a negative value at $0$ and a positive value for large enough $x$. As polynomials are continuous, this implies that $d(x)$ has a real root.
Then every $d \in B$ is in $D$, hence we have an open ball centered at $c$ entirely within $D$, therefore $c$ is interior to $D$.


text:
Q: NextJS | Pulling correct content from ACF Pro wysiwyg field I have a NextJs project, combined with a WordPress Headless CMS. I'm using the WP GraphQL, WPGraphQL Gutenberg and WPGraphQL for ACF plugins.
I have a file contentBlock.js which calls the Content Block from ACF:
export default function ContentBlock(attributes) {

    const parsedData = JSON.parse(attributes.attributesJSON).data;
    let largeHeading;
    let smallHeading;
    let sectionId;
    let content = parsedData.content;

    if (parsedData.include_large_heading == 1) {
        largeHeading =
{parsedData.large_heading}
;
        sectionId = parsedData.section_id;
    }

    if (parsedData.include_small_heading == 1) {
        smallHeading =
{parsedData.small_heading}
;
    }

    return (
        <section className={`${styles.contentBlock} blog-container`} id={sectionId}>
            {largeHeading}
            {smallHeading}

    )
}

the content variable returns the following:
This is a bold line of text.

This is a paragraph of some text. It doesn't have any line breaks. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae sollicitudin orci, at auctor elit. Donec libero odio, aliquet nec fringilla eu, viverra non magna. Pellentesque in sapien ac lectus egestas aliquam. Sed convallis dapibus magna a finibus. Vivamus consequat ex sed mauris consectetur, a volutpat sapien condimentum. Praesent consequat pharetra diam id aliquam. Duis dictum pharetra nibh. Proin quam augue, tincidunt at mollis a, posuere id lorem.

This is a bullet points

this is another bullet point

This is a paragraph of some text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae sollicitudin orci, at auctor elit. Donec libero odio, aliquet nec fringilla eu, viverra non magna. Pellentesque in sapien ac lectus egestas aliquam. Sed convallis dapibus magna a finibus. Vivamus consequat ex sed mauris consectetur, a volutpat sapien condimentum. Praesent consequat pharetra diam id aliquam. Duis dictum pharetra nibh. Proin quam augue, tincidunt at mollis a, posuere id lorem.

This is a paragraph of some text. It doesn't have any line breaks. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae sollicitudin orci, at auctor elit. Donec libero odio, aliquet nec fringilla eu, viverra non magna. Pellentesque in sapien ac lectus egestas aliquam. Sed convallis dapibus magna a finibus. Vivamus consequat ex sed mauris consectetur, a volutpat sapien condimentum. Praesent consequat pharetra diam id aliquam. Duis dictum pharetra nibh. Proin quam augue, tincidunt at mollis a, posuere id lorem.

The following code snippets return the following code:

{content}
 returns:
This is a bold line of text. This is a paragraph of some text. It doesn't have any line breaks. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae sollicitudin orci, at auctor elit. Donec libero odio, aliquet nec fringilla eu, viverra non magna. Pellentesque in sapien ac lectus egestas aliquam. Sed convallis dapibus magna a finibus. Vivamus consequat ex sed mauris consectetur, a volutpat sapien condimentum. Praesent consequat pharetra diam id aliquam. Duis dictum pharetra nibh. Proin quam augue, tincidunt at mollis a, posuere id lorem.

This is a bullet points

this is another bullet point

 This is a paragraph of some text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae sollicitudin orci, at auctor elit. Donec libero odio, aliquet nec fringilla eu, viverra non magna. Pellentesque in sapien ac lectus egestas aliquam. Sed convallis dapibus magna a finibus. Vivamus consequat ex sed mauris consectetur, a volutpat sapien condimentum. Praesent consequat pharetra diam id aliquam. Duis dictum pharetra nibh. Proin quam augue, tincidunt at mollis a, posuere id lorem. This is a paragraph of some text. It doesn't have any line breaks. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae sollicitudin orci, at auctor elit. Donec libero odio, aliquet nec fringilla eu, viverra non magna. Pellentesque in sapien ac lectus egestas aliquam. Sed convallis dapibus magna a finibus. Vivamus consequat ex sed mauris consectetur, a volutpat sapien condimentum. Praesent consequat pharetra diam id aliquam. Duis dictum pharetra nibh. Proin quam augue, tincidunt at mollis a, posuere id lorem.

 returns:
This is a bold line of text. This is a paragraph of some text. It doesn't have any line breaks. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae sollicitudin orci, at auctor elit. Donec libero odio, aliquet nec fringilla eu, viverra non magna. Pellentesque in sapien ac lectus egestas aliquam. Sed convallis dapibus magna a finibus. Vivamus consequat ex sed mauris consectetur, a volutpat sapien condimentum. Praesent consequat pharetra diam id aliquam. Duis dictum pharetra nibh. Proin quam augue, tincidunt at mollis a, posuere id lorem.

 - This is a bullet points
 - This is another bullet point

This is a paragraph of some text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae sollicitudin orci, at auctor elit. Donec libero odio, aliquet nec fringilla eu, viverra non magna. Pellentesque in sapien ac lectus egestas aliquam. Sed convallis dapibus magna a finibus. Vivamus consequat ex sed mauris consectetur, a volutpat sapien condimentum. Praesent consequat pharetra diam id aliquam. Duis dictum pharetra nibh. Proin quam augue, tincidunt at mollis a, posuere id lorem. This is a paragraph of some text. It doesn't have any line breaks. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae sollicitudin orci, at auctor elit. Donec libero odio, aliquet nec fringilla eu, viverra non magna. Pellentesque in sapien ac lectus egestas aliquam. Sed convallis dapibus magna a finibus. Vivamus consequat ex sed mauris consectetur, a volutpat sapien condimentum. Praesent consequat pharetra diam id aliquam. Duis dictum pharetra nibh. Proin quam augue, tincidunt at mollis a, posuere id lorem.

Is there a way I can get it to format correctly like:
This is a bold line of text.
This is a paragraph of some text. It doesn't have any line breaks. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae sollicitudin orci, at auctor elit. Donec libero odio, aliquet nec fringilla eu, viverra non magna. Pellentesque in sapien ac lectus egestas aliquam. Sed convallis dapibus magna a finibus. Vivamus consequat ex sed mauris consectetur, a volutpat sapien condimentum. Praesent consequat pharetra diam id aliquam. Duis dictum pharetra nibh. Proin quam augue, tincidunt at mollis a, posuere id lorem.

*

*This is a bullet points

*This is another bullet point

This is a paragraph of some text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae sollicitudin orci, at auctor elit. Donec libero odio, aliquet nec fringilla eu, viverra non magna. Pellentesque in sapien ac lectus egestas aliquam. Sed convallis dapibus magna a finibus. Vivamus consequat ex sed mauris consectetur, a volutpat sapien condimentum. Praesent consequat pharetra diam id aliquam. Duis dictum pharetra nibh. Proin quam augue, tincidunt at mollis a, posuere id lorem.
This is a paragraph of some text. It doesn't have any line breaks. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae sollicitudin orci, at auctor elit. Donec libero odio, aliquet nec fringilla eu, viverra non magna. Pellentesque in sapien ac lectus egestas aliquam. Sed convallis dapibus magna a finibus. Vivamus consequat ex sed mauris consectetur, a volutpat sapien condimentum. Praesent consequat pharetra diam id aliquam. Duis dictum pharetra nibh. Proin quam augue, tincidunt at mollis a, posuere id lorem.


text:
Q: How to set inbox refresh rate in Outlook How do I set the inbox refresh rate in Outlook?

A: It's very simple to set refresh rate in Outlook.
Just go to File >> Options >> Advanced >> Send and receive option is available...
Set the time.

A: Ctrl + Alt + s
Update it here:

A: In Outlook 2007 settings are under
Tools >> Send/Receive >> Send/Receive Settings >> Define Send/Receive Groups.....

Or use shortcut given by Jay
Ctrl + Alt + s


text:
Q: Multiple Window Oracle SQL Developer I am using SQL developer to access 2 different databases.
I have 2 connections and while working I need to open multiple windows for each database.
How does one do that?

A: *

*You can right click on a connection and chose 'Open SQL Worksheet' it will create another window for the existing session.

*Use Alt + F10and select the connection from the list.

If you need to create another independent session you can use Ctrl + Shift + N for an ongoing session.

A: In preferences, go to Database > ObjectViewer and check the Automatically Freeze Object Viewer Windows checkbox.

A: dbardelas answer helped me, the only thing is that he missed where is Database.
Database can be found in tools -> preferences
I had similar issue as victorien sukarieh the only issue I had is that every conexion to a table or database was opened on top of the previous one. It didn't let me visualize multiple tables, with the answer of dbardelas I can open multiple table visualization.


text:
Q: center div HTML code So I have my codes here and what I want to do is center it but can't figure out how.

Here is what my code is JS fiddle looks like as is...
https://jsfiddle.net/4fc07vL7/

A: Maybe you want to something like this :

A: Try this

.container{
  position:relative;
  float:left;
  -ms-transform:translateX(-50%);
  -webkit-transform:translateX(-50%);
  -moz-transform:translateX(-50%);
  transform:translateX(-50%);
  left:50%;
}

A: The  align attribute is not supported in HTML5. So, Use CSS instead.
CSS syntax:

So, you can do this.


text:
Q: Understanding that there are infinitely many primes of form $4n+3$ I read the proof of, that there are infinitely many primes of form $4n+3$ and it goes here:

Proof. In anticipation of a contradiction, let us assume that there exist only finitely many primes of the form $4n+3$; call them $q_1,q_2,\ldots ,q_s$. Consider the positive integer $$N=4q_1q_2\cdots q_s -1 = 4(q_1q_2\cdots q_s -1)+3$$ and let $N=r_1r_2\cdots r_t$ be its prime factorization. Because $N$ is an odd integer, we have $r_k\ne 2$ for all $k$, so that each $r_k$ is either of the form $4n+1$ or $4n+3$. By the lemma, the product of any number of primes of the form $4n+1$ is again an integer of this type. For $N$ to take the form $4n+3$, as it clearly does, $N$ must contain at least one prime factor $r_i$ of the form $4n+3$. But $r_i$ cannot be found among the listing $q_1,q_2,\ldots ,q_s$, for this would lead to the contradiction that $r_i \mid 1$. The only possible conclusion is that there are infinitely many primes of the form $4n+3$.

$q_1,q_2,\ldots ,q_s$
I need an explanation from last three line i.e. this.
They said that:

*

*$q_{1},q_{2}, \cdots ,q_{s}$ is of the form $4n+3$ (let).

*$r_{i}$ is of form $4n+3$ (at least one).

*$r_{i}$ cannot be found in listing $q_{1},q_{2}, \cdots ,q_{s}$

And lemma they used is:
The product of two or more integers of the form $4n+1$ is of the same form.
My problems:

*

*If above two holds then why $r_{i}$ cannot be found in listing $q_{1},q_{2}, \cdots ,q_{s}$.

*And how $r_{i}|1$

*If all this holds then why $q's$ are infinite.

Please give the most elementary explanation as you can, any help worth a lot to me, Thanks.
(I took this from David M. Burton book).

A: The proof assumes that there are only finitely many primes of the form $4n+3.$ They are listed as $q_1,\cdots,q_s.$ From them the number $N=4q_1\cdots q_s-1$ is defined. (Note that the proof argues by reduction ad absurdum. Do you remember Euclid's proof for the existence of infinitely many primes? He assumed that there are finitely many and arrives at a contradiction.)
Then it is shown that $N$ is of the form $4n+3$ and it is considered its prime factorization. Why must be at least one of the $r_i$'s of the form $4n+3?$ If all of them are of the form $4n+1$ then it would be $$N=r_1\cdots r_t=4n+1.$$ This is not possible because $N=4n+3.$
Finally, we have that
$$N=4q_1\cdots q_s-1=r_1\cdots r_t.$$ If $r_i=q_j$ for some $j$ then we have that $r_i$ divides $4q_1\cdots q_s$ and $r_1\cdots r_t.$ So, it must divide $$1=r_1\cdots r_t-4q_1\cdots q_s.$$ And this is not possible.
Thus we conclude that the number of primes of the form $4n+3$ must be infinite. Why? Because if we assume they are finite, say $q_1,\cdots, q_s$ we find a prime number $r_i$ of the form $4n+3$ that is not in the list above. This contradicts the assumption that all prime numbers of the form $4n+3$ are $q_1,\cdots, q_s.$

A: Imagine that $r_i=q_k$. Then clearly $r_i \mid 4q_1q_2\cdots q_s$, but we are also given that $r_i \mid N=4q_1q_2\cdots q_s-1$ These two results together imply that  $r_i \mid 1$, a contradiction that eliminates $r_i$ from the list of $q$ primes.
This means that $r_i$ is additional to the list of $q$ primes - given any finite list of $4n+3$ primes we can generate another, therefore the number of such primes is infinite.

A: Fact:  If $x|a$ and $x|b$ then $x|a \pm b$.  Therefore if $x|4q_1...q_s$ and $x|4q_1.....q_s - 1$ then $x|(4q_1....q_s) - (4q_1....q_s - 1)=1$.  So $x|1$ so $x=1$.
Fact:  If $q_i \in \{q_1,....,q_s\}$ then $q_i|4q_1...q_s$.
So if $r > 1$ and $r|N =4q_1....q_s - 1$ then we can not have $r \in  \{q_1,....,q_s\}$ because if we did we would have both $r = q_i|4q_1....q_s$ and $r|4q_1....q_s$ which would mean, by the above fact, that $r =1$ which is a contradiction.
Now if $N=4q_1....q_s -1 > 1$ then $N$ has a prime factor $r$ and as $r|N$, $r \not \in \{q_1,....,q_s\}$ by the above facts.
....  And that's the heart of it.  If $\{q_1,.....,q_s\}$ have something in common and $r$ has it in common too, then  $\{q_1,.....,q_s\}$ can not be ALL the numbers with that in common because $r$ is not in $\{q_1,.....,q_s\}$.
So the proof continues to show that if $q_i$ are all primes of the form $4k+3$ then $N$ has a prime factor $r$ that is also in the form $4k+3$.  That's the thrust of the proof.  Once we prove that, it follows that there must be an infinite number of primes in that form because...  By the facts above $r$ is not in  $\{q_1,.....,q_s\}$.  So that list can not contain all the primes in that form.
... but  we DEFINED $\{q_1,.....,q_s\}$ to be ALL primes of that form by definition.
So....  it is impossible to make such a list.
If the number of primes of that form were finite we could make such a list.  But we cant.  So there must be an infinite number of primes of that form.

A: The key ideas (colored below) become much clearer after a slight amount of abstraction. Below we prove a lemma that includes both Euclid's classical proof, as well as the OP (and others).
Lemma $\ $ Suppose  $\,S\,$ is a set of positive integers that is $\rm\color{#0a0}{closed}$ under multiplication, and $\,\color{#c00}{\bf 1}\in S,\,$ and for any  $\,n\in S\,$ there exists a positive integer  $\,c(n)\color{darkorange}{\not\in S}\,$ such that $\,c(n)\,$ is $\rm\color{#90f}{coprime}$ to $\,n.\ $ Then there  exist infinitely many primes not in $\,S.$
Proof $\ $ For induction, let $\,p_1,\ldots, p_k\,$ be primes $\not\in S.\,$ Then $\,c := c(p_1\!\cdots p_k)\color{darkorange}{\not\in S}\,$  so $\,c >\color{#c00}{\bf  1}\,$ thus $\,c\,$ has a prime factor. Not every prime factor of $\,c\,$ lies in $\,S\,$ (else their product $\,c\,$ would be in $\,S\,$ by $\,S\,$ $\rm\color{#0a0}{closed}$ under products). Thus $\,c\,$ has a prime factor $\,p\not\in S.\,$ Since $\,c\,$ is $\rm\color{#90f}{coprime}$ to $\,p_1\cdots p_k\,$ so too is its factor $\,p,\,$ hence $\,p_{k+1} := p\neq p_i\,$ is a new prime $\not\in S.$

Euclid's proof is the special case $\ S = \{1\}\ $ and $\,\ c(n) = n+1.$
The OP is also a special case: $\, S = 4\,\Bbb N + 1\,$ and $\,c(n) = 4n\!-\!1.\ $ Let's trace this particular proof.
Starting with the empty list of prime with product $= \color{#c00}{\bf 1},$ we construct the new prime
$ 4(\ \ )-1 = 4(\color{#c00}{\bf 1)}-1 = 3  =: p_1.\ $ Repeating with the singleton list $\, p_1\,$ leads to
$4(p_1)\!-\!1 = 4(3)\!-\!1 = 11 =: p_2.\ $  Repeating with the list $\, p_1,p_2\,$ leads to
$4(p_1p_2 )-1 = 4(3\cdot 11)-1 =  131 =: p_3.\ $
They remain prime $\ 3, 11, 131, 17291, 298995971 \ $ till we reach the sixth element
$$ n = 89398590973228811 = 8779\cdot 10079\cdot 1010341471$$
where we need to choose a (guaranteed) factor $\,\not \equiv 1\pmod{4},\,$ e.g. the least $= 8779$.
You can find further terms in OEIS sequence A057205


text:
Q: Inhering properties of constructor function i'm trying to inherit properties from one constructor function in other constructor function.
I have my Event constructor function:
var Controller  = require('./controller');

var Event = function() {
  this.element = 'element';

  Controller.call(this);
};

var event = new Event();

And my Controller constructor function:
var Controller = function() {
  console.log(this.element) // prints 'element'.

  this.method(); // < error
};

Controller.prototype.method = function() {
  console.log(this.element);
};

module.exports = Controller;

I already can access the Event properties and methods in the Controller, but i can't create my own controller methods.
Can by solved?
Thanks.

A: You should set the prototype of Event. This will add Controller to Event's prototype chain, resulting in the Controller's methods being available on the Event's instance.
var Controller  = require('./controller');

var Event = function() {
  this.element = 'element';

  Controller.call(this);
};

// See here!
Event.prototype = Object.create(Controller.prototype);

// Note other Event.prototype additions must be *after* the above line.
Event.prototype.another = function () {
    console.log('Another');

    this.method();
};

var event = new Event();


text:
Q: Can I customise the look of Stormpath's login screen? Stormpath's login view https://docs.stormpath.com/nodejs/express/latest/product.html#disable-the-built-in-views doesn't match the styling of the rest of my app. Can I customise the look, either by providing my own styling or replacing the view completely?
I've tried to find documentation on this but all I've been able to find out is that StormPath allows disabling the built in views.

A: I literally just found the official docs on Customising the Built-in Views 30 seconds after writing that question.


text:
Q: Clicking on HTML  tag with selenium python I try to click on html a tag with selenium but I get an error.
How can I get selenium to click on such tag?
I've tried this code but I get an error:
driver.find_element_by_id("btnCreateJE").click()
HTML code:
<a id="btnCreateJE" data-permission="true" onclick="NewManualJE()" href="@" class="btn waves-effect waves-light"> New </a>
Python selenium code:
driver.find_element_by_id("btnCreateJE").click()
I get that error:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="btnCreateJE"]"}
  (Session info: chrome=75.0.3770.142)

A: *

*Make sure that the element doesn't belong to the iframe, if this is the case - you will need to switch_to_frame first

*Make sure that the element doesn't belong to the Shadow DOM, if this is the case - you will have to find the relevant ShadowRoot and locate your element relatively

*It might be the case the link is not immediately present in DOM, i.e. it's being added later as a result of an AJAX call. If this is the case - consider adding Explicit Wait like:
WebDriverWait(driver, 10).until(expected_conditions.presence_of_element_located((By.ID, "btnCreateJE"))).click()

A: The desired element is a JavaScript enabled element so to click() on the element you have to induce WebDriverWait for the element to be clickable and you can use either of the following solutions:

*

*Using PARTIAL_LINK_TEXT:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "New"))).click()

*Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.btn.waves-effect.waves-light#btnCreateJE[onclick^='NewManualJE']"))).click()

*Using XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='btn waves-effect waves-light' and @id='btnCreateJE'][starts-with(@onclick, 'NewManualJE')]"))).click()

*Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


text:
Q: C# LINQ join with conditional where clause on two different data sets I have two collections that I am comparing data against. I can join the two collections by ids. I need to have a where clause that returns a list of data where certain items in collection B were not found in collection A

    public class Contract
    {
        public string ContractId { get; set; }
        public IList InvoiceList { get; set; }

        public class Invoice
        {
            public int InvoiceNumber { get; set; }
        }
    }

    public class PaymentRequest
    {
        public IList Contracts { get; set; }
        public class ContractList
        {
            public string ContractId { get; set; }
            public IList Invoices { get; set; }
        }

        public class InvoiceList
        {
            public int InvoiceNumber { get; set; }
        }
    }

I have the following so far but can't quite get the where clause down.

    var query = (
    from request in (
        from contract in paymentRequest.Contracts
        from invoice in contract.Invoices
        select new { contract, invoice })
    join valid in (
        from contract in validContracts
        select new { contract })
    on new { request.contract.ContractId } equals new { valid.contract.ContractId }
    where !(
        // get a list of invoice numbers in the request data set that are not in the valid data set
    )
    select "Contract Id: " + request.contract.ContractId +
           ", Invoice Number: " + request.invoice.InvoiceNumber
).ToList();

Any help is appreciated.

A: var collectionAIds = new HashSet<int>(collectionA.Select(colAItem => colAItem.Id));
var itemsInCollectionBNotInCollectionA = collectionB.Where(colBItem =>
                                             !collectionAIds.Contains(colBItem.Id));

basically, we want to get the Ids in collection A, and then select all items from collection B, not in A's list of ids.
A HashSet is optional. it just avoids repetitive O(n) lookups, if you don't use that variable.
p.s. i am assuming int, as the type of id.. use the data type of id for the Hashset.

A: Using contains gets you less performance than something that reminds a regular Sql query. This will be better
var result =
    from itm1 in Coll1
    from itm2 in Coll2.Where(x => x.Id == itm1.Id).DefaultIfEmpty()
    where itm2 == null
    select itm1;

This will give you all items in Coll1 that don't exist in Coll2. And this is gonna be faster than using Contains any time

A: It seems to me that your query should look like this:
var query =
(
    from request in
    (
        from contract in paymentRequest.Contracts
        from invoice in contract.Invoices
        select new { contract, invoice }
    )
    join valid in
    (
        from contract in validContracts
        select new { contract }
    ) on new { request.contract.ContractId } equals new { valid.contract.ContractId } into gvs
    where
        gvs
            .SelectMany(gv => gv.contract.Invoices)
            .Select(i => i.InvoiceNumber)
            .All(n => n != request.invoice.InvoiceNumber)
    select "Contract Id: " + request.contract.ContractId +
           ", Invoice Number: " + request.invoice.InvoiceNumber
).ToList();


text:
Q: MySQL data does not appear in tooltip I want to show MySQL data inside a tooltip.
Here is the code:
<?php
    $abfrage = "SELECT * FROM tester";
    $ergebnis = mysql_query($abfrage);
    while($row = mysql_fetch_object($ergebnis)){
        $Name=$row->Name;
        $Bech=$row->Beschreibung;
    }
?>

<a href="" title="<?=$Name?> <?=$Bech?>">Test Link

It shows me an empty tooltip with nothing inside. If I print those two variables, the MySQL data appear. Is there any mistake in the code?
Thanks.

A: This is in conjunction with Seth McClaine's answer.
Echo your values using:
<?php echo $Name; ?> <?php echo $Bech; ?>

Instead of <?=$Name?> <?=$Bech?>
The use of short tags is not recommended for something like this.
Reformatted code:
<?php
    $abfrage = "SELECT * FROM tester";
    $ergebnis = mysql_query($abfrage);
    $row = mysql_fetch_object($ergebnis);
    $Name=$row->Name;
    $Bech=$row->Beschreibung;
?>

<a href="" title="<?php echo $Name; ?> <?php echo $Bech; ?>">Test Link

A: If you just want the first result remove the while...
 <?php
    $abfrage = "SELECT * FROM tester";
    $ergebnis = mysql_query($abfrage);
    $row = mysql_fetch_object($ergebnis);
        $Name=$row->Name;
        $Bech=$row->Beschreibung;
?>

<a href="" title="<?=$Name?> <?=$Bech?>">Test Link


text:
Q: In Vim, why does V select more lines after yanking? The first time I use 2V, Vim selects 2 lines in a visual block, as I would expect. When I clear the selection and do 2V again, it again selects 2 lines. Cool.
But when I do 2V, then yank with y, the next 2V will select 4 lines. If I keep alternating between 2V and y, the 2V will double the number of lines selected each time.
Why does this happen? I'm assuming it has something to do with registers, but I can't find a straight answer... why would the contents of a register affect V?

A: This is special behavior in vim.  It is documented in the help:

If Visual mode is not active and the "v", "V" or CTRL-V is preceded with a
  count, the size of the previously highlighted area is used for a start.  You
  can then move the end of the highlighted area and give an operator.  The type
  of the old area is used (character, line or blockwise).

*

*Linewise Visual mode: The number of lines is multiplied with the count.


text:
Q: Python - query for inverted index This is my first post on SO and I apologize in advance if my question turns out to be a bit trivial, I'm relatively new to programming world, and I chose python for my first "serious" OOP language. I did a search through SO archive but I couldn't find any question completely related to mine. Okay, long story short, here's the problem:
I'm working on inverted index. I found a couple of tutorials and tips on the net to follow and I did the following:

*

*class Document for stemming the words and returning them with their start and end position thanks to finditer function.

*class Inverted_Index that takes a collection of a documents (list in a list), tokenize them and puts them in inverted index in a form of

    {'word':{document_id:(start_pos, end_pos)}}

like
{'cloud': {0: [(5, 10)]}, 'document': {1: [(11, 19)], 2: [(22, 30)]} ...}.
(I did document_id with a help of SO topic, iterating through enumerated collection of a documents. And about nested dictionaries, I made them amateurishly, like:
if nested_dict not in existing_dict:
    existing_dict[nested_dict] = {}

While I was reading stack owerflow I noticed that "defaultdict" datatype is pretty much superior way for doing that, but I haven't yet figured out "collections" module.).
Back on track: inside of Inverted_Index I did a Query method (just a version of OR operator) that takes string as a query, and if that string matches a key/term in my inverted index, returns back document_id with start and ending point of a term, like:
[(1, [(0, 4), (11, 19)]), ...]

And after that I was... stuck. I want to make a query output that prints out found word in a document along with it's environment, but I don't know how to connect result from a query method (document_id with start and end position) and inverted index, and I don't have a clue how to highlight that matched query inside her environment. Because of that I made starting and end point, but I have no idea how to accentuate it in python? Bold it?
I thought of result something like:

###################
      Your query:'chocolate pudding'
      Results:
      ########
      In a document with id: 1
      yaddi yaddi yadda chocolate bla bla bla pudding
      hocolate bla bla bla pudding yaddi yaddi yadda bla

I mean, I was reading http://docs.python.org/2/library/string.html#string.center and thinking that aligning found words/queries in same column would do to trick. But I don't know how to get there, so any kind of hint would be great, because I'm not stuck in my program as I'm stuck in understanding the logic behind python, and in that case tutorials don't do justice. (Yes, I got some python books, but they have extended approach to this kind of matter, possibly considering it is not for beginners, but I don't know where to begin with, what programs to make that I can make use of. The thing is, we learn linguistic theory and IR theory in college, but we do a few things in practice.).
Thanks!
And sorry about this story-of-my-life end :D

I forgot, a code for not making this topic vague:
class inverted_index(dict):

    def __init__(self,collection_of_docs):
        for doc_id,document in enumerate(collection_of_docs):
            for word,start,end in document.tokenize(): #form: [('sky', 0, 4)]
                if word not in self:
                    self[word]={}
                if doc_id not in self[word]:
                    self[word][doc_id]=[]
                self[word][doc_id].append((start,end))

    def query(self,query_string):
        result={}
        for query_term in re.findall(r'\w+',query_string.lower(),re.UNICODE):
            for doc_id in self.get(query_term,{}):
                if doc_id not in result:
                    result[doc_id]=self[query_term][doc_id]
                else:
                    result[doc_id]=result[doc_id]+self[query_term][doc_id]
        return sorted(result.items(),key=lambda e:-len(e[1]))

A: You will need a 'get_with_surroundings' method on your text.
it could look like
class inverted_index(dict):
    def __init__(self,collection_of_docs):
        self.collection_of_docs = collection_of_docs #to store those
        # ... rest of your code

    def get_with_surroundings(document_id, position_tuple):
        start, end = position_tuple
        return self.collection_of_docs[document_id].text[start-10:end+10]

Where +10 and -10 could change depending on how much surroundings do you need to display.
I assume there that your Document class has some 'text' attribute that is plain python string of that document.
Calling this method with one of results of your query will more-or-less archieve what you need.
This How do I print bold text in Python? could be helpful about bold text in python.


text:
Q: Highlight the current line number for the active buffer in `nlinum-mode` I am using the package nlinum 1.9 for showing line numbers in the margin.
In order to highlight the current line, I set the variable (setq nlinum-highlight-current-line t).
It correctly works.
However, if I have multiple windows in my frame I would like to only highlight the line of the active window.
The current behavior:

The left window is active, but the line 5 is highlighted for the right windows too.

A: You can use hlinum "https://github.com/tom-tan/hlinum-mode"
that is an linum-mode extension to highlight current line number.
Simple add this 2 lines to your .emacs
(require 'hlinum)
(hlinum-activate)


text:
Q: How to amend gnome extension Specifically this one - Windows Blur Effects | GNOME Shell Extensions that blurs inactive windows.
Want to be able exclude some windows. And such feature must be already there (on github README it's marked as closed in version 3). But all i've found is:
const excludeList = []; // an array of wm-class to be excluded from filters

inside the extension.js. So 2 questions:

*

*This array is what i looking for?

*If yes, and i amend it with, let's say, ["Firefox"] - how to make changes active (do i need to "recompile" this extension.js)? Simple saving changes and switching extension off/on doesn't make any difference..

A: You may have to restart the GNOME shell in order to see the effect of the changes made.
If you're in an Xorg session, press alt+f2, then type r and press enter.
If you're in a Wayland session the above will not work, either reboot your system or log out and log in again.


text:
Q: USB transaction error completion code for Address Device Command with BSR = 0 I am writing a driver for the xHCI and I have been having a problem with the address assignment.
Here's what I am doing:

*

*Reset the controller by writing 1 to the USBCMD.HCRST and wait for USBSTATUS.CONTROLLER_NOT_READY flag to clear.

*Set the maximum slots enabled in the config register to 16 (which is the max supported by my xHC).

*Allocate the device context base address register on a 64 byte aligned memory location and write that address to the dcbaap register.

*allocate scratchpad buffers, write their addresses in an array, then write the address of that array in the 0th entry of the dcbaap.

*Allocate a command  ring and write its address in CRCR.

*Set the R/S bit and wait for the controller not ready flag CNR to clear.

*Allocate event ring, and event ring segment table with one entry, and write the address of table in ERSTBA

*Then the software waits until a device is connected on port 12, I connect the device to port 12 and I can see the port goes to the enabled state as indicated by PP, CCS, PED being 1, and PR and PLS being 0.

*Submit an enable slot command and I get an event on the event ring with a success completion code and a slot ID.

*allocate output and input device contexts data structures and initialize them to valid values.

*allocate transfer ring and write its address to the input context.

*Submit the first address device command with BSR = 1 and I get an event on the event ring with success completion code.

*Here is where things go wrong: submit the second address device command with BSR = 0, and I get USB transaction error for the completion code.

In the xhci spec rev 1.2, it says the USB transaction error is the result of a USB3 DPP(Data Packet Payload) Error. I looked in the USB3.2 rev 1 and it said DPP error could happen due to any of the following:
1.CRC incorrect
2.DPP aborted
3.DPP missing
4.Data Length in the Setup DPH does not match the actual data payload length.
I've been trying on this for about 2-3 weeks now and getting nowhere. I did see a post here where someone had this issue with the EHCI and they fixed it by reducing their delays. I tried to do a similar thing but still didn't fix it.
Does anyone have an idea why am I getting this error or how do I go about fixing it?
Something I want to note is that if skip step 8, an continue to enable slot command, I still get the same results. So I still get a device slot and I still get a successful first Address Device command even though there is no device connected. Which makes me think that the usb device isn't even talking? I'm using a thumb drive, I tried different thumb drives and different ports and still the same issue. I'm using a USB 3.0 thumb drive on a SS port.


text:
Q: Only one way of string concatenation works with SMTPlib? I have a code like this:
for each in foo:
    if each not in foo2:
        msg = ("""
        Some message:
        %s
        """
        % (each))
        server.sendmail(from, to, msg)

And it works fine and dandy. When I try to make it like this, however:
for each in foo:
    if each not in foo2:
        msg = "Some message:\n"+each
        server.sendmail(from, to, msg)

It sends blank email. It may be also worth noting that each is always a URL. Does it have something to do with how SMTPlib parses emails?


text:
Q: Load data via SQL * Loader in IDENTITY column in Oracle 12c I need to load data using SQL* Loader into Oracle table with GENERATE ALWAYS AS IDENTITY
CREATE TABLE tbl_identity
(
  col1 NUMBER(10,0) GENERATED ALWAYS AS IDENTITY(START WITH 7 INCREMENT BY 1)    NOT NULL,
  col2 VARCHAR2(20)
);

But when I try to load data in this table, I get an error
ORA-32795: cannot insert into a generated always identity column

Maybe there are any option in SQLLDR which skip IDENTITY for a while?
Or maybe there are any ideas how I can load data into GENERATED ALWAYS IDENTITY column using SQLLDR?
SQLLDR command
sqlldr userid=user/passw@TNS control=tbl_identity.ctl log=tbl_identity.log rows=1000 readsize=65535 bindsize=65535

CTL-file
OPTIONS(direct=false)
LOAD DATA
INFILE 'tbl_identity.txt'
INTO TABLE tbl_identity
INSERT
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' TRAILING NULLCOLS
(col1,
 col2)

A: Change your DDL from GENERATED ALWAYS to GENERATED BY DEFAULT

A: I use the following script before loading the data :
begin
  for rec in (
    select owner, table_name, column_name, generation_type
    from all_tab_identity_cols
    where owner = 'owner '
      and generation_type in ('ALWAYS')
      and table_name in ('','',......)
  )loop
     -- before load data
     if rec.generation_type = 'ALWAYS' then
       execute immediate 'alter table '||rec.owner||'.'||rec.table_name||' modify '||rec.column_name||' generated by default as identity';
     end if;
     if rec.generation_type = 'BY DEFAULT' then
     -- return (after data load)
       execute immediate 'alter table '||rec.owner||'.'||rec.table_name||' modify '||rec.column_name||' generated always as identity';
     end if;
  end loop;
end;
/

and then return everything to the way it was.
Be careful, list the right tables in the query!


text:
Q: Show square brackets in yml file How to generate content in yml file with this format:
required_groups:
- ["member", "cn=serviceboard-users,cn=groups,cn=accounts,dc=int,dc=dostack,dc=io"]

Instead of this format:
required_groups:
- - member
  - cn=serviceboard-users,cn=groups,cn=accounts,dc=int,dc=dostack,dc=io

Input:
[["member", "cn=serviceboard-users,cn=groups,cn=accounts,dc=int,dc=dostack,dc=io"]]

Current Code:
File.open("config/ldap/#{Rails.env}.yml", "w") do |file|
  data = {}

  formatted_groups_array = []
  Setting.ldap_users_filter_required_groups.each { |group| formatted_groups_array.push([Setting.ldap_group_membership_attribute.to_s, group.to_s])}
  data["required_groups"] = formatted_groups_array

  file.write(data.to_yaml)
end

A: As stated in this answer, the default ruby library Psych does not have many options available, and you cannot customize the output the way you are trying to do.
In the meantime I've found an old possibile custom solution to your problem, but I had to rewrite a small part of it to make it compatible to the most recent ruby version (I am using 2.7.0 for this example). This is my updated script. Basically it will introduce a new way to edit the YAML output using a more concise syntax.
You can use it this way:
 File.open("config/ldap/#{Rails.env}.yml", "w") do |file|
  data = {}

  formatted_groups_array = []
  Setting.ldap_users_filter_required_groups.each { |group| formatted_groups_array.push([Setting.ldap_group_membership_attribute.to_s, group.to_s])}
  data["required_groups"] = formatted_groups_array

  styled_yaml = StyledYAML.inline(data)
  file.write(StyledYAML.dump(styled_yaml))
end


text:
Q: how to get class of a variable in R using loop? I have data frame in R with four columns and I am trying to get class of each variable using for loop, depending on a class of variable I could write a further code. Below is the data frame.
   var1 var2 var3 var4
1     1    a    a    s
2     2    g    a    s
3     3    b         s
4     4    n    s    s
5    NA    m    f    f
6     6    r    g    v
7     7    t         b
8     8         j
9     9    y    i    g
10   10    h    i    t

As of now I have tried below code but it is giving NULL for a class of variable
for (i in names(df)){
  print(names(df[i]))
  name <- names(df[i])
  print(class(df$name))
}

Result with above code:
[1] "var1"
[1] "NULL"
[1] "var2"
[1] "NULL"
[1] "var3"
[1] "NULL"
[1] "var4"
[1] "NULL"

Expecting Result
    [1] "var1"
    [1] "integer"
    [1] "var2"
    [1] "factor"
    [1] "var3"
    [1] "factor"
    [1] "var4"
    [1] "integer"

Requesting your help.

A: Since data.frames are really just a list of columns, I do this often  using lapply:
lapply(df, class)

As for the for loop you have in the example, when you call df$name, R is trying to find the column called "name". Instead, you want df[, name]:
for (i in names(df)){
  name <- names(df[i])
  print(name)
  print(class(df[, name]))
}

A: Using mtcars as an example:
for (i in names(mtcars)){
    print(names(mtcars[i]))
    name <- names(mtcars[i])
    print(class(mtcars[,i]))
    }


text:
Q: Show that there is a sequence such that the limit is Sup A Let $A\subset\mathbb{R}$ be non-empty and bounded above.
Show that there is a sequence $\left(x_{n}\right)_{n \in \mathbb{N}}$ in A such that $\lim_{n\rightarrow\infty}x_{n}=\sup A$
I understand the proof will end on showing we have satisfied the limit definition,
$\forall \varepsilon > 0 \exists n\in \mathbb{N} \forall n>N$ : $\left|x_{n}-\alpha\right| < \varepsilon$
however I am unsure of how to start.


text:
Q: sequence of entire functions that converges to $\sqrt{q}$ uniformly on compact subsets of the line Re $(z)=q$ for each positive rational $q$ I'm scheduled to host a prep course for the complex analysis qualifying exam at my university this summer, so I'm going through old qualifying exams to prepare. I'm stuck on the following:

Show that there exists a sequence $\{f_n\}$ of entire functions with the following property: For each rational number $q\geq 0$, the sequence converges to $\sqrt{q}$ uniformly on compact subsets of the line $\{z\in\mathbb{C}\,:\,\text{Re }(z)=q\}$.

I wish I could share my thoughts on this problem, but I honestly don't even know where to start. I imagine it uses the Mittag-Leffler or Weierstrass factorization theorem in some way but I can't put together how. I also assume that the countability of $\mathbb{Q}$ is exploited in some way, however the square root seems a bit mysterious.
Would anyone mind nudging me in the right direction? Thanks!

A: Enumerate the nonnegative rationals as $q_n$.  Use Runge's theorem to find $f_n$ so $|f_n(q_k+iy) - \sqrt{q_k}| \le 1/n$ for  $k=1\ldots n$ when $|y| \le n$.
The square root is a red herring.  Any function on the nonnegative rationals would do.


text:
Q: Before Delete Test Class - Getting "De-reference Null Object error on other trigger" I'm new to Apex and Code...
A trigger from a managed package is causing my test class to fail. Here's the code for the trigger causing the error:
trigger RAPID_SVMXC_BeforeInsertUpdateDelete_WorkDetails on SVMXC__Service_Order_Line__c (before insert, before update,before delete) {

Activate_Timesheet__c Activate_Timesheet   = new Activate_Timesheet__c();  // name of Custom Setting
Activate_Timesheet = Activate_Timesheet__c.getValues('TimesheetState');  // grab the specific setting

if (Activate_Timesheet.Enable_Timesheet__c==true || RAPID_SVMXC_TimesheetUtils_UT.TimesheetUtilsTest==true)
{
    if (trigger.isDelete)
    {
        RAPID_SVMXC_TimesheetUtils.removeTimesheetEntriesFromWorkDetails(trigger.oldMap.keySet());
    }
    else
    {
        RAPID_SVMXC_TimesheetUtils.checkForWorkDetailOverlap(trigger.new,trigger.oldMap);
    }
}}

The error message is:

caused by: System.NullPointerException: Attempt to de-reference a null object
  Trigger.RAPID_SVMXC_BeforeInsertUpdateDelete_WorkDetails: line 7, column 1: []

Line 7 in that trigger is: if (Activate_Timesheet.Enable_Timesheet__c==true || RAPID_SVMXC_TimesheetUtils_UT.TimesheetUtilsTest==true)...
I can't figure out why it's causing this error if "Activate_Timesheet__c" is a Custom Setting, why is a missing lookup field on my record insert causing that?

A: You need to create custom setting in your test class.
Insert new Activate_Timesheet__c (field__c = value);


text:
Q: How to filter Flat File Source using script component I have the following scenario:
I have thousands of text files with the below format.The column names are written in separate lines where as the row values are delimited by Pipe(|).
START-OF-FILE
PROGRAMNAME=getdata
DATEFORMAT=yyyymmdd

#Some Text
#Some Text
#Some Text
#Some Text
#Some Text
START-OF-FIELDS
Field1
Field2
Field3
------
FieldN
END-OF-FIELDS
TIMESTARTED=Tue May 12 16:04:42 JST 2015
START-OF-DATA
Field1Value|Field2value|Field3Value|...|Field N Value
Field1Value|Field2value|Field3Value|...|Field N Value
------|...........|----|-------
END-OF-DATA
DATARECORDS=30747
TIMEFINISHED=Tue May 12 16:11:53 JST 2015
END-OF-FILE

Now I have a corresponding SQL Server table, where I can easily load the data as destination.
Since I am new to SSIS, having trouble as to how to write the Script Component so that I can filter the Source Text files and easily load into sql server table.
Thanks in advance!

A: There are a few ways to do it. If the format of the files are constant, there are some useful properties of the flat file connection manager editor. For example, you can add a new flat file connection into the connection managers. There are some properties such as "Rows to skip" for the above file, you could set this to 18. Then it would start at the columns line with the "|".
Another property of the flat file connection manager that may be useful is that if you open the flat file connection manager, and then click on columns in the side menu, you can set the column delimter to the pipe "|"
But if the format of the file will change, e.g. variable number of header rows, you can use a script task to remove any non-piped rows. e.g. the header and footer.
For example, you can add a method such as file.readalllines and then edit or remove the lines as needed then save the file.
Info about that method is here:
https://msdn.microsoft.com/en-us/library/s2tte0y1%28v=vs.110%29.aspx
e.g. to remove last line in script task
string[] lines = File.ReadAllLines( "input.txt" );
StringBuilder sb = new StringBuilder();
int count = lines.Length - 1; // all except last line
for (int i = 0; i < count; i++)
{
    sb.AppendLine(lines[i]);
}
File.WriteAllText("output.txt", sb.ToString());

A: USE Below VB Script in your SSIS SCript Component Task as source
enter code here

Imports System
Imports System.Data
Imports System.Math
Imports System.IO
Imports Microsoft.SqlServer.Dts.Runtime
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper

<Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute()> _
<CLSCompliant(False)> _
Public Class ScriptMain
    Inherits UserComponent
    'Private strSourceDirectory As String
    'Private strSourceFileName As String
    Private strSourceSystem As String
    Private strSourceSubSystem As String
    Private dtBusinessDate As Date

    Public Overrides Sub PreExecute()
        MyBase.PreExecute()
        '
        ' Add your code here for preprocessing or remove if not needed
        ''

    End Sub

    Public Overrides Sub PostExecute()
        MyBase.PostExecute()
        '
        ' Add your code here for postprocessing or remove if not needed
        ' You can set read/write variables here, for example:
        Dim strSourceDirectory As String = Me.Variables.GLOBALSourceDirectory.ToString()
        Dim strSourceFileName As String = Me.Variables.GLOBALSourceFileName.ToString()
        'Dim strSourceSystem As String = Me.Variables.GLOBALSourceSystem.ToString()
        'Dim strSourceSubSystem As String = Me.Variables.GLOBALSourceSubSystem.ToString()
        'Dim dtBusinessDate As Date = Me.Variables.GLOBALBusinessDate.Date

    End Sub

    Public Overrides Sub CreateNewOutputRows()
        '
        ' Add rows by calling the AddRow method on the member variable named "<Output Name>Buffer".
        ' For example, call MyOutputBuffer.AddRow() if your output was named "MyOutput".
        '
        Dim sr As System.IO.StreamReader
        Dim strSourceDirectory As String = Me.Variables.GLOBALSourceDirectory.ToString()
        Dim strSourceFileName As String = Me.Variables.GLOBALSourceFileName.ToString()
        'Dim strSourceSystem As String = Me.Variables.GLOBALSourceSystem.ToString()
        'Dim strSourceSubSystem As String = Me.Variables.GLOBALSourceSubSystem.ToString()
        'Dim dtBusinessDate As Date = Me.Variables.GLOBALBusinessDate.Date

        'sr = New System.IO.StreamReader("C:\QRM_SourceFiles\BBG_BONDS_OUTPUT_YYYYMMDD.txt")
        sr = New System.IO.StreamReader(strSourceDirectory & strSourceFileName)
        Dim lineIndex As Integer = 0
        While (Not sr.EndOfStream)
            Dim line As String = sr.ReadLine()
            If (lineIndex <> 0) Then 'remove header row
                Dim columnArray As String() = line.Split(Convert.ToChar("|"))
                If (columnArray.Length > 1) Then
                    Output0Buffer.AddRow()
                    Output0Buffer.Col0 = columnArray(0).ToString()
                    Output0Buffer.Col3 = columnArray(3).ToString()
                    Output0Buffer.Col4 = columnArray(4).ToString()
                    Output0Buffer.Col5 = columnArray(5).ToString()
                    Output0Buffer.Col6 = columnArray(6).ToString()
                    Output0Buffer.Col7 = columnArray(7).ToString()
                    Output0Buffer.Col8 = columnArray(8).ToString()
                    Output0Buffer.Col9 = columnArray(9).ToString()
                    Output0Buffer.Col10 = columnArray(10).ToString()
                    Output0Buffer.Col11 = columnArray(11).ToString()
                    Output0Buffer.Col12 = columnArray(12).ToString()
                    Output0Buffer.Col13 = columnArray(13).ToString()
                    Output0Buffer.Col14 = columnArray(14).ToString()
                    Output0Buffer.Col15 = columnArray(15).ToString()
                    Output0Buffer.Col16 = columnArray(16).ToString()
                    Output0Buffer.Col17 = columnArray(17).ToString()
                    Output0Buffer.Col18 = columnArray(18).ToString()
                    Output0Buffer.Col19 = columnArray(19).ToString()
                    Output0Buffer.Col20 = columnArray(20).ToString()
                    Output0Buffer.Col21 = columnArray(21).ToString()
                    Output0Buffer.Col22 = columnArray(22).ToString()
                    Output0Buffer.Col23 = columnArray(23).ToString()
                    Output0Buffer.Col24 = columnArray(24).ToString()

                End If
            End If
            lineIndex = lineIndex + 1
        End While
        sr.Close()

    End Sub

End Class

Code End


text:
Q: Java convert 4 bytes to single variable What I am trying to do is place 4 bytes that are currently in an array into a single byte variable.  For example:
public myMethod()
{
   byte[] data = {(byte) 0x03, (byte) 0x4C, (byte) 0xD6, (byte) 0x00 };
   writeData(testMethod((byte)0x4C, data));
}

public byte[] testMethod(byte location, byte[] data)
{
    byte[] response = {(byte) 0x00, (byte) 0x21, location, data);
    return response;
}

This obviously dose not work because you cannot cast byte to byte[].
Any ideas?
EDIT:
There is some confusion as to what I am asking.  What I am looking for is
data = (byte) 0x034CD600;

In the "testMethod".

A: You could try something like that:
private static final byte[] HEADER = new byte[] { (byte) 0x00, (byte) 0x21 };

public static byte[] testMethod(byte location, byte[] data) {
    byte[] response = Arrays.copyOf(HEADER, HEADER.length + data.length + 1);
    response[HEADER.length] = location;
    System.arraycopy(data, 0, response, HEADER.length + 1, data.length);
    return response;
}

or if you are using ByteBuffers
public static ByteBuffer testMethodBB(ByteBuffer bb, byte location, byte[] data) {
    if(bb.remaining() < HEADER.length + 1 + data.length) {
        bb.put(HEADER);
        bb.put(location);
        bb.put(data);
        bb.flip();
        return bb;
    }
    throw new IllegalStateException("Buffer overflow!");
}

A: Just create a byte[] big enough to store the elements from data.
public byte[] testMethod(byte location, byte[] data)
{
    byte[] response = new byte[3 + data.length];
    response[0] = (byte) 0x00;
    response[1] = (byte) 0x21;
    response[2] = location;
    for (int i = 0; i < data.length; i++) {
        response[3 + i] = data[i];
    }
    return response;
}

Use System.arraycopy() if speed is important. I find the above more understandable.
The notation
byte[] response = {(byte) 0x00, (byte) 0x21, location, date);

is, as you said, illegal. The {...} initializer only accepts variables or literals of type byte.


text:
Q: Plotting resampled time-series area chart with one line of code? I'm trying to find a way to efficiently/quickly plot a resampled time series area plot in one line of code.
Let's say I have a simple time series; I know I can use the following method
    SERIES.resample('M').mean()

to create a new time series (resampled to the Month via mean).
I know I could just do
    df=SERIES.resample('M').mean()
    df.plot(kind='area')

And be done--but is there another way to do it via one line of code? I looked at
    plt.fill()

and
    plt.stackedplot()

But those require x,y arguments

A: You can do the following:
SERIES.resample('M').mean().plot(kind='area')


text:
Q: Are we in a nonstandard model of arithmetic? My question is: is $\mathbb{N}$ a nonstandard model of arithmetic for someone else?
Let $\mathbb{N}^*$ be a nonstandard model of Peano Arithmetic. Then that consists of a copy of $\mathbb{N}$ followed by a dense linear order of copies of $\mathbb{Z}$.
Is the reverse also true? Is our familiar $\mathbb{N}$ nonstandard with respect to someone else?
If this question is ill-posed, it is because I do not fully understand the nuances of model theory, not to mention non-standard model theory. So feel free to re-pose this precisely and answer it.
I would like to understand whether some models of arithmetic are inherently richer than others, or whether they are all equally rich.

A: Your question is not ill-posed and in fact admits a rather precise answer in the context of Joel David Hamkins' multiverse.  The technical details of this may be beyond the level of this question but the basic assumption, on this view, is that there is not a single set-theoretic universe (governed by ZFC or whatever) but rather a multitude of such universes, in precise relationship to each other governed by the rules set out by Hamkins and collaborators.
On this view, whichever universe a particular observer happens to be in, his particular version of $\mathbb N$ is indeed nonstandard with respect to another universe in the Hamkins multiverse.
This recent MO thread provides additional information relevant to this question.
For a discussion see this paper.

A: The natural numbers are the prime model of PA: in a precise sense, they are the least rich model. There are lots of notions of richness of models; these are usually expressed in terms of the realized types, essentially what sort of behavior occurs in the model. E.g. the natural numbers are not very rich since "is divisible by $2$ and $3$ and $5$ and ..." is a very easily-describable behavior which is not realized in $\mathbb{N}$.
As to whether $\mathbb{N}$ is nonstandard in any sense: certainly not in the sense that we use the word when speaking of nonstandard models. Since $\mathbb{N}$ is the smallest model of PA, there's no way to shrink it further and still have a model of PA.
Incidentally, there's an interesting set-theoretic difficulty here: conceivably the thing we think is $\mathbb{N}$ could actually be a very clever nonstandard model. This has been investigated by a number of mathematicians and philosophers, and has had lots of discussion on this site (see e.g. this question). But that wouldn't mean "$\mathbb{N}$ is nonstandard," that would mean "we were wrong about what $\mathbb{N}$ is" - $\mathbb{N}$ is defined as the smallest thing it could be (this can be made completely precise via second-order logic (this question says a bit about that), but since second-order logic is intimately bound up in set theory this isn't entirely satisfying).