text:
Q: The gzip compressor is not going with the while loop I am trying to query from database with Java JDBC and compress data in one column  to gzip file in specific directory. I have tested my JDBC query and it working fine, but the Gzip code not going with the while loop, it's run with the loop firt row and stuck there. Why it's stuck? help me please!
These folders already existed:  D:\Directory\My\year\id1\id2
//Some query JDBC code here, it's work well. I query all rows Data, year, id1,id2,id3
 while (myRs1.next()){

        String str = Data;
    File myGzipFile = new File("D:\\Directory\\My\\"+year+"\\"+id1+"\\"+id2+"\\"+id3+".gzip");

    GZIPOutputStream gos = null;
    InputStream is = new ByteArrayInputStream(str.getBytes());
    gos = new GZIPOutputStream(new FileOutputStream(myGzipFile));

    byte[] buffer = new byte[1024];
    int len;
    while ((len = is.read(buffer)) != -1) {
        gos.write(buffer, 0, len);
        System.out.print("done for:"+id3);
    }

    try { gos.close(); } catch (IOException e) { }
}

A: Try formatting the source like this to catch exceptions.
public class InputStreamDemo {
   public static void main(String[] args) throws Exception {

      InputStream is = null;
      int i;
      char c;

      try{
         is = new FileInputStream("C://test.txt");

         System.out.println("Characters printed:");

         // reads till the end of the stream
         while((i=is.read())!=-1)
         {
            // converts integer to character
            c=(char)i;

            // prints character
            System.out.print(c);
         }
      }catch(Exception e){

         // if any I/O error occurs
         e.printStackTrace();
      }finally{

         // releases system resources associated with this stream
         if(is!=null)
            is.close();
      }
   }
}


text:
Q: oracle connection in jsp I am new to both jsp as well as oracle.
I just want to know the steps for connecting an oracle 10g database with a jsp page.

A: Here are the steps.

*

*Don't do this in a JSP file. Do this in a Java class.

*Read the JDBC tutorial. You can download the Oracle JDBC driver here and find Oracle-specific JDBC documentation here (code samples starts in chapter 3). Play around it in a simple Java class with a main() method in an IDE or CMD as long until you get the grasp. May take a day or two. It boils down to loading the JDBC driver, getting a DB connection and then executing the query on it.

*Create a Javabean class which represents a single entity containing information of a single table row. Create a DAO (Data Access Object) class which offers methods to create, read, update and delete the entity/entities. Test it thoroughly using a simple Java class with a main().

*Create a Servlet class which has the doGet() and/or doPost() methods implemented according to the functional requirements and uses the DAO class to obtain or persist the entities of interest.
Related questions:

*

*Displaying resultset in JSP

*Places where Javabeans are used

*DAO tutorial - Basic introduction to a JDBC DAO

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multidimensional Array Function not behaving as expected in a webpage I am trying to understand why my code does not function as expected. This code I am running in a snippet in the browser:

    function generateMaze(n) {
      //   let n = document.getElementById("maze-size").value;
      let maze = [];
      for (let i = 0; i < n; i++) {
        let mazeWidth = new Array(n)
          .fill(1)
          .map((x) => (Math.random() >= 0.3 ? 1 : 0));
        maze.push(mazeWidth);
      }
      console.log(maze);
    }

    console.log(generateMaze(5))

In the webpage I have the html: The only thing that differs here is that there is these 2 lines above the function to get the value and pass it to the function. I will include the full index.js at the end

    <!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="styles.css" />
        <title></title>

          Input desired Maze Size
          <input id="maze-size" name="mazesize" type="text" />
          <button id="generateMaze">

            Generate
          </button>

index.js

    "use strict";

    const button = document.getElementById("generateMaze");

    button.addEventListener("click", generateMaze);

    function generateMaze() {
      let n = document.getElementById("maze-size").value;
      let maze = [];
      for (let i = 0; i < n; i++) {
        let mazeWidth = new Array(n)
          .fill(1)
          .map((x) => (Math.random() >= 0.3 ? 1 : 0));
        maze.push(mazeWidth);
      }
    }

Summary is:
This works perfectly as a standalone function generating a matrix 2d array with the defined input:
eg:
[
   [0, 0, 1, 1, 1],
   [1, 1, 1, 1, 1],
   [1, 1, 1, 1, 0],
   [1, 1, 0, 1, 1],
   [0, 0, 1, 1, 1],
]

but when I use this function attached to a button I get an output of only 1 element in n number of arrays and I do not understand why.
Thank you in advance for any help you can provide.


text:
Q: Unable to launch app for broadcast intent I wrote a small clock widget.  Like all clocks, it has to be updated every minute.  So I set up an alarm to do this.  It worked fine.  It was just a little too small.  So I fiddled with an XML attribute and tried again.  It force-closed.  I changed the attribute back to the original and tried again.  It again force-closed.
The LogCat follows(from package install to the OS killing it):
01-19 13:38:52.292: DEBUG/PackageManager(57): New package installed in /data/app/com.---.clock-2.apk
01-19 13:38:52.571: INFO/ActivityManager(57): Force stopping package com.---.clock uid=10043
01-19 13:38:52.571: INFO/Process(57): Sending signal. PID: 593 SIG: 9
01-19 13:38:52.612: INFO/ActivityManager(57): Force stopping package com.---.clock uid=10043
01-19 13:38:53.022: DEBUG/PhotoAppWidgetProvider(282): getPhoto query count=0
01-19 13:38:53.022: DEBUG/PhotoAppWidgetProvider(282): sending out views=null for id=0
01-19 13:38:53.131: INFO/ActivityManager(57): Start proc com.---.clock for broadcast com.---.clock/.Clock: pid=613 uid=10043 gids={1015}
01-19 13:38:53.713: DEBUG/Clock widget(613): updated
01-19 13:38:54.011: INFO/ActivityManager(57): Force stopping package com.---.clock uid=10043
01-19 13:38:54.021: INFO/Process(57): Sending signal. PID: 613 SIG: 9
01-19 13:38:54.301: DEBUG/dalvikvm(121): GC_EXPLICIT freed 13673 objects / 524360 bytes in 177ms
01-19 13:38:54.542: DEBUG/dalvikvm(125): GC_EXPLICIT freed 4956 objects / 200960 bytes in 440ms
01-19 13:38:54.801: WARN/RecognitionManagerService(57): no available voice recognition services found
01-19 13:38:55.032: DEBUG/dalvikvm(57): GC_EXPLICIT freed 4960 objects / 290104 bytes in 201ms
01-19 13:38:55.042: INFO/installd(35): unlink /data/dalvik-cache/data@app@com.---.clock-1.apk@classes.dex
01-19 13:38:55.131: DEBUG/AndroidRuntime(605): Shutting down VM
01-19 13:38:55.151: DEBUG/dalvikvm(605): Debugger has detached; object registry had 1 entries
01-19 13:38:55.212: INFO/AndroidRuntime(605): NOTE: attach of thread 'Binder Thread #3' failed
01-19 13:38:55.571: DEBUG/PhotoAppWidgetProvider(282): getPhoto query count=0
01-19 13:38:55.571: DEBUG/PhotoAppWidgetProvider(282): sending out views=null for id=0
01-19 13:38:55.762: INFO/ActivityManager(57): Start proc com.---.clock for broadcast com.---.clock/.Clock: pid=622 uid=10043 gids={1015}
01-19 13:38:56.332: WARN/asset(622): Asset path /data/app/com.---.clock-1.apk is neither a directory nor file (type=1).
01-19 13:38:56.373: DEBUG/AndroidRuntime(622): Shutting down VM
01-19 13:38:56.373: WARN/dalvikvm(622): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-19 13:38:56.722: DEBUG/PhotoAppWidgetProvider(282): getPhoto query count=0
01-19 13:38:56.732: DEBUG/PhotoAppWidgetProvider(282): sending out views=null for id=0
01-19 13:38:56.841: ERROR/AndroidRuntime(622): FATAL EXCEPTION: main
01-19 13:38:56.841: ERROR/AndroidRuntime(622): java.lang.RuntimeException: Unable to instantiate receiver com.---.clock.Clock: java.lang.ClassNotFoundException: com.---.clock.Clock in loader dalvik.system.PathClassLoader[/data/app/com.---.clock-1.apk]
01-19 13:38:56.841: ERROR/AndroidRuntime(622):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2789)
01-19 13:38:56.841: ERROR/AndroidRuntime(622):     at android.app.ActivityThread.access$3200(ActivityThread.java:125)
01-19 13:38:56.841: ERROR/AndroidRuntime(622):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2083)
01-19 13:38:56.841: ERROR/AndroidRuntime(622):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-19 13:38:56.841: ERROR/AndroidRuntime(622):     at android.os.Looper.loop(Looper.java:123)
01-19 13:38:56.841: ERROR/AndroidRuntime(622):     at android.app.ActivityThread.main(ActivityThread.java:4627)
01-19 13:38:56.841: ERROR/AndroidRuntime(622):     at java.lang.reflect.Method.invokeNative(Native Method)
01-19 13:38:56.841: ERROR/AndroidRuntime(622):     at java.lang.reflect.Method.invoke(Method.java:521)
01-19 13:38:56.841: ERROR/AndroidRuntime(622):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-19 13:38:56.841: ERROR/AndroidRuntime(622):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-19 13:38:56.841: ERROR/AndroidRuntime(622):     at dalvik.system.NativeStart.main(Native Method)
01-19 13:38:56.841: ERROR/AndroidRuntime(622): Caused by: java.lang.ClassNotFoundException: com.---.clock.Clock in loader dalvik.system.PathClassLoader[/data/app/com.---.clock-1.apk]
01-19 13:38:56.841: ERROR/AndroidRuntime(622):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
01-19 13:38:56.841: ERROR/AndroidRuntime(622):     at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
01-19 13:38:56.841: ERROR/AndroidRuntime(622):     at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
01-19 13:38:56.841: ERROR/AndroidRuntime(622):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2780)
01-19 13:38:56.841: ERROR/AndroidRuntime(622):     ... 10 more
01-19 13:38:56.901: WARN/asset(57): Asset path /data/app/com.---.clock-1.apk is neither a directory nor file (type=1).
01-19 13:38:56.913: WARN/PackageManager(57): Failure retrieving resources forcom.---.clock
01-19 13:38:57.932: DEBUG/PhotoAppWidgetProvider(282): getPhoto query count=0
01-19 13:38:58.003: DEBUG/PhotoAppWidgetProvider(282): sending out views=null for id=0
01-19 13:39:05.101: INFO/Process(622): Sending signal. PID: 622 SIG: 9
01-19 13:39:05.151: INFO/ActivityManager(57): Process com.---.clock (pid 622) has died.
01-19 13:39:05.182: WARN/InputManagerService(57): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@43ecc698
01-19 13:39:05.892: DEBUG/PhotoAppWidgetProvider(282): getPhoto query count=0
01-19 13:39:05.892: DEBUG/PhotoAppWidgetProvider(282): sending out views=null for id=0
01-19 13:39:06.011: INFO/ActivityManager(57): Start proc com.---.clock for broadcast com.---.clock/.Clock: pid=630 uid=10043 gids={1015}
01-19 13:39:06.413: WARN/asset(630): Asset path /data/app/com.---.clock-1.apk is neither a directory nor file (type=1).
01-19 13:39:06.472: DEBUG/AndroidRuntime(630): Shutting down VM
01-19 13:39:06.482: WARN/dalvikvm(630): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-19 13:39:06.901: ERROR/AndroidRuntime(630): FATAL EXCEPTION: main
01-19 13:39:06.901: ERROR/AndroidRuntime(630): java.lang.RuntimeException: Unable to instantiate receiver com.---.clock.Clock: java.lang.ClassNotFoundException: com.---.clock.Clock in loader dalvik.system.PathClassLoader[/data/app/com.---.clock-1.apk]
01-19 13:39:06.901: ERROR/AndroidRuntime(630):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2789)
01-19 13:39:06.901: ERROR/AndroidRuntime(630):     at android.app.ActivityThread.access$3200(ActivityThread.java:125)
01-19 13:39:06.901: ERROR/AndroidRuntime(630):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2083)
01-19 13:39:06.901: ERROR/AndroidRuntime(630):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-19 13:39:06.901: ERROR/AndroidRuntime(630):     at android.os.Looper.loop(Looper.java:123)
01-19 13:39:06.901: ERROR/AndroidRuntime(630):     at android.app.ActivityThread.main(ActivityThread.java:4627)
01-19 13:39:06.901: ERROR/AndroidRuntime(630):     at java.lang.reflect.Method.invokeNative(Native Method)
01-19 13:39:06.901: ERROR/AndroidRuntime(630):     at java.lang.reflect.Method.invoke(Method.java:521)
01-19 13:39:06.901: ERROR/AndroidRuntime(630):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-19 13:39:06.901: ERROR/AndroidRuntime(630):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-19 13:39:06.901: ERROR/AndroidRuntime(630):     at dalvik.system.NativeStart.main(Native Method)
01-19 13:39:06.901: ERROR/AndroidRuntime(630): Caused by: java.lang.ClassNotFoundException: com.---.clock.Clock in loader dalvik.system.PathClassLoader[/data/app/com.---.clock-1.apk]
01-19 13:39:06.901: ERROR/AndroidRuntime(630):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
01-19 13:39:06.901: ERROR/AndroidRuntime(630):     at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
01-19 13:39:06.901: ERROR/AndroidRuntime(630):     at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
01-19 13:39:06.901: ERROR/AndroidRuntime(630):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2780)
01-19 13:39:06.901: ERROR/AndroidRuntime(630):     ... 10 more
01-19 13:39:06.901: DEBUG/PhotoAppWidgetProvider(282): getPhoto query count=0
01-19 13:39:06.922: DEBUG/PhotoAppWidgetProvider(282): sending out views=null for id=0
01-19 13:39:07.051: WARN/ActivityManager(57): Process com.---.clock has crashed too many times: killing!
01-19 13:39:07.062: INFO/Process(57): Sending signal. PID: 630 SIG: 9
01-19 13:39:07.151: WARN/ActivityManager(57): Unable to launch app com.---.clock/10043 for broadcast Intent { act=android.appwidget.action.APPWIDGET_UPDATE cmp=com.---.clock/.Clock (has extras) }: process is bad
01-19 13:39:07.151: WARN/ActivityManager(57): finishReceiver called but none active

