text:
Q: Getting timestamp of each frame in a video I have recorded several videos from the front cam of my tablet with an Android 5.2 application I have written. I have stored the start timestamp in milliseconds (Unix time) for each video.
Unfortunately each video has a different framerate (ranging from 20 to 30). With OpenCV I'm able to get the framerate for each video:
import cv2
video = cv2.VideoCapture(videoFile)
fps = video.get(cv2.CAP_PROP_FPS)

This works well and theoretically I could just add 1000/fps (due to milliseconds) for each frame in the video. But this assumes that the framerate remains stable throughout the whole recording. I don't know if this is the case.
Is there a possibility in Python to get the timestamp (in milliseconds) of each frame in the video independent of the framerate?

A: You want cv2.CAP_PROP_POS_MSEC. See all the different capture properties here.
Edit: Actually, as Dan Mašek pointed out to me, when you grab that property, it looks like OpenCV is exactly doing that calculation (at least assuming you're using FFMPEG):
case CV_FFMPEG_CAP_PROP_POS_MSEC:
    return 1000.0*(double)frame_number/get_fps();

So it seems you're always going to rely on a constant frame rate assumption. However, even assuming a constant frame rate, it's important that you multiply by the frame number and not just keep adding 1000/fps. Errors will build up when you're repeatedly adding floats which, over a long video, can make a big difference. For example:
import cv2

cap = cv2.VideoCapture('vancouver2.mp4')
fps = cap.get(cv2.CAP_PROP_FPS)

timestamps = [cap.get(cv2.CAP_PROP_POS_MSEC)]
calc_timestamps = [0.0]

while(cap.isOpened()):
    frame_exists, curr_frame = cap.read()
    if frame_exists:
        timestamps.append(cap.get(cv2.CAP_PROP_POS_MSEC))
        calc_timestamps.append(calc_timestamps[-1] + 1000/fps)
    else:
        break

cap.release()

for i, (ts, cts) in enumerate(zip(timestamps, calc_timestamps)):
    print('Frame %d difference:'%i, abs(ts - cts))

Frame 0 difference: 0.0
  Frame 1 difference: 0.0
  Frame 2 difference: 0.0
  Frame 3 difference: 1.4210854715202004e-14
  Frame 4 difference: 0.011111111111091532
  Frame 5 difference: 0.011111111111091532
  Frame 6 difference: 0.011111111111091532
  Frame 7 difference: 0.011111111111119953
  Frame 8 difference: 0.022222222222183063
  Frame 9 difference: 0.022222222222183063
  ...
  Frame 294 difference: 0.8111111111411446

This is of course in milliseconds, so maybe it doesn't seem that big. But here I'm almost 1ms off in the calculation, and this is just for an 11-second video. And anyways, using this property is just easier.

A: I have use  moviepy to get time in seconds of individual frame
pip install moviepy

import sys
import numpy as np
import cv2
import moviepy.editor as mpy
from matplotlib import pyplot as plt

vid = mpy.VideoFileClip('input_video\\v3.mp4')

for i, (tstamp, frame) in enumerate(vid.iter_frames(with_times=True)):
    print(tstamp%60)
    plt.imshow(frame)
    plt.show()

A: I did some test with multiple library.

*

*decord

*ffprobe

*MoviePy

*PyAV

*pyffms2

*OpenCV
import av
import cv2
import json
import os
import shutil
import sys
import subprocess
import time
from decimal import Decimal
from decord import VideoReader
from ffms2 import VideoSource
from moviepy.editor import VideoFileClip
from typing import List

def with_movie_py(video: str) -> List[int]:
    """
    Link: https://pypi.org/project/moviepy/
    My comments:
        The timestamps I get are not good compared to gMKVExtractGUI or ffms2. (I only tried with VFR video)

    Parameters:
        video (str): Video path
    Returns:
        List of timestamps in ms
    """
    vid = VideoFileClip(video)

    timestamps = [
        round(tstamp * 1000) for tstamp, frame in vid.iter_frames(with_times=True)
    ]

    return timestamps

def with_cv2(video: str) -> List[int]:
    """
    Link: https://pypi.org/project/opencv-python/
    My comments:
        I don't know why, but the last 4 or 5 timestamps are equal to 0 when they should not.
        Also, cv2 is slow. It took my computer 132 seconds to process the video.

    Parameters:
        video (str): Video path
    Returns:
        List of timestamps in ms
    """
    timestamps = []
    cap = cv2.VideoCapture(video)

    while cap.isOpened():
        frame_exists, curr_frame = cap.read()
        if frame_exists:
            timestamps.append(round(cap.get(cv2.CAP_PROP_POS_MSEC)))
        else:
            break

    cap.release()

    return timestamps

def with_pyffms2(video: str) -> List[int]:
    """
    Link: https://pypi.org/project/ffms2/
    My comments:
        Works really well, but it doesn't install ffms2 automatically, so you need to do it by yourself.
        The easiest way is to install Vapoursynth and use it to install ffms2.
        Also, the library doesn't seems to be really maintained.

    Parameters:
        video (str): Video path
    Returns:
        List of timestamps in ms
    """
    video_source = VideoSource(video)

    # You can also do: video_source.track.timecodes
    timestamps = [
        int(
            (frame.PTS * video_source.track.time_base.numerator)
            / video_source.track.time_base.denominator
        )
        for frame in video_source.track.frame_info_list
    ]

    return timestamps

def with_decord(video: str) -> List[int]:
    """
    Link: https://github.com/dmlc/decord
    My comments:
        Works really well, but it seems to only work with mkv and mp4 file.
        Important, Decord seems to automatically normalise the timestamps which can cause many issue: https://github.com/dmlc/decord/issues/238
        Mp4 file can have a +- 1 ms difference with ffms2, but it is acceptable.

    Parameters:
        video (str): Video path
    Returns:
        List of timestamps in ms
    """
    vr = VideoReader(video)

    timestamps = vr.get_frame_timestamp(range(len(vr)))
    timestamps = (timestamps[:, 0] * 1000).round().astype(int).tolist()

    return timestamps

def with_pyav(video: str, index: int = 0) -> List[int]:
    """
    Link: https://pypi.org/project/av/
    My comments:
        Works really well, but it is slower than ffprobe.
        The big advantage is that ffmpeg does not have to be installed on the computer, because pyav installs it automatically

    Parameters:
        video (str): Video path
        index (int): Stream index of the video.
    Returns:
        List of timestamps in ms
    """
    container = av.open(video)
    video = container.streams.get(index)[0]

    if video.type != "video":
            raise ValueError(
                f'The index {index} is not a video stream. It is an {video.type} stream.'
            )

    av_timestamps = [
        int(packet.pts * video.time_base * 1000) for packet in container.demux(video) if packet.pts is not None
    ]

    container.close()
    av_timestamps.sort()

    return av_timestamps

def with_ffprobe(video_path: str, index: int = 0) -> List[int]:
    """
    Link: https://ffmpeg.org/ffprobe.html
    My comments:
        Works really well, but the user need to have FFMpeg in his environment variables.

    Parameters:
        video (str): Video path
        index (int): Index of the stream of the video
    Returns:
        List of timestamps in ms
    """

    def get_pts(packets) -> List[int]:
        pts: List[int] = []

        for packet in packets:
            pts.append(int(Decimal(packet["pts_time"]) * 1000))

        pts.sort()
        return pts

    # Verify if ffprobe is installed
    if shutil.which("ffprobe") is None:
        raise Exception("ffprobe is not in the environment variable.")

    # Getting video absolute path and checking for its existance
    if not os.path.isabs(video_path):
        dirname = os.path.dirname(os.path.abspath(sys.argv[0]))
        video_path = os.path.join(dirname, video_path)
    if not os.path.isfile(video_path):
        raise FileNotFoundError(f'Invalid path for the video file: "{video_path}"')

    cmd = f'ffprobe -select_streams {index} -show_entries packet=pts_time:stream=codec_type "{video_path}" -print_format json'
    ffprobeOutput = subprocess.run(cmd, capture_output=True, text=True)
    ffprobeOutput = json.loads(ffprobeOutput.stdout)

    if len(ffprobeOutput) == 0:
        raise Exception(
            f"The file {video_path} is not a video file or the file does not exist."
        )

    if len(ffprobeOutput["streams"]) == 0:
        raise ValueError(f"The index {index} is not in the file {video_path}.")

    if ffprobeOutput["streams"][0]["codec_type"] != "video":
        raise ValueError(
            f'The index {index} is not a video stream. It is an {ffprobeOutput["streams"][0]["codec_type"]} stream.'
        )

    return get_pts(ffprobeOutput["packets"])

def main():
    video = r"WRITE_YOUR_VIDEO_PATH"

    start = time.process_time()
    movie_py_timestamps = with_movie_py(video)
    print(f"With Movie py {time.process_time() - start} seconds")

    start = time.process_time()
    cv2_timestamps = with_cv2(video)
    print(f"With cv2 {time.process_time() - start} seconds")

    start = time.process_time()
    ffms2_timestamps = with_pyffms2(video)
    print(f"With ffms2 {time.process_time() - start} seconds")

    start = time.process_time()
    decord_timestamps = with_decord(video)
    print(f"With decord {time.process_time() - start} seconds")

    start = time.process_time()
    av_timestamps = with_pyav(video)
    print(f"With av {time.process_time() - start} seconds")

    start = time.process_time()
    ffprobe_timestamps = with_ffprobe(video)
    print(f"With ffprobe {time.process_time() - start} seconds")

if __name__ == "__main__":
    main()

Here is how much times it took to get the timestamps for an mp4 of 24 minutes.
With Movie py 11.421875 seconds
With cv2 131.890625 seconds
With ffms2 0.640625 seconds
With decord 0.328125 seconds
With av 0.6875 seconds
With ffprobe 0.21875 seconds

A: This is a simplified version that just reads in a video and prints out a frame number with its timestamp.
import cv2

cap = cv2.VideoCapture('path_to_video/video_filename.avi')

frame_no = 0
while(cap.isOpened()):
    frame_exists, curr_frame = cap.read()
    if frame_exists:
        print("for frame : " + str(frame_no) + "   timestamp is: ", str(cap.get(cv2.CAP_PROP_POS_MSEC)))
    else:
        break
    frame_no += 1

cap.release()

This gives an output that looks like this:
for frame : 0   timestamp is:  0.0
for frame : 1   timestamp is:  40.0
for frame : 2   timestamp is:  80.0
for frame : 3   timestamp is:  120.0
for frame : 4   timestamp is:  160.0
for frame : 5   timestamp is:  200.0
for frame : 6   timestamp is:  240.0
for frame : 7   timestamp is:  280.0
for frame : 8   timestamp is:  320.0
for frame : 9   timestamp is:  360.0
for frame : 10   timestamp is:  400.0
for frame : 11   timestamp is:  440.0
for frame : 12   timestamp is:  480.0
...

A: Normally these camera's have a rolling shutter, this implies that the image is scanned line by line, so strickly speaking one cannot put one time stamp on the image. I've been working on the synchronisation of multiple rolling shutter camera's (iPhone 6) using an exactly timed (ns-scale) led-flash. I found that the framerate is variable (nominal 240 fps at high speed, but varies between 239,something and 241,something. Mutual synching can be done up to 1/500000 s, but this requires a special setup. If you are interested I can send you some documentation (I'm afraid my software is in Matlab, so no readily available python code)


