text:
Q: Error of the Numerov Method The Numerov method is an iterative algorithm for solving second order differential equations. A full derivation is here on the Wikipedia page: https://en.wikipedia.org/wiki/Numerov's_method. I am interested in the derivation of the error bound of this algorithm (which is supposedly $O(n^4)$). I understand how in the derivation on this Wikipedia page that we achieve error of $O(n^5)$, but then it concludes that "It follows that the order of convergence (assuming stability) is 4." Could someone explain how we went from an error of order 5 to error of order 4?
I am interested for the following reason. Suppose we have two values for the numerov method N(n) and N(2n) for step size $n$. Then I desire to determine constants $\alpha$ and $\beta$ such that
$$\alpha N(2n) + \beta N(n)$$
reduces the overall error of the result. Any help and advice would bemuch appreciated!


text:
Q: Simplifying Stacked Exponents I'm trying to simplify the following:
$$10^{24}(.1^{10^9})$$
I think this can be rewritten as:
$$10^{24}((10^{-1})^{10^9})$$
If memory serves (though algebra was 30 years ago) if we have stacked exponents (for example ${10^3}^{^5}$), I can simplify by multiplying the exponents (for example, ${10^3}^{^5}$ = $10^{15}$).
But this is $10^{-1}$, raised to $10^9$.  Am I on the right track here, rewriting as follows:
$$10^{24}((10^{-1})^{10^9})$$
$$10^{24}((10^{-1})^{1,000,000,000})$$
$$10^{24}(10^{-1,000,000,000})$$
and then after we multiply 24 times -1,000,000,000 we get
$$10^{-24,000,000,000}$$

A: Your last step is incorrect, when you have $10^x10^y$, you add the exponents, so you get
$$
10^{24 - 1,000,000,000} = 10^{-999,999,976}
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP/PCRE regex starts with on recursive pattern I'm trying to match markdown tags with recursive.
Input Syntax
(TYPE: VALUE ATTR_KEY: ATTR_VALUE)