I have never seen this error before and have no idea what's causing it or how to fix it.  Can someone interpret this for me please?

A: For whatever reason, (MAGIC!) Rebooting the emulator worked.  I still have no idea why it messed up in the first place, but the reboot worked.


text:
Q: Learn Python the Hard Way - ex.23: Why does it only show one line? Trying to read python (and anything programming related) for the first time now with Zed A. Shaw's book "Learn Python the Hard Way" and got stuck in exercise 23 with a problem for which I did not find an answer online.
I wrote the code as shown in the book:
import sys
script, encoding, error = sys.argv

def main(language_file, encoding, errors):
    line = language_file.readline()

    if line:
        print_line(line,encoding,errors)
        return (main, language_file, encoding, errors)

def print_line(line, encoding, errors):
    next_lang= line.strip()
    raw_bytes = next_lang.encode(encoding, errors=errors)
    cooked_string = raw_bytes.decode(encoding, errors=errors)

    print(raw_bytes, "<===>", cooked_string)

languages = open("languages.txt", encoding="UTF-8")

main(languages, encoding, error)

as seen here
But when running it on Powershell, it only displays the first line:
PS C:\Usuários\Saulo\Python> python ex23.py utf-8 script
b'\xef\xbb\xbfAfrikaans' <===> Afrikaans
PS C:\Usuários\Saulo\Python>

as seen here
I've tried in on cmd but got the same result.
Am I doing something wrong?


text:
Q: How to edit column value in Sheetjs(angular 13.3.0)? I am trying to create an excel download function by linking Angular and sheetJS.
I want to change the values of G2 columns in Excel.
The value of the payType category column is 0, 1, 5, and so on.
I want to change the payType column value to 'immediate payment' if 0, 'pre-payment' if 1, and 'additional payment' if 5
How come there is no way? I want to know the code that works in Angular.
import * as XLSX from 'xlsx';

exportToExcel(): void {
  this.svc.billExcel(this.filter).subscribe((res) => {
    let heading = [['seq','userID','userName','userType','userGrade','itemType',
    'payType','workTime','realTime','defaultPrice','timePrice','workYear','yearPrice',
    'payAmt','userRate','realAMT','feeRate','lastAmt','startDate',
    'endDate','inSeq','payDesc','regDate']];

  var dataList = [
      {
        "seq": 9,
        "userId": "0730003",
        "userName": null,
        "userType": "latent intelligence",
        "gradeCode": "5",
        "itemType": "main book",
        "payType": 0,
        "workTime": 30,
        "realTime": 0,
        "defaultPrice": 70000,
        "timePrice": 15000,
        "workYear": 2026,
        "yearPrice": 15000,
        "payAmt": 100000,
        "userRate": 0,
        "realAmt": 100000,
        "feeRate": 30,
        "lastAmt": 70000,
        "startDate": "20220416160825",
        "endDate": "20220416174105",
        "inSeq": "0",
        "payDesc": "client[James] Consultation has been.",
        "regDate": "20220416160825"
        },
        {
          "seq": 10,
          "userId": "0730003",
          "userName": null,
          "userType": "latent intelligence",
          "gradeCode": "5",
          "itemType": "main book",
          "payType": 0,
          "workTime": 30,
          "realTime": 0,
          "defaultPrice": 70000,
          "timePrice": 15000,
          "workYear": 2026,
          "yearPrice": 15000,
          "payAmt": 100000,
          "userRate": 0,
          "realAmt": 100000,
          "feeRate": 30,
          "lastAmt": 70000,
          "startDate": "20220416160825",
          "endDate": "20220416174105",
          "inSeq": "0",
          "payDesc": ""client[Mary] Consultation has been.",
          "regDate": "20220416161008"
        }
  ];

  const worksheet: XLSX.WorkSheet =
  XLSX.utils.json_to_sheet(dataList);
  XLSX.utils.sheet_add_aoa(worksheet, heading);
  XLSX.utils.sheet_add_json(worksheet, dataList, { origin: 'A2', skipHeader: true });
  const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
  XLSX.writeFile(workbook, BillsDailyComponent.toExportFileName('Payment Status'));

  static toExportFileName(excelFileName: string): string {
     return `${excelFileName}.xlsx`;

}


text:
Q: Unsafe Copy to Memory Mapped File Accessor view handle wrapper corrupts file I have the following code, which essentially reads an HTTP Response into a byte array and uses unsafe operations to copy data from the byte buffer into a specified region of a memory mapped file:
private static readonly ArrayPool<byte> Pool = ArrayPool<byte>.Shared;
    [Obsolete("Obsolete")]
    private static async Task GetStream(string url, long start, long end, MemoryMappedFile mmf, int bufferSize, CancellationToken cancellationToken)
    {
        var r = (HttpWebRequest)WebRequest.Create(url);
        r.Method = "GET";
        r.AddRange(start,end);
        r.Pipelined = true;
        r.KeepAlive = true;

        using var response = await r.GetResponseAsync().ConfigureAwait(false);
        var buffer = Pool.Rent(bufferSize);
        try
        {
            await using var stream = response.GetResponseStream();
            var accessor = mmf.CreateViewAccessor(start, response.ContentLength, MemoryMappedFileAccess.ReadWrite);
            var bytesRead = 0;
            var brtot = 0;
            var total = 0;
            int i = -1;
            do
            {
                Array.Clear(buffer);
                var offset = 0;
                do {
                    bytesRead = await stream.ReadAsync(buffer, offset, bufferSize - offset, cancellationToken).ConfigureAwait(false);
                    brtot += bytesRead;
                    offset += bytesRead;
                } while (bytesRead != 0 && offset < bufferSize);

                if (offset == 0) {continue;}

                i = i + 1;
                if (brtot - total > 1)
                {
                    CopyBytes(buffer, total, accessor, i == 0 ? brtot : brtot - total);

                    Console.WriteLine(String.Format("{0} - {1} ==== {2}", total, brtot - bytesRead, i));
                    total = brtot + 1;
                }
            } while (bytesRead != 0);

            await stream.FlushAsync(cancellationToken);
        }
        finally
        {
            Pool.Return(buffer);
            response.Close();
        }
    }

    private static void CopyBytes(byte[] buff, int offset, MemoryMappedViewAccessor s, int length)
    {
        unsafe
        {
            var pointer = (byte*)0;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                s.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer);
                Marshal.Copy(buff, 0, IntPtr.Add(new IntPtr(pointer), offset), length);
            }
            finally {
                if (pointer != null)
                    s.SafeMemoryMappedViewHandle.ReleasePointer();

            }
        }
    }

Then I have this code that calls it:
public static async Task DownloadFile(string url, String outFile, int parts, int bufferSize)
        {
            var responseLength = (await WebRequest.Create(url).GetResponseAsync()).ContentLength;
            var partSize = (long)Math.Floor(responseLength / (parts + 0.0));
            var pieces = new List<ValueTuple<long, long>>();
            var uri = new Uri(url);
            var filename = outFile ?? Path.GetFileName(uri.LocalPath);

            Console.WriteLine(responseLength);
            Console.WriteLine(partSize);

            ServicePointManager.Expect100Continue = false;
            ServicePointManager.DefaultConnectionLimit = 10000;
            ServicePointManager.FindServicePoint(new Uri(url)).ConnectionLimit = parts;

#if NET6_0_OR_GREATER
            ServicePointManager.ReusePort = true;
#endif

            //Loop to add all the events to the queue
            for (long i = 0; i < responseLength; i += partSize) {
                pieces.Insert(0,(i + partSize < responseLength ? new ValueTuple<long, long>(i, i + partSize) : new ValueTuple<long, long>(i, responseLength)));
            }

            var cs = new CancellationToken(false);
            File.Delete(filename);
            var mmf = MemoryMappedFile.CreateFromFile(filename, FileMode.CreateNew,null, responseLength, MemoryMappedFileAccess.ReadWrite);

            GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
            await Parallel.ForEachAsync(pieces, new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount}, async (tuple, token) =>
            {
                await GetStream(url,tuple.Item1, tuple.Item2, mmf, bufferSize, cs);
            });
        }