text:
Q: Xamarin.Forms when click on ListView ViewCell background color changed to orange , but not initialized to a color This is my code
<ListView x:Name="listViewClient"  ItemsSource="{Binding Client}" HasUnevenRows="True">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell >

                        <Grid  Margin="10">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="5"/>
                                <ColumnDefinition />
                            </Grid.ColumnDefinitions>
                            <BoxView  Grid.Column="0" Color="#84DCC6"/>
                            <StackLayout Grid.Column="1" Padding="20, 10">

                                <Frame BorderColor="WhiteSmoke">
                                    <StackLayout>
                                <Label Text="Name:" FontSize="16" />
                                <Label FontSize="Medium" Text="{Binding Name}" FontAttributes="Bold" />
                                    </StackLayout>
                                </Frame>
                                <Frame BorderColor="WhiteSmoke">
                                    <StackLayout>
                                    <Label Text="Adress:"  FontSize="16"/>
                                <Label FontSize="Medium" Text="{Binding Adress}" FontAttributes="Bold"/>
                                    </StackLayout>
                                </Frame>
                                <Frame BorderColor="WhiteSmoke">
                                    <StackLayout>
                                    <Label Text="Place:"  FontSize="16"/>
                                    <Label FontSize="Medium" Text="{Binding Place}" FontAttributes="Bold" />
                                    </StackLayout>
                                </Frame>

                                <Frame BorderColor="WhiteSmoke" >
                                    <Grid >

                                    <StackLayout Grid.Column="0">
                                    <Label Text="Mobile:"  FontSize="16"/>
                                    <Label  FontSize="Medium" Text="{Binding Mobile}" FontAttributes="Bold" />
                                    </StackLayout>
                                        <Button Grid.Column="1" Text="Call" Clicked="PovikajPartnerClicked" BackgroundColor="#84DCC6"></Button>
                                    </Grid>
                                </Frame>
                                <Frame BorderColor="WhiteSmoke">
                                    <StackLayout>
                                        <Label Text="Е-mail:"  FontSize="16"/>
                                        <Label FontSize="Medium" Text="{Binding EMAIL}" FontAttributes="Bold" />
                                    </StackLayout>
                                </Frame>
                                <Frame BorderColor="WhiteSmoke">
                                    <StackLayout>
                                        <Label Text="LAW:"  FontSize="16"/>
                                        <Label FontSize="Medium" Text="{Binding LAW}" FontAttributes="Bold" />
                                    </StackLayout>
                                </Frame>

                                <Frame BorderColor="WhiteSmoke
                                       ">
                                    <StackLayout>
                                <Label Text="SECNUM:"  FontSize="16"/>
                                <Label FontSize="Medium" Text="{Binding SECNUM}" FontAttributes="Bold" />
                                    </StackLayout>
                                </Frame>

                            </StackLayout>
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

I dont know from where get that orange background color when i tap on the listview. From the code you can see that i dont have choosed samo backgroud color . Is there a default tap event to make the color orange? I tried everything but cant find is there anyplace i forgot to add a color.

A: I know this may be a bit late, but I hope it will help someone, Just go your styles.xml file under AppName.Android/Resources/values and inside your Main Theme add the following:
<item name="android:colorActivatedHighlight">@android:color/transparent</item>

A: That is the default selection colour of your ListView that comes from the theme of your App that Xamarin by default has set in the template to solve it just add the following to your ListView
<ListView SelectionMode="None" ..../>

A: I am late to the party, but this solution I found on Grepper might be helpful. It is simple and is unique for each content page.
You can alter the background color of the current cell and the previous cell using the ViewCell Tapped event.
XAML:
<ListView.ItemTemplate>
    <DataTemplate>
        <ViewCell Tapped="ViewCell_Tapped" >
            <Label Text="{Binding Name}" TextColor="DarkGoldenrod" />
        </ViewCell>
    </DataTemplate>
</ListView.ItemTemplate>