Note that syntax should be starts with: [a-z0-9_-]+:
Sample Inputs:
(image: sky.jpg)
(image: sky.jpg caption: Sky (Issue This) View)
(link: https://stackoverflow.com text: Stack Overflow)
(link: https://stackoverflow.com text: Stack Overflow rel=nofollow)
(video: http://www.youtube.com/watch?v=49Kh1mS4Fhs)

Currently using following regex:
(?=[^\]])\([a-z0-9_-]+:.*?\)

But issue coming from here, because match with:
(image: sky.jpg caption: Sky (Issue This)

Expected match:
(image: sky.jpg caption: Sky (Issue This) View)

If parentheses are used again in parentheses, it does not match exactly.
I tried following recursive patterns and works but i need to restrict starts with characters.
(?s)\((?:[^()]+|(?R))*+\)
\((?:[^)(]+|(?R))*+\)

A: You should use a positive lookahead to match sure the match starts with that pattern, but you will have to wrap the whole parentheses matching pattern within another capturing group and use a (?1) subroutine instead of (?R) to only recurse that pattern, not the whole regex:
(?=\([a-z0-9_-]+:)(\((?:[^()]+|(?1))*+\))
^^^^^^^^^^^^^^^^^^^            ^^^^     ^

See the regex demo.
Details

*

*(?=\([a-z0-9_-]+:) - a positive lookahead that requires (, 1+ lowercase ASCII letters, digits, underscores or hyphens followed with : immediately to the right of the current location

*(\((?:[^()]+|(?1))*+\)) - Capturing group 1 (it will be recursed later):

*

*\( - (

*(?:[^()]+|(?1))*+ - 1+ repetitions of 1+ any chars other than ( and ) or the whole Group 1 pattern (recursed)

*\) - )
In case you want to also support smileys, you may add their specific patterns in the alternation group where the regex subroutine resides, as the first alternative:
(?=\([a-z0-9_-]+:)(\((?::[)(]|[^()]|(?1))*+\))
                        ^^^^^

I add :[)(] that matches :) or :( and removed + from after [^()] so as to be able to check the string inside nested parentheses character by character.
Feel free to adjust it to your needs, or add more smiley patterns.
See this regex demo with the (?=\([a-z0-9_-]+:)(\((?::(?:[()pPDd*oO]|'\()|<3|;\)|[^()]|(?1))*+\)) regex.


text:
Q: How to convert [list] BBCode to HTML via JavaScript? I'm writing BBCode to HTML praser via JavaScript. I successed with [b], [i], [img], ... tags, but with [list] tag, I dont know how to do, because it's element maybe 2, 3, n,... Can you help me convert from:
[list]
item 1
item 2
item 3
[/list]

to

item 1

item 2

item 3

Thank you very much.

A: If you are using that horrid combination of indexOf, split and substring @Dai is talking about, something similar to the following will do it.
var start = this.value.indexOf("[list]"),
    ending = this.value.indexOf("[/list]"),
    lines = this.value.substring(start + 7, ending - 1).split("\n");

//perform loop on `lines`:
//    "
" + lines[i] + "
"

Essentially, this will get the start position of [list] and [/list] and then get the lines in between. You'll notice that in the substring(), I say start+7 and ending-1. This can be explained by the fact that the start position of your actual lines will be at the index of [list] + the actual length of the string [list] + the enter character. The end subtracts one to remove that enter character. A better way to do this would be to simply add six to start instead of seven, subtract zero and then just get rid of any empty array values, however, either way is fine depending on the exact syntax you're requiring for your users.
Keep in mind that the lines variable will hold all of the lines entered between the two list bbcodes meaning you have to loop through them and then wrap them with

 tags. Also, I suggest validating multiple things such as making sure that start > ending and performing this multiple times so you know every occurrence of [list] instead of just the first.


text:
Q: WIX Sideloading fails to deploy dependencies appx I am deploying an appx package using WIX following this tutorial:
http://nicholasarmstrong.com/2014/08/sideloading-windows-8-apps-with-wix/
When I run the resulting setup on a freshly installed Windows 10 PC, the logs provide me with the following error:
    CAQuietExec:  Found dependency package(s):
MSI (s) (94!10) [18:07:10:376]: Closing MSIHANDLE (78) of type 790531 for thread 2832
MSI (s) (94!10) [18:07:10:423]: Creating MSIHANDLE (79) of type 790531 for thread 2832
CAQuietExec:  C:\Program Files (x86)\SoftwareSetup\Software_Test\Dependencies\x86\Microsoft.NET.CoreRuntime.1.0.appx
MSI (s) (94!10) [18:07:10:423]: Closing MSIHANDLE (79) of type 790531 for thread 2832
MSI (s) (94!10) [18:07:10:423]: Creating MSIHANDLE (80) of type 790531 for thread 2832
CAQuietExec:  C:\Program Files (x86)\SoftwareSetup\Software_Test\Dependencies\x86\Microsoft.VCLibs.x86.Debug.14.00.appx
MSI (s) (94!10) [18:07:10:423]: Closing MSIHANDLE (80) of type 790531 for thread 2832
MSI (s) (94!10) [18:07:17:283]: Creating MSIHANDLE (81) of type 790531 for thread 2832
CAQuietExec:  Add-AppxPackage : Deployment failed with HRESULT: 0x80073CF3, Package failed updates, dependency or conflict
MSI (s) (94!10) [18:07:17:298]: Closing MSIHANDLE (81) of type 790531 for thread 2832
MSI (s) (94!10) [18:07:17:298]: Creating MSIHANDLE (82) of type 790531 for thread 2832
CAQuietExec:  validation.
MSI (s) (94!10) [18:07:17:298]: Closing MSIHANDLE (82) of type 790531 for thread 2832
MSI (s) (94!10) [18:07:17:298]: Creating MSIHANDLE (83) of type 790531 for thread 2832
CAQuietExec:
MSI (s) (94!10) [18:07:17:298]: Closing MSIHANDLE (83) of type 790531 for thread 2832
MSI (s) (94!10) [18:07:17:298]: Creating MSIHANDLE (84) of type 790531 for thread 2832
CAQuietExec:  Windows cannot install package Software because this package depends on another package that couldn't be found. This
MSI (s) (94!10) [18:07:17:298]: Closing MSIHANDLE (84) of type 790531 for thread 2832
MSI (s) (94!10) [18:07:17:298]: Creating MSIHANDLE (85) of type 790531 for thread 2832
CAQuietExec:  package requires minimum version 1.0.23430.0 of framework Microsoft.NET.CoreRuntime.1.0 published by CN=Microsoft
MSI (s) (94!10) [18:07:17:298]: Closing MSIHANDLE (85) of type 790531 for thread 2832
MSI (s) (94!10) [18:07:17:298]: Creating MSIHANDLE (86) of type 790531 for thread 2832
CAQuietExec:  Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US to install; the frameworks with name
MSI (s) (94!10) [18:07:17:298]: Closing MSIHANDLE (86) of type 790531 for thread 2832
MSI (s) (94!10) [18:07:17:298]: Creating MSIHANDLE (87) of type 790531 for thread 2832
CAQuietExec:  Microsoft.NET.CoreRuntime.1.0 available to the user are Microsoft.NET.CoreRuntime.1.0_1.0.23430.0_x86__8wekyb3d8bbwe.

When I do a manual deployment (doubleclick the AddAppxPackage powershell command), the deployment finishes without any problems. It seems that running this same powershell script through the Wix installer does not deploy the dependencies in the right manner, even though the dependencies are included with the installer.
Any ideas?


text:
Q: What methods exist for distributing a semi-live dataset with an R package? I am building a package for internal use using devtools. I would like to have the package load in data from a file/connection (that differs depending on the date package is built). The data is large-ish so having a onetime cost of parsing and loading the data during package building is preferable.
Currently, I have a data.R file under R/ that assigns the data to package-level variables, the values are assigned during package installation (or at least that's what appears to be happening). This less than ideal setup mostly works. In order to get all instances of the package to have the same data I have to distribute the data file with the package (currently it's being copied to inst/ by a helper script before building the package) instead of just having it all be packaged together. There must be a better way.
Such as:

*

*Generate .rda files during package building (but this requires not running the same code during package install)

*

*I can do this with a Makefile but that seems like overkill

*Can I have R code that is only run during package building and not during install?

*Run R code in data/

*

*But the data is munged using code in the package in question. I can fix that with Collate (I think) but then I have to maintain the order of all of the .R files (but with that added complexity I might as well use a Makefile?)

*Build two packages, one with all of the code I want, one with the data.

*Obvious, clever things I've not thought of.

tl;dr: What are some methods for adding a snapshot of dynamically changing data to an R package frozen for deployment?

A: As @BenBolker points out in the comments above, splitting the dataset out into a different package has precedent in the community (most notably the core package datasets) and has additional benefits.
The separation of functions from data also makes working on historic versions of the data easier to do with the up to date functions.
I currently have an tools-to-munge package and a things-to-munge package. Using a helper script I can build the tools-to-munge and setup a Suggests (or Depends) in the DESCRIPTION of both packages to point to the appropriate incrementing version of the packages. After the new tools-to-munge package has been built I can build the things-to-munge package as necessary using the functions in the tools-to-munge package.


text:
Q: ImportMany of MEF loading Contracts twice I have two classes which Exports IScreen, but when I import the same using
[ImportMany(typeof(IScreen))]
private IEnumerable<Lazy<IScreen,IJIMSMetadata>> _modules;
public IEnumerable<Lazy<IScreen, IJIMSMetadata>> Modules
{
        get { return _modules; }
}

The Modules contain four instance of IScreen, but I have Exported only two.
This is Container
container = new CompositionContainer(
                new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x)))
                );

protected override IEnumerable<Assembly> SelectAssemblies()
{
    string _modulePath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Modules");
    var files = Directory.GetFiles(_modulePath, "*.dll", SearchOption.AllDirectories);

    List<Assembly> assemblies = new List<Assembly>();
    assemblies.Add(Assembly.GetExecutingAssembly());
    foreach (var file in files)
    {
        assemblies.Add(Assembly.LoadFrom(file));
    }
    return assemblies;
}

A: Since you are using an AggregateCatalog, check to be sure you are not adding both an AssemblyCatalog and a DirectoryCatalog for the location containing the executing assembly.
For example, the following code avoids processing the same assembly twice.
var catalog = new AggregateCatalog();
var locations = new List<string>();
foreach (var loc in GetPluginDirectories())
    if (!locations.Contains(loc))
    {
        catalog.Catalogs.Add(new DirectoryCatalog(loc));
        locations.Add(loc);
    }

var asm = Assembly.GetExecutingAssembly();
if (!locations.Contains(Path.GetDirectoryName(asm.Location)))
    catalog.Catalogs.Add(new AssemblyCatalog(asm));


text:
Q: How to retrieve a .app file from the .xcarchive? I am trying to use Appium to automate our mobile app, and I realize that in order to do so we need to specify the path to .app file. However after archiving I get only the .xcarchive file which I don't know what to do next..
My xcode version is 5.1.
Please advise how to proceed, thanks!

A: While sheep test's answer works, there is another way. The .app bundle is included inside the .xcarchive file. If you already have a .xcarchive file, follow these steps to get the .app

*

*Navigate to your .xcarchive file in the finder

*Right click on the .xcarchive file and select "Show Package Contents" in the popup menu

*The finder will switch to showing the contents of the .xcarchive file.

*Navigate to Products/Applications

*your .app will be located in Products/Applications

A: Two options:

*

*Build an .ipa instead of .xcarchive (Instructions here) Appium's --app arugment accepts .ipa's as well as .app's and even .zip files. (Try pointing it at .xcarchive! I have no idea if it'll work)

*Build and Run

*

*go to /Users/blah/Library/Application\ Support/iPhone\ Simulator/7.1/Applications

*Find your app

*copy the .app file

*put it somewhere outside of the simulator directory (so when appium resets the simulator, it will do a clean install of the app)


text:
Q: firestore where() filter collection by field for context provider next.js i have a problem as follows:
i'm retrieving my firestore documents via useEffect function and it works just fine.
Right now I'm retrieving all "profiles" documents (3 at this point). But now i want to retrieve only the documents, which field "workerProfile" is true. I have 2 docs with false and 1 with true, so it should only show me an array with 1 doc.
When doing so in firebase console manually, it is working.

below is my useEffect function with the ,where('workerProfile', '==', true) which is not working, but also not giving any errors.
useEffect(() => {
        const getProfiles = async () => {
            const querySnapshot = await getDocs(collection(fireDb, "profiles"),where('workerProfile', '==', true))
            console.log(querySnapshot, "CHECK OUT")
            setProfiles(querySnapshot.docs.map(doc => {
                return {
                    id: doc.id,
                    data: {
                        userProfileUrl: doc.data().userProfileUrl,
                        displayName: doc.data().displayName,
                        likesCount: doc.data().likesCount,
                        bio: doc.data().bio
                    }
                }
            }))
        }
        getProfiles()
    }, [])

but my console.log(querySnapshot, "CHECK OUT") still shows all 3 profiles, instead of only 1.

I already tried to find some hints from the firebase documentation, but i still have no idea, why it is not working. Maybe I'm missing something here?
I would really appreciate if someone could help me here, because this is starting to annoy me really bad.
I'm working with

*

*firebase 9.14.0

*firebase-admin ^11.2.1

*firebase-functions ^4.0.2

*next 13.0.2

*react: 18.2.0

Below is my complete context-file for further information:
import { createContext, useEffect, useState, useContext } from "react"
import { collection, getDocs, getDoc, doc, where, query, setDoc } from "firebase/firestore"
import { fireDb } from "../../firebaseClient"

const FantsyContext = createContext()

const FantsyProvider = ({ children }) => {

    const [users, setUsers] = useState([])
    const [currentLoggedUser, setCurrentUser] = useState([])
    const [profiles, setProfiles] = useState([])

    // GET USERS
    useEffect(() => {
        const getUsers = async () => {
            const querySnapshot = await getDocs(collection(fireDb, "users"))
            setUsers(querySnapshot.docs.map(doc => {
                return {
                    id: doc.id,
                    data: {
                        ...doc.data()
                    }
                }
            }))
        }
        getUsers()
    }, [])

    // GET PROFILES
    useEffect(() => {
        const getProfiles = async () => {
            const querySnapshot = await getDocs(collection(fireDb, "profiles"),where('workerProfile', '==', true))
            console.log(querySnapshot, "CHECK OUT")
            setProfiles(querySnapshot.docs.map(doc => {
                return {
                    id: doc.id,
                    data: {
                        userProfileUrl: doc.data().userProfileUrl,
                        displayName: doc.data().displayName,
                        likesCount: doc.data().likesCount,
                        bio: doc.data().bio
                    }
                }
            }))
        }
        getProfiles()
    }, [])

    return (
        <FantsyContext.Provider
            value={{ profiles, users }}
        >{children}</FantsyContext.Provider>
    )
}

export { FantsyContext, FantsyProvider }

A: Try
await getDocs(query(collection(fireDb, "profiles"), where('workerProfile', '==', true)))

I think you just used getDocs(collection(<ref>, <collection name>)) and so getDocs() function ignored the rest args(where() query).
So, use query() function inside getDocs().


text:
Q: Julia WebSocket slow to read/write I was testing Julia WebSockets and I found that they are much slower than the Python/Node equivalents. I wrote a test to send a ping and measure the time taken for a pong response from some crypto exchanges as an example. Julia consistently takes 50ms for the test below, whereas python takes 2-4 ms. Is this expected?
Julia:
using WebSockets
function main()
    WebSockets.open("wss://wsaws.okex.com:8443/ws/v5/public") do ws
        for i = 1:100
            a = time_ns()
            write(ws, "ping")
            data, success = readguarded(ws)
            b = time_ns()
            println(String(data), " ", (b - a) / 1000000)
            sleep(0.1)
        end
    end
end
main()

Equivalent Python:

import websockets
import asyncio
import time

async def main():
    uri = "wss://wsaws.okex.com:8443/ws/v5/public"
    async with websockets.connect(uri) as websocket:
        msg = "hello"
        for i in range(101):
            a = time.time()
            await websocket.send(msg)
            x = await websocket.recv()
            b = time.time()
            print(b-a)
            time.sleep(0.1)

asyncio.get_event_loop().run_until_complete(main())


text:
Q: Why I can't change an array element obtained from another class? I created a class that implements the wrapper over the array double [] but I can not change the element of the received array. These are tests
public void SetCorrectly ()
public void IndexerDoesNotCopyArray ()

The problem sounds like this. Write the class Indexer, which is created as a wrapper over the array double [], and opens access to its subarray of some length, starting with some element. Your decision must pass the tests contained in the project. As always, you must monitor the integrity of the data in Indexer.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Incapsulation.Weights
{
    public class Indexer
    {
        double[] array;
        int start;
        int length;
        public int Length
        {
            get { return length; }
        }

        public Indexer(double[] array, int start, int length)
        {
            if (start < 0 || start >= array.Length) throw new ArgumentException();
            this.start = start;
            if (length < start || length > array.Length) throw new ArgumentException();
            this.length = length;
            this.array = array.Skip(start).Take(length).ToArray();
        }

        public double this[int index]
        {
            get { return array[index]; }
            set { array[index] = value; }
        }
    }
}

This is tests
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Incapsulation.Weights
{
    [TestFixture]
    public class Indexer_should
    {
        double[] array = new double[] { 1, 2, 3, 4 };

        [Test]
        public void HaveCorrectLength()
        {
            var indexer = new Indexer(array, 1, 2);
            Assert.AreEqual(2, indexer.Length);
        }

        [Test]
        public void GetCorrectly()
        {
            var indexer = new Indexer(array, 1, 2);
            Assert.AreEqual(2, indexer[0]);
            Assert.AreEqual(3, indexer[1]);
        }

        [Test]
        public void SetCorrectly()
        {
            var indexer = new Indexer(array, 1, 2);
            indexer[0] = 10;
            Assert.AreEqual(10, array[1]);
        }

        [Test]
        public void IndexerDoesNotCopyArray()
        {
            var indexer1 = new Indexer(array, 1, 2);
            var indexer2 = new Indexer(array, 0, 2);
            indexer1[0] = 100500;
            Assert.AreEqual(100500, indexer2[1]);
        }

}

A: The problem you are facing here is that the last test requires that your wrapper provides access to the underlying array. In other words, whatever number of Indexers are created, they all point to the same underlying array.
Your line here this.array = array.Skip(start).Take(length).ToArray(); violates this requirement creating a new instance of Array class. Because of this the value changed by first indexer is not reflected in the second one - they point to different memory areas.
To fix this, instead of creating a new Array using LINQ, simply store the original array passed through constructor. Your this[] indexer property must take care of passed start and end adding start to the index and checking the out-of-boundaries condition manually.

A: All linq extension methods create a new enumeration, they do not mutate or return the one the method is called on:
var newArray = array.Skip(...).ToArray();
ReferenceEquals(array, newArray); //returns false

Any change you might make in an element of newArray will not change anything whatsoever in array.
Your SetCorrectly test is comparing indexer and array and it will always fail. Your other test also fails because indexer1 and indexer2 reference two different arrays.
However because Linq is lazy, modifying array can be seen by the result of the Linq extension method depending on when you materialize the enumeration; this can happen:
var skippedA = array.Skip(1); //deferred execution
array[1] = //some different value...,
var newArray =skipped.ToArray(); //Skip is materialized here!
newArray[1] == array[1]; //true!


text:
Q: Is there a Java local queue library I can use that keeps memory usage low by dumping to the hard drive? This maybe not possible but I thought I might just give it a try.  I have some work that process some data, it makes 3 decisions with each data it proceses: keep, discard or modify/reprocess(because its unsure to keep/discard).  This generates a very large amount of data because the reprocess may break the data into many different parts.
My initial method was to send it to my executionservice that was processing the data but because the number of items to process was large I would run out of memory very quickly.  Then I decided to maybe offload the queue off to a messaging server(rabbitmq) which works fine but now I'm bound by network IO.  What I like about rabbitmq is it keeps messages in memory up to a certain level and then dumps old messages to the local drive so if I have 8 gigs of memory on my server I can still have a 100 gig message queue.
So my question is, is there any library that has a similar feature in Java? Something that I can use as a nonblocking queue that keeps only X items in queue(either by number of items or size) and writes the rest to the local drive.
note: Right now I'm only asking for this to be used on one server.  In the future I might add more servers but because each server is self-generating data I would try to take messages from one queue and push them to another if one server's queue is empty.  The library would not need to have network access but I would need to access the queue from another Java process.  I know this is a long shot but thought if anyone knew it would be SO.

A: Not sure if it id the approach you are looking for, but why not using a lightweight database like hsqldb and a persistence layer like hibernate? You can have your messages in memory, then commit to db to save on disk, and later query them, with a convenient SQL query.

A: Actually, as Cuevas wrote, HSQLDB could be a solution. If you use the "cached table" provided, you can specify the maximum amount of memory used, exceeding data will be sent to the hard drive.

A: Use the filesystem.  It's old-school, yet so many engineers get bitten with libraries because they are lazy.  True that HSQLDB provides lots of value-add features, but in the context of being light weight....


text:
Q: C++ Why does my code give the desired results on Ubuntu but has undefined behavior on Windows 7 I am taking a C++ course in University, every week we are required to write a program with given specifications. It's usually basic tasks that resolve around the topics we discussed in class the week before. As we are discussing pointers arrays and dynamic memory naturally this week's program was all about using arrays and dynamic memory allocation.
To break it down, the program we were asked to write was supposed to take a random user input (no white spaces, just some random characters) and divide the user input in 3 categories: Upper case, lower case and special characters.
The method I used is probably not the most efficient one but it does the job, considering the only libraries we are allowed to use are iostream and cmath, however here comes my problem. In class I wrote the program in almost no time, compiled it and it ran straight away no issues. If you give a user input such as aAghC4 it will have as output AC agh 4
So I went ahead and downloaded my program from my university folder on my private machine at home to work on it a little, make it more efficient as practice. However when I compiled the (unedited and original) .cpp on my windows machine it's output is random, undefined behavior. Both in class and at home I use g++ to compile my files, however at home I run Windows 7, in class we use Ubuntu 14.04.
I would be very greatful if someone could take a look at my code and tell me why it doesn't work on a windows machine.
#include<iostream>

using namespace std;

int main(){

  char input[80];
  int counter = 0;

  cin >> input;
  for(int i = 0; input[i] != '\0'; i++){
  counter++;
  }

  char *uppercase = new char[counter];
  char *lowercase = new char[counter];
  char *special = new char[counter];

  for(int i = 0; i < (counter+1); i++){
  switch(input[i]){
    case 'a': lowercase[i] = input[i]; break;
    case 'b': lowercase[i] = input[i]; break;
    // I edited this part it basically goes on for the entire
    // alphabet, first lowercase letters then uppercase
    case 'Y': uppercase[i] = input[i]; break;
    case 'Z': uppercase[i] = input[i]; break;
    default: special[i] = input[i]; break;
    }
  }

  for(int i = 0; i <= counter; i++){
    cout << uppercase[i];
  }

  cout << " ";
  for(int i = 0; i <= counter; i++){
    cout << lowercase[i];
  }

  cout << " ";
  for(int i = 0; i <= counter; i++){
    cout << special[i];
  }

  delete[] uppercase;
  delete[] lowercase;
  delete[] special;
  cout << endl;
}

This is the entire source code, nothing more and nothing less, thank you for any replies!

A: You have undefined behavior in both programs, no matter if you run it on ubuntu or windows 7; you are just lucky that it shows the behavior you expected on the former.

reading uninitialized memory = undefined behavior
You are assuming that the valid range of elements to read in all of uppercase, lowercase, and special is that of [0, counter] which isn't the case; you are effectively reading uninitialized memory in your loops that iterate over the elements of these arrays (and undefined behavior emerge).
The reason you think it's working when running the code on ubuntu is probably because the memory of your three arrays happens to be zero-initialized; meaning that your loops will print a bunch of '\0' (normally not visible in a terminal) when you haven't assigned a particular element a value.
char * p = new char[counter]   ; // default-initialized `char`s (could have any value)
char * p = new char[counter] (); // value-initialized, all elements are `char()` ie. 0

reading past the end of an array = undefined behavior
There's also a problem that your loops that prints the contents of uppercase, lowercase, and special has an off-by-one problem.
The last element offset for all of these loops are counter-1, but you assume it to be counter (i <= counter).

Solution

*

*Don't print elements which you haven't, explicitly, given a value.
This can be accomplished by a separate counter for each of your arrays, or some other means (like initializing every element of the arrays to 0 and stop iterating when such value is found).

*Don't read elements that aren't part of the memory you allocated.

A: Most of the elements in your uppercase, lowercase etc array are uninitialized causing the issue. When you print (read) uninitialized variables or memory, it invokes undefined behaviour. You should have separate counters for all arrays.
#include<iostream>

using namespace std;

int main(){

  char input[80];
  int counter = 0;
  int u = 0, l = 0, s = 0;

  cin >> input;
  for(int i = 0; input[i] != '\0'; i++){
  counter++;
  }

  char *uppercase = new char[counter];
  char *lowercase = new char[counter];
  char *special = new char[counter];

  for(int i = 0; i < (counter+1); i++){
    if('a' <= input[i] && input[i] <= 'a') lowercase[l++] = input[i];
    else if('A' <= input[i] && input[i] <= 'Z') uppercase[u++] = input[i];
    else special[s++] = input[i]; break;
  }

  for(int i = 0; i <= u; i++){
    cout << uppercase[i];
  }

  cout << " ";
  for(int i = 0; i <= l; i++){
    cout << lowercase[i];
  }

  cout << " ";
  for(int i = 0; i <= s; i++){
    cout << special[i];
  }

  delete[] uppercase;
  delete[] lowercase;
  delete[] special;
  cout << endl;
}

A: There is at least one error, the for loops have problems.
The one with the switch inside should have a stop condition like i<counter not counter+1.
Every other following loops should also have a stop condition like i<counter not <=.
You should also initialize you arrays with some predefined value (ascii NUL for example) :
for (i=0; i<counter; i++) lowercase[i] = '\0';

and at the end when printing, only print non nul chars :
for (i=0; i<counter; i++) if (lowercase[i]!='\0') cout << lowercase[i];


text:
Q: Powershell hash tables and PSObjects - multiple values I need help with the following for my project in SharePoint. I have an external list with values like:
*ToolId*                   *ProductId*

T001                       ProductA
T001                       ProductB
T002                       ProductA
T002                       ProductC

I use PowerShell to exort that list into a CSV. I need to manipulate the external list and my final result needs to be like that:
*ToolId*                 *ProductId*

T001                     ProductA; ProductB
T002                     ProductA; ProductC

This is my PS code so far:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get the context
$ctx = Get-SPServiceContext https://path

#Get the scope
$scope = new-object Microsoft.SharePoint.SPServiceContextScope $ctx

#Get the target site collection
$webTarget = Get-SPWeb -identity "https://path"

#Get the Target List
$list = $webTarget.Lists["Name of List"]

#Array to Hold Result - PSObjects
$ListItemCollection = @()

#Get All List items
$list.Items |  Where-Object { $_["ToolId"] -ne ''} | foreach {
$ExportItem = New-Object PSObject
$ExportItem | Add-Member -MemberType NoteProperty -name "ToolId" -value    $_["ToolId"]
$ExportItem | Add-Member -MemberType NoteProperty -name "ProductId" -value $_["ProductId"]
#Add the object with property to an Array
$ListItemCollection += $ExportItem
}
#Export the result Array to CSV file
$ListItemCollection | Export-CSV "\\path\test.csv" -NoTypeInformation
#Dispose the web Object
$webTarget.Dispose()

I'm having problems with PSObjects and hash tables to get all the items of the same ToolId and collect all the ProductId's relevant to them to populate my CSV.

A: You can group items byt ToolId using Group-Object and then build your result using Select-Object.
Try this one:
$ListItemCollection | Group-Object ToolId |
  Select @{ Label = "ToolId"; Expression = { $_.Name } }, @{ Label = "Products"; Expression = { ($_.Group | Select-Object -ExpandProperty ProductId) } }

Shorter version:
$ListItemCollection | group ToolId | select @{ L = "ToolId"; E = { $_.Name } }, @{ L = "Products"; E = { $_.Group.ProductId } }

Select-Object cmdlet can take a collection of Label-Expression pairs instead of property names. See Example #4.
Personally I'd use hashtables instead PSObject.
Also it's generally bad practice to use SPList.Items collection. You should use SPList.GetItems() method instead.


text:
Q: How to split python list into chunks - but in backwards order? I want to split a given python list into chunks, similar to the following link, but in reverse.
Currently I have the output forward_chunk([1,2,3],2) = [[1,2], [3]]
However I want the output backward_chunk([1,2,3],2) = [[1], [2,3]]
# what I currently have
def forward_chunk(list, size):
    for i in range(0, len(list), size):
        yield list[i:i+size]

Despite my best efforts, I am unable to get the ranges and list slices to work and achieve the desired result. Does anyone have any suggestions?

A: Sth. like this maybe:
def backward_chunk(l, size):
    start = 0
    for end in range(len(l)%size, len(l)+1, size):
        yield l[start:end]
        start = end

> list(backward_chunk([1, 2, 3], 2))
[[1], [2, 3]]

The first chunk size is calculated as the modulo of list length and general chunk size. And please, don't call variables list.

A: Find how many extra elements there will be, split the list in two, yield the first piece, then do the chunk operation and yield the rest.
def forward_chunk(lst, size):
    piece = len(lst) % size
    piece, lst = lst[:piece], lst[piece:]
    yield piece
    for i in range(0, len(lst), size):
        yield lst[i:i+size]

A: You can use a normal chunk generator and reverse the list if you want.
def chunk(data, size, reverse=False):
    data = data[::-1] if reverse else data
    for n in range(0, len(data), size):
        yield data[n:n+size]

Example usage:
info = [1, 2, 3, 4, 5, 6, 7, 8]
for i in chunk(info, 4):
    print(i)  # => [1, 2, 3, 4], [5, 6, 7, 8]
for i in chunk(info, 4, True):
    print(i)  # => [8, 7, 6, 5], [4, 3, 2, 1]

If you want to only reverse the ORDER and not the list itself, just yield data[n:n+size][::-1] if reverse is True.


text:
Q: How to sum Column of MS SQL I like SUM (@columName) but

ERROR: Operand data type nvarchar is invalid for sum operator.

I have to do.
This is example code :
DECLARE @columnName nvarchar(4000)
DECLARE @sql nvarchar(4000)

set @columnName = '[$ Sales]'

SET @sql = N' SELECT ' + sum(@columnName)+ ' FROM [WISH_BAP_SA01].[dbo].[12DSA01F] '

EXEC sp_executesql @sql

Please suggest me.

A: Try this:
SET @sql = N' SELECT  + sum(' + @columnName+ ') FROM [WISH_BAP_SA01].[dbo].[12DSA01F] '

You need to keep only the @columnName as variable. The rest of the query is fixed.


text:
Q: Best practice for outputting breadcrumbs in PHP As part of an eCommerce solution we're working on, the CMS has the option for product categories to have an unlimited number of sub-categories, and each sub-category can have an unlimited number of sub-categories. Basically, there is an unlimited nesting-level for product categories.
The database table schema for the categories looks something like this:
+-------------+-----------------+----------------+
| category_id |      name       |   parent_id    |
+-------------+-----------------+----------------+
|     1       |    Parent 1     |      null      |
|     2       | Child of Parent |        1       |
+-------------+-----------------+----------------+

We want to add in a breadcrumbs navigation for each level of the category navigation, so my question is, what is the best practice for looping through the categories while there is a parent assigned, until it reaches the top level?
Obviously, we can code it in a fixed loop (for example if($child->hasParent()) { echo '1'; if($child->children->hasParent() {  } } etc.
How do you iterate through an unknown number of categories until you reach the top-level category (i.e. the category which has no parent_id assigned?

A: Just use the while loop for this.
while($child->hasParent()) {
     echo $child->name();
     $child = $child->Parent();
}

A: If(parent class==null)
then
child class==null
else
hasparent class(null)==0
repeat


text:
Q: Bringing Values Down My result looks like this (Output1):
 ID     Year    YearWeek    Week    ID1         (No column name)

479474  2017    201718      18          479474  201718
479474  2017    201719      19          NULL    NULL
479474  2017    201720      20          NULL    NULL
479474  2017    201721      21          479474  201721
479474  2017    201722      22          NULL    NULL
479474  2017    201723      23          479474  201723
479474  2017    201724      24          479474  201724

However, I would like for it to look like the following:
 ID     Year    YearWeek    Week    ID1         (No column name)

479474  2017    201718      18          479474  201718
479474  2017    201719      19          NULL    201718
479474  2017    201720      20          NULL    201718
479474  2017    201721      21          479474  201721
479474  2017    201722      22          NULL    201721
479474  2017    201723      23          479474  201723
479474  2017    201724      24          479474  201724

Can someone please make some suggestions to make code so that the values in (No column name) are dragged down?  The values are 201718, 201721, 201723, and 201724.

A: Take this for a spin...
IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL
DROP TABLE #TestData;

CREATE TABLE #TestData (
    ID INT NOT NULL,
    [Year] INT NOT NULL,
    YearWeek INT NOT NULL,
    [Week] INT NOT NULL,
    ID1 int NULL
    );

INSERT #TestData (ID, Year, YearWeek, Week, ID1) VALUES
    (479474, 2017, 201718, 18, 479474),
    (479474, 2017, 201719, 19, NULL  ),
    (479474, 2017, 201720, 20, NULL  ),
    (479474, 2017, 201721, 21, 479474),
    (479474, 2017, 201722, 22, NULL  ),
    (479474, 2017, 201723, 23, 479474),
    (479474, 2017, 201724, 24, 479474);

--  SELECT * FROM #TestData td

--============================================================

SELECT
    td.ID, td.Year, td.YearWeek, td.Week, td.ID1,
    CAST(SUBSTRING(MAX(CAST(td.YearWeek AS BINARY(4)) + CAST(td.ID1 AS BINARY(4))) OVER (ORDER BY td.YearWeek ROWS UNBOUNDED PRECEDING), 1, 4) AS INT)
FROM
    #TestData td;

A: Your issue is the lack of a catch-all in the case-statement following the CTE.
Update your Select statement to read as follows:
SELECT
    Y.*,
    CASE
        WHEN Y.[ID1] IS NOT NULL THEN Y.[YearWeek]
        ELSE NULL   ----> ADDED TO HAVE A NULL WHEN THERE'S NO VALUE IN PREVIOUS COLUMN
    END AS Column1
FROM Y
ORDER BY Y.[Customer ID], Y.Year, Y.[YearWeek], Y.Week;


text:
Q: Mysterious Vertical Space After Theorem/Proof Environments I have defined my own theorem style to have 0pt above and 0pt below. For simplicity I have also set all other relevant spacings to 0pt. However, when I use a theorem or proof environment I get some mysterious white space below.
Note that I don't get any space above (so the 0pt above in \newtheoremstyle seems to be working). Can anyone tell me where the space is coming from? Here is my code:
\documentclass[11pt,a4paper]{report}

\usepackage{amsmath,amssymb,amsthm}

\setlength{\topsep}{0pt}
\setlength{\partopsep}{0pt plus 0pt minus 0pt}
\setlength{\parskip}{0pt}
\setlength{\parindent}{0pt}

\newtheoremstyle{mytheoremstyle}{0pt}{0pt}{\itshape}{}{\bf}{.}{.5em}{}

\theoremstyle{mytheoremstyle}

\newtheorem{theorem}{Theorem}[chapter]
\newtheorem{lemma}[theorem]{Lemma}

\begin{document}
Some normal text goes here, with a lemma immediately below.
\begin{lemma}
This is the statement of the lemma.
\end{lemma}
\begin{proof}
This is the proof of the lemma, with a mysterious space above.
\end{proof}
Some normal text goes here, with a mysterious space above. \par
The next paragraph comes immediately below.

\end{document}

A: The proof environment resets \topsep before opening a trivlist; you can remove this setting by redefining \proof or by patching it.
\documentclass[11pt,a4paper]{report}

\usepackage{amsmath,amssymb,amsthm,xpatch}

\setlength{\topsep}{0pt}
\setlength{\partopsep}{0pt plus 0pt minus 0pt}
\setlength{\parskip}{0pt}
\setlength{\parindent}{0pt}

\newtheoremstyle{mytheoremstyle}{0pt}{0pt}{\itshape}{}{\bfseries}{.}{.5em}{}

\theoremstyle{mytheoremstyle}

\newtheorem{theorem}{Theorem}[chapter]
\newtheorem{lemma}[theorem]{Lemma}

\makeatletter
\xpatchcmd{\proof}{\topsep6\p@\@plus6\p@\relax}{}{}{}
\makeatother

\begin{document}
Some normal text goes here, with a lemma immediately below.
\begin{lemma}
This is the statement of the lemma.
\end{lemma}
\begin{proof}
This is the proof of the lemma, with a mysterious space above.
\end{proof}
Some normal text goes here, with a mysterious space above. \par
The next paragraph comes immediately below.

\end{document}

I hope this is just for studying how LaTeX works, because the output is terrible.
Please, note that \bf has been obsolete for twenty years and \bfseries should be used.


text:
Q: ASP.NET Web API Vs/AND/OR NODE API I have been working with .NET WEB APIs since long and have learnt NODE APIs a bit.
I love working with Javascript and/or C#.
If I look at .NET WEB API, I really can see that things are already developed and taken care by MICROSOFT.
If I look at NODE APIs, I can (at this stage) understand things are working greatly and growing day by day and may be taken care greatly (but I don't know too much about it).
Now being a software developer(.NET), I can play with .NET WEB APIs as I want as I have pretty much experienced with it. .NET WEB API does almost every thing that I want.
Recently,I came across alasql.js(I think its APIs are written in NODE (not sure)). In order to create an excel , I just have to get the list of objects from .NET WEB API, throw it to client end, at client end I will use single line code and it will generate an excel. (So simple. Same thing is possible in C# .and NET WEB API)...
I know NODE is widely used. but at this stage it seems a different platform to me. I'd like to go on with NODE.
I know its amazing if I could run javascript code onto server with NODE.
I know both are great.
But I'm confused with How and When to use them together, individually?


text:
Q: (React Native iOS) - Scroll to top when tapping on status bar My code is the following:
    <ScrollView style={styles.scrollView}>
      <RefreshControl
        refreshing={refreshing}
        onRefresh={onRefresh}
      />

      <Text>
        {"\n"}
      </Text>

      <FlatList
        data={data}
        keyExtractor={({ id }, index) => id}
        renderItem={({ item }) => <Item item={item} />}
      />

      <Text style={{ textAlign: "center", color: "white", fontSize: 24, fontFamily: 'Montserrat_600SemiBold' }}>
        Hi there!
        {"\n"}
        {"\n"}
      </Text>
    </ScrollView>

It displays a FlatList within a ScrollView. I want the ScrollView to go back to the top when the user taps on the status bar on an iOS device.


text:
Q: Accessing an Amazon RDS MySQL database from CodeIgniter leads a blank display This is related to this previous question. I'm making it a new question because at this point I believe it's a database access issue.
Essentially, I've switched the database from a MySql sever to an Amazon RDS MySql server, due to server migration.  To summarize, I'm attempting to migrate a PHP site based on CodeIgniter (version 1.7.2) to a new server which has AmazonLinux as the OS. The previous server was Ubuntu, running PHP 5.3.3-1ubuntu9.5 on Apache2. The PHP version on the new AmazonLinux server is 5.3.29, running on httpd.
The problem is, when I try to access the URL in the new server, I get a blank display. The code is stopping in system/core/CodeIgniter.php at this line:
$CI = new $class();

The last line of the application log is this:
DEBUG - 2015-04-25 17:17:58 --> Database Driver Class Initialized

So, it's happening around the database. I've also read that you get a blank display if it's a database issue due to an "@" being used for database-related messages.
These are the settings in database.php:
$active_group = "default";
$active_record = TRUE;
$db['default']['hostname'] = "xxxxx.xxxxxxxx.us-east-1.rds.amazonaws.com";
$db['default']['username'] = "xxxxx";
$db['default']['password'] = "xxxxx";
$db['default']['database'] = "xxxxx";
$db['default']['dbdriver'] = "mysql";
$db['default']['port'] = 3306;
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = "TRUE";
// $db['default']['cache_on'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "/opt/xxxxx/cachedb/";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";

I also tried it without the port specified (as it's set up on the current production site) as well as with the port specified at the end of the url:
$db['default']['hostname'] = "xxxxx.xxxxxxxx.us-east-1.rds.amazonaws.com:3306";

But I'm still getting the blank display.
We have a Java/Tomcat application running on the same server that is able to access the RDS database, using the same url, name and password, so it doesn't appear to be an issue of security groups.
Any thoughts on what the problem might be?  and if so how to solve?
Edit 1: I've tracked down the problem - not surprisingly, it's the database driver. It fails when calling this function:
system/database/drivers/mysqli/mysqli_driver.php:  function db_pconnect()
The question is, can I just copy in a more recent driver into this older version of CodeIgnitor and it will miraculously work? I'll try that experiment tomorrow. Otherwise, we might be looking at an upgrade. Grim, but it should theoretically work, since it will have an up-to-date driver. Right?

A: The problem turned out to be a database access issue. Specifically, the version of PHP on the new server turned out to not support deprecated calls to php-mysql APIs (e.g. @mysql_pconnect or @mysql_connect)
The solution was to
1) Download the mysql library which supports the legacy calls. In the case of AmazonLinux, this is accomplished as follows:
sudo yum install php-mysql

2) Find where the library was downloaded e.g.
find / -name mysql.so

This may have been shown in the install as well, but that is a way to find it anytime. YMMV, but in my case, the library name was:
/usr/lib64/php-zts/modules/mysql.so

3) Change php.ini (as shown in phpinfo when called from a php page on the httpd/apached server) as follows:
a) change "extension_dir" to show where the mysql.so is installed:
extension_dir = "/usr/lib64/php-zts/modules"

b) Then add the following lines:
extension=mysqli.so
extension=mysql.so
extension=pdo_mysql.so

Reboot apache and you should be good to go.
Note: the specific legacy call not supported, which is part of of the version of CodeIgnitor I'm working with, was this:
   return @mysql_pconnect($this->hostname, $this->username, $this-// etc.

The php error log showed this error:
 PHP Fatal error:  Call to undefined function mysql_connect() in xxx.php on line xx

A: Allow 3306 port in your server. I will only possible when you have WHM access. Otherwise contact with your server administrator.


text:
Q: Can we limit the domain we visit from ios in-app browser? I am developing an ios app, and I wish to use the in-app browser. But I wish to limit the domain visited with in-app browser. (Ex: limited to the .com website only.) Is there a way to implement this restriction?

A:
Sent before a web view begins loading a frame.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

Parameters
webView The web view that is about to load a new frame. request The
  content location. navigationType The type of user action that started
  the load request.
Return Value
YES if the web view should begin**
  loading content; otherwise, NO .

You should always read the documentation

A: If you need to know if you can do something with a web view, start by looking at the documentation - UIWebView class reference.
From there, you can see that it has a delegate property that is sent messages when content is loading.  So next, you look at the documentation for the UIWebViewDelegate protocol.
From there, you can see that the delegate is sent a webView:shouldStartLoadWithRequest:navigationType: message before the web view loads content.  Looking at the documentation for that method tells you that you need simply return NO from that method to cancel loading content.
So provide a delegate for the web view that implements that method which returns NO when you see a URL you don't like.
In future, please check the documentation before asking on Stack Overflow.


text:
Q: Importing Core Data to existing project fails I have a workspace and I'm trying to add Core Data to it.  I went to the project I want to add Core Data to, selected the Target, hit the + sign under Link Wit Binary Files and added the Core Data framework.  That part works fine.  I can build and run.  When I try the next and using this line:
#import <CoreData/CoreData.h>

I get build errors.  These build errors look like:
"ARC Semantic Issue"
Pointer to non-const type 'id' with no explicit ownership

These errors are present in
NSEntityDescription.h
NSManagedObjectModel.h
NSMnagedObject.h
NSManagedObjectContext.h
NSPersistentStore.h

Does anyone know why I'm not able to import Core Data to an existing iOS project?  Thanks in advance!

A: In my framework search paths, I had an erroneous path that correctly built once I removed it:
$(DEVELOPER_DIR)/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/System/Library/Frameworks

A: It should be as simple as adding CoreData.framework to your target:

Click the plus button (+) under Linked Frameworks and Libraries
Then in your Prefix file (Tabs-Prefix.pch in this case) in the #ifdef __OBJC__ declaration:
#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
    #impport <CoreData/CoreData.h> //Added core data here
#endif

If this does not work, perhaps you have an older version of Xcode installed and the paths are messed up. It could be trying to import an older framework.

A: I think this could be related to your entity definitions. Is it possible that you have declared entities that use the attribute name id? That would typically be a NSNumber type in the model subclasses, i.e. *id.
It seems that in this case, the compiler instead of complaining about the *id in the class files, it indicates the id in the header files, which is confusing.
--> Try changing your attribute names.

A: I had the same problem. It was solved by the following steps:

*

*Remove Reference to CoreData.framework from Frameworks group in Xcode.

*Remove CoreData.framework from 'Link Binary with Libraries' in target settings.

*Quit Xcode (Cmd + Q).

*Open your project folder in Finder and delete CoreData.framework file.

*Start Xcode, open your project. Now you may to add the CoreData.framework in 'Link Binary with Libraries'.

*Don't forget to add #import <CoreData/CoreData.h> into <projectName>-Prefix.pch located at Supported Files. My prefix header seems like this:

`
#import <Availability.h>

#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif

#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
    #import <CoreData/CoreData.h>
#endif

`
I don't know how existance of any file in project directory can affect to compile errors, but it works for me.
Hope this helps for anyone who reads it.


text:
Q: How to get last part of nvarchar with variable size in T-SQL? Imagine that I have the following value in my nvarchar variable:
DECLARE @txt nvarchar(255)
SET @txt = '32|foo|foo2|123'

Is there a way to easily get the last part just after the last | that is 123 in this case ?
I could write a split function but I'm not interested in the first parts of this string. Is there another way to get that last part of the string without getting the first parts ?
Note that all parts of my string have variable sizes.

A: You can use a combination of LEFT, REVERSE and CHARINDEX for this.
The query below reverses the string, finds the first occurance of |, strips out other characters and then straightens the string back.
DECLARE @txt nvarchar(255)
SET @txt = '32|foo|foo2|123'

SELECT REVERSE(LEFT(REVERSE(@txt),CHARINDEX('|',REVERSE(@txt))-1))

Output
123

Edit
If your string only has 4 parts or less and . isn't a valid character, you can also use PARSENAME for this.
DECLARE @txt nvarchar(255)
SET @txt = '32|foo|foo2|123'
SELECT PARSENAME(REPLACE(@txt,'|','.'),1)

A: You can reverse your string to get the desired result:
DECLARE @txt nvarchar(255) = '32|foo|foo2|123'
SELECT REVERSE(SUBSTRING(REVERSE(@txt), 1, CHARINDEX('|', REVERSE(@txt)) -1))


text:
Q: wp7 contentpresenter - setting content to the same page I use a page (named containerpage) with a ContentPresenter (named PageContent) and set its content to a PhoneApplicationPage instance (contentpage) in the page's OnNavigatedTo() eventhandler. I also have a mainpage with a button "Show Form". When I click on that button, the program navigates to the containerpage, that sets its contentpresenter's content to the contentpage. My problem is: if I click on "show form", then press the back button and click on "show form" again, I get ArgumentException with the text

"The parameter is incorrect"

on line
this.PageContent.Content = contentpage;

in the containerpage's OnNavigatedTo() eventhandler. I guess this is because I already set another ContentPresenter's Content to this contentpage (because navigating creates a new page), but if this is the problem, how can I unassign my contentpage from the previous ContentPresenter's Content?

A: As decyclone mentioned, your question would be a lot clearer with detailed code.  That said, you might implement OnNavigatedFrom() on your conatinerpage and set the Content to null.
You might want to consider how this design holds up if the app gets tombstoned on containerpage.

A: To be honest, I'm amazed that setting the Content property of one page to be an instance of another page even works! I really would advise against that as a long term solution. If the content of the first page is dynamic based on some condition, then use different UserControls instead.
If the data for the UserControl is not persistent between calls to ShowForm, then you can just create a new instance each time and then you won't have the re-parenting problem.
If you can elaborate on your application scenario and what you are trying to achieve, then we might be able to provide a better answer.


text:
Q: Why does the mass-energy associated with nuclear potentials obey $m = \gamma m_0$? Here is a thought experiment that has me confused.
Imagine a particle, the nonexiston. If possible, ignore quantum mechanics and let the nonexiston be a classical particle with spooky action at a distance.
The nonexiston has a field that exerts huge forces on other nonexistons. The nonexiston field is an inverse square field. An isolated nonexiston has a very tiny rest mass $m_n$, but a pair of nonexistons separated by $r_0$ has a large associated potential of $V = M c^2$ such that their combined mass-energy is $m_0 =M + 2m_n \gg m_n$
We accelerate the pair of nonexistons from $0$ to $v$ while holding their proper length of separation constant and try to predict how much energy we will need. Without assuming a priori that field energy counts as mass, can we prove it will be $(\gamma-1)(m_0)c^2$?
Yes.

*

*The nonexiston field is inverse-square dependent so the separation potential is $V\propto r^{-1}$ dependent.

*Increasing velocity from $0$ to $v$ length-contracts the separation distance by $1/\gamma(v)$

*Therefore increasing velocity from $0$ to $v$ increases the separation energy of the nonexistons, as measured by the original rest frame, by a factor of $(1/\gamma(v))^{-1} = \gamma$.

*$V = \gamma Mc^2$

*$E = V + 2\gamma m_n c^2 = \gamma(M+2m_n)c^2 = \gamma m_0c^2$
So far so good. Relativity is internally consistent if we make the nonexiston field one for which potential goes as $1/r$.
But what if we make the nonexiston potential vary like that of the strong nuclear force?
$V \propto e^{-B r}/r$
Now we should get (for some constants $A$ and $B$)
$E = \gamma(Ae^{-B r_0/\gamma}/r_0 + 2m_n c^2)$
Which is very much not $\gamma m_0c^2$
What's going on? I feel like I must be missing something.

I realized later that I packed a variable (mass) into one of my constants (B). If we assume that that means $B' = \gamma B$ then $V = \gamma V_0$ and $m = \gamma m_0$ for $\vec r \parallel \vec v$, which is just as it should be.

A: Separation distance is parallel to motion:
Increasing velocity from 0 to v length-contracts the separation distance by 1/γ(v)
Increasing velocity from 0 to v multiplies the force that is associated with the potential energy, which is associated with the potential, by 1.  (Because from basic special relativity we know that transformation of forces parallel to motion is: F'=F)
From those two effects we can see that the potential changes by 1/γ(v).
Separation distance is perpendicular to motion:
Increasing velocity from 0 to v length-contracts the separation distance by 1.
Increasing velocity from 0 to v multiplies the force that is associated with the potential energy which is associated with the potential, by 1/γ(v). (Because from basic special relativity we know that transformation of forces perpendicular to motion is: F'=F/γ(v) )
From those two effects we can see that the potential changes by 1/γ(v).
Notice that we did not need to know how the force depends on the distance.

A:
Increasing velocity from 0 to v length-contracts the separation distance by $1/γ(v)$

I think your first error is here. Length contraction only takes place along the dimension parallel to motion.
Suppose your molecule of di-nonexiston is at rest and we accelerate towards it instead. Your length- contraction approach predicts that an observer moving parallel to the inter-nonexiston axis would measure a different effective mass than an observer moving at the same speed in a perpendicular direction. If your molecule is rotating, would a moving observer see its relativistic mass fluctuate?
In electromagnetism, these issues are resolved by coming up with rules for transformation of the electric and magnetic fields under boosts.


text:
Q: ValueError: could not convert string to float: 'Status' To do logistic regression on python, this is my code below:
Imported Dataset:Facebook Metrics
# Load dataset
url = "dataset_Facebook.csv"
dataset1 = pandas.read_csv(url, sep = ";", header = 0)

# Split-out validation dataset
array = dataset1.values
X = array[:,0:4]
Y = array[:,4]
validation_size = 0.20
seed = 7
X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=validation_size, random_state=seed)

# Test options and evaluation metric
seed = 7
scoring = 'accuracy'

# Spot Check Algorithms
models = []
models.append(('LR', LogisticRegression()))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))
models.append(('NB', GaussianNB()))
models.append(('SVM', SVC()))
# evaluate each model in turn
results = []
names = []
for name, model in models:
    kfold = model_selection.KFold(n_splits=10, random_state=seed)
    cv_results = np.log10(model_selection.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring))
    results.append(cv_results)
    names.append(name)
    msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
    print(msg)

When compiling the program, i get these sets of error:
Traceback (most recent call last):
  File "/Users/ernestsoo/Desktop/WESTWORLD (Season 01) DUB 720/Assignment2.JackyTen.ErnestSoo/assignment2.py", line 93, in <module>
    cv_results = np.log10(model_selection.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring))
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/model_selection/_validation.py", line 140, in cross_val_score
    for train, test in cv_iter)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py", line 758, in __call__
    while self.dispatch_one_batch(iterator):
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py", line 608, in dispatch_one_batch
    self._dispatch(tasks)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py", line 571, in _dispatch
    job = self._backend.apply_async(batch, callback=cb)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/externals/joblib/_parallel_backends.py", line 109, in apply_async
    result = ImmediateResult(func)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/externals/joblib/_parallel_backends.py", line 326, in __init__
    self.results = batch()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py", line 131, in __call__
    return [func(*args, **kwargs) for func, args, kwargs in self.items]
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py", line 131, in <listcomp>
    return [func(*args, **kwargs) for func, args, kwargs in self.items]
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/model_selection/_validation.py", line 238, in _fit_and_score
    estimator.fit(X_train, y_train, **fit_params)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/linear_model/logistic.py", line 1173, in fit
    order="C")
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/utils/validation.py", line 521, in check_X_y
    ensure_min_features, warn_on_dtype, estimator)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/utils/validation.py", line 382, in check_array
    array = np.array(array, dtype=dtype, order=order, copy=copy)
ValueError: could not convert string to float: 'Status'

Because it seem like a DataType problem, i tried parsing the value from the dataset to float:
array = float(dataset1.values)

But this is not working.
How can I solve this problem?

A:
ValueError: could not convert string to float: 'Status'

This error means that at some point your code is trying to convert the string 'Status' to float. Casting your data to float won't solve the problem. The problem is that your code is trying to cast something it shouldn't.
If you execute that code: float("Hello") it raise ValueError: could not convert string to float: 'Hello'. Use the error information to debug your code. Try to find where the "Status" string is given where a float is expected.
Hope it will help you to debug your code


text:
Q: How to extract computer/machine SID? I'm looking for a way to extract the computer SID using Delphi code. There's a tool called PsGetSid from SysInternals that does this, but I can't use it in my application. I searched for a code example in Google and couldn't find one.
How can I achieve this in Delphi?
Please help.

A: You can use the Win32_Account WMI class, extracting the  machine SID from an user account SID.
for example for a user account where the SID is
S-1-5-21-1299824301-1797996836-594316699-1009

The Machine SID will be
S-1-5-21-1299824301-1797996836-594316699

Check this sample
program GetWMI_Info;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  ActiveX,
  ComObj,
  Variants;

function  GetComputerSID:string;
const
  WbemUser            ='';
  WbemPassword        ='';
  WbemComputer        ='localhost';
  wbemFlagForwardOnly = $00000020;
var
  FSWbemLocator : OLEVariant;
  FWMIService   : OLEVariant;
  FWbemObjectSet: OLEVariant;
  FWbemObject   : OLEVariant;
  oEnum         : IEnumvariant;
  iValue        : LongWord;
begin;
  FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
  FWMIService   := FSWbemLocator.ConnectServer(WbemComputer, 'root\CIMV2', WbemUser, WbemPassword);
  FWbemObjectSet:= FWMIService.ExecQuery('SELECT SID FROM Win32_Account Where SIDType=1','WQL',wbemFlagForwardOnly);
  oEnum         := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
  if oEnum.Next(1, FWbemObject, iValue) = 0 then
  begin
    Result:=FWbemObject.SID;
    Result:=Copy(Result,1,LastDelimiter('-',Result)-1);
    FWbemObject:=Unassigned;
  end;
end;

begin
 try
    CoInitialize(nil);
    try
      Writeln(GetComputerSID);
    finally
      CoUninitialize;
    end;
 except
    on E:EOleException do
        Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode]));
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;
end.

A: This is a sample using the LookupAccountName WinAPi function as @MikeKwan suggest.
{$APPTYPE CONSOLE}

uses
  Windows,
  SysUtils;

function ConvertSidToStringSid(Sid: PSID; out StringSid: PChar): BOOL; stdcall;  external 'ADVAPI32.DLL' name {$IFDEF UNICODE} 'ConvertSidToStringSidW'{$ELSE} 'ConvertSidToStringSidA'{$ENDIF};

function SIDToString(ASID: PSID): string;
var
  StringSid : PChar;
begin
  if not ConvertSidToStringSid(ASID, StringSid) then
    RaiseLastWin32Error;

  Result := string(StringSid);
end;

function GetLocalComputerName: string;
var
  nSize: DWORD;
begin
  nSize := MAX_COMPUTERNAME_LENGTH + 1;
  SetLength(Result, nSize);
  if not GetComputerName(PChar(Result), {var}nSize) then
  begin
    Result := '';
    Exit;
  end;

  SetLength(Result, nSize);
end;

function GetComputerSID:string;
var
  Sid: PSID;
  cbSid: DWORD;
  cbReferencedDomainName : DWORD;
  ReferencedDomainName: string;
  peUse: SID_NAME_USE;
  Success: BOOL;
  lpSystemName : string;
  lpAccountName: string;
begin
  Sid:=nil;
  try
    lpSystemName:='';
    lpAccountName:=GetLocalComputerName;

    cbSid := 0;
    cbReferencedDomainName := 0;
    // First call to LookupAccountName to get the buffer sizes.
    Success := LookupAccountName(PChar(lpSystemName), PChar(lpAccountName), nil, cbSid, nil, cbReferencedDomainName, peUse);
    if (not Success) and (GetLastError = ERROR_INSUFFICIENT_BUFFER) then
    begin
      SetLength(ReferencedDomainName, cbReferencedDomainName);
      Sid := AllocMem(cbSid);
      // Second call to LookupAccountName to get the SID.
      Success := LookupAccountName(PChar(lpSystemName), PChar(lpAccountName), Sid, cbSid, PChar(ReferencedDomainName), cbReferencedDomainName, peUse);
      if not Success then
      begin
        FreeMem(Sid);
        Sid := nil;
        RaiseLastOSError;
      end
      else
        Result := SIDToString(Sid);
    end
    else
      RaiseLastOSError;
  finally
    if Assigned(Sid) then
     FreeMem(Sid);
  end;
end;

begin
 try
   Writeln(GetComputerSID);
 except
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;
end.

A: You can get it with LookupAccountName. Pass in NULL for the first parameter and the machine name for the second.


text:
Q: Generating html from tabular chat conversation data I have this table of  chat conversation mydf
mydf = structure(list(User = c("Ana", "Ana", "Brian", "Ana", "Brian"), Message = c("Hi",
"How are you?", "Good. You?", "Ok", "What's up?"), Time = structure(c(1512156236.17704,
1512156238.67704, 1512156241.17704, 1512156243.67704, 1512156246.17704
), class = c("POSIXct", "POSIXt"))), .Names = c("User", "Message",
"Time"), row.names = c(NA, -5L), class = "data.frame")

#> mydf
#   User      Message                Time
#1   Ana           Hi 2017-12-01 13:23:56
#2   Ana How are you? 2017-12-01 13:23:58
#3 Brian   Good. You? 2017-12-01 13:24:01
#4   Ana           Ok 2017-12-01 13:24:03
#5 Brian   What's up? 2017-12-01 13:24:06

My goal is to convert this data into conversation format in HTML. I am currently doing it by adding tags to the data and saving it. Then I have to work some more with CSS to make it better. Is there an easier way in R?
#REMOVE REPEATING NAMES
mydf$User = with(rle(mydf$User), unlist(sapply(seq_along(values),
                  function(i) c(rep(values[i], 1), rep("", lengths[i] - 1)))))

#ADD TAGS
mydf$User = ifelse(mydf$User == "", "", paste0("
", mydf$User, "
"))
mydf$Message = paste0("
", mydf$Message, "
")
mydf$Time = paste0("", mydf$Time, "")

#SAVE HTML
writeLines(paste(paste(mydf$User, mydf$Message, mydf$Time), collapse = "\n"),"~/test.html")

A: I am not sure if this satisfies you, but I would go with an approach that extends the data.frame and writes it directly in the file
#REMOVE REPEATING NAMES
mydf$User = with(rle(mydf$User), unlist(sapply(seq_along(values),
              function(i) c(rep(values[i], 1), rep("", lengths[i] - 1)))))

#SAVE HTML
write.table(
    data.frame(
        ifelse(mydf$User!="", "
",""), mydf$User, ifelse(mydf$User!="","
",""),
        "
", mydf$Message, "
",
        "", mydf$Time, ""),
    file = "~/test.html", quote = F, col.names = F, row.names = F )


text:
Q: SAM4N Backup Mode - no wakeup I do have an ATSAM4N and try to go to backup mode as soon as the external power is turned off to keep the RTC time running. Therefore, a battery is added to support VDDIO.
I manage to get the SAM4N in backup mode by activating the supply monitor interupt and
#define SUPC_SMMR_SMTH     (11 << 0)
#define SUPC_SMMR_SMSMPL   (1 << 8)
#define SUPC_SMMR_SIMEN    (1 << 13)

#define SUPC_CR_VROFF    (1 << 2)
#define SUPC_CR_KEY      (0xA5 << 24)

int main()
{
   //...
   SUPC->SUPC_SMMR = SUPC_SMMR_SMTH | SUPC_SMMR_SMSMPL | SUPC_SMMR_SIMEN;
   //...
}

void SUPC_IRQHandler()
{
   SUPC->SUPC_CR = SUPC_CR_VROFF | SUPC_CR_KEY;
}

I figured that this works, because when I cut power, the VDDCORE drops to zero (which is not the case if I comment the line in interrupt).
I thought that waking up the SAM4N by supply monitor would be easy.
Just set the registers right.
#define SUPC_WUMR_SMEN     (1 <<  0)

int main()
{
   //...
   SUPC->SUPC_WUMR = SUPC_WUMR_SMEN;
   //...
}

But when I apply power again, nothing happens.
What did I forget to get the SAM4N restarted again?
Thanks


text:
Q: Navigation Rule/Case problems I created simple dynamic web project using Eclipse Juno, JSF and PrimeFaces (OS Debian). I deployed my application on JBoss AS 7.1 server (standalone). There are free pages: index, add and contact. My navigations rules are: from index to add and contact, from add to index and contact, from contact to index and add. Everythings work well but from add and contact pages I cant go to index. Index page appears only if I refresh webbrowser (Google Chrome). Has someone got the same issue? I searched it but didnt find any solutions. Thanks a lot for any help.
Here are my files:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>excite-bike</param-value>
</context-param>
<display-name>Example2</display-name>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
    <welcome-file>add.xhtml</welcome-file>
    <welcome-file>contact.xhtml</welcome-file>

</welcome-file-list>
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<servlet>
    <description>JAX-RS Tools Generated - Do not modify</description>
    <servlet-name>JAX-RS Servlet</servlet-name>
    <servlet-class></servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>JAX-RS Servlet</servlet-name>
    <url-pattern>/jaxrs/*</url-pattern>
</servlet-mapping>

faces-config.xml:
    <managed-bean>
    <managed-bean-name>addBean</managed-bean-name>
    <managed-bean-class>web.AddBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    <managed-bean>
    <managed-bean-name>menuBean</managed-bean-name>
    <managed-bean-class>web.MenuBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    <navigation-rule>
   <from-view-id>/index.xhtml</from-view-id>
   <navigation-case>
  <from-outcome>add</from-outcome>
  <to-view-id>/add.xhtml</to-view-id>
  </navigation-case>
  <navigation-case>
  <from-outcome>contact</from-outcome>
  <to-view-id>/contact.xhtml</to-view-id>
  </navigation-case>
  </navigation-rule>
  <navigation-rule>
  <from-view-id>/add.xhtml</from-view-id>
  <navigation-case>
  <from-outcome>home</from-outcome>
  <to-view-id>/index.xhtml</to-view-id>
  </navigation-case>
  <navigation-case>
  <from-outcome>contact</from-outcome>
  <to-view-id>/contact.xhtml</to-view-id>
  </navigation-case>
 </navigation-rule>
<navigation-rule>
<from-view-id>/contact.xhtml</from-view-id>
 <navigation-case>
 <from-outcome>add</from-outcome>
 <to-view-id>/add.xhtml</to-view-id>
</navigation-case>
<navigation-case>
 <from-outcome>home</from-outcome>
 <to-view-id>/index.xhtml</to-view-id>
</navigation-case>

MenuBean.java:
package web;
import javax.annotation.ManagedBean;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class MenuBean {
public String home(){return "home";}
public String add(){return "add";}
public String contact(){return "contact";}}
               <br>

code of menu in .xhtml pages:
<h:form>
            <p:tabMenu activeIndex="1">
                <p:menuitem value="HOME" icon="ui-icon-star"
                    action="#{menuBean.home()}" />
                <p:menuitem value="ADDS" icon="ui-icon-document"
                    action="#{menuBean.add()}" />
                <p:menuitem value="CONTACT" icon="ui-icon-person"
                    action="#{menuBean.contact()}" />

            </p:tabMenu>
        </h:form>

A: You'll skip a lot of problems if you use plain links for simple navigation.
The navigation rule mechanism is more useful when used to create flows like a shopping cart, for example. Simple navigation like a menu shouldn't use the navigation rules, just make your menu a list of links, you do not need to create action methods for that.
Also, if you are using the @ManagedBean and @SessionScoped annotations in your bean you do not need to declare it in your faces-config.xml, the annotation is meant to replace the XML configuration. In your case, the faces-config.xml is actually setting up your bean to be RequestScoped.
Related:
When should I use h:outputLink instead of h:commandLink?


text:
Q: SSL issues on a mobile website We are experiencing issues with some mobile devices such as Windows Mobile (not Phone 7) and BlackBerry's not able to go to a SSL website of ours. The errors returned are below on our Windows Server 2008 R2 box. Any help would be much appreciated to get this working. The only workaround is to have the mobile users install Opera/FireFox mini/mobile browsers. However this is not ideal and not the answer I'm looking for.
Note: Using a PC/Mac/Android/iOS device works fine.
Windows Mobile -

*

*Error! Unable to complete secure transaction.

*Secure connection: fatal error (50)

*https://mymobilewebsite.com (not our actual site)

*We've also intermittently seen: "Secure connection: fatal error (10)"

BlackBerry -

*

*Selected Server returned an error when attempting to fulfill your request.

(Note: we did follow the instructions to configure ASP.NET 2.0 for BlackBerry, but still get an error.)
Update 2011-05-25: We've found through testing (only with Windows Mobile) that if we disable 3G and go through WiFi it will connect to the website just fine. The kicker is that when we switch off WiFi and go back to 3G the website works. Again this is only for Windows Mobile.

A: The root certificates on the device are almost certainly out of date, and your SSL Cert is signed by a root CA they don't recognize. I've seen this quite a bit lately as several popular root CAs have expired in the last year or two.

A: If you chucked us a copy of the public cert we might be able to help more but if not as an add to Chris S post I'd just add to be careful of Intermediate certs in the chain.
The full certificate chain must be present and accounted for on the device and a lot of times the Intermediate's are left out.
Also if its just some devices and not others its probably not a problem with the certificate encoding.


text:
Q: EaselJS mouse events not working - debug canvas appears to be catching them I'm building an app in HTML5, using CreateJS (EaselJS), Box2D and written in CoffeeScript using Browserify (built with Gulp).
I've just spent the best part of a half a day beating my head against the keyboard trying to work out why I couldn't get my EaselJS events working. Window/document events were fine. Any and all EaselJS event just did nothing. It turns out the debug canvas was trapping them, overlaying invisibly.
I accidentally discovered this eventually by toggling the debug canvas on and off which allowed the events to get though and they started responding.
So now, my question is: what's the best way to handle events so that they will work
a) without me first toggling the debug canvas, and
b) when debug is active, how can I pass events through to the main canvas below so that it can handle them?
Is that possible? It would be ideal that even with debug draw on, mouseevents worked as normal.
HTML is this:
<body>
  <canvas id="arcade"></canvas>
  <canvas id="debug"></canvas>
    <button id="toggle-debug">Toggle Debug</button>

    <script src="compiled.js"></script>
</body>

My app class sets up events calling bindEvents from its constructor thus:
bindEvents: =>
  # Pause when window is blurred
  window.addEventListener 'blur', @setPaused
  # Play when window is focused
  window.addEventListener 'focus', @setPlay
  # Toggle showing/hiding of the Debug <canvas>
  document.getElementById('toggle-debug').onclick = @toggleDebug

toggleDebug: =>
  @showDebug = !@showDebug
  # Shows/hides Debug canvas
  Universe.debug.canvas.style.display = (if @showDebug then 'block' else 'none')

setPlay: =>
  @play = true
  createjs.Ticker.setPaused false

setPaused: =>
  @play = false
  createjs.Ticker.setPaused true

My objects (which contain box2d body in @body and easelJS display objects in @view) set up their events in a similar method, e.g.
bindEvents: ->
  @view.on "click", () =>  alert("ball #{@options.id} clicked")

A: Unfortunately the DOM does not provide a good way to ignore mouse events on an object, or pass them through. You can however use the Stage.nextStage property.

*

*Create an EaselJS stage, and pass in your debug canvas

*Set the nextStage property on the new Stage to the stage that is below that one.

Here is a quick code sample:
var stage2 = new createjs.Stage("DebugCanvasId");
stage2.nextStage = stage1;

EaselJS 0.7.0 added the nextStage property, but the very latest NEXT version in GitHub vastly improved support for this. There is a demo in GitHub where you can see this working (TwoStages.html). Here is the online sample: http://createjs.com/Demos/EaselJS/TwoStages.html
Cheers.

A: I've solved part a) by changing the html to
<canvas id="debug" style="display: none;"></canvas>

I also tried doing this programmatically in the game (toggling the debug twice) but for some reason it didn't work. I don't know why.
I'd still like to get an answer to B though. How to pass mouse events though the debug canvas to the one below.


text:
Q: Calling preprocessing.scale on a heterogeneous array I have this TypeError as per below, I have checked my df and it all contains numbers only, can this be caused when I converted to numpy array? After the conversion the array has items like
[Timestamp('1993-02-11 00:00:00') 28.1216 28.3374 ...]

Any suggestion how to solve this, please?
df:
    Date      Open      High       Low     Close     Volume
9    1993-02-11   28.1216   28.3374   28.1216   28.2197      19500
10   1993-02-12   28.1804   28.1804   28.0038   28.0038      42500
11   1993-02-16   27.9253   27.9253   27.2581   27.2974     374800
12   1993-02-17   27.2974   27.3366   27.1796   27.2777     210900

X = np.array(df.drop(['High'], 1))
X = preprocessing.scale(X)

TypeError: float() argument must be a string or a number

A: While you're saying that your dataframe "all contains numbers only", you also note that the first column consists of datetime objects. The error is telling you that preprocessing.scale only wants to work with float values.
The real question, however, is what you expect to happen to begin with. preprocessing.scale centers values on the mean and normalizes the variance. This is such that measured quantities are all represented on roughly the same footing. Now, your first column tells you what dates your data correspond to, while the rest of the columns are numeric data themselves. Why would you want to normalize the dates? How would you normalize the dates?
Semantically speaking, I believe you should leave your dates alone. Whatever post-processing you're planning to perform on your numerical data, the normalized data should still be parameterized by the original dates. If you want to process your dates too, you need to come up with an explicit way to handle your dates to something numeric (say, elapsed time from a given date in given units).
So I believe you should drop your dates from your processing round altogether, and start with
X = df.drop(['Date','High'], 1).as_matrix()


text:
Q: Tablespaces not created on oracle dump file import operation I am trying to import a dump into Oracle 11g. I have run this command :
impdp david/coucou@Louis-PC directory=geismar file=EXPDP_TOP.dmp log=EXPDP_TOP.log full=y;

The import process is successfully launched but I get a lot of errors. Here's a subset of my logfile :
Import: Release 11.2.0.2.0 - Production on Dim. Juin 25 12:02:28 2017
Connected to: Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production
;;; Legacy Mode Active due to the following parameters:
;;; Legacy Mode Parameter: "file=EXPDP_TOP.dmp" Location: Command Line, Replaced with: "dumpfile=EXPDP_TOP.dmp"
;;; Legacy Mode Parameter: "log=EXPDP_TOP.log" Location: Command Line, Replaced with: "logfile=EXPDP_TOP.log"
Master table "DAVID"."SYS_IMPORT_FULL_01" successfully loaded/unloaded
Starting "DAVID"."SYS_IMPORT_FULL_01":  david/********@Louis-PC directory=geismar dumpfile=EXPDP_TOP.dmp logfile=EXPDP_TOP.log full=y;
Processing object type SCHEMA_EXPORT/USER
ORA-39083: Object type USER failed to create with error:
ORA-00959: tablespace 'TOPADDIN' does not exist
Failing sql is:
CREATE USER "TOPADDIN" IDENTIFIED BY VALUES 'S:A86A3644C5EA64C9320A5C66457EE39C51888BBD1110001C5776E9D7A554;C4D29EC4F0EAB8DE' DEFAULT TABLESPACE "TOPADDIN" TEMPORARY TABLESPACE "TEMP"
ORA-39083: Object type USER failed to create with error:
ORA-00959: tablespace 'TOPDBA' does not exist
Failing sql is:
CREATE USER "TOPDBA" IDENTIFIED BY VALUES 'S:29F9686B7D8B5861F84CA3D5720C6C8A8CFC8C7D01374D49D77DE152C234;F3A449A6B2BF4CD0' DEFAULT TABLESPACE "TOPDBA" TEMPORARY TABLESPACE "TEMP"
ORA-39083: Object type USER failed to create with error:
ORA-00959: tablespace 'TOPERP' does not exist
Failing sql is:
CREATE USER "TOPERP" IDENTIFIED BY VALUES 'S:3EC63E08F86B4922FE5328678F5E5DDD7A23D6092D539C31492FC97F2FFB;B3B7BBDA73271B0C' DEFAULT TABLESPACE "TOPERP" TEMPORARY TABLESPACE "TEMP"
ORA-39083: Object type USER failed to create with error:
ORA-00959: tablespace 'TOPMAN_USERS' does not exist

It seems that the import does not include the tablespaces' definition and does not create tablespaces.
Shouldnt the option full=y also import tablespace definitions ?
What am I doing wrong ?

A: First you can do
impdp david/coucou@Louis-PC directory=geismar dumpfile=EXPDP_TOP.dmp SQLFILE=check.sql

to see exactly what DDL the import is going to run, by viewing check.sql.
Then test some parameters, for example:
INCLUDE=TABLESPACE:"IN ('TOPADDIN','TOPDBA')"
INCLUDE=SCHEMA:"IN ('TOPADDIN','TOPDBA')"

And possibly some remaps:
remap_schema=
remap_tablespace=


text:
Q: Unable to view image on thumbnail in fine-uploader Hi I am working on upload feature which has been done successfully using fine uploader, but for new functionality for edit i searched for same plugin and found that session can handle this functionality.
but i am not getting view of image in fine uploader section as below is the view i am getting.

I am passing name,uuid and thumbnailUrl as response.
Edited:
At Server Side:
 List<PropertyImageEntity> propertyImageEntity=propertyService.getImagesUrlNames(Integer.parseInt(request.getParameter("id")),Constant.PROP_VAL);
       for(PropertyImageEntity propertyImagesDetails: propertyImageEntity)
         {
            ImageDataResponse imageResponseData=new ImageDataResponse();
            imageResponseData.setName(propertyImagesDetails.getFilename());
            String test=String.valueOf(UUID.randomUUID());
            imageResponseData.setUuid(this.uuid);
            imageResponseData.setId(String.valueOf(propertyImagesDetails.getImageid()));
            imageResponseData.setSize(propertyImagesDetails.getSize());
            imageResponseData.setStatus("upload successful");
            imageResponseData.setThumbnailUrl(propertyImagesDetails.getUrl());
            imageResponse.add(imageResponseData);
         }

at client side:
var manualUploader1 = new qq.FineUploader(
        {
            element : document
                    .getElementById('fine-uploader-manual-trigger1'),
            template : 'qq-template-manual-trigger1',
            request : {
                endpoint : '/server/uploads?${_csrf.parameterName}=${_csrf.token}&id=${id}'
            },
            thumbnails : {
                placeholders : {
                    waitingPath : '../assets/js/property/fileupload/placeholders/waiting-generic.png',
                    notAvailablePath : '../assets/js/property/fileupload/placeholders/not_available-generic.png'
                }
            },
            validation : {
                allowedExtensions : [ 'png', 'jpeg', 'jpg' , 'gif'],
                itemLimit : 6,
                sizeLimit : 100000000
            },
            autoUpload : false,
            debug : true,
            callbacks: {
                onError: function(id, name, errorReason, xhrOrXdr) {

                        $("#errorMsg4").html(errorReason);
                }
            },
            session: {
                endpoint: '/server/get?id=${id}',
                params: {},
                customHeaders: {},
                refreshOnReset: true
            },
            messages: {
                typeError: jQuery.i18n.prop("invalid.extention.error"),
                sizeError: jQuery.i18n.prop("upload.filesize.error"),
                noFilesError: jQuery.i18n.prop("nofiles.toupload.error"),
                tooManyItemsError: jQuery.i18n.prop("toomany.items.error"),
                retryFailTooManyItems: jQuery.i18n.prop("retry.fail.error")
            }
        });

qq(document.getElementById("trigger-upload1")).attach("click",
        function() {
        $("#errorMsg4").html("");
            manualUploader1.uploadStoredFiles();
        });

but response for image url in console showing 200 ok.
Response:
[{"name":"b.png","uuid":"e3a5581e-aee9-4b8d-813f-63e0d400c9bc","thumbnailUrl":"http://192.168.1.68/html/1465290007617b.png","id":"84","size":26507,"status"
:null}]

Console Log:

A: The above problem was solved by adding cors headers in apache2.conf.
Header set Access-Control-Allow-Origin "*"

Thanks to @Ray for his answer on this post.


text:
Q: malformedXML: Index or size is negative or greater than the allowed amount I use JSF 2.0 and Twitter Bootstrap.
I am trying to change a value in field after an ajax request. However, I get a malformedXML error when I change value and inputText lost focus. The xhtml file looks like :
<h:inputText value="#{product.count}>
    <f:ajax listener="#{orderBean.changeTotal} render="outputTotal" />
    <f:attribute name="productId" value="#{product.id}" />
</h:inputText>

.....

<h:outputText id="outputTotal" value="#{product.total}" />

.....

And the OrderBean have a code:
public void changeTotal(AjaxBehaviorEvent event) {

    Integer id = (Integer) event.getComponent().getAttributes().get("productId");
        for (FoProduct pio : fo_orderList) {

            if (pio.getId() == id) {

                pio.setTotal(pio.getCount() * pio.getPrice());

            }

        }
}

Result: total value is changed, and JSF show me message "mallformedXML: Index or size is negative or greater than the allowed amount"
P.S.: More xhtml for Hector William:
<ui:repeat value="#{orderBean.fo_orderList}" var="product">
<h:form>

                Count:

                    <h:inputText class="input-sm" value="#{product.count}" >
                      <f:ajax listener="#{orderBean.changeTotal}" render="outputTotal"/>
                        <f:attribute name="productId" value="#{product.id}" />
                    </h:inputText>

                <h:outputLabel value="Price:" />

                    <h:outputText value="#{product.price}" />

               <h:outputLabel value="Total:" />

                    <h:outputText id="outputTotal" value="#{product.total}" />

</h:form>
</ui:repeat>


text:
Q: Custom 'Precision at k' scoring object in sklearn for GridSearchCV I am currently trying to tune hyperparameters using GridSearchCV in scikit-learn using a 'Precision at k' scoring metric which will give me precision if I classify the top kth percentile of my classifier's score as the positive class. I know it is possible to create a custom scorer using make_scorer and creating a score function. This is what I have now:
from sklearn import metrics
from sklearn.grid_search import GridSearchCV
from sklearn.linear_model import LogisticRegression

def precision_at_k(y_true, y_score, k):
    df = pd.DataFrame({'true': y_true, 'score': y_score}).sort('score')
    threshold = df.iloc[int(k*len(df)),1]
    y_pred = pd.Series([1 if i >= threshold else 0 for i in df['score']])
    return metrics.precision_score(y_true, y_pred)

custom_scorer = metrics.make_scorer(precision_at_k, needs_proba=True, k=0.1)

X = np.random.randn(100, 10)
Y = np.random.binomial(1, 0.3, 100)

train_index = range(0, 70)
test_index = range(70, 100)
train_x = X[train_index]
train_Y = Y[train_index]
test_x = X[test_index]
test_Y = Y[test_index]

clf = LogisticRegression()
params = {'C': [0.01, 0.1, 1, 10]}
clf_gs = GridSearchCV(clf, params, scoring=custom_scorer)
clf_gs.fit(train_x, train_Y)

However, attempting to call fit gives me Exception: Data must be 1-dimensional and I'm not sure why. Can anyone help? Thanks in advance.

A: Arguments for pd.DataFrame should be 'list' not 'numpy.arrays'
So, just try converting y_true to python list...
df = pd.DataFrame({'true': y_true.tolist(), 'score': y_score.tolist()}).sort('score')


text:
Q: Compile error with pointer to template function in Visual Studio 2008 I'm trying to create a template class that stores a function pointer to a template function, but ran into a compile error in Visual Studio 2008.  I created a simplified test case for it(see below) which still fails to compile in VS2008, but appeared to compile successfully on the online Comeau and online GCC compilers I tried.
The error I'm seeing is:
error C2436: 'func' : member function or nested class in constructor initializer list
temp.cpp(21) : while compiling class template member function 'test_class<T>::test_class(T (__cdecl &))'
1>        with
1>        [
1>            T=int (const int &)
1>        ]

The same test using a non-template function works.  Short of that, does anyone know a workaround for the issue, or if VS2008 is expecting some kind of different syntax for this?
Thanks,
Jerry
template<class T>
T template_function(const T& arg)
{
    return arg;
}

int non_template_function(const int& arg)
{
    return arg;
}

template<class T>
class test_class
{
public:
    test_class(const T& arg) : func(arg) {}
private:
    T func;
};

template<class T>
void create_class(const T& arg)
{
new test_class<T>(arg);
}

int main()
{
    create_class(&template_function<int>); //compile fails unless this is commented out
    create_class(&non_template_function);
    return 0;
}

A: Fix at two places;
T* func; //make this pointer type!

and,
 create_class(template_function<int>); //remove '&'
 create_class(non_template_function); //remove '&'

Done!

A: It seems like a compiler bug because it actually thinks that you are trying to invoke that function instead of initializing.
I don't have VS C++ compiler, but declaring T as a pointer may work around the problem:
template<class T>
class test_class
{
public:
    test_class(const T& arg) :
        func(&arg)
    {
    }

private:
    T *func;
};

template<class T>
void create_class(const T& arg)
{
    new test_class<T>(arg);
}

int main()
{
    create_class(template_function<int>); //compile fails unless this is commented out
    create_class(non_template_function);
}

A: It looks to me like the "const T& arg" in test_class and create_class are your problem. Changing those to a simple "T arg" seems to smooth things out.


text:
Q: Colocar Variável dentro do FormData Como eu posso colocar uma variável em jquery dentro do FormData?
Exemplo:
Eu tenho um CKEDITOR, porém não estou conseguindo salvar no banco de dados, mais estou utilizando o formato de envio com ajax, que eu encontrei em um site, para fazer upload de imagens, e essa forma, utiliza o FormData, porém eu não sei como fazer para os dados do CKEDITOR, serem cadastrados no banco de dados.
Segue o código:
$(function () {
    $("#load").hide();
    var enviando_formulario = false;
    $('#form-post').submit(function (e) {
        e.preventDefault();
        var post_content = CKEDITOR.instances['post_content'].getData();
        var obj = this;

        var form = $(obj);
        console.log(obj);

        var submit_btn = $('#form-post :submit');
        var submit_btn_text = submit_btn.val();
        var dados = new FormData(obj);

        console.log(dados);

        function volta_submit() {

            submit_btn.removeAttr('disabled');
            submit_btn.val(submit_btn_text);
            enviando_formulario = false;
        }

        if (!enviando_formulario) {

            $.ajax({
                beforeSend: function () {
                    enviando_formulario = true;
                    submit_btn.attr('disabled', true);
                    submit_btn.val('Enviando...');

                    $("#load").show();
                    $('.error').remove();
                },
                url: form.attr('action'),
                type: form.attr('method'),
                data: dados,
                processData: false,
                cache: false,
                contentType: false,
                success: function (data) {
                    $('.info').remove();
                    volta_submit();
                    if (data > 0) {
                        $('#load').hide();
                        $('#form-grupo input').val("");
                        $('#form-grupo textarea').val("");

                    } else {
                        submit_btn.before('
' + data + '
');
                    }
                    $('.suc').remove();
                },

                error: function (request, status, error) {
                    volta_submit();
                    alert(request.responseText);
                }
            });
        }

        return false;

    });
});

A: Bom pessoal, depois de furçar o Google aqui, acabei encontrando a solução neste link:
https://developer.mozilla.org/pt-BR/docs/Web/API/FormData/set
Está aí para quem estiver com o mesmo problema futuramente.


text:
Q: Firebase - Firestore data structure I need help best approach how to structure collection and documents.
What I am wanting to achieve is simple in a traditional sql query.
I have collection of cards, each card with a id.
I have a collection of users that earn cards and store the card id.
I want to filter a user cards.
Traditional sql
SELECT cards.cardID, cards.CardName, cards.CardDescription, myCards.uid
FROM cards
INNER JOIN myCards ON cards.cardID = myCards.cardID
WHERE (((myCards.uid)=1));

I know it not done like this.

A: There is no concept of a server-side join in Cloud Firestore (nor in many other NoSQL databases).
If you need data from two collections, you'll need (at least) two read operations.
Alternatively, you can duplicate data from myCards into the relevant documents in the cards collection. In that case you stored duplicate data, but need fewer read operations. You're trading off the scalability of your read operations, for more complex (and less scaleable) write operations.
Which of these approaches you prefer depends largely on your experience level with NoSQL databases. Neither is always better than the other. To get more comfortable with these considerations, I recommend reading NoSQL data modeling, watching Firebase for SQL developers, and Get to know Cloud Firestore.