The only issue with the code is that it is corrupting whatever file I download with no errors. I am sure this is due to my parameters specified to CopyBytes(). But unfortunately, I can't get the right calculations for the parameters, can someone help me with this or at least point me on the right direction? I know some of the methods are obsolete, and I will address this, but I am currently more focused on getting the unsafe memory copying to work. Thank you!


text:
Q: how to identify time overlap in r I have a dataframe (df) with admission and discharge dates of patients, with 4 columns:

ID,  admitDate (as date),  dcDate (as date), los (length of stay in
  days).

$ admitDate  : Date, format: "2009-09-19" "2010-01-24" "2010-09-30" ...
$ dcDate     : Date, format: "2009-09-23" "2010-01-27" "2010-10-04" ...
$ los        : num  4 3 4 25 6 3 6 2 2 3 ...

I need to be able to tell at any given time how many patients (and which patients) were admitted. That is, I think I need to find out the overlap between the patients' los. Here is how I'm defining overlap: (df$admitDate[x] <= df$disDate[y]) & (df$admitDate[y] <= df$disDate[x])
Any help is much appreciated.
Here is the output of dput for the first 20 patients:
> dput(head(df,20))
structure(list(Unit.Number = c(2013459L, 2013459L, 2047815L,
1362858L, 1331174L, 2068040L, 1363711L, 2175972L, 2036695L, 1426614L,
1403126L, 2083126L, 1334063L, 1349385L, 1404482L, 2175545L, 1296600L,
1293220L, 1336768L, 2148401L), admitDate = structure(c(14506,
14633, 14882, 15172, 14945, 15632, 15482, 15601, 16096, 15843,
16013, 15548, 15436, 15605, 16115, 15597, 15111, 15050, 15500,
15896), class = "Date"), dcDate = structure(c(14510, 14636, 14886,
15197, 14951, 15635, 15488, 15603, 16098, 15846, 16016, 15552,
15438, 15606, 16118, 15598, 15113, 15058, 15501, 15915), class = "Date"),
los = c(4, 3, 4, 25, 6, 3, 6, 2, 2, 3, 3, 4, 2, 1, 3, 1,
2, 8, 1, 19)), .Names = c("Unit.Number", "admitDate", "dcDate",
"los"), row.names = c(NA, 20L), class = "data.frame")

First, I tried the code suggested by  G. Grothendieck:
days <- seq(min(df$admitDate), max(df$dcDate), "day")
no.patients <- data.frame(
  Date = days,
  Num = sapply(days, function(d) sum(d >= df$admitDate & d <= df$dcDate)),
  Patients = sapply(days, function(d)
        toString(df$Unit.Number[d >= df$admitDate & d <= df$dcDate]))
)