In your code add:
ViewCell lastCell;
private void ViewCell_Tapped(object sender, System.EventArgs e)
{
    if (lastCell != null)
        lastCell.View.BackgroundColor = Color.Transparent;
    var viewCell = (ViewCell)sender;
    if (viewCell.View != null)
    {
        viewCell.View.BackgroundColor = Color.LightGray;
        lastCell = viewCell;
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: QuitStrategy is gone in eawt jdk 8 I have an application which on exit should close all windows and write some configuration files.
Without the things I did below, the following was never triggered and so the closeEXES which writes all the configs out was never run.
    mainframe.addWindowListener(new java.awt.event.WindowAdapter() {

        @Override
        public void windowClosing(WindowEvent winEvt) {
            closeEXES();
        }
    });

I used the following to catch the Cmd-Q on Mac OS:
import com.apple.eawt.QuitStrategy;
import com.apple.eawt.Application;

And in main:
    if (System.getProperty("os.name").equals("Mac OS X")) {
        Application.getApplication().setQuitStrategy(QuitStrategy.CLOSE_ALL_WINDOWS);

The version before that I did:
        public class MacQuitAdapter extends ApplicationAdapter {
            @Override
            public void handleQuit(ApplicationEvent e) {
                System.out.println("Using deprecated AplicationAdapter for handling Quit.");
            }
        }

How would I accomplish the same thing with JDK 8? The "same thing" is to make sure that when Command-Q is hit, the closing of the windows will be passed to AWT so that the windowClosing method will do what I want.
Alternatively, is there some other listener I need to sense the Command-Q?  I'll keep looking but thought it was worth asking here.
Thanks.

A: I'm sorry to answer my own question. Please let me know if this is a faux pas. I used this plus still kept the close-window part of the code.  For JDK 8 this does most of what I want.
So now the code looks like this:
    mainframe.addWindowListener(new java.awt.event.WindowAdapter() {

        @Override
        public void windowClosing(WindowEvent winEvt) {
            closeEXES();
        }
    });

    if (System.getProperty("os.name").equals("Mac OS X"))
    {
        Runtime.getRuntime().addShutdownHook(new Thread()
        {
            @Override
            public void run()
            {
                System.out.println("in : run () : shutdownHook");
                doCloses();
                System.out.println("Shutdown hook completed...");
            }
        });
    }

one method, closeEXES, prompts the user to make SURE they really meant to quit the application.  The other checks a condition (have the files been closed before?) and closes them if they have not been closed.
For completeness:
public void closeEXES() {
    int n = JOptionPane.showConfirmDialog(mainframe,
            "Close EXES GUI?", "Closing EXES GUI",
            JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    if (n == 0) {
        System.out.println("Exiting...start");
        doCloses();
        System.exit(0);
    }
}

public void doCloses() {
    if ( beenClosed )
    {
        System.out.println("Already closed all files.");
    }
    else
    {
        // ... a bunch of stuff here writing GUI screen positions to a file and
        // things like that ...

        beenClosed = true;
    }
}


text:
Q: Doctrine MOD - even date doctrine with symfony With doctrine i have generate a controller to show a movie title.
I have this error

[Syntax Error] line 0, col 52: Error: Expected =, <, <=, <>, >, >=,
  !=, got '%'

The First code work but the second code dont show even year.
Why?
/** Mostrare i film usciti tra il 1980 e il 1990
 *
 * @Route("/findBetweenYears/{yearStart}/{yearStop}", name ="movie_between")
 * @Method("GET")
 *
*/
public function showMovieBetweenAction($yearStart,$yearStop){
  $em = $this->getDoctrine()->getManager();
  $qb = $em->createQueryBuilder();
  $qb->select('m')
  ->from(Movie::class,'m')
  ->where('m.year >= 1980 and m.year <=1990');
  $movies = $qb->getQuery()->getResult();
  return $this->render('movie/yearshow.html.twig',array(
   'movies' => $movies,
  ));

}
/** Mostrare i film usciti in un anno pari
 *
 * @Route("/findEvenYears/{year}", name = "movie_even")
 * @Method("GET")
 *
*/
public function showMovieYearEven(){
  $em = $this->getDoctrine()->getManager();
  $qb = $em->createQueryBuilder();
  $qb->select('m')
  ->from(Movie::class,'m')
  ->where('m.year % 2 = 0');
  $movies = $qb->getQuery()->getResult();
  return $this->render('movie/yeareven.html.twig',array(
    'movies' => $movies
  ));
}

A: Doctrine mod DQL is defined in the documentation as

MOD(a, b) - Return a MOD b.

Meaning you should use it as
  ->where('MOD(m.year, 2) = 0')


text:
Q: C programming printing a linked list, not moving along list and crashing I am trying to print a linked list, it is acting strangely, when it is suppose to move to the next item it will not, for instance the first item printed is "Granny Smith" and then the rest in the struct, when it goes to the next line what should be a new food is "ranny Smith" Always without the G, and most of the other details are corrupted or gibberish. Any help would be greatly appreciated.
#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define cls system("cls");
#define flush fflush(stdin)
#define pause system("pause");

struct food  // Declaration of struct
{
    char produce[20];
    char type[20];
    char soldBy[20];
    float price;
    int quantityInStock;
    struct food *next;
};

void addPres(struct food** tip, char tokenPro[20], char tokenType[20], char tokenSold[20], float tokenFloat, int tokenInt);
void display ();
void displayMenu ();
int getChoice ();
void readDataIn();

int main()
{
    int choice = 0;
    int ;
    struct food first;
    char *saveFloat, *saveInt;
    char tokenPro[20], tokenType[20], tokenSold[20], savePro[20], saveType[20], saveSold[20], j[1900];
    float tokenFloat, messFloat;
    int danint, tokenInt;
    struct food* a = NULL;
    FILE* file;

    a = NULL; // sets the first item on the list to empty

//readDataIn();
    do
    {
        choice = getChoice();//function to present choices and receive an answer
        switch (choice)//switch routes the choice
        {
        case 1: //to enter a new node on the list
            cls;
            printf("Enter the produce type: ");
            fgets(tokenPro, 20, stdin);
            printf("Enter the type: ");
            fgets(tokenType, 20, stdin);
            printf("Enter the units of measurement: ");
            fgets(tokenSold, 20, stdin);
            printf("\nEnter the price per %s: ", &tokenSold);
            scanf("%f", &tokenFloat );
            printf("\nEnter the quantity in stock: ");
            scanf("%i", &tokenInt );
            //pause;
            addPres(&a, tokenPro, tokenType, tokenSold, tokenFloat, tokenInt);
            break;
        case 2: //to display the linked list
            display(a);

            break;
        case 3: //to reverse the order

            if((file=fopen("AssignmentTwoInput.txt", "r")) != NULL)  //opens files
            {
                while(fgets(j, sizeof(j), file))  //while information is being sent to j from the file
                {
                    strcpy(savePro, strtok(j, ","));
                    strcpy(saveType, strtok(NULL, ","));
                    strcpy(saveSold, strtok(NULL, ","));
                    saveFloat = strtok(NULL, ",");
                    saveInt = strtok(NULL, "\n");
                    messFloat = atof(saveFloat); //ID number is assigned to token2
                    danint = atoi(saveInt); //converts  the value token2 points to into an int (previously read in as an string)
                    addPres(&a, savePro, saveType, saveSold, messFloat, danint); //sends the name and ID to the function to add a person
//printf("\n %s \t %s \t %s \t %f \t %i", savePro, saveType, saveSold, messFloat, danint);
//pause;
                }//end while loop
            }//end if loop
            printf("\nSuccessfully loaded input file\n\n\n"); //message to tell user the back was found and imported successfully
            pause;
            fclose(file);
            break;
        case 4: //to export data

            break;
        case 5: //option to exit

            exit(0);
            break;
        default://error checking
            printf("Please enter a valid choice.\n");
            break;
        }//switch loop close

    }
    while (choice != 5);   //end menu choices

    return 0;
}//end main

void addPres(struct food** tip, char tokenPro[20], char tokenType[20], char tokenSold[20], float tokenFloat, int tokenInt)
{

    struct food* temp =

        (struct food*) malloc(sizeof(struct food));
    strcpy(temp->produce, tokenPro);
    strcpy(temp->type, tokenType);
    strcpy(temp->soldBy, tokenSold);
    temp->price = tokenFloat;
    temp->quantityInStock = tokenInt;

//printf("\n %s \t %s \t %s \t %f \t %i", temp->produce, temp->type, temp->soldBy, temp->price, temp->quantityInStock);
//pause;
    if (tip == NULL) //if the tip node is empty
    {
        tip = temp; //tip node becomes this node
        (*tip)->next = NULL; // since there are no others yet the next node will be empty
    }

    else
    {
        temp->next = tip; // reassigns the tip node to the next one
        (*tip) = temp; //inserts current node as the tip
    }
}

void display(struct food* c)
{
//c = first; //assigns c to the first node on the linked list
    int count = 1;
    struct food *temp;
    temp = c;
    cls;
    printf("==========================================================================\n"); //prints a header to say which info is which
    printf(" Item #   Produce       Type             Sold By         Price    In Stock\n");
    printf("==========================================================================\n");
    while( c != NULL)
    {
        printf("%3i \t", count);
        printf("%s \t", c->produce ); //prints name
        printf("%s \t", c->type ); //prints name
        printf("%s \t", c->soldBy); //prints name
        printf("%-3.2f \t", c->price); //prints ID
        printf("%i\n", c->quantityInStock); //prints ID
        pause;
        count = count + 1;
        c = c->next; //advances to next item in the linked list

        if(c == NULL)
        {
            printf("\n end \n"); //once end is found user is told

            pause;
        }
    }
    printf("\n done \n");
    pause;
}//end display

A: You have three important mistakes, one of them seems to be caused by copying and pasting some code,

*

*This printf() statement would cause undefined behavior
printf("\nEnter the price per %s: ", &tokenSold);

because you are passing the correct address but the pointer type is wrong so pointer arithmetic will cause undefined behavior inside printf()
printf("\nEnter the price per %s: ", tokenSold);
/* remove the & --------------------^ here */

*You passed a double pointer to addPres but you never dereference it to access the actual poitner, which is what you want to modify, that is causing both, undefined behavior and the observed effect of an empty list, since once the function returns it did not alter the original poitner, you should access the double pointer with the dereference operator inside this function, for example instead of
if (tip == NULL)

it has to be
if (*tip == NULL)

and the same applies for every access inside this function.

*

*How did I find out all these problems so quickly?

Because I compiled your programs with compiler warnings enabled and it started showing those problems.

*Will there be other issues in your code?

Yes probably, but you need to fix these first.

*You fflush(stdin), a very common mistake which seems to come from some tutorials or books or online resources, the standard clearly states that fflush() is for output streams, and the behavior is undefined for input streams, the following was taken from the C11 draft

7.21.5.2 The fflush function

*If stream points to an output stream or an update stream in which the most recent
  operation was not input, the fflush function causes any unwritten data for that stream
  to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.


text:
Q: How to send array of arrays as data in ajax I have an array like this
var data = ["id","userId",[{item:[1,2]},{item:[1,2]}]]

Currently i'm sending this data as
var data = ["id","userId","[{\"item\":[\"1\",\"2\"]},{\"item\":[\"1\",\"2\"]}"]]
by using JSON.stringify()

Now when i receive this data for parsing this i have to split it across [{ ,}]
and then splitting at }, to run a for loop on the array elements
vars args = args[2].toString().split("[{")[1].split("}]")[0];
args = '{' +args;
var list = args.split("},");
list.forEach((elem)=>{
   elem = elem + '}';
   elem = JSON.parse(elem);
   var items = elem.item;
});

otherwise with JSON.parse() i'm getting unexpected token error.I tried using JSON.stringify() and then parsing it but i got the same error.
How do i parse this data correctly on the server side?

A: I think you can format your data a bit better, so it's a valid JSON.
example:
     {
       "id": "userId",
       "data": [
                {
                  "item": [1,2]
                },
                {
                   "item": [1,2]
                }
              ]
      }

A: If you really want to send a stringified Array instead of the original Array JSON.stringify is the way to go.
Your code will look something like this:

const data = ["id", "userId", [{item: [1, 2]}, {item: [1, 2]}]];

// check for each item in data if its an array and convert it to a JSON string
data.forEach((d, i) => {
  if (Array.isArray(d)) {
    data[i] = JSON.stringify(d);
  }
});

console.log(data);

This will be a more sustainable solution because the script checks and converts every item on the list. So if the list changes in the future this script still converts it successfully.


text:
Q: Automatically refresh the web page after updating the database I have developed a web page using php and mysql lanuages. But,I want to refresh the web page which is run on local host  automatically after updating the connected database.How can I do it?

A: Do an AJAX request that goes to PHP function that makes the update. If should check the status of the update (success, failure etc) and deliver that back to the JavaScript. If fail, print a message to HTML. If success, do:
window.reload();

A: after the connection is done write in javascript this line
window.reload();

A: use mysql_affected_rows() function it returns the number of affected rows on success in case of insert,update and delete and -1 on failure.
check if condition is success use setTimeout(function(){location.reload();}, 500); to refresh the page automatically.


text:
Q: Is there any 3rd party library available in iOS(Objc) for `textinputlayout` like android I am search a Library in iOS (Objc) for textinputLayout like android has.
here is the video url for more clarity,
https://youtu.be/YnQHb0fNtF8
Can anyone please tell if there is any 3rd party library available or do I need to write my own code with the help of animations.

A: You can use your custom view with textfield validation on didEndEditing delegate and validate and make your custom design for your validations .
or
you can find similar library with

*

*https://github.com/enisgayretli/EGFloatingTextField (swift)

*https://www.cocoacontrols.com/controls/swiftyform (swift)


text:
Q: Find the volume of the region using cylindrical shells. A region is bounded by the line $y=x+6$ and the parabola $y=x^2$ rotated about the x-axis. I had a similar problem rotated about the $x=3$ line but now this is rotated on the x-axis. I am having trouble identifying what the height of the cylindrical shell is. I believe that the radius is $y$, thickness is $dy$ and the limits of integration go from $0$ to $9$. I drew the graph out and drew a line parallel to the axis of rotation, but the height seems to go from $y=x^2$ to $y=x+6$ and it also goes from one end of $y=x^2$ to the other when $y < 4$. Did I draw this picture wrong since I cannot determine the height of the shell?

A: The method of shells is non-optimal here, "washers" are much easier. And a picture, and being able to point to parts of it, would be very useful.
We will be integrating with respect to $y$. Note that the geometry  from $x=-2$ to $x=2$, is different from the geometry for $x$ between $2$ and $3$. Or, to put it in terms of $y$, the situation from $y=0$ to $y=4$ is different than the situation from $y=4$ to $y=9$.
So we will have to break up the integral into two parts, $y=0$ to $4$ and $y=4$ to $9$, and add.
First Integral: We are going from $y=0$ to $y=4$. Maybe draw a horizontal line at height $y=4$.
Draw a thin horizontal strip of width $dy$ at height $y$, where $0\le y\le 4$. The length of the strip is $2x$, which is $2\sqrt{y}$. The height (radius, distance from the $x$-axis) is $y$. Thus the volume of this chunk is
$$\int_{y=0}^4 (2\pi)(2\sqrt{y})(y)\,dy.$$
Second integral: Now we are going $y=0$ to $y=9$. The radius is again $y$. But now the length of the strip is different.  It starts on the line $x=y-6$, and ends on $x=\sqrt{y}$, so has length $\sqrt{y}-(y-6)$. So this part of our volume is
$$\int_{y=4}^9 (2\pi)(y)\left(\sqrt{y}-(y-6)\right)\,dy.$$
Evaluate the two integrals and add.


text:
Q: For BSP generation, How to intersect or locate a triangle with a plane defined by another triangle? I've hit a stumbling block in my project to draw the Utah teapot. I want to generate a binary space partition tree of a set of 3D triangles.
The decision step in the recursive tree-construction algorithm is determining whether one triangle is in front of or behind the plane defined by another triangle.
So, given two triangles, $T_0 = (P_1, P_2, P_3), T_1 = (P_4, P_5, P_6), P_1 = (x_1, y_1, z_1), P_2 = (x_2, y_2, z_2)$, ..., we take a normal vector of $T_0$, $N_0 = (P_2 - P_1) \times (P_3 - P_1)$.
And then I get confused. Help?
I think I need to describe the coordinates of $T_1$ in terms of a Plane [ a b c d ] + $N_0$. The magnitude of the resulting vector is the distance. Positive or negative determines whether it's in front of or behind the plane. But I'm fuzzy on step 2.

A: Using determinants
You can use the sign of the determinant
$$\begin{vmatrix}
x_1 & x_2 & x_3 & x_4 \\
y_1 & y_2 & y_3 & y_4 \\
z_1 & z_2 & z_3 & z_4 \\
1 & 1 & 1 & 1
\end{vmatrix}$$
to decide on which side of the plane spanned by $P_1, P_2, P_3$ the last point $P_4$ lies. So take the three corners of one triangle, and perhaps the center of the other triangle, and compute the sign of that determinant to make your decisions.
You could even move the division from the computation of the center into the determinant like this:
$$\begin{vmatrix}
x_1 & x_2 & x_3 & x_4 + x_5 + x_6 \\
y_1 & y_2 & y_3 & y_4 + y_5 + y_6 \\
z_1 & z_2 & z_3 & z_4 + z_5 + z_6 \\
1 & 1 & 1 & 3
\end{vmatrix}$$
The last column is the center of the triangle $P_4,P_5,P_6$, scaled by 3. This will scale the value of the determinant by 3 as well, but won't affect its sign.
Normal form
And in case you have to compare multiple points against a given plane, you can do Laplace expansion along the fourth column and end up with 4 numbers, each computed as a $3\times 3$ determinant, which represent something like the normal form of the plane and can be used to perform the subsequent checks using only 4 multiplications per point. So you'd compute
\begin{align*}
a &= -\begin{vmatrix}
y_1 & y_2 & y_3 \\
z_1 & z_2 & z_3 \\
1 & 1 & 1
\end{vmatrix} &
b &= \begin{vmatrix}
x_1 & x_2 & x_3 \\
z_1 & z_2 & z_3 \\
1 & 1 & 1
\end{vmatrix} \\[2ex]
c &= -\begin{vmatrix}
x_1 & x_2 & x_3 \\
y_1 & y_2 & y_3 \\
1 & 1 & 1
\end{vmatrix} &
d &= \begin{vmatrix}
x_1 & x_2 & x_3 \\
y_1 & y_2 & y_3 \\
z_1 & z_2 & z_3 \\
\end{vmatrix}
\end{align*}
After this precomputation, you can use the sign of $ax+by+cz+d$ to decide on which side of the plane a point $(x,y,z)$ lies. If you want to use centroids without division, you'd multiply $d$ by $3$ and the others by the coordinate sums. The plane itself is described as
$$ \left\{(x,y,z)\in\mathbb R^3\;\middle\vert\;ax+by+cz+d=0\right\} $$
Notice that this is not quite the Hesse normal form of the plane, because the normal vector $(a,b,c)$ isn't normalized to unit length, and $d$ isn't neccessarily positive but instead indicates on which side of the plane the origin lies. So for computing distances you'd do some more computations, but to decide sidedness, these numbers $a$ through $d$ are all you need.


text:
Q: Why, in AppleScript, can't you declare references to variables local to handlers? Why can't you declare and use references to variables unless the variable referenced is scoped globally?  Please explain the runtime memory or object structure that leads to the following phenomenon:
Script A fails:
on foo()
    set l to {0}
    set lref to a reference to l
    return item 1 of lref
end foo

foo()

Script B succeeds:
on run
    set l to {0}
    set lref to a reference to l
    return item 1 of lref
end run

Script C succeeds:
on foo()
    global l
    set l to {0}
    set lref to a reference to l
    return item 1 of lref
end foo

foo()

See also: How do you efficiently build a list within a handler in AppleScript? and Why Can't AppleScript make firstValue of hash into type reference in this test code?

A: Because a "reference" is the same thing as an object specifier, so you can't make a reference to something that isn't (or is contained by something that isn't) an object as far as AppleScript is concerned.
A global variable is owned by the top-level script object -- it's really a property with no initializer.  (You can also have a reference to a script property; it doesn't have to be strictly global.)
A local variable, on the other hand, is owned by the call frame of the handler that it's in, and call frames are not objects in AppleScript, therefore, no references.


text:
Q: CORS error: Turning CSV file into Javascript array I am trying convert a CSV file into a javascript array. In the CSV file, all of the values are on separate lines. Anyway, I found this piece of code in another post on Stackoverflow to turn such a file into an array:
var adressesList = []

  $(document).ready(function() {
    $.ajax({
      type: "GET",
      url: "Filepath",
      dataType: "text",
      success: function(data) {
        processData(data);
      }
    });
  });

  function processData(allText) {
    var allTextLines = allText.split(/\r\n|\n/);
    for (var i = 1; i < allTextLines.length; i++) {
      adressesList.push(allTextLines[i]);
    }
  }

I have tried this but I keep getting an error saying that I am not allowed to access the file (it is local on my computer in the same folder as the code).
This is the error I see:
Access to XMLHttpRequest at 'filepat' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

GET filepath net::ERR_FAILED

How could I solve it? I saw that you could put the file on a server. But, shouldn't there just be an easy way to do it locally?
Thank you.

A: If you only need this as a one time solution running locally, you might find it easier to load and process this file via File API.
Example:

function handleFiles(files) {
  getAsText(files[0])
}

function getAsText(fileToRead) {
  const reader = new FileReader()
  reader.readAsText(fileToRead)
  reader.onload = (event) => processData(event.target.result)
}

function processData(allText) {
  console.log(allText)
  // do your processing below
  var allTextLines = allText.split(/\r\n|\n/)
  for (var i = 1; i < allTextLines.length; i++) {
   adressesList.push(allTextLines[i]);
  }
}
<input type="file" onchange="handleFiles(this.files)" accept=".csv">

A: If the file is static (you write it once and it stays the same), then you can export it as a constant and won't need to use ajax. See more about how to do that here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export
If the file is dynamic and will change over time, you'll need to put it on a webserver you can request the file from, often called an "endpoint". If you're on a different domain (say the server is on foo.com and your website is on bar.com) you'll need to add permission on the server settings to allow requests from other domains.


text:
Q: Access a field in a row based on a function So, I'd like to read the value of J24, but J should be calculated. So I'm looking for a function that accept two parameters toe and column, instead of just writing J24.
GetFieldData('J',24).

A: Although I'm not sure whether I could correctly understand about J should be calculated, if you want to use 'J',24 as J24 of the A1Notation, how about using INDIRECT as follows?
=GetFieldData(INDIRECT("J"&24))

Note:

*

*Although I'm not sure about the script of GetFieldData, if you want to use the value from the cell J24 by giving J and 24 to the custom function, how about the following modification? In this case, value can be used by putting a formula of =GetFieldData("J",24) to a cell.
  function GetFieldData(a, b) {
    const value = SpreadsheetApp.getActiveSheet().getRange(a + b).getValue();

    // do something.

  }

Reference:

*

*INDIRECT


text:
Q: How to share a Mac OsX host folder to a Win Srvr 2008 virtualbox guest so that it can be mapped as a network drive (no Vbox shared folder) I need to share a Mac OsX (El Capitan) host folder to a Windows Server 2008 virtualbox guest machine so that it can be mapped as a network drive.
**I can't use VirtualBox shared folder functionalities because its basic ACL gives weird behaviors on PHP file system function checks (such as is_readable).
On a Windows host I was able to share and mount the folder and to map it as a network drive correctly. I need to reproduce the same on a Mac Host. I tried NFS but I wasn't able to mount the NFS folder on the guest machine.
Do you know a reliable way to do it?

A: OS X can share folders over SMB. Open System Preferences -> Sharing -> Options and enable SMB sharing.


text:
Q: Deploy project without /WEB-INF/lib by placing libs in Tomcat's common.loader I would like to deploy my project without /WEB-INF/lib.
I created a folder /usr/share/tomcat7/mylib and move all the files from /WEB-INF/lib. I ordered this directory for common.loader, but the application has stopped running.
java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.internal.engine.ConfigurationImpl
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
    ...

A: The error is due to org.hibernate.validator.internal.engine.ConfigurationImpl not spring libraries. Check for hibernate-validator jar


text:
Q: IntelliJ IDEA 2017.1 shows "var" instead of actual type After upgrading to IntelliJ IDEA 2017.1 variables now do not show their types. Instead, it shows var. Also, it abbreviates some method calls. For example instead me.getIdAsStr() it shows me.idAsStr. How to revert to the old behavior?

A: This behavior is caused by the Advanced Java Folding plug-in. Either disable the plug-in or change its setting to not fold certain code elements.

A: To disable showing val/var instead of variable type
go to Settings | Editor | General | Code Folding
and UnCheck Variable Declaration
And just next to it
Uncheck Getters and setters
to start showing getter Setter method calls with full method name


text:
Q: Generate OAuth 1.0 Nonce, Timestamp and Signature using the RequestURL, ConsumerKey and ConsumerSecret in Java or JMeter How to generate OAuth 1.0 Nonce, Timestamp and Signature using the RequestURL, ConsumerKey and ConsumerSecret in Java or JMeter. I have to send these as parameters in the LTI request.

A: As per Running Performance Tests on OAuth Secured Apps article:

*

*oauth_consumer_key - this is something you should have beforehand

*oauth_timestamp - Current timestamp (in seconds from 01.01.1970)

*oauth_nonce - Any random string (usually current timestamp in milliseconds from 01.01.1970)

*oauth_signature - calculated depending on signature type

*

*PLAINTEXT - URL-encoded Consumer Secret + & + Token Secret

*HMAC-SHA1 - base64 of the sha1 of the Signature Base String - the HTTP Method followed by "&", then the URL of the resource (http or https), and then followed by the parameters which are sent to the endpoint and sorted alphabetically - hashed by the Consumer Secret

*RSA-SHA1: PKCS#1 - of Signature Base String hashed by Consumer's private RSA key - and again Base64 and URL-encoded.

More information: https://oauth.net/core/1.0/
So you will need the following JMeter Functions:

*

*__time() - for the timestamps

*__urlencode() - for URL-encoding the signatures

*__base64Encode() - for encoding the signatures into Base64

*__digest() or __groovy() - for generating HMAC/RSA digests depending on the signature type


text:
Q: Calling jQuery function on page load with multiple elements I'm working with Volusion and am trying to call a jQuery function on page load. I'm a little new to jQuery so please bear with me. Basically there are '.productnamecolor.colors_productname' items that are wrapped together with a '.pricecolor.colors_productprice' in a div without a selector. There are six on the page and I'm trying to call a jQuery function on all of them. This is all dynamically generated so I'm having to do a little bit of a workaround.

            Peasant Blouse

            view details

So what I'm trying to do is add an anchor tag to the ('.pricecolor.colors_productprice') element with the same href attribute as the corresponding productnamecolor. I don't know how to call this on 'page load' though. The .load() function doesn't seem to work this way. I was going to write a function and call it on page load but I need to use the $(this) property since there are six of these elements on the same page. Here's what I've written out (be aware that the 'load' is wrong but it's as far as I've gotten):
$('.productnamecolor.colors_productname').load(function(){
var link = $(this).attr('href');
$(this).parent().find('.pricecolor.colors_productprice').wrap('');
});

Thanks for your help!

A: $(function () {
    $('.productnamecolor.colors_productname').each(function () {
        var link = $(this).attr('href');
        $(this).parent().find('.pricecolor.colors_productprice').wrap('');
    });
});


text:
Q: using HashSet with overridden .equals() I'm trying to use HashSet in java 8 with an overridden .equals() method.  Here's a example of the code I'm using:
import java.util.HashSet;

public class Test{
    String id;
    int a;

    public Test (String i, int a){
            this.id = i;
            this.a = a;
    }

    @Override
    public boolean equals(Object obj){
        if (obj instanceof Test){
            if (((Test)obj).id == this.id){
                    return true;
            }

        }
        return false;
    }

    public static void main(String[] args){
        HashSet<Test> set = new HashSet<Test>();

        Test a = new Test("hello", 1);
        Test b = new Test("hello", 2);

        System.out.println("equals?\t\t" + a.equals(b));

        set.add(a);

        System.out.println("contains b?\t" + set.contains(b));
        System.out.println("contains a?\t" + set.contains(a));

        System.out.println("specific?\t" + (b == null ? a == null : b.equals(a)));

    }

}

Here's the output:
equals?         true
contains b?     false
contains a?     true
specific?       true

As you can see, .equals() passes as expected, but contains() does not behave as I would expect.
According to the documentation, contains() should pass "if and only if this set contains an element e such that (o==null ? e==null : o.equals(e))".  I ran that exact code and it passes, so why does contains() still fail?


text:
Q: docker mysql image is not working in M1 Pro while its working fine in ubuntu I do have the following content on docker-compose.yml
version: '3.9'

services:
    nginx:
        build:
            context: "./docker/build/nginx"
            dockerfile: Dockerfile
        ports:
            - "${APP_PORT:-9090}:80"
        volumes:
            - "./docker/build/nginx/conf.d/default.conf:/etc/nginx/conf.d/default.conf"
            - ".:/var/www/html"
        links:
            - app
        networks:
            - php_mysql_network
    app:
        build:
            context: "./docker/build/php/8.2"
            target: app_dev
        environment:
            MYSQL_HOST: db
            MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
            MYSQL_DATABASE: '${DB_DATABASE}'
            MYSQL_USER: '${DB_USERNAME}'
            MYSQL_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ALLOW_EMPTY_PASSWORD: 1
            XDEBUG_MODE: "${XDEBUG_MODE:-off}"
        extra_hosts:
            - host.docker.internal:host-gateway
        volumes:
            - ".:/var/www/html"
            - ./docker/build/php/xdebug/conf.d/xdebug.ini:/usr/php/conf.d/xdebug.ini:ro
        depends_on:
            - mysql
        networks:
            - php_mysql_network
    mysql:
        image: 'mysql/mysql-server:8.0'
        ports:
            - '${FORWARD_DB_PORT:-3306}:3306'
        environment:
            MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ROOT_HOST: "%"
            MYSQL_DATABASE: '${DB_DATABASE}'
            MYSQL_USER: '${DB_USERNAME}'
            MYSQL_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ALLOW_EMPTY_PASSWORD: 1
        volumes:
            - './docker/build/mysql8:/var/lib/mysql'
        networks:
            - php_mysql_network

networks:
    php_mysql_network:
        driver: bridge

Which is working fine in ubuntu 20.04 and 22.04 OS. I have been using a similar structure since March 2021 over ubuntu. Unfortunately, with this docker-compose.yml M1 Pro is unable to run the MySQL instance using docker.
For the first time, I got the following error when I ran the docker compose up command

For the second time, I got the following error when I ran the docker compose up

What I am doing wrong here? As per error it seems like mysql is running twice

A: It might be support issue for M1 processors. Some images are not compatible to arm64v8. Try using compatible images for mysql
https://hub.docker.com/r/arm64v8/mysql/tags


text:
Q: How to update unique text in duplicate XML child nodes? I have an XML block with multiple groups of the same tags/nodes, but the data values are different across these groups. I need to parse them to update the text, but not sure how to do that since each group has the same tags.
I've tried some solutions I found on SE, but they don't get me all the way there.
  <attr>
    <attrlabl>STATE_NAME</attrlabl>
    <attrdef>State Name</attrdef>
  </attr>
  <attr>
    <attrlabl>STCOFIPS</attrlabl>
    <attrdef>State/County FIPS ID</attrdef>
  </attr>

I want to parse the second 'attr' group to change the 'attrdef' value to "STCOFIPS Value", but not sure how to parse with Python to do that. Expected value:
  <attr>
    <attrlabl>STATE_NAME</attrlabl>
    <attrdef>State Name</attrdef>
  </attr>
  <attr>
    <attrlabl>STCOFIPS</attrlabl>
    <attrdef>STCOFIPS Value</attrdef>
  </attr>


text:
Q: Inserting multiple elements in a numpy array Is there a function in python that allows me to insert number 100's  or consecutive non zeros in the array [1,2,3,4,5]?
Output should be [1, 100, 100, 100, 2, 100, 100, 100, 3 .....] or [ 1, 100, 101, 102, 2 , 100, 101, 102, 3...]
I have tried numpy.insert()
ar2=np.insert(ar1, slice(1,None), range(100,103))
Output: array([  1, 100,   2, 101,   3, 102,   4, 100,   5, 101])
Numpy.Insert() method allows addition of only a single number between the input elements. Let me know your thoughts on this.

A: You can use numpy.kron
np.kron([1,2,3,4,5],[1,0,0,0]) + 100*np.kron(np.ones(5),[0,1,1,1])

for the second one
np.kron([1,2,3,4,5],[1,0,0,0]) + np.kron(np.ones(5),[0,101,102,103])


text:
Q: CountDownTimer not initiating in if statement My problem is towards the bottom, I have a boolean, ongoing, which is false. It is supposed to become true with a button press, then initiate a countdown timer, but the timer is not initiated. The timer works placed elsewhere in the code. Sorry if it's a complete mess I'm new to this.
public int counter;
public boolean ongoing = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //0-59 number picker to represent seconds
    final NumberPicker secPicker = (NumberPicker) findViewById(R.id.secPicker);
    secPicker.setMaxValue(59);

    Button btnStart = (Button) findViewById(R.id.btnStart);
    Button btnSet = (Button) findViewById(R.id.btnSet);
    Button btnPause = (Button) findViewById(R.id.btnPause);
    final TextView label = (TextView) findViewById(R.id.txtCount);

    //sets the time chosen to timer with button press btnSet
    btnSet.setOnClickListener(
            new View.OnClickListener() {
                public void onClick(View v) {
                    counter = secPicker.getValue();
                    label.setText(String.valueOf(counter));
                }
            }
    );

    //starts timer from selected time, from number picker, with btnStart
    btnStart.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            ongoing = true;

        }
    });
    //disables, not worried about this yet
    btnPause.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            ongoing = false;

        }
    });

        //supposed to turn on a timer with button press btnStart, but it does nothing this is my problem.
        if (ongoing == true) {
            //any replacement for 9999999, as an infinite value?
            new CountDownTimer(999999999, 1000) {
                public void onTick(long millisUntilFinished) {
                    label.setText(String.valueOf(counter));
                    counter--;
                    if (counter == -1) {
                        counter = 0;
                        cancel();
                    }
                }

                public void onFinish() {

                }

            }.start();

        }
    }
}

A:  if (ongoing == true) // this will never work for you

You have putted above code inside oncreate before you click anything it will get call.
Either you should write below code inside btnStart click event or create one method and call from it.
//supposed to turn on a timer with button press btnStart, but it does nothing this is my problem.
if (ongoing == true) {
    //any replacement for 9999999, as an infinite value?
    new CountDownTimer(999999999, 1000) {
        public void onTick(long millisUntilFinished) {
            label.setText(String.valueOf(counter));
            counter--;
            if (counter == -1) {
                counter = 0;
                cancel();
            }
        }

        public void onFinish() {

        }

    }.start();

}

Hope these help you.


text:
Q: Multi-Monitor Support for incoming Remote Connections (Windows to Mac) I've currently got a Windows PC, and use it to RDP to a Windows laptop. When I do this, it passes through the multiple monitors from the host and lets me use them within the RDP session. In this way, I can use up to 4 monitors on my laptop without needing to futz around with KVMs and extra cables.
This is the physical setup.
Host Machine (Windows 11)    --RDP->   Target Laptop (Windows 11)
 |     |     |     |                        |
 M1    M2    M3    M4                       M5 (integrated)

With this setup, I am able to use M1-M4 as separate monitors within the RDP session.

I'd like to do the same with a Mac laptop, but I'm struggling to work out how. From what I can see, RDP is not supported on Mac, and the alternative (VNC viewer) does work but doesn't seem to support the use of multi-monitors from the host (just when they are connected to the target machine).
Host Machine (Windows 11)    --RDP->   Target Laptop (MacOS Monterey 12.6)
 |     |     |     |                        |
 M1    M2    M3    M4                       M1 (integrated)