And here is what happened:
> days <- seq(min(df$admitDate), max(df$dcDate), "day")
Error in seq.int(0, to0 - from, by) : 'to' cannot be NA, NaN or infinite
> no.patients <- data.frame(Date = d,
+                           Num = sapply(days, function(d) sum(d >= df$admitDate & d <=         df$dcDate)))
Error in data.frame(Date = d, Num = sapply(days, function(d) sum(d >=  :
object 'd' not found

Then, I thought maybe I need to get rid of NA's. So here is what I did:
> df <- df[rowSums(is.na(df)) < 0, ]

And tried again. Here is what I got:
> days <- seq(min(df$admitDate), max(df$dcDate), "day")
Error in seq.int(0, to0 - from, by) : 'to' cannot be NA, NaN or infinite
In addition: Warning messages:
1: In min.default(numeric(0), na.rm = FALSE) :
no non-missing arguments to min; returning Inf
2: In max.default(numeric(0), na.rm = FALSE) :
no non-missing arguments to max; returning -Inf
> no.patients <- data.frame(Date = d,
+                           Num = sapply(days, function(d) sum(d >= df$admitDate & d <=   df$dcDate)))
Error in data.frame(Date = d, Num = sapply(days, function(d) sum(d >=  :
object 'd' not found

A: Try this:
days <- seq(min(df$admitDate), max(df$dcDate), "day")
no.patients <- data.frame(
      Date = days,
      Num = sapply(days, function(d) sum(d >= df$admitDate & d <= df$dcDate)),
      Patients = sapply(days, function(d)
            toString(df$Unit.Number[d >= df$admitDate & d <= df$dcDate]))
)

giving:
> head(no.patients)
        Date Num Patients
1 2009-09-19   1  2013459
2 2009-09-20   1  2013459
3 2009-09-21   1  2013459
4 2009-09-22   1  2013459
5 2009-09-23   1  2013459
6 2009-09-24   0

ADDED patient list to each row.  Fixed case of df.

A: Here is another way.  This is a process that will create the size of the queue based on entry/exit times and can be used in this case to compute the number of patients:
df <- structure(list(Unit.Number = c(2013459L, 2013459L, 2047815L,
1362858L, 1331174L, 2068040L, 1363711L, 2175972L, 2036695L, 1426614L,
1403126L, 2083126L, 1334063L, 1349385L, 1404482L, 2175545L, 1296600L,
1293220L, 1336768L, 2148401L), admitDate = structure(c(14506,
14633, 14882, 15172, 14945, 15632, 15482, 15601, 16096, 15843,
16013, 15548, 15436, 15605, 16115, 15597, 15111, 15050, 15500,
15896), class = "Date"), dcDate = structure(c(14510, 14636, 14886,
15197, 14951, 15635, 15488, 15603, 16098, 15846, 16016, 15552,
15438, 15606, 16118, 15598, 15113, 15058, 15501, 15915), class = "Date"),
los = c(4, 3, 4, 25, 6, 3, 6, 2, 2, 3, 3, 4, 2, 1, 3, 1,
2, 8, 1, 19)), .Names = c("Unit.Number", "admitDate", "dcDate",
"los"), row.names = c(NA, 20L), class = "data.frame")

# create dataframe for computing the size of the queue (concurrent patients)
x <- data.frame(date = c(df$admitDate, df$dcDate)
            , op = c(rep(1, nrow(df)), rep(-1, nrow(df)))
            , Unit.Number = c(df$Unit.Number, df$Unit.Number)
            )
# sort and calculate concurrent patients
x <- x[order(x$date), ]  # sort in time order
x$cum <- cumsum(x$op)

# 'x' will have the 'cum' equal to the number of patients concurrently.
# for 'op' == 1, you have the patient ID and 'cum' will be the number of
# patients at that time.

plot(x$date, x$cum, type = 's')

This is what the first part of 'x' looks like:
> head(x,10)
         date op Unit.Number cum
1  2009-09-19  1     2013459   1
21 2009-09-23 -1     2013459   0
2  2010-01-24  1     2013459   1
22 2010-01-27 -1     2013459   0
3  2010-09-30  1     2047815   1
23 2010-10-04 -1     2047815   0
5  2010-12-02  1     1331174   1
25 2010-12-08 -1     1331174   0
18 2011-03-17  1     1293220   1
38 2011-03-25 -1     1293220   0
>


text:
Q: Syntax question for declaring variables I have a very basic syntax question for declaring $X_{hb}$ a variable.
f[Subscript[X, hb_]] := Subscript[X, hb]

In mathematica instead of writing the Subscript[] code, I simply use the ctrl+_ shortcut to place whatever I want in the subscript. However, after doing this I do not know how make mathematica consider $X_{hb}$ as a variable since placing the _ after it is considered to be an unrealted character.
See here: http://i.imgur.com/XWZHssm.png
How do I fix this issue?


text:
Q: Update ListBox collection immediately afted save I have MainWindow and user control AddEditData. Both using it's own viewmodel representation
MainWindowViewModel and AddEditViewModel.
On left side I have listbox with list of data items and on right side AddEditView which display data details selected on listbox. On AddEdit I have button save which saves data from textboxes.
Under the hood everything works, data is properly saved inside database but change on data details is not visible immediatly, change is visible on next app. execution.
I know about INotifyPropertyChanged and I implemented on my listbox data collection in the first place. Here's the code
MainWindowViewModel
public ObservableCollection<Book> Books
{
    get { return books; }
    set {
          books = value;
          OnPropertyChanged("Books");
        }
}

MainWindow.xaml
 <ListBox Name="listBoxData"
          DataContext="{Binding Source={StaticResource MainWindowViewModelDataSource}}"
          ItemTemplate="{DynamicResource BookTemplate}"
          ItemsSource="{Binding Books}"
          SelectedItem="{Binding SelectedBook, Mode=TwoWay}">

On AddEditViewModel I added command to save button which saves data to the db and using Mediator pattern send message to the MainWindow to inform that data is saved.
 Repository.Save(book);
 Mediator.NotifyColleagues("SaveData", book);

Again, how to update listbox item immediatly after save action?
Update
I've added UpdateSourceTrigger to PropertyChanged
 <ListBox Name="listBoxData"
              DataContext="{Binding Source={StaticResource MainWindowViewModelDataSource}}"
              ItemTemplate="{DynamicResource BookTemplate}"
              ItemsSource="{Binding Books, UpdateSourceTrigger=PropertyChanged}"
              SelectedItem="{Binding SelectedBook, Mode=TwoWay}">

but this nothing changes, listbox remains the same after saving data.

A: If you want the properties of the ListBoxItem to update when the fields in the AddEditData control are edited, then you'll also need to implement the INotifyPropertyChanged interface on the class of the items inside the Books collection.
If you want them to update only after a save, then you'll need to add UpdateSourceTrigger=Explicit to all of your Bindings in the AddEditData control and manually update them after a save... that's a bit of a pain because you'll need to access each Binding in turn to update the values:
BindingExpression bindingExpression =
    someTextBox.GetBindingExpression(TextBox.TextProperty);
bindingExpression.UpdateSource();

Alternatively, if you add UpdateSourceTrigger=PropertyChanged to all of your Bindings, then the fields in the items will update as soon as they are edited.


text:
Q: Verificar qual TextField está chamando textFieldDidBeginEditing Tenho vários textFields na minha tela e gostaria de saber qual deles começou uma ação.
Por exemplo:
func textFieldDidBeginEditing(textField: UITextField) {
    if textField // aqui eu não sei comparar para ver qual textField iniciou essa chamada
}

Posso utilizar o Outlet de cada textField ou há outra maneira de fazer isso?

A: Sim, você pode utilizar o Outlet para fazer essa verificação.
Basicamente você faria isso:
@IBOutlet weak var text1: UITextField!
@IBOutlet weak var text2: UITextField!

func textFieldDidBeginEditing(textField: UITextField) {

 if textField == text1 {
    print("Text 1 mudou");
 } else if textField == text2 {
    print("Text 2 mudou");
 } else {
    print("outro text mudou");
 }
}

Outra maneira que você pode fazer isso é verificando a tag do UITextView. Por exemplo, levando em consideração que text1 tem a tag '1' e text2 com a tag '2' o código ficaria assim:
 @IBOutlet weak var text1: UITextField!
 @IBOutlet weak var text2: UITextField!

     func textFieldDidBeginEditing(textField: UITextField) {

        if(textField.tag == 1) {
            print("Text 1 changed");
        } else if(textField.tag == 2) {
            print("Text 2 changed");
        } else {
            print("Text ?? changed");
        }
    }

Levando em consideração ambas as formas, é possível observar que através do Outlet o código fica mais legível.
Edit: Conforme complemento do Luis, também é possível utilizar constantes para realizar a comparação das tags, como no exemplo:
let kTextField1 = 1;
let kTextField2 = 2;

func textFieldDidBeginEditing(textField: UITextField) {

    if(textField.tag == kTextField1) {
        print("Text 1 changed");
    } else if(textField.tag == kTextField2) {
        print("Text 2 changed");
    } else {
        print("Text ?? changed");
    }
}


text:
Q: Google App Engine performs different from its local appserver The following function will extract URLs form Google search result. It works well in dev_appserver(localhost) but when I deployed it on Google App Engine it show some Error.
Program:
def googleSearch(keyword):
    from re import findall
    from urllib2 import build_opener
    from urllib import quote, unquote
    urlregex = r'<a[ ]href="/url\?q=(http://.+?)[&]'
    searchURL = 'https://www.google.com/search?q=' + quote(keyword, safe = '') # https will exclude Cached results
    #Google
    opener = build_opener()
    opener.addheaders = [('User-agent', 'Mozilla/5.0')]
    pagesource = opener.open(searchURL).read()
    result = findall(urlregex, pagesource)
    print result
    resultlist = []
    for url in result:
        resultlist.append(unquote(url))
    resultlist = sorted(set(resultlist), key=resultlist.index)
    return resultlist

GAE Error:
Internal Server Error

The server has either erred or is incapable of performing the requested operation.

Traceback (most recent call last):
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1535, in __call__
    rv = self.handle_exception(request, response, e)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1529, in __call__
    rv = self.router.dispatch(request, response)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
    return route.handler_adapter(request, response)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1102, in __call__
    return handler.dispatch()
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 572, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch
    return method(*args, **kwargs)
  File "/base/data/home/apps/s~crawlnsearch/1.370098233684025667/main.py", line 56, in get
    result = googleSearch(q)
  File "/base/data/home/apps/s~crawlnsearch/1.370098233684025667/goosearch.py", line 15, in googleSearch
    pagesource = opener.open(searchURL).read()
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 410, in open
    response = meth(req, response)
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 442, in error
    result = self._call_chain(*args)
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 629, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 410, in open
    response = meth(req, response)
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 503: Service Unavailable

Did any one know solution for this problem.


text:
Q: why my imageview doesn't take the bitmap and show it? public class UserlistActivity extends AppCompatActivity {

    static ListView userlist;
    static String[] users;
    ImageView user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userlist);
        setIDs();
        Bitmap userphoto = null;
        try {
            userphoto = getBitmapFromAsset("user dashboard.png");
        } catch (IOException e) {
            e.printStackTrace();
        }
        new Gate(this, "USERLIST").execute();
        String mDrawableName = "user dashboard";
        int resID = getResources().getIdentifier(mDrawableName , "assets", getPackageName());
        user.setImageResource(resID);
        user.setImageBitmap(userphoto);
    }

    private Bitmap getBitmapFromAsset(String strName) throws IOException
    {
        AssetManager assetManager = getAssets();
        InputStream istr = assetManager.open(strName);
        Bitmap bitmap = BitmapFactory.decodeStream(istr);
        return bitmap;
    }

    private void setIDs() {
        userlist = (ListView) findViewById(R.id.userlist);
        View inflatedView = getLayoutInflater().inflate(R.layout.userlist_list_item, null);
        user = (ImageView) inflatedView.findViewById(R.id.user);
    }

    static void fillData(Context context) {
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context, R.layout.userlist_list_item, R.id.listtext, users);
        userlist.setAdapter(arrayAdapter);
    }

here I am trying to getbitmap ( which is working in other activities fine ) and attatch it to image view that is part of a list item custom layout that I pass to adapter , but I don't know where is the issue , the image doesn't appear
EDIT ::
I fixed it by adding another copy of the photo to drawable so I can add it with source and skip the effort

A: I think you forgot to add the inflatedView to your parent view
use this code:
 LinearLayout parent = (LinearLayout)findViewById(R.id.parent_layout);
View inflatedView = getLayoutInflater().inflate(R.layout.userlist_list_item, null);
user = (ImageView) inflatedView.findViewById(R.id.user);
parent.addView(inflatedView);

use the Following method:
private Bitmap getBitmapFromAsset(String strName)
{
    AssetManager assetManager = getAssets();
    InputStream istr = null;
    try {
        istr = assetManager.open(strName);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Bitmap bitmap = BitmapFactory.decodeStream(istr);
    return bitmap;
}


text:
Q: Where do I put delegate methods and how do I invoke them? As a new iOS developer, I have finally stumbled across delegates.  I'm trying to follow a tutorial:  http://gabriel-tips.blogspot.com/2011/05/input-accessory-view-how-to-add-extra.html, But I'm having difficulty understanding where I am supposed to put the actual delegate methods.
Secondly, would anyone mind providing a dumbed down explanation of how a delegate method is invoked?
Thanks!

A: A delegate is simply a class that agrees to do work for another class. The delegate methods are invoked by the delegating class. The delegate must therefore, provide an implementation of the appropriate method. Let's make a simple view controller with a table view.
// MyViewController.h
@interface MyViewController : UIViewController <UITableViewDelegate>
@property (nonatomic, retain) UITableView *myTableView;
@end

Here in the MyViewController.h file I have declared my view controller to be a delegate of type UITableViewDelegate (it really means it implements the UITableViewDelegate protocol. More on this later). I have thus agreed to respond to requests to my view controller. The requests will come from the table view called myTableView. However, simply stating that I adhere to UITableViewDelegate does not make my view controller a delegate of anything. I must specify that directly:
// MyViewController.m
#import "MyViewController.h"

@implementation MyViewController

- (void)loadView
{
    myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    myTableView.delegate = self;
    self.view = myTableView;
}

@end

Here I specifically set MyViewController to be the delegate of myTableView. Now whenever the table view wants to ask its delegate to do something, it will send that message to my view controller. Thus, MyViewController MUST provide implementations of the appropriate delegate methods:
// MyViewController.m
#import "MyViewController.h"

@implementation MyViewController

- (void)loadView
{
    myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    myTableView.delegate = self;
    self.view = myTableView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Selected section:%i row:%i", indexPath.section, indexPath.row);
}

@end

Here I have provided an implementation for the delegate method tableView:didSelectRowAtIndexPath: which will be called by myTableView when it is appropriate (the user selects a row).
Here you can find all the delegate methods defined in UITableViewDelegate. Some are required and others are optional:
http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UITableViewDelegate_Protocol/Reference/Reference.html
In order to be a delegate of a class you should know which methods you are required to provide implementations for.
If you wanted to create your own delegate definitions, you would create a new protocol. You do not retain your delegates (see the property declaration), as this creates a retain cycle:
// MyViewController.h
@class MyViewController;

@protocol MyViewControllerDelegate
- (void)viewController:(MyViewController *)viewController didChangeSelection:(NSIndexPath *)newIndexPath;
@end

@interface MyViewController : UIViewController <UITableViewDelegate>
@property (nonatomic, retain) UITableView *myTableView;
@property (nonatomic, assign) id<MyViewControllerDelegate> delegate;
@end

Here we have created a new protocol. Any class that wants to be respond to the viewController:didChangeSelection: message could now do so. Just like with the table view above it would set the delegate to itself and then implement the method. Now that you have a delegate, you can invoke the method at an appropriate time.
// MyViewController.m
#import "MyViewController.h"

@implementation MyViewController

- (void)loadView
{
    myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    myTableView.delegate = self;
    self.view = myTableView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Selected section:%i row:%i", indexPath.section, indexPath.row);

    indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
    [self.delegate viewController:self didChangeSelection:indexPath];
}

@end

Now the delegate can receive the message and do what it wants knowing that my view controller changed the selection.

A: A delegate pattern is a convenient way to allow for the communication between independent controller that allows for loose coupling. So let's say you have a pattern like this:
        A
       / \
      B   C

Where A instantiates B and C.  Communicating between A to B and A to C are easy but how would you communicate between B and C? B to A? C to A? There are a couple different ways you could do so such as Key-Value Observing or Block Callbacks. Delegation, though, are still most frequently used although Blocks are coming on strong.
In this example, object A instantiates object B to create an object and fill it with info. How would object B pass the new object back to A as you want to keep things loose? Well, with these 9 easy steps, you can do it too!  It may not make sense but we'll start with ClassB…
// ClassB.h

@protocol ClassBDelegate; //(1)

@interface ClassB : NSObject

@property (nonatomic, weak) id<ClassBDelegate>bDelegate; //(2)

-(void)makeNewObjectAndSendBack;

@end

@protocol ClassBDelegate : NSObject //(3)

-(void) classB:(Class B *)theClassB finishedWithObject:(id)finishedObject; //(4)

@end

ClassB.m
@implementation
@synthesize bDelegate = _bDelegate; //(5)

-(void)makeNewObjectAndSendBack {

//something something something
[self.bDelegate classB:self finishedWithObject:newObject]; //(6)

}

@end

*

*define the protocol that will be established later

*set an instance of an object that will conform to that protocol

*set up the protocol

*set up the method call that you'll use to send the finishedObject back to A.

*synthesize the delegate

*after you do what you need to do, you send it back using the method
you defined in 4

// ClassA.h

@interface ClassA : NSObject <ClassBDelegate> //(7)

@property (nonatomic, strong) ClassB theClassB;

-(void)yourMethodToDoSomething;

@end

ClassA.m
@implementation
@synthesize theClassB = _theClassB;

-(void)randomMethod {

self.theClassB = [ClassB new];
self.theClassB.bDelegate = self; //(8)
[self.theClassB makeNewObjectAndSendBack];

}

-(void) classB:(Class B *)theClassB finishedWithObject:(id)finishedObject { //(9)
[self doSomethingWithFinishedObject:finishedObject]; //ta-da!
}

@end

7.Conform to the ClassBDelegate protocol. This basically says that you
   will implement the methods defined in the protocol definition.
8.Set the classB object's delegate object as self! This is crucial and
   often skipped.
9.Implement the delegate method for when you get the new object back.
So the process, in short is: A instanciate B. A sets B's delegate as self. A tells B to do something. B does something and sends object back via delegate method. A gets it back.
For more information, including what you can do with protocols, check out:
Big Nerd Ranch talk about Protocols
Part 1
Part 2
Part 3
Good luck!

A: It seems you might be a little confused as to what delegates are and how they are used.  Here are two links to Apple documentation you might find useful: A conceptual overview and a more in depth explaination.


text:
Q: change html in blogger soho theme After asking a few question the Help Center for Blogger I was directed here.
I am using the Soho Theme and have attempted with the help of Blogger Experts to change so CSS or HTML coding. As of now nothing is working.
I want to use a font that is not offered in the header above the image. I found and downloaded a font and use the CSS code they provided, entered it and applied to them but it won't show.
The other thing I would like to do is change the size that is used for that theme. I was given the code to enter into CSS, applied and it shows in the preview but when I actually view the website, it's still the standard large size. I even tried several different size images but it still goes to the size that seems to be part of the theme. Is there a way to use a smaller image?
Any help with these two issues is appreciated.
Thanks.


text:
Q: The usage of delegate i saw that delegate is used for custom events. as far example
delegate string FuncRef(string Val);

FuncRef fValue = GetFieldName;

fValue("hello");

what i do here just declare delegate and assign a function name to delegate and call like fValue("hello"); whenever it is required.
instead of calling the GetFieldName() through delegate i can call it directly. so i just want to know why should i use delegate to call function where as we can call function directly....what is the advantage of calling any function through delegate.
so please tell me in what kind of scenario delegate usage is required except event handling. please guide me with sample code and simulate a situation where i need to call function through delegate except event handling. please show me some real life scenario where we have to call function through delegate.

A: The reason to use delegates instead of calling the function directly is the same reason you do
var taxRate = 0.15;
var taxAmount = income * taxRate;

instead of
var taxAmount = income * 0.15;

In other words: using a variable to hold a reference to a callable entity (a delegate is exactly that) allows you to write code that can change its behavior depending on the parameters passed to it (the value of the delagate we 're passing in). This means more flexible code.
For examples of code that uses delegates you can look at LINQ (of course), but there's also the "delegates 101" example which is relevant in any language: filtering a list.

A: delegate string FuncRef(string Val);

FuncRef fValue;   // class member

if (condition1)
    fValue = GetFieldName1;
else if (condition2)
    fValue = GetFieldName2;
else
    fValue = GetFieldName3;

// Another function
fValue("hello");

A: Microsoft's tutorial code on C# delegates presents another interesting use case.  In their example, an object called Bookstore has a method ProcessPaperbackBooks which takes a book processing delegate and applies it to each item in the class.
The cool part is that then, if you need say, a method which collects all the ISBNs of all the books in the store, you don't need to change anything in the bookstore class, but only to define a function which acts on books and pass that into the ProcessPaperbackBooks method.  Delegated goodness will occur, and your new function will be applied to every item in the bookstore.  Snazzy, no?
http://msdn.microsoft.com/en-us/library/aa288459(v=vs.71).aspx

A: Basically any place where you want to be able to specify at runtime which function should be called.
The async BeginInvoke/EndInvoke pattern is a perfect example of this; the callback is specified via a delegate.

A: Shortly: You can use delegates and events members in combination to be able for example to assign an event handler to a class which does not know it before, the button class knows when it has to trigger the click event and does not know yet, internally, you will bind mybutton_Click handler to it.

A: Linq to objects makes extensive use of delegates:
myAnimals.Where(animal => animal.CanSwim)

the parameter supplied to the Where method ( animal => animal.CanSwim ) is a lambda expression that converts to a delegate that is applied to all elements in myAnimals.

A: One place I use delegates is my input handler (C#, XNA)
I have a public void OnKeyboardPress() delegate, which I bind to various functions when certain keys are pressed.
Input is a good example; rather than polling for it (i.e. every update you go 'is it ready yet?' you wait for it to call you)..such as a GUI. WPF  events are delegates.

A: Delegates are 1st class objects. IOW you can refer to them, reassign them, etc, just like any other object.


text:
Q: I have a mistake in calling a constructor (I think) don't know how to fix it I have this project in Java class and I chose to make a supermarket delivery service it provides the following:
- the products and their prices.
- The ability to choose the amount of products.
- The user gives his phone number, so the delivery man can contact them for direction.
- The user can enter a discount code.
- The user can cancel the order or confirm it, when the user confirms, the bill is printed with a note that the order will arrive soon.
- The user can enter the amount of money they will give the delivery, so the delivery man can bring the change.
I fixed this code a million times and I still get stupid mistakes because I have a blind eye for the mistakes
my mistake this time is as the netBeans told me
Exception in thread "main" java.lang.StackOverflowError
    at java.awt.Insets.<init>(Insets.java:103)
    at sun.awt.windows.WToolkit.getScreenInsets(Native Method)
    at sun.awt.windows.WToolkit.getScreenInsets(WToolkit.java:580)
    at java.awt.Window.init(Window.java:498)
    at java.awt.Window.<init>(Window.java:536)
    at java.awt.Frame.<init>(Frame.java:420)
    at java.awt.Frame.<init>(Frame.java:385)
    at javax.swing.JFrame.<init>(JFrame.java:180)
    at supermarket.SuperMarket.<init>(SuperMarket.java:61)
    at supermarket.SuperMarket.<init>(SuperMarket.java:132)

package supermarket;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

public class SuperMarket extends JFrame implements ActionListener {

        double juice = 1, tuna = 4, bread = 7, shampoo = 25;
        double discount = 0, subTotal = 0, total = 0, d=0;
        double jnum=0, tnum=0, bnum=0, snum=0;
        double shN, brN, tuN, juN;
        double shd, brd, tud, jud;

        private JTextField shField;
        private JTextField brField;
        private JTextField tuField;
        private JTextField juField;

    private JButton cancelButton;
    private JButton confirmButton;

    private JTextField nmField;

        private JLabel shLabel;
        private JLabel brLabel;
        private JLabel tuLabel;
        private JLabel juLabel;

        private JLabel shAmount;
        private JLabel brAmount;
        private JLabel tuAmount;
        private JLabel juAmount;

        private JPanel buttonPanel;

        private JLabel shError;
        private JLabel brError;
        private JLabel tuError;
        private JLabel juError;

        private SuperMarket mainFrm;
        private SuperMarket childFrm;

    /**
     * Create the order form.
     */

    public SuperMarket() {

            shLabel=new JLabel ("Shampoo    Price: 25   ",SwingConstants.LEFT);
            shField = new JTextField(10);
            shAmount = new JLabel(shLabel+"Amount:  "+shField);

            try{
                shd = Double.parseDouble(shField.getText());
            }
            catch(NumberFormatException shE){
                shField.setToolTipText("You must enter integers.");
                shField.setText("");
            }

            shN = (int) shd;
            snum=shN*shampoo;

            brLabel=new JLabel ("Bread  Price: 7    ",SwingConstants.LEFT);
            brField = new JTextField(10);
            brAmount= new JLabel(brLabel+"Amount:  "+brField);
            try{
                brd = Double.parseDouble(brField.getText());
            }
            catch(NumberFormatException shE){
                brField.setToolTipText("You must enter integers.");
                brField.setText("");
            }
            brN = (int) brd;
            bnum=brN*bread;

            tuLabel=new JLabel ("Tuna   Price: 4    ",SwingConstants.LEFT);
            tuField = new JTextField(10);
            tuAmount = new JLabel(tuLabel+"Amount:  "+tuField);

            try{
                tud = Double.parseDouble(tuField.getText());
            }
            catch(NumberFormatException shE){
                tuField.setToolTipText("You must enter integers.");
                tuField.setText("");
            }
            tuN = (int) tud;
            tnum=tuN*tuna;

            juLabel=new JLabel ("Juice  Price: 1    ",SwingConstants.LEFT);
            juField = new JTextField(10);
            juAmount = new JLabel(juLabel+"Amount:  "+juField);

            try{
                jud = Double.parseDouble(juField.getText());
            }
            catch(NumberFormatException shE){
                juField.setToolTipText("You must enter integers.");
                juField.setText("");
            }

            juN = (int) jud;
            jnum=juN*juice;

            // Order and cancel buttons
        buttonPanel = new JPanel();
        confirmButton = new JButton("Confirm");
        buttonPanel.add(confirmButton);

        cancelButton = new JButton("Cancel order");
                buttonPanel.add(cancelButton);

            mainFrm=new SuperMarket();

            confirmButton.addActionListener(this);
            cancelButton.addActionListener(this);
           add(shLabel);
            add(shAmount);
            add(tuLabel);
            add(tuAmount);
            add(brLabel);
            add(brAmount);
            add(juLabel);
        add(juAmount);
            add(buttonPanel);
            setVisible(true);
            pack();
    }

public static void main(String[] args) {

            SuperMarket market=new SuperMarket();
            market.setLayout(new FlowLayout());
            market.setTitle("AHL Supermarket Delivery Service");
            market.setSize(800, 700);
            market.setDefaultCloseOperation(EXIT_ON_CLOSE);
            market.setVisible(true);

    }

        @Override
    public void actionPerformed(ActionEvent buttonEvent) {
        if (buttonEvent.getSource() == confirmButton) {
                    childFrm=new SuperMarket();
            JButton dnBtn=new JButton("Done");
                        childFrm.setLayout(new FlowLayout());
                        childFrm.setSize(200, 200);
                        JPanel nmPanel = new JPanel();
                        nmPanel.add(new JLabel("Name:  "));
                        nmField = new JTextField(10);
                        nmPanel.add(nmField);
                        childFrm.add(nmPanel);
                        childFrm.add(dnBtn);
                        dnBtn.addActionListener(this);
                        childFrm.setVisible(true);
        }

        clearForm();
    }

    /**
     * Clear all entries in the order form.
     */
    private void clearForm() {
        shField.setText("");
        tuField.setText("");
        juField.setText("");
    }

}

I still haven't added the output nor the total and discount but I will deal with that when my current problem is fixed.
If anyone could help me I would appreciate it very much because I got completely frustrated.
( you could tell from the amount of unnecessary variables :[ )

A: You're creating a new instance of the same class in the constructor.
mainFrm=new SuperMarket();

This means you will be calling the constructor again, which will create a new instance, which will call the constructor again, and so on until you run out of "memory" (stack space in this case, hence the StackOverflowError).


text:
Q: Batch of multidimensional arrays multiplied by a batch of scalers (without loops) I have a batch, two data, of multidimensional arrays (3,3,2) as following:
batch= np.asarray([

              [
               [[1,2,3],
               [3,1,1,],
               [4,9,0,]],

               [[2,2,2],
               [5,6,7],
               [3,3,3]]
              ],

              [
               [[2,2,2],
               [5,6,7],
               [3,3,3]],

               [[1,2,3],
               [3,1,1],
               [4,9,0]]
              ]
                  ])

correspondingly I have batch, two data, of (1,1,2) as follows
scalers = np.asarray([

                [
                 [[1]],
                 [[2]]

                ],

                [
                 [[0]],
                 [[3]]
                ]

                    ])

each dimension in the batch should be multiplied by its corresponding scaler in the scalers array. For example:
# the first dimension

               [[1,2,3],
         1 *   [3,1,1,],
               [4,9,0,]]

# the second dimension

         2 *   [[2,2,2],
               [5,6,7],
               [3,3,3]]

             .
             .
             .

# the last dimension

          3*   [[1,2,3],
               [3,1,1],
               [4,9,0]]

So , the expected output should be like the following:
           [
              [
               [[1 2 3],
               [3 1 1 ],
               [4 9 0 ]],

               [[4 4 4],
               [10 12 14],
               [6 6 6]]
              ],

              [
               [[0 0 0],
               [0 0 0],
               [0 0 0]],

               [[3 6 9],
               [9 3 3],
               [12 27 0]]
              ]
           ]

I was trying to do the following to avoid any loops
batch * scalers

but it seems it is not correct, I wonder how to do the behavior above


text:
Q: Need to fetch count of objects created from a class in AutoCAD Civil3D It's very specific to AutoCAD SDK, developing an add-in for AutoCAD. I have loaded some DWG files in to a drawing and created some objects of the classes loaded. When these objects are created I add an Xdata containing some information on BlockTableRecord. Now, I need to remove BlockTableRecords for the objects that have been deleted from the drawing. I am getting a call back from AutoCAD when document is saved. In this call back, I am trying to traverse through all Block Table Records to find the records with our information. And the records that contain information that they were created using my add-in, I am trying to see the number of objects created from this record item. If there exists none, I will delete the block table record or at least update our footprint.
Here I am unable to get the count of objects created from one specific table record. Here's what I have done so far.
private static void CommandExecutionCallBack(object sender, CommandEventArgs e)
{
    string commando = e.GlobalCommandName.ToLower();
    if (commando.Contains("save"))
    {
        Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
        var documentManager = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager;
        Editor ed = doc.Editor;
        Database db = doc.Database;
        Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
        using (Transaction myT = tm.StartTransaction())
        {
            BlockTable bt = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead, false);
            SymbolTableEnumerator enumerator = bt.GetEnumerator();
            while (enumerator.MoveNext())
            {
                BlockTableRecord btr = tm.GetObject(enumerator.Current, OpenMode.ForRead, false) as BlockTableRecord;
                ResultBuffer xdata = btr.GetXDataForApplication(REGAPP_NAME);
                if (null != xdata)
                {

                    //Here I am trying to fetch the objects that exist against the selected btr.
                    AcadApplication acApp = Autodesk.AutoCAD.ApplicationServices.Application.AcadApplication as AcadApplication;
                    AcadDocument thisDrawing = acApp.ActiveDocument;

                    thisDrawing.SendCommand("(command MAPSELECTCLASSIFIED " + btr.Name + ")" + Environment.NewLine);
                    AcadSelectionSet selectionSet = thisDrawing.PickfirstSelectionSet;

                    //I am always getting selectionSet.Count as zero.
                    MessageBox.Show(btr.Name + " -> SelectionSet Count: " + selectionSet.Count.ToString());
                }
                else
                {
                    //Will ignore this condition. The current btr is not created by our add-in
                }
            }
        }
    }
}

Any help in this regard would be appreciated.
I have taken some help from AutoCAD forum, https://forums.autodesk.com/t5/net/how-to-find-and-export-object-classess-from-drawing/m-p/5814774#M45948
Regards,
Umar

A: Delating unreferenced BlockTableRecord (or any other SymbolTableRecord) is commonly called: Purge.
The Database class provide a Purge() method which can be used to get the "purgeable" objects.
    private static ObjectIdCollection GetPurgeableBlocks(Database db)
    {
        var ids = new ObjectIdCollection();
        using (var tr = new OpenCloseTransaction())
        {
            var bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
            foreach (ObjectId id in bt)
            {
                var btr = (BlockTableRecord)tr.GetObject(id, OpenMode.ForRead);
                if (btr.GetXDataForApplication(REGAPP_NAME) != null)
                {
                    ids.Add(id);
                }
            }
            tr.Commit();
        }
        db.Purge(ids);
        return ids;
    }


text:
Q: GeForce 650 Video Card for dual monitors with HDMI splitter I am trying to connect both of my TVs with my computer. I bought an HDMI splitter, and I am connecting the hdmi cable from my GeForce 650 to the input of the splitter, and connecting both hdmi output cables to my TVs. However, the computer is recognizing both TVs as one :(. I am extending the monitors and trying to change the resolution, but nothing seems to work. Any ideas will greatly help.
Thank you

A: Yeah the splitter just copies the original signal, there is no way for the card to know you have two monitors.
But that card has one or two DVI sockets so you just have to buy a dvi to hdmi connector (super cheap) and you are good to go.


text:
Q: Java Compile Time Error: reached end of file while parsing public class Test{
    public static void main(String[] arg){
        System.out.println("Alexander The Great");
    }
}

In this code, if I remove the first quotation mark in the string, I get 3 errors.
1. ')' expected
2. unclosed string literal
3. not a statement
ok, I understood above errors.
If I remove the second quotation mark in the string, I also get 3 errors.
1. unclosed string literal
2. ';' expected
3. reached end of file while parsing
I understood 1 and 2, but why 3??
Doesn't it usually occur when braces are missing? But clearly, I have correct number of braces.
Also, why not the first case give the error "reached end of file while parsing"?
P.S. I'm using jGrasp, java 1.6.

A: Leaving off the first quote potentially gives the parser a bit more to work with, because it will try to treat "Alexander" as a reference. Once it hits the space, the only legal stuff is the rest of an expression, but instead it thinks it's another identifier.
It may be inserting a bonus ) to try to recover; depends on the implementation.
Leaving off the last quote will send the parser to the end of the line. Instead of trying to close off that statement, it gets a little lost and spins off and can't recover and hits the end of the file.
Off the top of my head, to me it seems that since Java strings are single-line only, it could do much the same thing and try to close off the string and/or statement in that case and recover a bit more gracefully. I might just be missing something obvious, though.

A: Because EOF was encountered while searching for a quote mark. I'm not sure whether the exact error messages to be emitted for bad code are specified or not.

A: use                public static void main(String arg[])
in place of        public static void main(String[] arg)


text:
Q: postgis and geodjango *and* in filter I have a filter, that is working but I want to add more brains to it by looking for anything that is +- 12 days
So I came up with this:
last_date = firstPointCheck.acquisition_date - timedelta(days=12)
next_date = firstPointCheck.acquisition_date + timedelta(days=12)

object_list2 = object_list.filter(center__distance_lte=(firstPointCheck.center, D(m=deltaCenter)), acquisition_date__lte=firstPointCheck.acquisition_date, acquisition_date__gte=last_date)

I am not sure how to and the dates so I can find everything greater than and equal to last date and less than or equal next date?
Now

A: You can check if date of your object is in specified range using Django's range lookup. It will look like this:
last_date = firstPointCheck.acquisition_date - timedelta(days=12)
next_date = firstPointCheck.acquisition_date + timedelta(days=12)

object_list2 = object_list.filter(center__distance_lte=(firstPointCheck.center, D(m=deltaCenter)), acquisition_date__range=[last_date, next_date])

range lookup in django is inclusive, that means range will include start and end value. It is equivalent to:
last_date = firstPointCheck.acquisition_date - timedelta(days=12)
next_date = firstPointCheck.acquisition_date + timedelta(days=12)

object_list2 = object_list.filter(center__distance_lte=(firstPointCheck.center, D(m=deltaCenter)), acquisition_date__lte=next_date, acquisition_date__gte=last_date)


text:
Q: sshd_config all disabled - default setup ?- Ubuntu/Apache Had a look at my sshd_config while setting up public/private keys (new server) and noticed that almost everything is disabled (#)
Is that the default setup for this file ?
Just wondering because I gave sudo access to a fiverr guy yesterday
Thanks for the help
# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

Include /etc/ssh/sshd_config.d/*.conf

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
#HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none
# Logging
#SyslogFacility AUTH
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
#PermitRootLogin prohibit-password
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#PubkeyAuthentication yes

# Expect .ssh/authorized_keys2 to be disregarded by default in future.
#AuthorizedKeysFile     .ssh/authorized_keys .ssh/authorized_keys2

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
PasswordAuthentication yes
#PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

# Set this to 'yes' to enable PAM authentication, account processing,

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
PrintMotd no
#PrintLastLog yes
#TCPKeepAlive yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

# override default of no subsystems
Subsystem sftp  /usr/lib/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       PermitTTY no
#       ForceCommand cvs server

A: The commented out entries don't show disabled configuration, but by convention for documentation purposes show default options.
So for example, if there's the entry:

#PermitTunnel no

That means by default on this system when there's no PermitTunnel option defined anywhere, sshd will behave as if -o PermitTunnel=no had been given.

#PermitTTY yes

tells sshd will behave by default as if -o PermitTTY=yes had been given.
or even this:

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

means it behaves by default as if -o Port=22 -o AddressFamily=any -o ListenAddress=0.0.0.0 -o ListenAddress=:: options had been provided.
Of course, it's possible that the commented-out configuration won't match the reality, but as they are built and packaged together, they're expected to match.
The default shipped uncommented entries might reflect a configuration different from default sshd (or possibly from upstream), or might not and would just enforce or underscore an important configuration.
This information is available in upstream openssh-portable source for  sshd_config:

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.


text:
Q: why does "F" only not work in `qbinom(p=0.025,size=25, prob=0.5, lower.tail = F) `? I am running this in R:
qbinom(p=0.025,size=25, prob=0.5, lower.tail = F)
It gives me 8
Actually, what I need is really this:
qbinom(.025, 25, .5, lower.tail = FALSE)
why does "F" only does not work here?

A: F is a variable name.  Initially it is set to the value FALSE, but it can be changed.
For example:
F <- FALSE
qbinom(.025, 25, .5, lower.tail = F)
#> [1] 17
F <- TRUE
qbinom(.025, 25, .5, lower.tail = F)
#> [1] 8
FALSE <- TRUE
#> Error in FALSE <- TRUE: invalid (do_set) left-hand side to assignment

Created on 2021-10-09 by the reprex package (v2.0.0)
You should avoid using F to mean FALSE.  The savings from less typing are much less than the time wasted when its value changes.  You can't change the value of FALSE.


text:
Q: Doob's Optional Sample Theorem the version of Doobs Optional sampling theorem that I Have is as follows:
Let $\sigma, \tau$ be bounded stopping times with $\sigma \leq \tau.$
Then we have
(i) If $(X_{t})$ is a martingale, then
\begin{align*}
\mathbb{E}[X_{\tau} \mid F_{\sigma}] = X_{\sigma} \quad \text{and thus} \quad \mathbb{E}[X_{\tau}] = X_{0}
\end{align*}
(ii)If $(X_{t})$ is a sub-martingale (super-martingale), then
\begin{align*}
\mathbb{E}[X_{\tau} \mid F_{\sigma}] \geq X_{\sigma} \quad (\mathbb{E}[X_{\tau} \mid F_{\sigma}] \leq X_{\sigma})
\end{align*}
My question is now: Why is it not if and only if? Because every konstant is a stopping time and therefore I could easily get the conditions for a martingale.


text: Q: Two Stage Signup Form using Divi Theme I want to create a two stage signup Form  using Divi Theme, on page 1 the user enters only their email-id and is taken to second page upon click a button, on this page the user completes the profile info and submits the page. How can this be achieved? Somebody plese help.


text:
Q: Compiler optimization with infinite loop I have the following snippet of code:
foo();
std::cout << "Foo";
loop();

Where loop is a function that does not terminate because it runs into some infinite loop (not intentional). However, it seems like my program is running into the infinte loop without printing the output ("Foo"). Is the compiler allowed to change the behavior of the code in this way?
Neither foo() nor loop() interfere with standard output.
Unfortunately, I cannot give more specific information about the setup. So I just want do know whether there needs to be a bug (in code or compiler) before the call of loop() or if the compiler is allowed to assume that later code is bugfree?
Edit: The reason for this behavior is probably a missing std::flush. The original question is therefore not that interesting for me anymore (but it probably is still a question one can ask).


text:
Q: Индексатор на typescript В моем классе есть индексатор this[key] = value ну как в словаре. Как сделать геттер и сеттер на индексатор, чтоб на пример key перед тем как получить значение по ключу, перевести в json?

A: Используйте Proxy:

let _data = {
  key: {value: 42}
}, data = new Proxy(_data, {
  get(target, key){
    if(key in target)
      return JSON.stringify(target[key]);
    else
      return null;
  }
});

console.info(data.key); // {"value":42}


text:
Q: Changing bootstrapped sample variables w/o regenerating bootstrap I am using a bootstrapped dataset to fit a model. After fitting the model, I would like to change the bootstrapped dataset and use this new dataset to predict.
My problem is that I can't change the bootstrapped dataset. It often tells me that the variable that I am trying to change cannot be found. Other times (as in the case below) it won't let me calculate the mean by bootstrapped sample.
Why is this?
library(tidymodels)
library(broom)

year <- rep(2014:2016, length.out=10000)
group <- factor(sample(c(0,1,2,3,4,5,6), replace=TRUE, size=10000))
female <- sample(c(0,1), replace=TRUE, size=10000)
smoker <- sample(c(0,1), replace=TRUE, size=10000)
dta <- tibble(year = year, group = group, female = female, smoker = smoker)

boot <- bootstraps(dta,
                   times = 2,
                   apparent = TRUE,
                   replace = TRUE)

mods <- boot %>%
  nest(data = c(-all_of(female))) %>%
  mutate(model = map(data, ~ glm(smoker ~ group, data = .,
                                 family = binomial(link = "probit"))))
new_boot <- boot %>%
  group_by(id) %>%  # calculate the mean by bootstrapped sample
  mutate(female=mean(female),
         smoker=mean(smoker))

new_boot # female and smoker are calculated for entire dataset

splits                id         female smoker
  <list>                <chr>       <dbl>  <dbl>
1 <split [10000/3578]>  Bootstrap1  0.492  0.502
2 <split [10000/3681]>  Bootstrap2  0.492  0.502
3 <split [10000/10000]> Apparent    0.492  0.502

Why is this? How can I change the bootstrapped sample?


text:
Q: Definition of relative Cartier divisors I'm a bit confused about the definition of relative Cartier divisors which I found in Hida's book "Geometric Modular Forms". In Chapter $2$, section $2.1$, he says that, given a locally Noetherian Scheme $S$ and a proper flat reduced curve $C$ over $S$, a relative Cartier divisor is a closed subscheme $D\subseteq X$ such that $D$ is flat over $S$ and the ideal sheaf of $D$, say $I(D)$ is invertible over $C$. Then, at the end of the section he gives the following, apparently trivial, example. He considers $D_N=\text{Spec}(\mathbb{Z}/N\mathbb{Z})\subseteq\text{Spec}(\mathbb{Z})$ where $N>1$ is an integer, and he says it is a Cartier divisor. I assume he uses $\text{Spec}(\mathbb{Z})$ both as the basis $S$ and as the curve $C$. By the way, since $\mathbb{Z}$ is a PID, flatness coincides with torsion freenes, and clearly $\mathbb{Z}/N\mathbb{Z}$ is not torsion free as a $\mathbb{Z}$-module, since $N$ is nonzero in $\mathbb{Z}$ and it annihilates every element in $\mathbb{Z}/N\mathbb{Z}$. Am I misunderstanding something? What is the mistake in all this picture? Thank you very much for any suggestion!

A: Yes, $\DeclareMathOperator{\Spec}{Spec}\newcommand{\Z}{\mathbb{Z}}\Spec(\Z/N\Z)\hookrightarrow\Spec(\Z)$ is not a relative effective Cartier divisor over $\Spec(\Z)$ because it is not flat over $\Spec(\Z)$. Here's another way to see this. Relative effective divisors are stable under base change by [Tag 056P]. Hence, given a relative effective Cartier divisor $D\to S$, each fiber $D_s$ has to be a relative effective Cartier divisor over $\Spec(\kappa(s))$. This is not the case here.
However, $\Spec(\Z/N\Z)$ is still an effective Cartier divisor on $\Spec(\Z)$ in the absolute sense. This just means that it is a closed subscheme of $\Spec(\Z)$ whose ideal sheaf is invertible. See [Tag 01WQ] for more information. This is most likely what the author meant.


text:
Q: htaccess stop processing if given directory I have an instalation on my htdocs folder that needs rewriterules to be processed like this:
RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} ^$

RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteCond %{REQUEST_URI} !^/admin?
RewriteCond %{REQUEST_URI} !^/payment?
RewriteRule ^(.*)$ %1/$1 [QSA]

RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^admin/(.*)?$ BACKEND-PHP/$1?domain=%1 [QSA]

RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^payment/(.*)?$ PAYPAL-API/$1?domain=%1 [QSA]

But now, to test joomla i need add some rule in the htaccess file that stop processing rules if the given directory is "localhost/joomla" in order to joomla work properly.
in pseudocode will be like this:
RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} ^$

**RewriteCond %{HTTP_HOST} ^(localhost)$
**RewriteRule ^/joomla$ [END]

# (if the requested file is at joomla directory
# htaccess will stop processing)

RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteCond %{REQUEST_URI} !^/admin?
RewriteCond %{REQUEST_URI} !^/payment?
RewriteRule ^(.*)$ %1/$1 [QSA]

RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^admin/(.*)?$ BACKEND-PHP/$1?domain=%1 [QSA]

RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^payment/(.*)?$ PAYPAL-API/$1?domain=%1 [QSA]

A: You were close. Just modify your rules to
RewriteCond %{HTTP_HOST} ^localhost$ [NC]
RewriteRule ^joomla(/.*)?$ - [END]

The - says we do no processing on this URL. The [End] flag prevents all the rules below from firing.

A: You can use this in the subdirectory:
RewriteEngine off


text:
Q: Rxjava: observeOn affects observer's disposal logic I have the following example:
private var dis: Disposable? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_login)
    val btn = findViewById<Button>(R.id.btn)
    val btn2 = findViewById<Button>(R.id.btn2)

    btn.setOnClickListener {
        dis = Single.fromCallable {
            Thread.sleep(1000)
            15
        }
        .subscribeOn(Schedulers.io())
        //.observeOn(AndroidSchedulers.mainThread())
        .subscribe({ v ->
            log("Success: $v")
        }, { e ->
            log("Error: $e")
        })
    }

    btn2.setOnClickListener {
        dis?.dispose()
    }
}

fun log(msg: String) {
    Log.d("TAGG", msg + " on " + Thread.currentThread().name);
}

When ".observeOn(..)" line is COMMENTED and I:

*

*press btn

*press btn2 immediately after pressing btn

Then observer's onError block of code WILL be called.
When ".observeOn(..)" line UNCOMMENTED and I:

*

*press btn

*press btn2 immediately after pressing btn

Then observer's onError block of code WILL NOT be called.
I just can not understand such behaviour. In my understanding this line of code shouldn't affect logic of whether onError will be called or not.
Why does this happen? Is this documented behaviour? Please, give me some explanation or redirects.
Thank you!

A: By using a unit test, I do not reproduce your issue. With or without observeOn, I observe an UndeliverableException thrown to RxJavaPlugins and the doOnDispose called.
What do you see?
@Test
  public void testObserveOnEffect() throws Exception {
    Disposable dis = Single.fromCallable(() -> {
      Thread.sleep(1000);
      return 15;
    })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .doOnDispose(() -> logThread("dispose"))
        .subscribe(v -> logThread(v), e -> logThread(e));

    Single.timer(50, TimeUnit.MILLISECONDS).subscribe(o -> dis.dispose());
    Thread.sleep(2000);
  }

A: If you have observeOn line and disposable is disposed the RxJava will interrupt flow before trying to deliver result to the subscriber.
Here is the issue link https://github.com/ReactiveX/RxJava/issues/4673


text:
Q: HTML Rendering with TCPDF(PHP) I am using TCPDF's writeHtml function for a page that renders properly in the browser.
In the output PDF, the fonts are too small. I've tried with setFont, but it doesn't seem to have an effect. Does anyone have experience with this?
I'd like to add here that the HTML is not always in my control, so I would prefer to do this with TCPDF options(and not by modifying the source html)
UPDATE: I am able to change the font size by setting it on the body. The only remaining problem is that, to render correctly in the browser, it needs to be 12px. To render correctly in the PDF, it needs be something like 30px. Do I set the media on the css? What is the media type for TCPDF?

A: Are you using tags? tcpdf's HTML engine gives the tag precedence over any CSS, or other size-adjusting tags. If you remove any extraneous tags from the HTML and use straight CSS, things should render as expected. Or, if you aren't using CSS, you should. Just because a browser displays it correctly doesn't mean it will look the same on other formats. The browser has likely performed some magic of its own to fill in the gaps in your CSS specifications.

UPDATE
Here's an example of specifying CSS declarations with your HTML when using tcpdf. Note how all the styling is applied using the CSS declarations inside the

Example of HTML + CSS

Example of 12pt styled paragraph.

EOF;

$pdf->writeHTML($html, true, false, true, false, '');

?>

A: The best solution that worked for me was to replace 'px' to 'pt' in html code:
$tidy = str_replace ('px', 'pt', $tidy);

Before on the left side and after replacing on the right:

A: TCPDF recognizes basic CSS such as font-size, font-color, and font-family.
For a little more information, check out TCPDF not render all CSS properties


text:
Q: The data couldn't be read because it isn't in the correct format. in IOS using swift 2 I'm developing an ios app, however when I try to get a server response by using this:
 if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary

I get an error from the server that says:

The data couldn't be read because it's in an incorrect format.

Because my server has the problematic line of code:
{"tripReport":[{"duration":-,"distance":0.0,"reportText1":" " ,"reportText2":"-" ,"totalDistance":0.0,"message1":" ","message2":" ","dateTime2":" ","dateTime1":" "}],"size":0}

I want to get the server response before this line instead, like:{"movementReport":[{"message":"7.88 KM SE of Police Line Constibilary, Faisalabad - Jaranwala Road, FAISALABAD, PUNJAB, PK","reportText":"POSITION","speed":53.0,"dateTime":"2016-Jan-20 11:36 AM","route":null,"longitude":73.270053,"latitude":31.37281}
by using split func or any thing else.. can i brake my response into two strings?


text:
Q: array of object in C++ in sfml I am trying to use vectors in sfml C++ and I am semi-failing because I am not able to create a vector consisting of 4 RectangleShapes :(
I am skipping some lines of the code which are not causing the problem
This is the code which is working but it is least optimized in my opinion
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <vector>
#include <iostream>
#include "mainCharacter.h" // it consists the mainCharacter class

class classBackground{
public:
    sf::Texture texture;
    sf::Sprite image;
    sf::RectangleShape rectTopBorder,rectBotBorder,rectLeftBorder,rectRightBorder;
    std::vector<sf::RectangleShape> rect;
    classBackground(){
        texture.loadFromFile("wagon.png");
        image.setTexture(texture);
        image.setPosition(300,250);
        rectTopBorder.setSize(sf::Vector2f(230,5));
        rectTopBorder.setPosition(image.getPosition());
        rectTopBorder.move(0,60);
        rectBotBorder.setSize(sf::Vector2f(230,5));
        rectBotBorder.setPosition(image.getPosition());
        rectBotBorder.move(0,225);
        rectLeftBorder.setSize(sf::Vector2f(5,170));
        rectLeftBorder.setPosition(image.getPosition());
        rectLeftBorder.move(0,60);
        rectRightBorder.setSize(sf::Vector2f(5,170));
        rectRightBorder.setPosition(image.getPosition());
        rectRightBorder.move(225,60);
        rect.push_back(rectTopBorder);
        rect.push_back(rectBotBorder);
        rect.push_back(rectLeftBorder);
        rect.push_back(rectRightBorder);
    }
};

//in the main function
classMainCharacter mainCharacter; ///another class which has collision detection
classBackground background;
///in the loop
    for(int i = 0; i<=3; i++){
        mainCharacter.collision(background.rect[i]); ///colision is a function in the mainCharacter class (detects collision)
    }

And this is the code which I want to work but my game is crushing :(
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <vector>
#include <iostream>
#include "mainCharacter.h" // it consists the mainCharacter class

class classBackground{
public:
    sf::Texture texture;
    sf::Sprite image;
    std::vector<sf::RectangleShape> rect; // it doesn't work if I write rect(4) or rect = {rect1,rect2,rect3,rect3} or even rect(4)={rect1,....}
    classBackground(){
        texture.loadFromFile("wagon.png");
        image.setTexture(texture);
        image.setPosition(300,250);
        rect[0].setSize(sf::Vector2f(230,5));
        rect[0].setPosition(image.getPosition());
        rect[0].move(0,60);
        rect[1].setSize(sf::Vector2f(230,5));
        rect[1].setPosition(image.getPosition());
        rect[1].move(0,225);
        rect[2].setSize(sf::Vector2f(5,170));
        rect[2].setPosition(image.getPosition());
        rect[2].move(0,60);
        rect[3].setSize(sf::Vector2f(5,170));
        rect[3].setPosition(image.getPosition());
        rect[3].move(225,60);
    }
};

//in the main function
classMainCharacter mainCharacter; ///another class which has collision detection
classBackground background;
///in the loop
    for(int i = 0; i<=3; i++){
        mainCharacter.collision(background.rect[i]); ///colision is a function in the mainCharacter class (detects collision)
    }

what am I doing wrong? :(
I tried to defined the rects before vector and then inserting into the vector but it also doesn't work (in such way vector<...> rect = {......}).

A: Well even if I would not expect to much difference between the two versions, an answer is worth telling anyway as your problem has neither to do with performance nor with sfml at all but is more general.
What you try is to instantiate a class member at its declaration, what is not possible. But what you can do is either one of the following methods:
1) Use the default member initializer with the C++ 11 unified initialization syntax like so (wich may only be syntactic sugar for (2) prior to this: http://en.cppreference.com/w/cpp/language/data_members#Member_initialization):
std::vector<sf::RectangleShape> rect{4}

2) Use the initializer list in the constructor:
classBackground() : rect(4) {...}

3) Or call the resize method in the constructor:
classBackground(){
    rect.resize(4);
    ...
}

The last one might be the worst as it first calls the standard constructor of vector<...> and changes it afterwards.

A: In the first version, you were successfully creating a vector of 4 elements by using push_back.
In the second version, you never allocate space for your 4 elements, so when you try and assign values to the elements of the vector, that's your crash.
If you really don't want to use push_back you can instead use resize to set the size of the vector.
Here's a simplified version of what you're trying to do
#include <vector>

class classBackground {
    std::vector<int> rect;
public:
    classBackground() {
        rect.resize(4);
        rect[0] = 1;
        rect[1] = 2;
        rect[2] = 3;
        rect[3] = 4;
    }
};

int main() {
    classBackground cb;
    // there, it worked.
}

Demo: http://ideone.com/YYq0oA
Alternatively if you have C++11 and your vector is always going to be 4 elements large, which in this case it seems like it might be, you should consider using std::array instead.
#include <array>

class classBackground {
    std::array<int, 4> rect;
public:
    classBackground() {
        rect[0] = 1;
        rect[1] = 2;
        rect[2] = 3;
        rect[3] = 4;
    }
};

int main() {
    classBackground cb;
    // there, it worked.
}

Array works like vector in most ways, you just can't change the size, but it can potentially be more efficient.


text:
Q: javascript callback functions, variable mapping I've always used callback functions in javascript, but I've never understood how the callback knows what variables it can take in.
Let's take the following example code;
var friends = ["Mike", "Stacy", "Andy", "Rick"];

friends.forEach(function (name, index){
    console.log(index + 1 + ". " + name);
});

This logically outputs;
1. Mike
2. Stacy
3. Andy
4. Rick

In fact, all of the following will output the same;
friends.forEach(function (index, name){
    console.log(name + 1 + ". " + index);
});

friends.forEach(function (foo, bar){
    console.log(bar + 1 + ". " + foo);
});

friends.forEach(function (x, y){
    console.log(y + 1 + ". " + x);
});

How does the callback function within forEach know how to interpret name and index? In other words; how does the callback know that the array has values and indexes? It is clear that the name you give to the input variables of the callback function aren't important but the order is, so how are things mapped?
From here I would also like to apply this knowledge to other objects in general, not just lists. So how are variables mapped from the object into the callback functions? Is this something that is defined beforehand in the object?

A: In browsers that support Array.prototype.forEach natively it may be implemented differently, but in general you'd use Function.prototype.call to execute the callback function provided with arguments in the correct order (whatever that may be) whilst iterating through your collection.
The MDN entry for forEach has the following code for implementing it for arrays in browsers that don't support it:
if (!Array.prototype.forEach) {
    Array.prototype.forEach = function (fn, scope) {
        'use strict';
        var i, len;
        for (i = 0, len = this.length; i < len; ++i) {
            if (i in this) {
                fn.call(scope, this[i], i, this);
            }
        }
    };
}

In other words; how does the callback know that the array has values and indexes? It is clear that the name you give to the input variables of the callback function aren't important but the order is, so how are things mapped?

To elaborate, the callback function is just a function like any other, with parameters that can be arbitrarily named (a and b works just as well as index and value); before it's executed it doesn't know anything about the array. The array that you're calling forEach on knows that it has indexes, and that those indexes have values, and it also expects the callback function to accept arguments in a specific order. Things aren't exactly mapped between the array and the callback function, the forEach function just passes each index and its corresponding value to the callback function in turn.

A: The function expects three arguments. It doesn't matter what they are called. It will pass the correct values into the function for you.

forEach executes the provided callback once for each element of the array with an assigned value. It is not invoked for indexes which have been deleted or which have been initialized to undefined.
callback is invoked with three arguments:

*

*the element value

*the element index

*the array being traversed

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

A: For easier understanding for that particular method, let's have a look at Array.prototype.forEach compatibility code:
if (!Array.prototype.forEach) {
    Array.prototype.forEach = function (fn, scope) {
        'use strict';
        var i, len;
        for (i = 0, len = this.length; i < len; ++i) {
            if (i in this) {
                fn.call(scope, this[i], i, this);
            }
        }
    };
}

Take a closer look at fn.call: this line invokes the passed callback function, passing the context (scope), and the arguments (this[i] - current element, i - the index, this - the entire array).
For more information about how to invoke functions different from someFunction(arguments) have a look at this links:
1.Function.prototype.bind
2.Function.prototype.call
3.Function.prototype.apply