Is there any way to replicate this setup when connecting from Windows to Mac?


text:
Q: Windows 7 Set metric to use 2 different network interfaces at the same time I'm looking for a way to use at the same time wired and wireless interfaces.
My situation:

*

*1 Gbit ethernet interface (10.100.x.x)

*1 WiFi 802.11 b/g/n interface (192.168.x.x)

*The PC is part of a domain (10.100.x.x) and I logon using a LDAP user.

I want to use the Ethernet interface to connect to the domain and navigate through LAN, but every time I need to access the internet, I want to use the WiFi.
The Ethernet interface is configured for the domain, so there's a DHCP that assigns every setting, from PC IP address to default gateway IP and DNS.
I tried almost everything...

*

*"Advanced settings" on "Network Connection Panel" to change the
interfaces order.

*Route table to adjust interfaces and gateways metrics.

*"Network Adapter Advanced Settings" to uncheck the automatic metric
and set a manual value.

When both my interfaces are activated this is my Route table:
IPv4 Tabella route
===========================================================================
Route attive:
     Indirizzo rete             Mask          Gateway     Interfaccia Metrica
          0.0.0.0          0.0.0.0       10.100.1.1      10.100.1.55    276
          0.0.0.0          0.0.0.0     192.168.10.1   192.168.10.208    281
       10.100.1.0    255.255.255.0         On-link       10.100.1.55    276
      10.100.1.55  255.255.255.255         On-link       10.100.1.55    276
     10.100.1.255  255.255.255.255         On-link       10.100.1.55    276
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    306
        127.0.0.1  255.255.255.255         On-link         127.0.0.1    306
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    306
     192.168.10.0    255.255.255.0         On-link    192.168.10.208    281
   192.168.10.208  255.255.255.255         On-link    192.168.10.208    281
   192.168.10.255  255.255.255.255         On-link    192.168.10.208    281
    192.168.184.0    255.255.255.0         On-link     192.168.184.1    276
    192.168.184.1  255.255.255.255         On-link     192.168.184.1    276
  192.168.184.255  255.255.255.255         On-link     192.168.184.1    276
    192.168.222.0    255.255.255.0         On-link     192.168.222.1    276
    192.168.222.1  255.255.255.255         On-link     192.168.222.1    276
  192.168.222.255  255.255.255.255         On-link     192.168.222.1    276
        224.0.0.0        240.0.0.0         On-link         127.0.0.1    306
        224.0.0.0        240.0.0.0         On-link     192.168.222.1    276
        224.0.0.0        240.0.0.0         On-link     192.168.184.1    276
        224.0.0.0        240.0.0.0         On-link       10.100.1.55    276
        224.0.0.0        240.0.0.0         On-link    192.168.10.208    281
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    306
  255.255.255.255  255.255.255.255         On-link     192.168.222.1    276
  255.255.255.255  255.255.255.255         On-link     192.168.184.1    276
  255.255.255.255  255.255.255.255         On-link       10.100.1.55    276
  255.255.255.255  255.255.255.255         On-link    192.168.10.208    281
===========================================================================
Route permanenti:
  Nessuna

The best I was able to obtain was to set a manual metric value to the Ethernet interface so the metric of gateway increased till a value greater than the WiFi gateway. This way lead me to gain access to the Internet by the WiFi gateway (as I wanted) BUT I loose my network connections access so I cannot access my domain resources (server, shares, printers...).
Using the procedure described above I finally have this Route table:
IPv4 Tabella route
===========================================================================
Route attive:
     Indirizzo rete             Mask          Gateway     Interfaccia Metrica
          0.0.0.0          0.0.0.0       10.100.1.1      10.100.1.55    356
          0.0.0.0          0.0.0.0     192.168.10.1   192.168.10.208    281
       10.100.1.0    255.255.255.0         On-link       10.100.1.55    356
      10.100.1.55  255.255.255.255         On-link       10.100.1.55    356
     10.100.1.255  255.255.255.255         On-link       10.100.1.55    356
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    306
        127.0.0.1  255.255.255.255         On-link         127.0.0.1    306
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    306
     192.168.10.0    255.255.255.0         On-link    192.168.10.208    281
   192.168.10.208  255.255.255.255         On-link    192.168.10.208    281
   192.168.10.255  255.255.255.255         On-link    192.168.10.208    281
    192.168.184.0    255.255.255.0         On-link     192.168.184.1    276
    192.168.184.1  255.255.255.255         On-link     192.168.184.1    276
  192.168.184.255  255.255.255.255         On-link     192.168.184.1    276
    192.168.222.0    255.255.255.0         On-link     192.168.222.1    276
    192.168.222.1  255.255.255.255         On-link     192.168.222.1    276
  192.168.222.255  255.255.255.255         On-link     192.168.222.1    276
        224.0.0.0        240.0.0.0         On-link         127.0.0.1    306
        224.0.0.0        240.0.0.0         On-link     192.168.222.1    276
        224.0.0.0        240.0.0.0         On-link     192.168.184.1    276
        224.0.0.0        240.0.0.0         On-link       10.100.1.55    356
        224.0.0.0        240.0.0.0         On-link    192.168.10.208    281
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    306
  255.255.255.255  255.255.255.255         On-link     192.168.222.1    276
  255.255.255.255  255.255.255.255         On-link     192.168.184.1    276
  255.255.255.255  255.255.255.255         On-link       10.100.1.55    356
  255.255.255.255  255.255.255.255         On-link    192.168.10.208    281
===========================================================================
Route permanenti:
  Nessuna

Here the WiFi gateway (192.168.x.x) has lower metrics than ethernet one, so I can go to the WAN with that but I cannot access my network resources anymore.
It seems that with that route table, every LAN connection tries to pass through WiFi interface.
I tried to change and delete the 0.0.0.0    0.0.0.0    10.100.1.1    10.100.1.55    276 route but nothing appened...

A: Try these two commands:
route delete 0.0.0.0 10.100.1.1
route add 10.0.0.0 mask 255.0.0.0 10.100.1.1
If that works, put them in a batch file in your StartUp folder to automatically run every time you log in.  This should do the job.


text:
Q: Resetting a variable later in the code makes an earlier block of code run slower. Why? I have the following program. I was just kind of messing around with other stuff when I noticed something unusual. The line "y = 3;" seems to have an effect on how fast the previous block of code can be run. When the line is commented out, the first half of the code runs around ten times slower than the second half. However, when the line is uncommented, both halves run at the same speed. Interestingly, the line in question should not be doing anything, as at that point the value of y is already 3.
EDIT:
I added line "System.out.println(y)" right above "y=3" and it prints 3. That's why I think it's 3. And I'm measuring based on the output of the program. The two lines that it prints are the two runtimes, and the Timer code at the bottom shows clearly how I am measuring time.
/**
 * @author lpreams
 */
public class Misc {
    public static void main(String[] args) {
        new Misc().run();
    }

    public void run() {
        Timer t = new Timer();
        t.start();
        int y = Integer.MIN_VALUE;
        for (int j = 0; j < Integer.MAX_VALUE; ++j) {
            for (int i = 0; i < Integer.MAX_VALUE; ++i) {
                ++y;
            }
        }
        t.stop();
        System.out.println(t.getElapsedTime());
        t.reset();
        //y = 3;
        t.start();
        for (int j = 0; j < Integer.MAX_VALUE; ++j) {
            for (int i = 0; i < Integer.MAX_VALUE; ++i) {
                ++y;
            }
        }
        t.stop();
        System.out.println(t.getElapsedTime());
    }

    private static class Timer {

        private long startTime = 0;
        private long stopTime = 0;
        private long elapsed = 0;

        public void start() {
            this.startTime = System.nanoTime()/1000000;
        }

        public void stop() {
            this.stopTime = System.nanoTime()/1000000;
            elapsed += stopTime - startTime;
        }

        public long getElapsedTime() {
            return elapsed;
        }
        public void reset() {
            elapsed = 0;
        }
    }
}

I am running this code in Eclipse on OS X 10.9.2. I am running the latest version of java. My machine is a MacBook Pro with a 2.4ghz Core 2 Duo with 8gb of RAM.

A: This is potentially JIT optimisation.  If you run with the following vm argument:
-Djava.compiler=NONE
based on this stackoverflow article:
how to make sure no jvm and compiler optimization occurs
You can prevent this and should see the same result. I ran with this argument and got almost the exact same processing time.

A: Any results that you get from this micro-benchmark are suspect.  You are not taking account of JVM warmup effects.
Having said that, if we can assume that the effect is real I would put it down to the JIT optimizer being unable to detect that the first loop body can be optimized away ... when the y = 3 assignment is there.  You are running into a case where adding a bit more "complexity" is inhibiting an optimization.  It happens.
(The value being assigned is immaterial.  This is all to do with code generation by the JIT compiler ... which happens before the y value that you predict will be 3 can be calculated by anything.  It can influence the JIT compiler's behaviour.)


text:
Q: defining default value of enumeration type attribute in xsd While working on defining enumeration types in xsd i am facing following problem
I have defined enum structure as :
<xsd:simpleType name="ProvServiceTypeEnumV1">
        <xsd:annotation>
            <xsd:documentation>

Service Types

            </xsd:documentation>
        </xsd:annotation>
        <xsd:restriction base="xsd:string">
            <xsd:enumeration value="HOME" />
            <xsd:enumeration value="ORIGINAL" />
            <xsd:enumeration value="DESTINATION" />
            <xsd:enumeration value="WORKING" />
            <xsd:enumeration value="PROTECTING" />
            <xsd:enumeration value="NA" />
        </xsd:restriction>
    </xsd:simpleType>

Now i want to use this type ProvServiceTypeEnumV1 as attribute in some other model with default value as "NA" which means when i convert this xsd to java model the default value should always come as NA.
For the boolean types this achieved by using as :
<xsd:element name="cktID" type="xsd:boolean" maxOccurs="1" minOccurs="1"
                        default="false">

Going by the same methodology i tried using the same for this as :
<xsd:element name="serviceType" type="tns:ProvServiceTypeEnumV1" maxOccurs="1" minOccurs="1"
                        default="NA">

When i compiled it using xjc i am not getting the default value of serviceType. However boolean value is coming as default
Please suggest what might be missing here.
Thanks

A: From the JAXB specification (2.0):

The default value is derived from the element declaration's {value
  constraint} property's value. Unlike attribute defaulting, an element only
  defaults when there is an empty element tag in an XML document. The
  element's default value is captured by mapping annotation
  @XmlElement.defaultValue(). The unmarshaller sets the
  property to this default value when it encounters an empty element tag.
  The marshaller can output an empty element tag whenever the element's
  @XmlValue property value is the same as its defaulted value.

This may be disappointing to you, but that's been specified, and I think there's some reason behind this since other variants may appear to be flawed, too.
The main reason for not setting the element by default is that it wouldn't be possible to distinguish a missing element (field == null) from a defaulted value.
Edit
Checking some old examples I have around, I see that the getter generated for an attribute using
<xs:attribute name="field" type="FieldType" use="optional"
              default="value1"/>

with FieldType being an enumeration is generated as
public FieldType getField() {
    if (field == null) {
        return FieldType.VALUE_1;
    } else {
        return field;
    }
}

Note that XML Schema permits a default for an attribute only when use="optional". Obviously, attributes are meant to be another "category" of XML values in contrast to elements.


text:
Q: Not able to inherit the One struct from another When I tried to inherit one struct from another struct, I am getting this error:
from solidity:
ParserError: Expected '{' but got 'is'
  --> contracts/Structure.sol:11:26:
   |
11 |     struct DerivedStruct is BaseStruct {

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

contract Structure {
    struct BaseStruct {
        uint256 a;
        uint256 b;
    }

    struct DerivedStruct is BaseStruct {
        uint256 c;
        uint256 d;
    }
}

Got this error:

Can't we inherit one struct to another in Solidity?

A: You can inherit one sturct from another in Solidity.
Syntax you are using is incorrect. In solidity the 'is' keyword is used to inherit interfaces. To inherit form a struct you simply use its as the type of a new struct.
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

contract Structure {
    struct BaseStruct {
        uint256 a;
        uint256 b;
    }

    struct DerivedStruct {
        BaseStruct base;
        uint256 c;
        uint256 d;
    }
}

DerivedStruct struct contains a BaseStruct field, which inherits its properties


text:
Q: Choosing an appropriate constant current LED driver I am trying to replace a (suspected) constant current LED driver in a plant lamp as it has a terrible plastics smell. I am searching for a more high quality driver. I do not know then forward voltage of the LEDs, and at the moment I do not have a multimeter at hand (I will next week).
Driver to be replaced:

So far I have understood, that I will have to pick a constant current LED driver, which supplies 650mA and which voltage range convers at minimum the entire range of the current driver.
I have found the Mean Well HLG-60H-C700A, which supplies 420 ~ 700mA (adjustable via inbuilt potentiometer) and 50 ~ 100V, which should cover the needed voltage range.
The current driver is dimmable, but I do not really need that functionality. I am fine with setting the driver to some output current, and then leave it there.
I have the following questions:

*

*Will the Mean Well driver be able to replace the current driver (as its max voltage is significantly higher than the current drivers)

*Can I adjust the output current to, say, 500mA and by that drive the LEDs at a lower brightness? Will this cause the driver to output significant heat (I could not find out if it is linear).

*Assuming I wanted to add dimming functionality (e.g. through an ESP8266 and PWM, using the mean well B model). How would I limit the driver to 650mA? Is this what the AB model achieves?

A:
Will the Mean Well driver be able to replace the current driver

Yes.
Note this meanwell driver has a Protection Earth wire which must be connected. Your original wire does not.

Can I adjust the output current to, say, 500mA and by that drive the LEDs at a lower brightness?

Yes

Will this cause the driver to output significant heat (I could not find out if it is linear).

No, dimming controls the switching converter inside. Efficiency vs load is mentioned in the datasheet. While efficiency decreases slightly at light load, it's still pretty good. At max output power, having low % losses is important. At low output power it matters less.

Assuming I wanted to add dimming functionality (e.g. through an ESP8266 and PWM, using the mean well B model). How would I limit the driver to 650mA? Is this what the AB model achieves?

Yes it'll work.
If you want the ESP8266 to be able to turn off the Meanwell supply, then ESP8266 needs its own power supply, like a USB cellphone "charger". Besides powering it from 60V would be inconvenient.
Note datasheet says DO NOT connect "DIM- to -V"
Check if the Meanwell can turn off the LED completely. I don't think it can. So if you want this you'll probably need a relay driven from ESP8266 to switch the mains.
Dimming needs a 10V PWM though, so an ESP8266 powered from 3V3 won't achieve this.
However the Meanwell has a built-in 100μA current source pulling the DIM input up to 10V. All that's needed is a transistor driven by PWM to short the DIM input pins together. You can also use an optocoupler. When the transistor/opto is on, it shorts the DIM input. When it's off, the internal 100µA pulls it up to 10V. So all you have to do is PWM the transistor's base (or the opto LED) and here you go.

A:
Assuming I wanted to add dimming functionality (e.g. through an ESP8266 and PWM, using the mean well B model). How would I limit the driver to 650mA? Is this what the AB model achieves?

The AB model includes dimmer pins for a microcontroller and a dimmer knob on the power supply. Unless you need to remotely control the brightness, you can simply turn the knob to set the brightness.
Also, these power supplies are usually turned off by using a relay on the mains side. This is by convention for agriculture lighting.


text:
Q: How to open a new GUI and close an old GUI in ApplescriptObjC I'm trying to make it so when a button is clicked, the current GUI closes and a new GUI opens.
I created a second interface to open. So right now, I have 2 xib files, and the AppDelegate file. Do I program both of the GUIs with the same AppDelegate file?
Second of all, How do I get the first xib file to close and the second xib file to open.
on buttonClicked_(sender)

-- Code that closes current GUI and opens new GUI here

end buttonClicked_

A: Normally you only have one application delegate in AppleScriptObjC. The choice if an window needs to be in another xib file or not totally depends of the purpose of the window. Most developers prefer not to have an window in the MainMenu.xib at all but create a MainWindow.xib or some developers prefer to create UI on the fly. So having 2, 1 or even 3 xib files doesn't say much, anyway I would prefer to have a xib for every window.
To keep it simple and make it all work:

*

*Add new window to your project (and I saved it as MainWindow.xib)

*Set class of file's owner to NSWindowController

*Connect window with file's owner and make it the window

*Add new AppleScript to your project (subclass of NSObject)

*Write the IBOutLet and actions for the window (see below)

*Add new NSObject to the xib file

*Set class of NSObject (blue cube) to new AppleScript object

*Connect the window with the IBOutlets and IBActions.

*Connect also the window's delegate to the script (blue cube)

script for window:
   script mainWindow
       property parent : "NSObject"
       property myWindow : missing value
       property myButton : missing value

       on myButtonClicked:sender
          log "I'm clicked"
       end myButtonClicked:
    end script

To load the window we need something like this in our app delegate:
set theController to current application's class "NSWindowController"'s alloc()'s init()
current application's class "NSBundle"'s loadNibNamed:"MainWindow" owner:theController

Now when we're in the application delegate and loaded our nib properly we can close our window by doing just theController's close() and show the window by using theController's showWindow:me For the other window just repeat those steps above and you can switch between them.


text:
Q: Parsing SoapObject Responst in android My code is:
public class MainActivity extends Activity implements OnClickListener {

Button b;
private static String NAMESPACE = "http://tempuri.org/";
private static String METHOD_NAME = "GetList";
private static String SOAP_ACTION = "http://tempuri.org/IWCFMasterRole/GetList";
private static String URL = "http://172.16.0.1:55355/WCFMasterRole.svc";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    b = (Button) findViewById(R.id.button1);
    b.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    if (v.getId() == R.id.button1) {
        new MyClass().execute("");
    }
}

class MyClass extends AsyncTask<String, Void, SoapObject> {
    SoapObject result;
    @Override
    protected SoapObject doInBackground(String... params) {
        try {

            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
            // request.addProperty("CityId", "CITY0001");
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);
            envelope.setOutputSoapObject(request);
            HttpTransportSE transport = new HttpTransportSE(URL);
            try {
                transport.call(SOAP_ACTION, envelope);
            } catch (Exception e) {
                e.printStackTrace();
            }
            result = (SoapObject) envelope.bodyIn;
            System.out.println("Result is : " + result);
        } catch (Exception e) {
            System.out.println("Exception : "+e.toString());
        }

        return result;
    }
}
}

And my response in logcat is:
    Result is :
GetListResponse
 {
   GetListResult=anyType
   {schema=anyType
    {element=anyType
     {complexType=anyType
      {choice=anyType
       {element=anyType
        {complexType=anyType
         {sequence=anyType
          {element=anyType{}; element=anyType{}; element=anyType{};
          };
         };
        };
       };
      };
     };
    };
    diffgram=anyType
    {DocumentElement=anyType
     {Table1=anyType

      {RoleID=ROLEAAAA0000; RoleName=Administrator; };
      Table1=anyType
      {RoleID=ROLEAAAA0001; RoleName=Developer; };
      Table1=anyType
      {RoleID=ROLEAAAA0003; RoleName=Senior Developer; };
      Table1=anyType
      {RoleID=ROLEAAAA0004; RoleName=Junior Developer; };
      Table1=anyType
      {RoleID=ROLEAAAA0005; RoleName=Trainee; };

     };
    };
   };
 }

I want to get RoleID and RoleName from this response.
I have tried with result.getAttribute(0) and result.getProperty(0). But They didn't help. Also I have googled lot. Any help to parse this response will be highly appriciated.
Thank you.

A: Basicly it's something like this:
SoapObject GetListResponse = (SoapObject)result.getProperty(0);
SoapObject DocumentElement = (SoapObject)GetListResponse.getProperty(3);
SoapObject Table1 = (SoapObject)DocumentElement.getProperty(0);

This contains SoapObjects within SoapObjects, so the best thing to do is to write a recursive method to scan through all properties and find the information you need. Something like this:
private static void ScanSoapObject(SoapObject result)
{
    for(int i=0;i<result.getPropertyCount();i++)
    {
        if(result.getProperty(i) instanceof SoapObject)
        {
             ScanSoapObject((SoapObject)result.getProperty(i));
        }
        else
        {
            //do something with the current property

            //get the current property name:
            PropertyInfo pi = new PropertyInfo();
            result.getPropertyInfo(i,pi);
            String name = pi.getName();
        }
    }
}


text:
Q: VB.NET read .XML file and write into DataGridView I'm trying to read an .XML file online and then write it into the DataGridView.
Downloading the file works. But how can i put the downloaded data to my DataGridView.
VB.NET Code:
Dim xmlfile As String
        Dim WebC As New System.Net.WebClient
        Dim datas As New DataSet

        Try
            xmlfile = WebC.DownloadString("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml")
            datas.ReadXml(xmlfile)
            DataGridView1.DataSource = datas.Tables("cube")
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

and this is the .XML File:
https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
thanks for every help..
I expect the .xml file to be displayed in the DataGridView. Because I want to display all currency rates.

A: Put data into a datatable than make the datagridview1.DataSource = dt;
vb.net
Imports System
Imports System.Xml
Imports System.Xml.Linq
Imports System.Data

Module Program
    Const URL As String = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
    Sub Main(args As String())
        Dim dt As New DataTable

        dt.Columns.Add("currenct", GetType(String))
        dt.Columns.Add("rate", GetType(Decimal))
        Dim doc As XDocument = XDocument.Load(URL)
        Dim ns As XNamespace = doc.Root.GetDefaultNamespace()
        For Each cube As XElement In doc.Descendants(ns + "Cube").Where(Function(x) Not x.Attribute("currency") Is Nothing)

            Dim currency As String = CType(cube.Attribute("currency"), String)
            Dim rate As Decimal = CType(cube.Attribute("rate"), Decimal)
            dt.Rows.Add(New Object() {currency, rate})

        Next
    End Sub
End Module

c# solution
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;

namespace ConsoleApplication2
{
    class Program
    {
        const string URL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("currenct", typeof(string));
            dt.Columns.Add("rate", typeof(decimal));
            XDocument doc = XDocument.Load(URL);
            XNamespace ns = doc.Root.GetDefaultNamespace();
            foreach(XElement cube in doc.Descendants(ns + "Cube").Where(x => x.Attribute("currency") != null))
            {
                string currency = (string)cube.Attribute("currency");
                decimal rate = (decimal)cube.Attribute("rate");
                dt.Rows.Add(new object[] { currency, rate });

            }
        }

    }
}


text:
Q: Design an experiment to identify a (binary) category There are two types of alien, type A and type B, on a newly discovered planet. You have noticed that type A aliens seem to enjoy listening to the Beatles more than type B aliens. Specifically, you note that,
$$P(\mbox{dance to a Beatles song} ~|~ \mbox{type A}) \geq 0.5,$$
and,
$$P(\mbox{dance to a Beatles song} ~|~ \mbox{type B}) = 0.25.$$
Furthermore, you know that there are equal numbers of type A and type B aliens, so that,
$$P(\mbox{type A})=P(\mbox{type B})=0.5.$$
Question: Design an experiment with $N$ questions to determine, with 95% confidence, whether a given alien is of type A or type B. What is the smallest size $N$ for such an experiment?
Specifically, I want to know if it is possible to do better than the following.
Binomial Calculation
Let $X$ denote the Bernoulli random variable that is 1 if the alien dances, and 0 otherwise. Our experiment consists of $N$ draws $X_1, \ldots, X_N$ (think of playing $N$ different songs and seeing if they dance each time).
Experiment: Fix $N, \tau$. Say alien is type A  if $Y_N := \sum_{i=1}^N X_i \geq \tau$, otherwise they are of type B. From the binomial distribution we have,
$$P(Y_N \geq \tau ~|~ \mbox{type A}) \geq \sum_{i = \tau}^N {N \choose i} (0.5)^i(0.5)^{N-i}$$
$$P(Y_N < \tau ~|~ \mbox{type B}) = \sum_{i = 0}^{\tau - 1} {N \choose i} (0.25)^i(0.75)^{N-i}$$
It remains to find $N$ and $\tau$ such that,
$$P(Y_N \geq \tau ~\cap~ \mbox{type A}) + P(Y_N < \tau ~\cap~ \mbox{type B}) \geq 0.95,$$
or equivalently,
$$P(Y_N \geq \tau ~|~ \mbox{type A})\cdot P(\mbox{type A}) + P(Y_N < \tau ~|~ \mbox{type B})\cdot P(\mbox{type B}) \geq 0.95.$$
Solving this we see that the minimum $N, \tau$ pair is,
$$N = 39, \tau = 15.$$


text:
Q: VS Code, copyright symbol © shown as � and saved as � or � In my html source code I have some special symbols like the copyright one <meta content="© Copyright... />
For some text editors these are shown correctly as above, but on VS Code I see it as � and after I save the file, the symbol will be shown as � and � on other editors.
If I explicitly paste the © on VS Code and save it, then on another text editor it will be saved as ©.
How can I solve this? What should I do?

A: Ensure your file's encoding is set to something which can accurately display the symbol (like UTF-8):

This can be found in the bottom right of the program in the status bar.
See their documentation on File Encoding Support.

A: I've found out that the files were saved in ISO-8859-1 encoding, that caused to see like that the symbols even If I had UTF8 set as my default.

A: Same problem here - solved by setting "files.encoding": "windows1252" for this workspace.

A: Try use HTML codes for special symbols: http://www.ascii.cl/htmlcodes.htm


text:
Q: Preventing indent of tables with border-collapse, separate I have some very basic html:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

        Addressed to
        Sender
        Price
        Comments

        Joe smith
        Ralph Lauren
        $200
        Lorem ipsum dolor sit amer

        Joe smith
        Ralph Lauren
        $200
        Lorem ipsum dolor sit amer

It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Now, I'd like to add spacing between my table rows and columns, so I add this css:
table {
border-collapse: separate;
border-spacing: 20px 10px;
}

Great.  Except now the table itself is no longer flush left with the 2 paragraphs.

My question is how can the table get the needed spacing but NOT the indent, or how can apply the least CSS to overcome the indent?
See this code at http://jsfiddle.net/smlombardi/9mzzdsrn/1/

A: For a quick solution (especially if it's a static site) just knock the margin back by 20px (the same as the indent on the table)
margin-left:-20px;

here is a working example

A: Instead of using border-spacing you can just set the margin on the table and then also set padding to each row to achieve the same effect with the text flush left
table {
    border-collapse: separate;
    margin-right:20px;
}
td {
    padding-top:10px;
}

A: table {
    border-collapse: separate;
    margin-right:20px;
}
td {
    padding:10px;
}


text:
Q: Partition of a set A where $A= \{0,1\}^3$ Let $A = \{0, 1\}^3$: that is, $A$ is the set of all ordered triples with entries from 0 and 1.
Then define a relation $R \subseteq A \times A$ such that $xRy$ if and only if $x$ and $y$ have the same number of 0s. Note that $R$ is an equivalence relation.
Give the partition of $A$ created by the equivalence classes of $R$.
I'm going through set partition theory and although I understand the definition of partition, I'm not sure how to be sure that all the partitions I have listed are truly all the partitions of a set.
And then I'm not quite sure how to begin thinking about this question. Can anyone help out?

A: The equivalence classes are $$\{(0,0,0)\}$$ $$\{(1,0,0),(0,1,0),(0,0,1)\}$$ $$\{(1,1,0), (1,0,1),(0,1,1)\}$$ $$\{(1,1,1)\}$$

A: Hint:
The equivalence classes naturally correspond to the possible numbers of $0$s, namely $0,1,2$ or $3$. So there is a partition in at most four subsets. (I say "at most" in case some of the subsets would be empty.)
Regroup
$$000: 0,001: 1, 010: 1, 011: 2, 100: 1,101: 2, 110: 2, 111: 3.$$


text:
Q: Edittext cursor pointer goes out of view I have used an Edittext whose "maxlines" is set to 1. When I enter some large text, a certain portion of the text is not visible. So I use the cursor pointer (blue color which appears on single tap on edittext) to scroll through the text. But when I try to use it, it goes beyond the view instead of showing the text which is hidden.
Is there something I'm missing?

A: Set below properties of your Edittext, it will solve your problem.
android:singleLine="true"
android:ellipsize="end"

A: http://developer.android.com/reference/android/widget/EditText.html states the following
        android:maxLength
        setFilters(InputFilter)
        Set an input filter to constrain the text length to the specified number.

You can use this to specify the length of the EditText input
or you want the Text to be wider than the view then you can use
        android:scrollHorizontally
        setHorizontallyScrolling(boolean)
        Whether the text is allowed to be wider than the view (and therefore can be scrolled horizontally).

A: Not sure of what you mean, my answer is based on what I understand of your question:
Try using the following lines of code in your XML:
    android:paddingRight="08dp"
    android:paddingLeft="08dp"


text:
Q: Teemo's global taunt Why do people say Teemo has a global taunt?
I'm guessing that it's because everyone focuses him on teamfights but my theory may be wrong.

A: Teemo's global taunt is a meme. Teemo is arguably the cutest and squishiest AND most annoying hero in the game. Hence, everyone wants him dead, hence, 'Global Taunt'.
Teemo has in actuality, no taunt of any kind.


text:
Q: Regarding Ladder Operators and Quantum Harmonic Oscillators When dealing with the Quantum Harmonic Oscillator Operator $H=-\frac{d^{2}}{dx^{2}}+x^{2}$, there is the approach of using the Ladder Operator:
Suppose that are two operators $L^{+}$ and $L^{-}$ and define $f_{n}$ such that
$$L^{+}(f_{n})=\sqrt{n+1}f_{n+1}$$
$$L^{-}(f_{n})=\sqrt{n}f_{n-1}$$
then $$L^{+}L^{-}(f_{n})=L^{+}(\sqrt{n}f_{n-1})=nf_{n}$$ $$L^{-}L^{+}(f_{n})=L^{-}(\sqrt{n+1}f_{n+1})=(n+1)f_{n}$$
Thus
$$L^{+}L^{-}+L^{-}L^{+}=(2n+1)f_{n}$$
Now since $$H=-\frac{d^{2}}{dx^{2}}+x^{2}=\left(x+\frac{d}{dx}\right)\left(x-\frac{d}{dx}\right)$$
$$=\frac{1}{2}\left[\left(x+\frac{d}{dx}\right)\left(x-\frac{d}{dx}\right)+\left(x+\frac{d}{dx}\right)\left(x-\frac{d}{dx}\right)\right]$$
$$=\frac{1}{\sqrt{2}}\left(x+\frac{d}{dx}\right)\frac{1}{\sqrt{2}}\left(x-\frac{d}{dx}\right)+\frac{1}{\sqrt{2}}\left(x-\frac{d}{dx}\right)\frac{1}{\sqrt{2}}\left(x+\frac{d}{dx}\right)$$
If we let $$L^{+}=\frac{1}{\sqrt{2}}\left(x+\frac{d}{dx}\right)\quad\text{and}\quad L^{-}=\frac{1}{\sqrt{2}}\left(x-\frac{d}{dx}\right)$$
then $$H=L^{+}L^{-}+L^{-}L^{+}$$
Since $$L^{+}(f_{n})=\sqrt{n+1}f_{n+1}\implies$$
$$f_{n}=\sqrt{n!}L^{n}(f_{0})$$
Thus if we can a $f_{0}$ such that
$$f_{n}=\sqrt{n!}L^{n}(f_{0})\implies L^{-}(f_{n})=\sqrt{n}f_{n-1}\tag{1}$$ would be satisfied, then we have found a set of eigenfunctions for H, which is $f_{n}$ and the corresponding eigenvalue is 2n+1.
Now my instructor says that if we let $f_{0}$ be in the kernel of $L^-$, meaning that:
$$L^{-1}f_{0}=0\tag{2},$$ then (1) would be true.
Specifically, this means that
$$f_{0}(x)=e^{-\frac{1}{2}x^{2}}.$$
As it is already verified (and commonly used in quantum mechanics) that this $f_{0}(x)$ does satisfy (1). But I can't really see how does (2) leads to (1). Is this choice $f_0$ really a lucky guess or actually a choice the generally works for all operators that can be expressed as $H=L^{+}L^{-}+L^{-}L^{+}$? A different way of asking this question is: are the ladder operator really just operators that tells us how to get from one state to another, or it is actually something that would be used as a general method of solving some differential equations?

A: I think the confusion begins where you write "and define $f_n$ such that" at the very beginning. The two lines after that are two ways of defining $f_n$, and part of what needs to be shown is that they're equivalent.
Also you seem to have got $L^\pm$ mixed up -- the one that contains the plus sign is the annihilation operator and the one that contains the minus sign is the creation operator, as you can tell from the fact that your $f_0$ is actually in the kernel of what you called $L^+$. I'll use your definitions so as not to confuse things further, but keep in mind that that means that $L^+$ is now the annihilation operator and $L^-$ is now the creation operator.
I'd proceed as follows. The commutator of the ladder operators is
$$[L^+,L^-]=1\;.$$
If $f_n$ is an eigenfunction of $H$ with eigenvalue $E_n$, then $L^-f_n$ is an eigenfunction of $H$ with eigenvalue $E_n+2$:
$$
\begin{eqnarray}
HL^-f_n&=&(L^+L^-+L^-L^+)L^-f_n
\\
&=&
(L^+L^-L^-+L^-L^+L^-)f_n
\\
&=&
(L^-L^+L^-+L^-+L^-L^-L^++L^-)f_n
\\
&=&
L^-(L^+L^-+1+L^-L^++1)f_n
\\
&=&
L^-(H+2)f_n
\\
&=&
L^-(E_n+2)f_n
\\
&=&
(E_n+2)L^-f_n\;.
\end{eqnarray}
$$
In the same way we can show that $L^+f_n$ is an eigenfunction of $H$ with eigenvalue $E_n-2$.
Now the eigenvalues of $H$ are non-negative. (You can show this for instance by taking the expectation value of $H$ and integrating by parts.) Thus successively applying $L^+$ to lower the eigenvalue must at some point annihilate the eigenfunction. Thus we've shown a) that any eigenfunction gives rise to an entire succession of eigenfunctions with equally spaced eigenvalues and b) this succession must end with a function that is annihilated by $L^+$, and this yields a differential equation whose solution is your $f_0$.
Then it only remains to normalize the resulting eigenfunctions, and to derive the non-recursive forms with the factorial factors becomes a straightforward exercise in induction.

A: I would say everything you need for (1) is given in (2): From $L^-$ you get $L^+$ and $f_0$ is given by (2).
If it's possible to express your Hamiltonian as ladder operators, this approach would also help to simplify the way to get the solution of your differential equation. They are for example also used in (finite dimensional) spin physics.
Concerning your question, if $f_0$ is just a lucky guess, you can check here, that the Hermite function $f_n$ fulfill the recursion relations
$$
 x\;f_{n}(x)  = \sqrt{\frac{n+1}{2}}f_{n+1}(x) + \sqrt{\frac{n}{2}}f_{n-1}(x)
$$
and
$$
f_n'(x) = -\sqrt{\frac{n+1}{2}}f_{n+1}(x) + \sqrt{\frac{n}{2}}f_{n-1}(x) .
$$
and
Together with definition of $L^-=\frac{1}{\sqrt{2}}(x+\frac{d}{dx})$, you see that $L^- f_0$ exactly cancels to $0$.


text:
Q: Question on a hypothesis test So I have population mean (for average production on some farms) = $3000$, and a test for a new fertilizer has sample size $n = 70$, sample mean = $3120$, sample standard deviation = $578$.
The company making the fertilizer claims that it knows that the fertilizer improves the production. Perform the appropriate test with a significance level of $0.05$.
So I computed the test statistic
$$\frac{3120 - 3000}{\frac{578}{\sqrt{70}}} = 1.73 \ ,$$
and since this is a one-sided test, we will compare with the respective normal quantile for 0.95 $= 1.96$.
Now is the correct null hypothesis $H_0: μ>3000$ or $H_0:μ \leq 3000$ (versus their respective negations)? And, whichever the case is, which is the correct rejection region?

A: The population standard deviation is not known, so looking ahead, you should understand that this situation really should be analyzed using a t test. However, for for such a large sample size as $n = 70,$ you can get by assuming that the population SD is $\sigma=578.$
T test--Population SD unknown: Here is a printout of the exact t test from Minitab (slightly edited for relevance).
One-Sample T

Test of μ = 3000 vs > 3000

 N    Mean  StDev  SE Mean      T      P
70  3120.0  578.0     69.1   1.74  0.043

(a) From printed t-tables, the 5% critical value for this one-sided t test is $c = 1.667;$
because $T = 1.74 > 1.667,$ you can reject $H_0: \mu = 5000.$
(b) From computer output, you can reject $H_0$ because the P-value 0.43 is less than 5%.
Z test--Population SD assumed: For comparison, this is a printout for your approximate z test. Here you have to "lie to the software," entering the sample standard $S = 578$ as if it were the population SD $\sigma.$ The (slightly edited) output is as follows:
One-Sample Z

Test of μ = 3000 vs > 3000
The assumed population standard deviation = 578

 N    Mean  SE Mean       Z      P
70  3120.0     69.1    1.74  0.041

(a) From printed normal tables, the 5% critical value for this one-sided z test is $c = 1.645;$
because $T = 1.74 > 1.645,$ you can reject $H_0: \mu = 5000.$
(b) From computer output, you can reject $H_0$ because the P-value 0.41 is less than 5%.

Summary: Either way, the observed mean $\bar X = 3120$ is enough larger than
the hypothetical population mean $\mu = 3000$ to reject the null hypothesis $H_0: \mu = 3000$ against the one-sided alternative $H_a: \mu > 3000$.
However, if the "z statistic" had turned out to be $Z = 1.650$ (between 1.667 and 1.645), then the "z test" would reject $H_0$ (just barely) and the t test would not. So if you're testing exactly at a particular significance level, the approximate z test is not always a good substitute for the t test--even with s sample size as large as 70.
Also, there can be a big difference between a one-sided test and a two-sided test: For your data, a test against a two-sided alternative $H_a:  \mu \ne 3000$ would
have a P-value of about 8% and you could not reject at the 5% level.
[By doing a one-sided test, you are, in effect,  ignoring the possibility that
the new fertilizer might be worse.]