text:
Q: How to implement a Thread Safe HashTable (PhoneBook) Data Structure in Swift? I am trying to implement a Thread-Safe PhoneBook object. The phone book should be able to add a person, and look up a person based on their name and phoneNumber. From an implementation perspective this simply involves two hash tables, one associating name -> Person and another associating phone# -> Person.
The caveat is I want this object to be threadSafe. This means I would like to be able to support concurrent lookups in the PhoneBook while ensuring only one thread can add a Person to the PhoneBook at a time. This is the basic reader-writers problem, and I am trying to solve this using GrandCentralDispatch and dispatch barriers. I am struggling to solve this though as I am running into issues.. Below is my Swift playground code:
//: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

public class Person: CustomStringConvertible {
    public var description: String {
        get {
            return "Person: \(name), \(phoneNumber)"
        }
    }

    public var name: String
    public var phoneNumber: String
    private var readLock = ReaderWriterLock()

    public init(name: String, phoneNumber: String) {
        self.name = name
        self.phoneNumber = phoneNumber
    }

    public func uniquePerson() -> Person {
        let randomID = UUID().uuidString
        return Person(name: randomID, phoneNumber: randomID)
    }
}

public enum Qos {
    case threadSafe, none
}

public class PhoneBook {

    private var qualityOfService: Qos = .none
    public var nameToPersonMap = [String: Person]()
    public var phoneNumberToPersonMap = [String: Person]()
    private var readWriteLock = ReaderWriterLock()

    public init(_ qos: Qos) {
        self.qualityOfService = qos
    }

    public func personByName(_ name: String) -> Person? {
        var person: Person? = nil
        if qualityOfService == .threadSafe {
            readWriteLock.concurrentlyRead { [weak self] in
                guard let strongSelf = self else { return }
                person = strongSelf.nameToPersonMap[name]
            }
        } else {
            person = nameToPersonMap[name]
        }

        return person
    }

    public func personByPhoneNumber( _ phoneNumber: String) -> Person? {
        var person: Person? = nil
        if qualityOfService == .threadSafe {
            readWriteLock.concurrentlyRead { [weak self] in
                guard let strongSelf = self else { return }
                person = strongSelf.phoneNumberToPersonMap[phoneNumber]
            }
        } else {
            person = phoneNumberToPersonMap[phoneNumber]
        }

        return person
    }

    public func addPerson(_ person: Person) {
        if qualityOfService == .threadSafe {
            readWriteLock.exclusivelyWrite { [weak self] in
                guard let strongSelf = self else { return }
                strongSelf.nameToPersonMap[person.name] = person
                strongSelf.phoneNumberToPersonMap[person.phoneNumber] = person
            }
        } else {
            nameToPersonMap[person.name] = person
            phoneNumberToPersonMap[person.phoneNumber] = person
        }
    }

}

// A ReaderWriterLock implemented using GCD and OS Barriers.
public class ReaderWriterLock {

    private let concurrentQueue = DispatchQueue(label: "com.ReaderWriterLock.Queue", attributes: DispatchQueue.Attributes.concurrent)
    private var writeClosure: (() -> Void)!

    public func concurrentlyRead(_ readClosure: (() -> Void)) {
        concurrentQueue.sync {
            readClosure()
        }
    }

    public func exclusivelyWrite(_ writeClosure: @escaping (() -> Void)) {
        self.writeClosure = writeClosure
        concurrentQueue.async(flags: .barrier) { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.writeClosure()
        }
    }

}

// MARK: Testing the synchronization and thread-safety

for _ in 0..<5 {
    let iterations = 1000
    let phoneBook = PhoneBook(.none)

    let concurrentTestQueue = DispatchQueue(label: "com.PhoneBookTest.Queue", attributes: DispatchQueue.Attributes.concurrent)
    for _ in 0..<iterations {
        let person = Person(name: "", phoneNumber: "").uniquePerson()
        concurrentTestQueue.async {
            phoneBook.addPerson(person)
        }
    }

    sleep(10)
    print(phoneBook.nameToPersonMap.count)
}

To test my code I run 1000 concurrent threads that simply add a new Person to the PhoneBook. Each Person is unique so after the 1000 threads complete I am expecting the PhoneBook to contain a count of 1000. Everytime I perform a write I perform a dispatch_barrier call, update the hash tables, and return. To my knowledge this is all we need to do; however, after repeated runs of the 1000 threads I get the number of entries in the PhoneBook to be inconsistent and all over the place:
Phone Book Entries: 856
Phone Book Entries: 901
Phone Book Entries: 876
Phone Book Entries: 902
Phone Book Entries: 912

Can anyone please help me figure out what is going on? Is there something wrong with my locking code or even worse something wrong with how my test is constructed? I am very new to this multi-threaded problem space, thanks!

A: The problem is your ReaderWriterLock. You are saving the writeClosure as a property, and then asynchronously dispatching a closure that calls that saved property. But if another exclusiveWrite came in during the intervening period of time, your writeClosure property would be replaced with the new closure.
In this case, it means that you can be adding the same Person multiple times. And because you're using a dictionary, those duplicates have the same key, and therefore don't result in you're seeing all 1000 entries.
You can actually simplify ReaderWriterLock, completely eliminating that property. I'd also make concurrentRead a generic, returning the value (just like sync does), and rethrowing any errors (if any).
public class ReaderWriterLock {
    private let queue = DispatchQueue(label: "com.domain.app.rwLock", attributes: .concurrent)

    public func concurrentlyRead<T>(_ block: (() throws -> T)) rethrows -> T {
        return try queue.sync {
            try block()
        }
    }

    public func exclusivelyWrite(_ block: @escaping (() -> Void)) {
        queue.async(flags: .barrier) {
            block()
        }
    }
}

A couple of other, unrelated observations:

*

*By the way, this simplified ReaderWriterLock happens to solves another concern. That writeClosure property, which we've now removed, could have easily introduced a strong reference cycle.
Yes, you were scrupulous about using [weak self], so there wasn't any strong reference cycle, but it was possible. I would advise that wherever you employ a closure property, that you set that closure property to nil when you're done with it, so any strong references that closure may have accidentally entailed will be resolved. That way a persistent strong reference cycle is never possible. (Plus, the closure itself and any local variables or other external references it has will be resolved.)

*You're sleeping for 10 seconds. That should be more than enough, but I'd advise against just adding random sleep calls (because you never can be 100% sure). Fortunately, you have a concurrent queue, so you can use that:
concurrentTestQueue.async(flags: .barrier) {
    print(phoneBook.count)
}

Because of that barrier, it will wait until everything else you put on that queue is done.

*Note, I did not just print nameToPersonMap.count. This array has been carefully synchronized within PhoneBook, so you can't just let random, external classes access it directly without synchronization.
Whenever you have some property which you're synchronizing internally, it should be private and then create a thread-safe function/variable to retrieve whatever you need:
public class PhoneBook {

    private var nameToPersonMap = [String: Person]()
    private var phoneNumberToPersonMap = [String: Person]()

    ...

    var count: Int {
        return readWriteLock.concurrentlyRead {
            nameToPersonMap.count
        }
    }
}

*You say you're testing thread safety, but then created PhoneBook with .none option (achieving no thread-safety). In that scenario, I'd expect problems. You have to create your PhoneBook with the .threadSafe option.

*You have a number of strongSelf patterns. That's rather unswifty. It is generally not needed in Swift as you can use [weak self] and then just do optional chaining.
Pulling all of this together, here is my final playground:
PlaygroundPage.current.needsIndefiniteExecution = true

public class Person {
    public let name: String
    public let phoneNumber: String

    public init(name: String, phoneNumber: String) {
        self.name = name
        self.phoneNumber = phoneNumber
    }

    public static func uniquePerson() -> Person {
        let randomID = UUID().uuidString
        return Person(name: randomID, phoneNumber: randomID)
    }
}

extension Person: CustomStringConvertible {
    public var description: String {
        return "Person: \(name), \(phoneNumber)"
    }
}

public enum ThreadSafety { // Changed the name from Qos, because this has nothing to do with quality of service, but is just a question of thread safety
    case threadSafe, none
}

public class PhoneBook {

    private var threadSafety: ThreadSafety
    private var nameToPersonMap = [String: Person]()        // if you're synchronizing these, you really shouldn't expose them to the public
    private var phoneNumberToPersonMap = [String: Person]() // if you're synchronizing these, you really shouldn't expose them to the public
    private var readWriteLock = ReaderWriterLock()

    public init(_ threadSafety: ThreadSafety) {
        self.threadSafety = threadSafety
    }

    public func personByName(_ name: String) -> Person? {
        if threadSafety == .threadSafe {
            return readWriteLock.concurrentlyRead { [weak self] in
                self?.nameToPersonMap[name]
            }
        } else {
            return nameToPersonMap[name]
        }
    }

    public func personByPhoneNumber(_ phoneNumber: String) -> Person? {
        if threadSafety == .threadSafe {
            return readWriteLock.concurrentlyRead { [weak self] in
                self?.phoneNumberToPersonMap[phoneNumber]
            }
        } else {
            return phoneNumberToPersonMap[phoneNumber]
        }
    }

    public func addPerson(_ person: Person) {
        if threadSafety == .threadSafe {
            readWriteLock.exclusivelyWrite { [weak self] in
                self?.nameToPersonMap[person.name] = person
                self?.phoneNumberToPersonMap[person.phoneNumber] = person
            }
        } else {
            nameToPersonMap[person.name] = person
            phoneNumberToPersonMap[person.phoneNumber] = person
        }
    }

    var count: Int {
        return readWriteLock.concurrentlyRead {
            nameToPersonMap.count
        }
    }
}

// A ReaderWriterLock implemented using GCD concurrent queue and barriers.

public class ReaderWriterLock {
    private let queue = DispatchQueue(label: "com.domain.app.rwLock", attributes: .concurrent)

    public func concurrentlyRead<T>(_ block: (() throws -> T)) rethrows -> T {
        return try queue.sync {
            try block()
        }
    }

    public func exclusivelyWrite(_ block: @escaping (() -> Void)) {
        queue.async(flags: .barrier) {
            block()
        }
    }
}

for _ in 0 ..< 5 {
    let iterations = 1000
    let phoneBook = PhoneBook(.threadSafe)

    let concurrentTestQueue = DispatchQueue(label: "com.PhoneBookTest.Queue", attributes: .concurrent)
    for _ in 0..<iterations {
        let person = Person.uniquePerson()
        concurrentTestQueue.async {
            phoneBook.addPerson(person)
        }
    }

    concurrentTestQueue.async(flags: .barrier) {
        print(phoneBook.count)
    }
}

Personally, I'd be inclined to take it a step further and

*

*move the synchronization into a generic class; and

*change the model to be an array of Person object, so that:

*

*The model supports multiple people with the same or phone number; and

*You can use value types if you want.

For example:
public struct Person {
    public let name: String
    public let phoneNumber: String

    public static func uniquePerson() -> Person {
        return Person(name: UUID().uuidString, phoneNumber: UUID().uuidString)
    }
}

public struct PhoneBook {

    private var synchronizedPeople = Synchronized([Person]())

    public func people(name: String? = nil, phone: String? = nil) -> [Person]? {
        return synchronizedPeople.value.filter {
            (name == nil || $0.name == name) && (phone == nil || $0.phoneNumber == phone)
        }
    }

    public func append(_ person: Person) {
        synchronizedPeople.writer { people in
            people.append(person)
        }
    }

    public var count: Int {
        return synchronizedPeople.reader { $0.count }
    }
}

/// A structure to provide thread-safe access to some underlying object using reader-writer pattern.

public class Synchronized<T> {
    /// Private value. Use `public` `value` computed property (or `reader` and `writer` methods)
    /// for safe, thread-safe access to this underlying value.

    private var _value: T

    /// Private reader-write synchronization queue

    private let queue = DispatchQueue(label: Bundle.main.bundleIdentifier! + ".synchronized", qos: .default, attributes: .concurrent)

    /// Create `Synchronized` object
    ///
    /// - Parameter value: The initial value to be synchronized.

    public init(_ value: T) {
        _value = value
    }

    /// A threadsafe variable to set and get the underlying object, as a convenience when higher level synchronization is not needed

    public var value: T {
        get { reader { $0 } }
        set { writer { $0 = newValue } }
    }

    /// A "reader" method to allow thread-safe, read-only concurrent access to the underlying object.
    ///
    /// - Warning: If the underlying object is a reference type, you are responsible for making sure you
    ///            do not mutating anything. If you stick with value types (`struct` or primitive types),
    ///            this will be enforced for you.

    public func reader<U>(_ block: (T) throws -> U) rethrows -> U {
        return try queue.sync { try block(_value) }
    }

    /// A "writer" method to allow thread-safe write with barrier to the underlying object

    func writer(_ block: @escaping (inout T) -> Void) {
        queue.async(flags: .barrier) {
            block(&self._value)
        }
    }
}

A: In some cases you use might NSCache class. The documentation claims that it's thread safe:

You can add, remove, and query items in the cache from different threads without having to lock the cache yourself.

Here is an article that describes quite useful tricks related to NSCache

A: I don't think you are using it wrong :).
The original (on macos) generates:
0  swift                    0x000000010c9c536a PrintStackTraceSignalHandler(void*) + 42
1  swift                    0x000000010c9c47a6 SignalHandler(int) + 662
2  libsystem_platform.dylib 0x00007fffbbdadb3a _sigtramp + 26
3  libsystem_platform.dylib 000000000000000000 _sigtramp + 1143284960
4  libswiftCore.dylib       0x0000000112696944 _T0SSwcp + 36
5  libswiftCore.dylib       0x000000011245fa92 _T0s24_VariantDictionaryBufferO018ensureUniqueNativeC0Sb11reallocated_Sb15capacityChangedtSiF + 1634
6  libswiftCore.dylib       0x0000000112461fd2 _T0s24_VariantDictionaryBufferO17nativeUpdateValueq_Sgq__x6forKeytF + 1074

If you remove the '.concurrent' from your ReaderWriter queue, "the problem disappears".©
If you restore the .concurrent, but change the async invocation in the writer side to be sync:
swift(10504,0x70000896f000) malloc: *** error for object 0x7fcaa440cee8: incorrect checksum for freed object - object was probably modified after being freed.
Which would be a bit astonishing if it weren't swift?
I dug in, replaced your 'string' based array with an Int one by interposing a hash function, replaced the sleep(10) with a barrier dispatch to flush any laggardly blocks through, and that made it more reproducibly crash with the somewhat more helpful:
x(10534,0x700000f01000) malloc: *** error for object 0x7f8c9ee00008: incorrect checksum for freed object - object was probably modified after being freed.
But when a search of the source revealed no malloc or free, perhaps the stack dump is more useful.
Anyways, best way to solve your problem:  use go instead; it actually makes sense.


text:
Q: numbers and words not numbers to words js I have a simple code gotten from the internet and it did not answer what I really wanted as output. I have two input fields; one for the input and another for the output and they are processed through this function:
<script type="text/javascript">
function AnEventHasOccurred() {
    var x = document.getElementById("onkeyup").value
    if (x >= "100") {
        document.getElementById("eventlog").value = "" +
        return x = ['Generalities'];
    }
}
</script>

What I'm really needing is that when I enter numbers below 100, output must be Generalities. I haven't got it correctly. And I went here to ask some help. Thanks.

A: You're never outputting your value back into the output field. All you're doing is returning the value. You need to set the value of your output field to "Generalities".
 Example
var input = document.getElementById("onkeyup").value;
// You should be giving your elements meaningful IDs.

if(+input < 100) {
    document.getElementById("output").value = 'Generalities';
    // Assumes an output field called "output".
}

A: Try this:
function AnEventHasOccurred() {

        var x = document.getElementById("onkeyup").value;

        if (x < 100){
           document.getElementById("eventlog").value = "Generalities";
         }

  }

A: I see a few errors.  Check this out for comparison:
function AnEventHasOccurred() {
    // should probably save the elements to variables
    // since you'll be checking and changing the values
    var x = document.getElementById("onkeyup");
    var y = document.getElementById("eventlog");
    // should be 100, not "100"
    if (x.value < 100) {
        y.value = "Generalities";
    } else {
        y.value = "";
    }
}

This should work fine.  Check it out on jsfiddle.
More Recommendations

*

*Your return statement doesn't correspond with your "output": it
does nothing valuable in this case.

*You check or set the value of an input by getting the element and
using its value key.

*You should put semi-colons at the end of most javascript lines, with the exceptions generally being curly brackets {}, comments // and /* */, and empty lines.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Powershell Remoting: using imported module cmdlets in a remote pssession Is there a way to use modules that were imported in a local session in a remote session? I looked at import-pssession, but I don't know how to get the local session. Here's a sample of what I want to do.
import-module .\MyModule\MyModule.ps1
$session = new-pssession -computerName RemoteComputer
invoke-command -session $session -scriptblock { Use-CmdletFromMyModule }

Also, I do not want to import-module in the remote session, as the ps1 files are not on that server.

A: As an alternate to what Jonathan mentions, if you have source modules you want to push over the wire, then you can do that without too much trouble.  If you have binaries, you might be able to do something similar.but I'd say all bets are off there.  Essentially you push the files over as params in a hash, write to temp, then import.
function Export-SourceModulesToSession
{
    Param(
     [Management.Automation.Runspaces.PSSession]
     [ValidateNotNull()]
     $Session,

    [IO.FileInfo[]]
    [ValidateNotNull()]
    [ValidateScript(
    {
      (Test-Path $_) -and (!$_.PSIsContainer) -and ($_.Extension -eq '.psm1')
    })]
   $ModulePaths
  )

   $remoteModuleImportScript = {
     Param($Modules)

     Write-Host "Writing $($Modules.Count) modules to temporary disk location"

     $Modules |
       % {
         $path = ([IO.Path]::GetTempFileName()  + '.psm1')
         $_.Contents | Out-File -FilePath $path -Force
         "Importing module [$($_.Name)] from [$path]"
         Import-Module $path
       }
   }

  $modules = $ModulePaths | % { @{Name = $_.Name; Contents = Get-Content $_ } }
  $params = @{
    Session = $Session;
    ScriptBlock = $remoteModuleImportScript;
    Argumentlist = @(,$modules);
  }

  Invoke-Command @params
}

Call like
$session = New-PSSession -ComputerName Foo
Export-SourceModulesToSession $session -ModulePaths '.\module.psm1','.\module2.psm1'

Also theoretically possible, exporting a current localhost session to module and pushing that over the wire -- untested pseudo-code.  This might not work...
$localSession = New-PSSession #defaults to localhost

# if you don't have modules automatically loading in the profile, etc, then manually load them
Invoke-Command -Computer $localSession -ScriptBlock { Import-Module 'foo'; Import-Module '.\module.ps1' }
Export-PSSession $localSession -OutputModule TempLocalModule
#now that you have TempLocalModule written out, it's possible you can send that thing across the wire in the same way

A: in case this helps:
if you can switch to PowerShell 3.0, then
the Get-Module and Import-Module cmdlets support modules on remote computers:
http://technet.microsoft.com/en-us/library/hh857339.aspx#BKMK_REM
It should be possible to run PowerShell on remote computer, that performs Import-Module,
without having any ps1 scripts on the remote computer.

A: So I was looking for something similar... In my case I just needed to export a single function to a remote session... this is what I came up with. Maybe you could loop over it to try it. It doesn't work with internal commands, but it does work on functions in custom modules (in the testing I've done).
function Export-FunctionToSession
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param
    (
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        $Session,
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        $FunctionName
    )
    $script = "Function $functionName(){" + (Get-Command $functionName).definition + '}'
    $scriptBlock = {Invoke-Expression $using:script}
    Invoke-Command -Session $session -ScriptBlock $scriptBlock
}

A: I ended up hacking this to work. What I did was create a local session, import modules into that session and used import-pssession to import modules from the created local session into the remote session. This is slow. If anyone has a better way of doing this, or if someone knows how to get an instance of the base session I'd love to hear from you!
Remoting.psm1
function Export-ModuleToSession {
 Param(
  [ValidateNotNull()]
  $session,
  [ValidateNotNull()]
  $modules
 )

 $computername = $env:computername

 $modulesToImport = get-module -name $modules

 invoke-command -session $session -argumentlist @($computername, $modulesToImport) -scriptblock {
  Param(
   $computername,
   $modules
  )

  write-host ("Creating Temp Session On: " + $computername)

  $localSession = New-psSession -computername $computername

  $modules | foreach-object {
   if($_.ModuleType -ne "Binary") {
    $path = $_.path
   }
   else {
    $path = join-path (split-path $_.Path) ("{0}.psd1" -f $_.name)
   }

   invoke-command -session $localSession -argumentList $path -scriptblock {
    Param(
     $path
    )

    $initializeDefaultBTSDrive = $false
    set-executionpolicy unrestricted

    write-host ("Importing Module To Temp Session: " + $path)
    import-module $path
   }
  }

  $initializeDefaultBTSDrive = $false

  $modules | foreach-object {
   write-host ("Exporting Module: " + $_.name)
   import-psSession -session $localSession -Module $_.name  | out-null
  }
 }
}

MyModule.psm1
function MyCmdlet {}

RemotingTest.ps1
import-module .\remoting.psm1
import-module .\MyModule.psm1

try
{
 $remoteSession = New-PsSession -computerName "RemoteComputer"
 Export-ModuleToSession -session $remoteSession -modules "MyModule"

 Invoke-Command -session $remoteSession -scriptblock { MyCmdlet } -verbose -ea Stop
}
finally
{
 Remove-PsSession $remoteSession -ea Continue
 Remove-Module "Remoting" -ea Continue
 Remove-Module "MyModule" -ea Continue
}

A: I don't believe you can.  You can go the other way - import commands loaded on the remote machine into your remote session running on the local machine. You can specify a script to invoke-command and it will copy that script over to the remote machine and run it.  But if you require snapins or additional modules, you will need to make sure those are installed on each remote machine and then load them into the remote session via commands or your script.

A: I would suggest something like:
$rs = New-PSSession -ComputerName "RemoteComputer"
Invoke-Command -Session $rs -scriptblock {import-module ActiveDirectory}
Import-PSSession -Session $rs -Module ActiveDirectory

Since then, you can use ActiveDirectory cmdlets in your session.
Hope this helps.

A: use credssp authentication
invoke-command -computername $localSession -Credential $Credential -Authentication Credssp


text:
Q: Partial fractions of $\frac{x^4}{(x^2-1)^3}$ (is it possible to find coefficients without expanding?) I want to decompose the fraction $\frac{x^4}{(x^2-1)^3}$ :
$$\frac{x^4}{(x^2-1)^3}=\frac A{x-1}+\frac B{(x-1)^2}+\frac C{(x-1)^3}+\frac D{x+1}+\frac E{(x+1)^2}+\frac F{(x+1)^3}$$
Because $f(x)=\frac{x^4}{(x^2-1)^3}$ is an even function we have $f(x)=f(-x)$. Hence we have $A=-D\;,\;B=E\;,\;C=-F$ :
$$\frac{x^4}{(x^2-1)^3}=\frac A{x-1}+\frac B{(x-1)^2}+\frac C{(x-1)^3}+\frac {-A}{x+1}+\frac B{(x+1)^2}+\frac {-C}{(x+1)^3}$$
Hence:
$$A(x-1)^2(x+1)^3+B(x-1)(x+1)^3+C(x+1)^3-A(x+1)^2(x-1)^3+B(x+1)(x-1)^3-C(x-1)^3=x^4$$
If we plug in $x=1$ we get $C=\frac18$. but I can't find $A$ and $B$ without expanding $(x-1)^2(x+1)^3\ldots$ is it possible to find them without expanding whole expression?

A: Following my comments, we may try two simple values of $x$ to reduce computations. Here I believe $x=0$ and $x=2$ are simple enough.
Plugging in $x=0$ gives $$A-B+C-(-A)+(-B)-(-C)=0\implies A-B=-\frac 1 8$$
and plugging in $x=2$ gives $$A\cdot 3^3 - B\cdot 3^3 + C\cdot 3^3 - A\cdot 3^2 + B\cdot 3 - C = 2^4\implies A + \frac 5 3 B =\frac {17} {24}$$
which gives us $A=\frac 3 {16}, B=\frac 5 {16}$.


text:
Q: How to use DataTable ReadXml to read small subsets of a large Xml file I have an datatable serialized to Xml. It has 1000's of records. Using the DataTable's ReadXml method works, but it is very slow. I am only interested in the first 100 records. Is there a way of reading the file, extracting the first 100 records, and loading that using the ReadXml method?

A: try something like this!
XmlDocument doc = new XmlDocument();
doc.Load( "c:\\testfile2.xml" );
foreach (XmlNode nd in doc.DocumentElement.SelectNodes( "xml/entry" ))
{
...
}

im not up on dot net so this could be different..
also please look at this link http://msdn.microsoft.com/en-us/library/ms998559.aspx

A: I believe you can use one of the classes derived from System.Xml.XmlReader to sequentially read the file rather than loading the entire file into memory.


text:
Q: AWS Contigo - authenticate to Google on my Flutter app I'm trying to implement Login Screen with Flutter that will authenticate with Google throw AWS Contigo authentication.
I'm using this library with Cognito's federated sign-in on mobile devices. I'm using flutter_webview to navigate to Cognito's authorized URL. Use flutter_webview's navigationDelegate to catch the redirect from the Google app. then I should make a POST request to Cognito's token URL to get your tokens. Create the session and user with the tokens.
I'm not sure what I should add in the redirect to Google?
https://${COGNITO_POOL_URL}" +
        ".amazoncognito.com/oauth2/token?grant_type=authorization_code&client_id=" +
        "${COGNITO_CLIENT_ID}&code=" + authCode + "&redirect_uri=myapp://WHAT TO ADD HERE??";

Thank you.


text:
Q: Unable to install Curb on Linux 14.04 using apt-get install libcurl4-openssl-dev I am trying to install Curb using command apt-get install libcurl4-openssl-dev
on Linux 14.04
Detail below
apt-get install libcurl4-openssl-dev
 Reading package lists... Done
 Building dependency tree
 Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:
The following packages have unmet dependencies:
libcurl4-openssl-dev : Depends: libidn11-dev but it is not
    installable
    Depends: libkrb5-dev but it is not going to be installed
    Depends: libldap2-dev but it is not installable
    Depends: librtmp-dev but it is not installable
    Depends: libssl-dev but it is not going to be installed
    Depends: zlib1g-dev but it is not installable
E: Unable to correct problems, you have held broken packages.


text:
Q: Page number on quotes generated in the quite object Is there a way to put page numbers on quotes in Salesforce ?
Under

Setup > Quote > Temoplates

In the quote editor I can't seem to find a page number option, Anyone know how to add that to quotes ?

A: Currently, we can not able to add Page Number on Quote Template. Seems, it is a Idea on appExchange.


text:
Q: Qt Visual Studio Tools for VS2019 Qt Visual Studio Tools 2.3.0 has recently been released but isn't recognised by Visual Studio 2019. Does anyone know if it can be modified/rebuilt for VS2019 or when support might be added?

A: Support for VS2019 has since been added and will be available in the next version of the Qt Visual Studio Tools, which is scheduled to be released in a few days' time.


text:
Q: Looping inside the ST monad I'm trying to implement insertion sort in Haskell on Data.Array.ST, with a monadic comparison function. i.e., sortByM :: (Monad m, Ix i, Enum i, Eq i) => (e -> e -> Ordering) -> STArray s i e -> m (ST s ()). Here's my code, for context:
import Data.Ord
import Data.Foldable
import Data.Array.ST
import Control.Monad.ST

sortByM :: (Monad m, Ix i, Enum i, Eq i)
        => (e -> e -> m Ordering)
        -> STArray s i e -> m (ST s ())
sortByM cmp xs = sequence_ <$> traverse (bubbleBack xs) [start..end]
  where
        (start, end) = runST $ getBounds xs
        bubbleBack :: (Monad m, Ix i, Enum i, Eq i)
                   => STArray s i e -> i -> m (ST s ())
        bubbleBack ary = loopM $ fmap (mapLeft runST) . bubbleBackOnce ary
        bubbleBackOnce :: (Monad m, Ix i, Enum i, Eq i)
                        => STArray s i e
                        -> i -> m (Either (ST s i) (ST s ()))
        bubbleBackOnce ary bubble =
           if bubble == start
           then return $ Right $ return ()
           else do
                  let elem = runST $ readArray ary bubble
                  let prev = runST $ readArray ary (pred bubble)
                  ordering <- cmp elem prev
                  return $ if ordering == LT
                           then Left $ do
                                         writeArray ary bubble prev
                                         writeArray ary (pred bubble) elem
                                         return $ pred bubble
                           else Right $ return ()
-- ...
mapLeft :: (a -> r) -> Either a b -> Either r b
mapLeft f (Left x)  = Left (f x)
mapLeft _ (Right x) = Right x

The problem I'm running into, as I understand it, is that loopM's first parameter is expected to have type ST s i -> m (Either i (ST s ())), but because of runST's method of hiding ST's internal state, fmap (mapLeft runST) . bubbleBackOnce ary has type (forall s'. ST s' i) -> Either i (ST s i). This is my first time using ST, so I'm not sure how to address this. Additionally, this is for a pet project, so I'm trying to avoid relying on existing libraries that would simplify things, e.g. STMonadTrans.


text:
Q: SQL - Convert column to rows including column name I have a table like this :
date    subj1   subj2   subj3   subj4
1       20       5      30      7
2       15      14      29      4
3       15      14      29      14

I want to get it arranged like the following:
date    1   2   3
subj1   20  15  35
subj2   5   14  14
subj3   30  29  29
subj4   7   4   14

How can I achieve this in SQL using pivot or unpivot ?

A: using cross apply() with values() to unpivot your data in a  common table expression, then pivoting it with pivot():
with cte as (
  select t.date, v.subject, v.value
  from t
  cross apply (values ('subj1',subj1),('subj2',subj2),('subj3',subj3),('subj4',subj4)) v(subject,value)
)

select subject, [1],[2],[3]
from cte
pivot (max(value) for [date] in ([1],[2],[3])) p

rextester demo: http://rextester.com/QJMRBF98845
returns:
+---------+----+----+----+
| subject | 1  | 2  | 3  |
+---------+----+----+----+
| subj1   | 20 | 15 | 15 |
| subj2   |  5 | 14 | 14 |
| subj3   | 30 | 29 | 29 |
| subj4   |  7 |  4 | 14 |
+---------+----+----+----+

If you want subject to be called date, then simply alias it in the select:
with cte as (
  select t.date, v.subject, v.value
  from t
  cross apply (values ('subj1',subj1),('subj2',subj2),('subj3',subj3),('subj4',subj4)) v(subject,value)
)

select subject as date, [1],[2],[3]
from cte
pivot (max(value) for [date] in ([1],[2],[3])) p

rextester demo: http://rextester.com/XQAE51432
returns:
+-------+----+----+----+
| date  | 1  | 2  | 3  |
+-------+----+----+----+
| subj1 | 20 | 15 | 15 |
| subj2 |  5 | 14 | 14 |
| subj3 | 30 | 29 | 29 |
| subj4 |  7 |  4 | 14 |
+-------+----+----+----+

A: using PIVOT
declare @table table (data int ,subj1 int ,subj2 int,subj3 int, subj4 int )

insert into  @table
select 1      , 20     ,  5     , 30  ,    7
union all select 2      , 15     , 14     , 29  ,    4
union all select 3      , 15     , 14     , 29  ,    14

select 'subj1' as [date],* from (
select data,subj1  from
@table) a
pivot ( sum(subj1) for data in ([1],[2],[3]))p

union all
select 'subj2' as [date],* from (
select data,subj2  from
@table) a
pivot ( sum(subj2) for data in ([1],[2],[3]))p

union all

select 'subj3' as [date],* from (
select data,subj3  from
@table) a
pivot ( sum(subj3) for data in ([1],[2],[3]))p
union all
select 'subj4' as [date],* from (
select data,subj4  from
@table) a
pivot ( sum(subj4) for data in ([1],[2],[3]))p

RESULT
+-------+----+----+----+
| date  | 1  | 2  | 3  |
+-------+----+----+----+
| subj1 | 20 | 15 | 15 |
| subj2 |  5 | 14 | 14 |
| subj3 | 30 | 29 | 29 |
| subj4 |  7 |  4 | 14 |

A: CREATE TABLE #TABLE12
    ([DATE] INT, [SUBJ1] INT, [SUBJ2] INT, [SUBJ3] INT, [SUBJ4] INT)
;

INSERT INTO #TABLE12
    ([DATE], [SUBJ1], [SUBJ2], [SUBJ3], [SUBJ4])
VALUES
    (1, 20, 5, 30, 7),
    (2, 15, 14, 29, 4),
    (3, 15, 14, 29, 14)

 SELECT SUBJECT
    ,MAX([1])[1]
    ,MAX([2])[2]
    ,MAX([3])[3]
FROM(SELECT *
FROM #TABLE12
CROSS APPLY (VALUES ('SUBJ1', SUBJ1),
                    ('SUBJ2', SUBJ2),
                    ('SUBJ3', SUBJ3),
                    ('SUBJ4', SUBJ4)
                    )
            CROSSAPPLIED ([SUBJECT], VALUE))A
PIVOT(MAX(VALUE) FOR [DATE] IN (
            [1]
            ,[2]
            ,[3]
            )) P
            GROUP BY SUBJECT

output
SUBJECT 1   2   3
SUBJ1   20  15  15
SUBJ2   5   14  14
SUBJ3   30  29  29
SUBJ4   7   4   14


text:
Q: How to get installed application path for executable in COM I am trying to get the installed location of all application using COM. I am able to get the display name of each application. But I am not able to get installed path of each application.
MY Code:
CComPtr<IShellItem> spPrinters;
CoInitialize(nullptr);
HRESULT hresult = ::SHCreateItemFromParsingName(L"::{26EE0668-A00A-44D7-9371-BEB064C98683}\\8\\"
    L"::{7B81BE6A-CE2B-4676-A29E-EB907A5126C5}", nullptr, IID_PPV_ARGS(&spPrinters));
CComPtr<IEnumShellItems> spEnum;
spPrinters->BindToHandler(nullptr, BHID_EnumItems, IID_PPV_ARGS(&spEnum));
for (CComPtr<IShellItem> spProgram; spEnum->Next(1, &spProgram, nullptr) == S_OK; spProgram.Release())
{
    CComHeapPtr<wchar_t> spszName;
    spProgram->GetDisplayName(SIGDN_NORMALDISPLAY, &spszName);
    CString cDisplayName = spszName;
}

Any idea how to get installed path from IEnumShellItems?

A: Here is a piece of code that will dump this out. The child's IPropertyStore does not return these, I don't know why, so we have to use the old
IShellFolder2::GetDetailsEx method with a special column id (which is the same as a PROPERTYKEY).
CComPtr<IShellItem> cpl;
CComPtr<IShellFolder2> folder;
CComPtr<IEnumShellItems> enumerator;
PROPERTYKEY pkLocation;
SHCreateItemFromParsingName(L"::{26EE0668-A00A-44D7-9371-BEB064C98683}\\8\\::{7B81BE6A-CE2B-4676-A29E-EB907A5126C5}", nullptr, IID_PPV_ARGS(&cpl));

// bind to IShellFolder
cpl->BindToHandler(NULL, BHID_SFObject, IID_PPV_ARGS(&folder));

// bind to IEnumShellItems
cpl->BindToHandler(NULL, BHID_EnumItems, IID_PPV_ARGS(&enumerator));

// get this property key's value
PSGetPropertyKeyFromName(L"System.Software.InstallLocation", &pkLocation);

for (CComPtr<IShellItem> child; enumerator->Next(1, &child, nullptr) == S_OK; child.Release())
{
    // get child's display name
    CComHeapPtr<wchar_t> name;
    child->GetDisplayName(SIGDN_NORMALDISPLAY, &name);
    wprintf(L"%s\n", name);

    // get child's PIDL
    CComHeapPtr<ITEMIDLIST> pidl;
    SHGetIDListFromObject(child, &pidl);

    // the PIDL is absolute, we need the relative one (the last itemId in the list)
    // get it's install location
    CComVariant v;
    if (SUCCEEDED(folder->GetDetailsEx(ILFindLastID(pidl), &pkLocation, &v)))
    {
        // it's a VT_BSTR
        wprintf(L" %s\n", v.bstrVal);
    }
}

Note it's using an undocumented System.Software.InstallLocation PROPERTYKEY. To find it I just dumped all columns with a code like this for each child:
    int iCol = 0;
    do
    {
        SHCOLUMNID colId;
        if (FAILED(folder->MapColumnToSCID(iCol, &colId)))
            break; // last column

        CComHeapPtr<wchar_t> name;
        PSGetNameFromPropertyKey(colId, &name);

        CComVariant v;
        if (SUCCEEDED(folder->GetDetailsEx(ILFindLastID(pidl), &colId, &v)))
        {
            if (v.vt == VT_BSTR)
            {
                wprintf(L" %s: %s\n", name, v.bstrVal);
            }
            else
            {
                wprintf(L" %s vt: %i\n", name, v.vt);
            }
        }

        iCol++;
    } while (true);
}

PS: I've not added much error checking, but you should.


text:
Q: Select Radio Button / input value in Open box on website using vba I am trying to punch the radio button question and want to input the value in an open text box as well (using VBA). Below is the script I am using.
I tried multiple things, looked at other websites as well but it is not working.
It would be great if someone can guide me.
Dim IE As Object
Dim Region, VOCSentDate As String

Sheets("Sheet1").Select
Region = ThisWorkbook.Worksheets("Sheet1").Range("A1").Value
VOCSentDate = ThisWorkbook.Worksheets("Sheet1").Range("B1").Value

Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate "website link....."
Application.StatusBar = "Submitting"
While IE.Busy
DoEvents
Wend

I'm not sure how to punch the radio button question. I tried the 3 types for Open textbox below but none of them are not working, throwing object required error
IE.Document.getElementById("ctl00_body_7F22FA6E-5D77-426A-AA84-68D833FA05C1_3").Value = VOCSentDate

IE.Document.getElementById("ctl00_body_7F22FA6E-5D77-426A-AA84-68D833FA05C1_3").innerText = VOCSentDate

IE.Document.all("ctl00_body_7F22FA6E-5D77-426A-AA84-68D833FA05C1_3").Value = VOCSentDate

Application.StatusBar = "Form Submitted"
IE.Quit
Set IE = Nothing

-------------- HTML of the Radio button --------------

    Please select your region:

    A response to this question is required

      <input id="ctl00_body_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1_1" type="radio" name="ctl00$body$ctl00_body_ctl00_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1" value="01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1_1" />Americas

      <input id="ctl00_body_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1_2" type="radio" name="ctl00$body$ctl00_body_ctl00_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1" value="01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1_2" />ANZ

      <input id="ctl00_body_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1_3" type="radio" name="ctl00$body$ctl00_body_ctl00_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1" value="01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1_3" />APAC

      <input id="ctl00_body_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1_4" type="radio" name="ctl00$body$ctl00_body_ctl00_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1" value="01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1_4" />APME

      <input id="ctl00_body_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1_5" type="radio" name="ctl00$body$ctl00_body_ctl00_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1" value="01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1_5" />Europe

      <input id="ctl00_body_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1_6" type="radio" name="ctl00$body$ctl00_body_ctl00_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1" value="01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1_6" />India

      <input id="ctl00_body_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1_7" type="radio" name="ctl00$body$ctl00_body_ctl00_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1" value="01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1_7" />North America

------------------- HTML of Open End -------------------------

    EOPR First Sent Date (dd/mm/yyyy)

    A response to this question is requiredIncorrect Date Format

    <input name="ctl00$body$01EE9560-B1F9-4BA3-A922-9D53A1120FC2_3" type="text" id="ctl00_body_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_3" class="TextBox" />

A: tl;dr;
The following are based on the HTML as shown. If there are parent form/frame/iframe tags involved they will also need to be negotiated before making the selections below.

Radio buttons:
For the radio buttons you can use a CSS selector combination to target the page styling and return a nodeList of all of the radio button elements. You can then select by index the appropriate button
Dim aNodeList As Object
Set aNodeList = ie.document.querySelectorAll(".ResponseOption [type=radio]")
aNodeList.item(0).Click '<==Select first  option

I think click may be likely method here as I can't see a checked attribute, else the syntax would be  aNodeList.item(0).checked = True
The returned nodeList is as follows by index

Textbox:
There is an ID for the input box so you can use an ID selector, #, to target
ie.document.querySelector("#ctl00_body_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_3").Value = "myText"

A: To choose a radio button style input, make the checked property true.
IE.Document.getElementById("ctl00_body_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_1_6").checked = true

An input textbox gets its value set.
IE.Document.getElementById("ctl00_body_01EE9560-B1F9-4BA3-A922-9D53A1120FC2_3").value = format(VOCSentDate, "d/m/yy")


text:
Q: How can I access a page's content inside a frame? I have a frame inside mainwindow, inside it there's a page with panels and various contents.
The mainwindow decides wich page to load, and then must interact with their contents (here is the problem).
I've tried many solution and the best is this, but returns pageLogin as a null object
    _mainFrame.Source = new Uri(@"/Pages/Login.xaml", UriKind.Relative);
    Page pageLogin = this._mainFrame.Content as Page;

where _mainFrame is of course the name of the frame inside t mainwindow, and Login.xaml is the content with the Login_panel Stackpanel inside

A: OK. So first, I think you might be going about this the wrong way to start. Check out this project.
http://www.wpfsharp.com/2011/04/05/navigation-and-pages-using-model-view-viewmodel-mvvm/
Try this example:
MainWindow.xaml
<Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        Loaded="Window_Loaded"
        >
    <Grid>
        <Frame Name="MainFrame" Source="/Login.xaml"></Frame>
    </Grid>
</Window>

MainWindow.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;

namespace Test
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var a = MainFrame.Content as Page;
            var grid = a.Content as Grid;
            var textBlock = grid.Children[0];
            // bla bla, you logged in
            MainFrame.Source = new Uri("/Home.xaml", UriKind.Relative);
            var b = MainFrame.Content as Page; // Still Login.xaml
            MainFrame.ContentRendered +=MainFrame_ContentRendered;
        }

        private void MainFrame_ContentRendered(object sender, EventArgs e)
        {
            var b = MainFrame.Content as Page; // Is now Home.xaml
        }
    }
}

Login.xaml
<Page x:Class="Test.Login"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      mc:Ignorable="d"
      d:DesignHeight="300" d:DesignWidth="300"
    Title="Login">

    <Grid>
        <TextBlock>This is a sample login page.</TextBlock>
    </Grid>
</Page>


text:
Q: Counting occurrences of factor by group I'm dealing with some dplyr issues. I would like to create a new variable which is the frequency of a factor's level, but I would like to do it by group. Here's an extract of my data:
head(Dataset)
Code_PR   Code_SP  Status_SP
  PR1        SP1       0
  PR1        SP2       0
  PR1        SP3       1
  PR2        SP1       0
  PR2        SP2       1

I would like to get a result like this:
Code_PR   Count  Ratio
  PR1      3       1/3
  PR2      2       1/2

I tried the following code, and modified it but I always get the same error:
RatioAb <-  Database_V2  %>%
group_by(CodePR, StatutSP) %>%
summarize(
n=n(),
Ratio =count(StatutSP, '1')/count(StatutSP)
)
Error in summarise_impl(.data, dots) :
Evaluation error:
no applicable method for 'group_by_' applied to an object of class
"logical"

How can I fix that?

A: df %>%
  group_by(Code_PR) %>%
  summarise(Count = n()
            , Ratio = mean(Status_SP))

## A tibble: 2 x 3
#   Code_PR Count Ratio
#   <chr>   <int> <dbl>
# 1 PR1         3 0.333
# 2 PR2         2 0.500

A: Dataset %>%
  group_by(Code_PR) %>%
  summarise(Count = n(), Ratio = paste0(sum(Status_SP),"/",n()))


text:
Q: Creating Attribute set is taking time because of "initFromSkeleton" I have written a script to create attribute set and attribute from csv and it worked fine on my localhost but after uploading it to server I found that it is taking so much time to do the job even with 1 entry. So I was debugging it and I found out that "initFromSkeleton" is taking time.
$entityTypeId = Mage::getModel('eav/entity')
                ->setType('catalog_product')
                ->getTypeId(); // 4 - Default

$newSet = Mage::getModel('eav/entity_attribute_set');
$newSet->setEntityTypeId($entityTypeId);
$newSet->setAttributeSetName($setName);
$newSet->save();

$newSet->initFromSkeleton($entityTypeId);
$newSet->save();

I don't know what to do because to build new attribute based on default attribute set I have to write this initFromSkeleton. While searching google I found this link. But it understood from there.
Could any one has done this before. Please help me out. Thanks in advance

A: initFromSkeleton builds an attribute set based on another attribute set. It probably takes so much time because that other attribute set is so big (i.e. has many attributes in it). If you take a really simple initFromSkeleton it might take less time.
In your case you also use wrong code. You call initFromSkeleton with an entity type id, but that's not how it works. You need to call it with an attribute set id which specifies the 'parent' attribute set from which it is built.
I'd suggest find the attribute set id of the default or the simplest attribute set you have and give that as parameter to initFromSkeleton.

A: This is a really "fun" Magento problem. If you're using the initFromSkeleton method, take note that calling "$newAttributeSet->save();" before executing initFromSkeleton is the correct process... However you have to look up the default attribute set for the entity type... I detailed the process in the blog post below in-case anyone is having a similar problem! I've also included the code you're missing.
Building a new attribute set in Magento - Programatically
     $templateAttributeSet = $this->_getDefaultAttributeSet();
      $newAttributeSet->initFromSkeleton($templateAttributeSet->getId());

protected function _getDefaultAttributeSet()
    {
        $entityTypeId = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId();
        $attributeSetCollection = Mage::getResourceModel('eav/entity_attribute_set_collection')
            ->setEntityTypeFilter($entityTypeId)
            ->addFilter('attribute_set_name', 'Default');

        if ($attributeSetCollection->count() > 0) {
            $response = $attributeSetCollection->getFirstItem();
        } else {
            $response = FALSE;
        }
        return $response;
    }


text:
Q: css transitions: hover out transition not working if hover in is not allowed to complete I have a div, for which css transitions are applied on hover,
on hover in, a transition is applied on the :before element, and on hover out, same transition (reversed) is applied on the :before element.
here is the html:

Title

and (important parts of) the css:
.strips .strip__content:hover:before {
  transform: skew(180deg) scale(1) translate(0, 0);
  opacity: 0.1;
}

.strips .strip__content:before {
  content: "";
  position: absolute;
  z-index: 1;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: white;
  opacity: 0.05;
  transform-origin: center center;
  transform: skew(180deg) scaleY(0) translate(0, 0);
  transition: all 0.6s cubic-bezier(0.23, 1, 0.32, 1);
}

Now, the transitions work smoothly if i allow tem to finish, but say, if i dont allow the hover in transition to finish , and quickly hover out, then the hover out transition does not work.
here is a fiddle:
https://jsfiddle.net/x2pavnac/
(try hovering out before the transition finishes).
I am not sure why this happens and how this issue can be addressed in css.
EDIT:
i have simplified the transition and also increased opacity, so it is more visible.
Updated fiddle: https://jsfiddle.net/x2pavnac/4/

A: I am not sure why this works well for others, but i found a typo in my css which was the issue in my case:
.strips .strip__content:before {
  transform: skew(180deg) scaleY(0) translate(0, 0);
}

.strips .strip__content:hover:before {
  transform: skew(180deg) scale(1) translate(0, 0);
  opacity: 0.1;
}

should be
.strips .strip__content:before {
  transform: skew(180deg) scaleY(0) translate(0, 0);
}

.strips .strip__content:hover:before {
  transform: skew(180deg) scaleY(1) translate(0, 0);
  opacity: 0.1;
}

notice the scaleY(1) instead of scale(1).
I am still not sure why it worked correctly for others though, even with the typo.


text:
Q: ios game gets out of sync while analysing process in Instruments - how can I avoid that? I am building an iOS game and I notice that the game performs fine while running normally in the XCode debugger. However, when i run it from within Instruments (Product-> Profile to trace  Leaks), the game freezes when Instruments displays 'Analyzing Process' in the left sidebar. After that the game messes up all its state since some parts of the game that were being analyzed froze up while other parts kept going.
Is this something I can/need to fix or is it sufficient to make sure the game runs in release?
If a fix is needed, what do I need to do to make it work?
Update 1:
So we found the issue - the same problem repros even if we are playing the game, press the home button and click on the game icon and continue playing.
The issue is that most of our work is done in the update method, and it relies on the value of the (ccTime)dt parameter. The value of dt is usually < 0.1 seconds, and occasionally somewhere upto 0.5 seconds).When we pause (either by clicking the home button, or when instruments pauses the game to take a snapshot) and resume playing, the value of dt is several seconds! And that throws all our calculations out of range.
We tried a temporary (but ugly) workaround that fixes the issue: at the beginning of the update method, we add this:
if(dt > 1)
  return;

And it now works as expected - doesn't go out of sync. However, this is not a permanent solution, since sometimes, the values of dt are legitimately close to 1 second, and in resource crunched situations, this may lead to stutter (or worse).
We also considered another (equally ugly) solution of storing the previous value of dt, and then check in the update method:
if(dt > 10 * prevDt)
{
  return;
}

We tried calling unscheduleUpdate in AppDelegate.m's applicationDidEnterBackground, and called scheduleUpdate in the applicationWillEnterForeground method, but that approach did not work.
What is the best way to deal with updates with erratic time values due to external pauses?
Thanks
Anand

A: Unfortunately this is a problem, for which there is no sure answer; at least not without access to your system to run a whole variety of checks.
The failure in the profile may be because your game is running tight loops the timing of which get's upset in unpredictable ways and your game is crashing due to timing or resource issues (where those timing issues don't crop up with the debugger in the same way). If that's the case, there is probably not much you can do about it. Or it may be because there is a problem in your code. The problem is it can be very difficult to figure out which of these is the case. It's probably best to assume the problem is in your code though and do some further investigation.
The first thing to do, if you haven't done it already, is run the static analysis tool (Analyse from the Product menu in Xcode). Consider each of the raised errors carefully, and work to remove all of them. Sometimes they might seem obvious and you think you can ignore them, but some prodding reveals they are a symptom of a deeper problem.
If you haven't tried already, try running the instrument to check for zombies. There's a high chance this will fail also if the allocation instrument is failing, but if there are some stale references to de-allocated objects hanging around they could be causing the problem you are experiencing. Another instrument you can try is the performance analyser, to check where your app is spending most of it's time. There may be some really significant problem with the overallocation of resources you are not aware of. If you can't run the memory profiler, it will be difficult for you to see if this is the case, but using the performance analyser, it might be possible to see if your app is getting hung up for too long somewhere it shouldn't be.
Lastly - if all else fails and this may be a sledgehammer to crack a nut - and also may not in any case provide the solution. If you aren't using ARC, consider how long it would take to convert your app to using it (definitely create a branch first before doing it though). The Apple algorithms for object allocation/deallocation are very efficient and there is a very good chance if you have subtle memory management errors, they will be eliminated by Automatic Reference Counting.

A: I don't know much about how cocos2D works, but if you've run out of options, I would simply clamp the delta time to an upper range. In whatever update methods used delta time, I would do the following.
double delta = (dt > 0.5) : (0.5) ? (dt);

Use delta instead of dt from that point onward. The result is that any frame with a delta of over half a second will be limited to a delta of half a second. You don't want to skip frames, because then you could potentially skip many frames in a row which would be bad for the user; they'd probably think the app crashed or something. However, you don't want to run a frame with a large delta because then delta-dependent objects and forces will get multiplied many times for that frame, preventing you from catching collisions and stuff. So, we prevent the game from getting completely screwed over while not skipping frames by simply clamping the value downwards.
The negative is that the app will appear to move more slowly when your frame rate drops to 2 frames per second. You lose the benefit of a time-based update method, which is the ability to always make the game appear to run at a well defined speed, when the engine is overburdened.
To be honest, if you ever run at 2 frames per second for an extended period of time, you've got bigger problems to worry about. I don't think the user will notice if objects move slightly more slowly per second if the game is only rendering once every who-knows-when anyways.


text:
Q: Jenkins fails with github "git clone" When I do build in Jenkins, it fails with this error. Any idea?
ERROR: Error cloning remote repo 'origin' : Could not clone git@github.com:test/test.git
ERROR: Cause: Error performing command: git clone --progress -o origin

git@github.com:test/test.git /var/lib/jenkins/jobs/test/workspace
Command "git clone --progress -o origin git@github.com:test/test.git
/var/lib/jenkins/jobs/test/workspace" returned status code 128: Initialized empty Git
repository in /var/lib/jenkins/jobs/test/workspace/.git/

No protocol specified

(ssh-askpass:801): Gtk-WARNING **: cannot open display: :0.0
Host key verification failed.
fatal: The remote end hung up unexpectedly

A: Had the same problem, even though the ssh-keys were correctly set up.
The issue was that on the first connection attempt, the git-server needed to be added to the known hosts file

/.ssh/known_hosts

. Git prompts you for this on first connect-attempt: Are you sure you want to continue connecting (yes/no)?, but Jenkins did not nor can it pass on the prompt, so it failed silently.
We solved it by walking to our ops-guy, bringing him a nice cup of espresso, and had him do a random git-checkout, where he answered yes to said prompt :) After that, checkouts through Jenkins worked as expected.
Found the clue here: http://www.ipsure.com/blog/2010/ssh-public-key-w-rsa-authentication-and-ssh-tunneling-part-1/

A: You need to copy your private ssh key into the .ssh folder beneath Jenkins.  Something like (on Ubuntu Lucid):
/var/lib/jenkins/.ssh

A: If you still have the Host key verification failed problem I answered a similar problem with a step by step solution here :
Jenkins & Github not using SSH Key

A: Host key verification failed. - make sure your SSH keys are setup properly.
http://help.github.com/linux-set-up-git/
After you are done with that,
ssh git@github.com

should give you a welcome message ( which also says no shell access ) from GitHub

A: Actually, I ended up with simply using https instead of ssh to clone the repository from GitHub to Jenkins.
So instead of: git@github.com:[user]/[repository].git I used: https://github.com/[user]/[repository].git as the repository URL.


text:
Q: How can I access the contents of a form submission via Javascript? I have server side caching running on a website, and need to trigger functionality based on the submission of a form.  How can I access the contents of a form submission via Javascript?  Usually I would access these with PHP via $_POST.
I can't get the values via PHP because the page that is being served after the form submission is the cached page, and no PHP will be executed.
I am using jQuery.

A: $_POST is a server side PHP variable and has nothing do to with JavaScript.
Now the $_POST variable usually contains some kind of values submitted by a form, which is accessible by JavaScript. You can loop over the form and get the filled in values very easily.
code sample
If you are using jQuery you can get the values like this:
$("#myform input[name=first_name]").val();

A: $('form').submit(function() {
  alert($(this).serialize());
  return false;
});

You can do the above if you are using jQuery,
You could also do:
var form = document.getElementById("<yourformid>");
for(var i =0; i < form.elements.length; i++){
   // grab form.elements[i]
}


text:
Q: What is the Ehcache TTL for Grails? Is TTL for ehcache in Grails defaulted to 0? I'm trying to locate documentation on the subject and I'm unsuccessful.
I'm simply guessing based on Ehcache documentation.

A: The default cache TTL is 2 minutes. All caches use defaults defined in ehcache-failsafe.xml that's bundled with the jar (in the root dir) unless they're explicitly configured, or if you create your own ehcache.xml and put it in the runtime classpath to prevent the failsafe file from being used.
See http://ehcache.org/ehcache.xml for an example file that's heavily commented.


text:
Q: Design pattern for corner-case logic without switch and conditional statements I have a class with many switch statements in it. The code looks very ugly to me but I can't figure out how to fix it. If somebody could suggest a design pattern or a trick that cleans this up that would be great. Below is a abbreviated version of the Class with some annotations for context.
/**
 * Slides a desktop Notification from the edge of the screen into the desktop by some margin.
 */
public class SlideManager extends NotificationManager {
    // Location enum provided below for reference:
    /*public enum Location {
        NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST
    }*/
    private Location m_loc; // the corner / edge of the screen where the Notification should appear
    // A Screen abstracts away the padding logic.
    // The idea was that you would just give it a padding and I could reuse
    // it later in all my NotificationManagers to give me the x and y for a Notification Location later.
    private Screen m_standardScreen;
    private Screen m_noPaddingScreen;
    // the direction that the Notification should slide in from.
    // For instance, if we had our Notification show up on the center east side of the screen,
    // it should slide in from the edge towards the west until it was a suitable margin away from the edge of the screen.
    private SlideDirection m_direction;
    private double m_slideSpeed;
    // this is a flag to signal when the user has overridden the default SlideDirection calculation.
    // If the user constructs the SlideManager without calling setSlideDirection later,
    // this will be false. However, if the user does setSlideDirection
    // we want to avoid changing that automatically if the user later calls setLocation.
    private boolean m_overwrite;

    public enum SlideDirection {
        NORTH, SOUTH, EAST, WEST
    }

    {
        m_standardScreen = Screen.standard();
        m_noPaddingScreen = Screen.withPadding(0);
        m_slideSpeed = 300;
        m_overwrite = false;
    }

    public SlideManager() {
        m_loc = Location.NORTHEAST;
        recalculateSlideDirection();
    }

    public SlideManager(Location loc) {
        m_loc = loc;
        recalculateSlideDirection();
    }

    /**
     * Sets the location where the Notifications show up.
     * If the user has not explicitly given a SlideDirection, this will also recalculate the SlideDirection.
     * For example, if the user moves the Notification spawn location from East to West
     * we want to change the SlideDirection from West to East, respectively.
     *
     * @param loc
     */
    public void setLocation(Location loc) {
        m_loc = loc;
        if (!m_overwrite)
            recalculateSlideDirection();
    }

    /**
     * Sets the direction that the Notification should slide in from.
     *
     * @param slide
     */
    public void setSlideDirection(SlideDirection slide) {
        m_direction = slide;
        m_overwrite = true;
    }

    private void recalculateSlideDirection() {
        switch (m_loc) {
        // The tricky part is when the user wants the Notification to appear in a corner of the screen.
        // If this weren't the case, it would make no sense for a user to set
        // his own SlideDirection because the SlideDirection for Location.
        // EAST would always be West, Location.NORTH would always be SOUTH, etc.
        // But for the (literal) corner cases I want to somehow give a way for the user to have a preference.
        // For example, in the top right corner the Notification could either slide in from the right or from the top.
        // By default I choose the top, but I want the user to be able to change this and also have that choice remembered if the Location changes.
        case NORTHWEST:
            m_direction = SlideDirection.SOUTH;
            break;
        case NORTH:
            m_direction = SlideDirection.SOUTH;
            break;
        case NORTHEAST:
            m_direction = SlideDirection.SOUTH;
            break;
        case EAST:
            m_direction = SlideDirection.WEST;
            break;
        case SOUTHEAST:
            m_direction = SlideDirection.NORTH;
            break;
        case SOUTH:
            m_direction = SlideDirection.NORTH;
            break;
        case SOUTHWEST:
            m_direction = SlideDirection.NORTH;
            break;
        case WEST:
            m_direction = SlideDirection.EAST;
            break;
        }
    }

    /*
        When a Notification is added it should slide in from the edge towards an area slightly off the edge.
    */
    @Override
    protected void notificationAdded(Notification note, Time time) {
        int noPaddingX = m_noPaddingScreen.getX(m_loc, note);
        int noPaddingY = m_noPaddingScreen.getY(m_loc, note);
        int standardX = m_standardScreen.getX(m_loc, note);
        int standardY = m_standardScreen.getY(m_loc, note);

        Slider slider = null;
        double frequency = 50;
        double slideDelta = m_slideSpeed / frequency;

        // How would I abstract this?
        switch (m_direction) {
        case NORTH: {
            note.setLocation(standardX, noPaddingY);
            slider = new Slider(note, m_direction, 0, -slideDelta, standardX, standardY);
        }
            break;
        case SOUTH: {
            note.setLocation(standardX, noPaddingY);
            slider = new Slider(note, m_direction, 0, slideDelta, standardX, standardY);
        }
            break;
        case EAST: {
            note.setLocation(noPaddingX, standardY);
            slider = new Slider(note, m_direction, slideDelta, 0, standardX, standardY);
        }
            break;
        case WEST:
            note.setLocation(noPaddingX, standardY);
            slider = new Slider(note, m_direction, -slideDelta, 0, standardX, standardY);
            break;
        }

        Timer timer = new Timer((int) frequency, slider);
        timer.start();
        note.show();
    }

    /*Slides a Notification from its current location to a desired location with fixed deltaX's and deltaY's. It needs the SlideDirection to know which end values to check for stopping.*/
    public class Slider implements ActionListener {
        private Notification m_note;
        private SlideDirection m_dir;
        private double m_deltaX;
        private double m_deltaY;
        private double m_stopX;
        private double m_stopY;

        private double m_x;
        private double m_y;

        public Slider(Notification note, SlideDirection dir, double deltaX, double deltaY, double stopX, double stopY) {
            m_note = note;
            m_dir = dir;
            m_deltaX = deltaX;
            m_deltaY = deltaY;
            m_stopX = stopX;
            m_stopY = stopY;

            m_x = note.getX();
            m_y = note.getY();
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            m_x += m_deltaX;
            m_y += m_deltaY;

            // another ugly heap of conditionals. Is there a way to abstract away the stopping logic?
            if (m_dir == SlideDirection.SOUTH) {
                if (m_y >= m_stopY) {
                    m_y = m_stopY;
                    ((Timer) e.getSource()).stop();
                }
            } else if (m_dir == SlideDirection.NORTH) {
                if (m_y <= m_stopY) {
                    m_y = m_stopY;
                    ((Timer) e.getSource()).stop();
                }
            } else if (m_dir == SlideDirection.EAST) {
                if (m_x >= m_stopX) {
                    m_x = m_stopX;
                    ((Timer) e.getSource()).stop();
                }
            } else if (m_dir == SlideDirection.WEST) {
                if (m_x <= m_stopX) {
                    m_x = m_stopX;
                    ((Timer) e.getSource()).stop();
                }
            }

            m_note.setLocation((int) (m_x), (int) (m_y));
        }
    }
}

Obviously, having two switchs and a conditional chain means something is wrong. My initial thought was to make some kind of a SlideVector class where I could give it a SlideDirection and it would calculate the translations and handle the end cases. What are the pros/cons of this approach? Is a HashMap of any use in this case? Are there any other ways I can approach this problem?

A: Look at the strategy pattern. You can move all your switch statements into a different class. Your class will have an instance of this translation class that will have a method to which you feed the state (all the information) and it will create the output for you.
In recalculateSlideDirection you can use fall through to save on lines (although ehh, it's not going to save you a lot).
Another option for notificationAdded is to define an interface and create a hashmap that will map the m_direction to an implemention of that interface. So you basically will just have a HashMap< SlideDirection, IYourInterface> yourMap...
And so you will basically call  yourMap.get(n_direction).action(); and this will replace your switch statement.


text:
Q: Upgrade Failled in Helm Upgrade stage I get the below error in my helm upgrade stage. I did the following change apiVersion: networking.k8s.io/v1beta1 to apiVersion: networking.k8s.io/v1 Could someone kindly let me know the reason why I encounter this issue and the fix for the same. Any help is much appreciated
Error: UPGRADE FAILED: current release manifest contains removed kubernetes api(s) for
this kubernetes version and it is therefore unable to build the kubernetes objects for
performing the diff. error from kubernetes: unable to recognize "": no matches for
kind "Ingress" in version "networking.k8s.io/v1beta1"

A: The reason why you encounter the issue is Helm attempts to create a diff patch between the current deployed release (which contains the Kubernetes APIs that are removed in your current Kubernetes version) against the chart you are passing with the updated/supported API versions. So when Kubernetes removes an API version, the Kubernetes Go client library can no longer parse the deprecated objects and Helm therefore fails when calling the library.
Helm has the official documentation on how to recover from that scenario:
https://helm.sh/docs/topics/kubernetes_apis/#updating-api-versions-of-a-release-manifest

A: Helm doesn't like that an old version of the template contains removed apiVersion's and results in the above error.To fix it, follow the steps in the official documentation from Helm.
Because we didn't upgrade the apiVersion before it was removed, we had to follow the manual approach. We have quite a few services that need updating, in two different kubernetes clusters (production and test). So there is a script that would update the apiVersion for the ingress object.You can find the script here.
The script assumes that you want to change networking.k8s.io/v1beta1 to networking.k8s.io/v1. If you have a problem with another apiVersion, change those values in the script in line 30. Updating your helm chart template if further changes are needed and deploy/apply the new helm chart.


text:
Q: Set  above Other Elements - CSS I have some html and while things are loading I have a
 that display while it loads, when it is loading currently the loading appears above everything, but I want the header to be above the loading screen. Here is the HTML
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JS Bin</title>

Loading...

Name

Hello

Profile

Info

Specials

Social

And here is the css
header {
  float:left;
  margin:0 0 30px 0;
  padding:5px 0 0 0;
  width:100%;
  z-index: 102;

}

#logo {
  text-align:center;
  margin:0;
}

h1 {
  font-family:'Nunito', 'sans-serif';
  margin: 15px 0;
  font-size:1.75em;
  font-weight:normal;
  line-height:0.8em;
}

h2 {
  margin:-5px 0 0;
  font-size:0.75em;
  font-weight:normal;
}

ul {
    padding: 0 0;
}

#loading {
    width: 100%;
    height: 100%;
    left: 0px;
    position: fixed;
    display: block;
    background: rgba(255, 255, 255, 0.5);
    z-index: 99;

}

#loading-container {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    background: rgba(255, 255, 255, 0);
    z-index: 99;
}

#loading_image {

    display: block;
  margin: auto;
    z-index: 100;

}

#loading_text {
    color: black;
  text-align: center;
  z-index: 101;
  vertical-align: middle

}

As you can see I set the z-index of the header higher than everything else but it is still below the loading screen here is a JSBin with a running example, in the example I show the loading screen for 3 seconds.
How can I get the header above the loading screen?
Thanks

A: Use this on the header tag:
position: relative;

this one will also work but could change the rest of the html, I don't know what else you have on it.
position: absolute;

A: just add in the header{}
  position:absolute;
  top:0;

If I've got the question right this should do what you need.

A: z-index woks by position. Add position:relative to the header.

Point, Note:
Only works on positioned elements(position: absolute;, position: relative; or position: fixed;).

JSbin


text:
Q: Observing on NSMutableArray - Only Array accessors to be used I have a mutable array which I have exposed in interface. I have also exposed the array accessors to modify the array. If any modification happens within the array, I would have to reset and re-calculate some data using KVO. To support KVO, I am using array accessors as shown below:
Array property + Array accessors + Wrapper for array accessors:
Mutable Array:
@property (nonatomic, strong) NSMutableArray *portfolioItemArray;

Array Accessors:
-(void)insertObject:(Service*)object inPortfolioItemArrayAtIndex:(NSUInteger)index;
-(void)removeObjectFromPortfolioItemArrayAtIndex:(NSUInteger)index;
-(void)insertPortfolioItemArray:(NSArray *)array atIndexes:(NSIndexSet *)indexes;
-(void)removePortfolioItemArrayAtIndexes:(NSIndexSet *)indexes;

Wrappers for Array Accessors:
-(void)addObjectToPortfolioItemArray:(Service*)inObject;
-(void)removeObjectFromPortfolioItemArray:(Service*)inObject;
-(void)addObjectsToPortfolioItemArray:(NSArray*)inPortfolioItemsArray;
-(void)removeObjectsFromPortfolioItemArray:(NSArray*)inPortfolioItemsArray;

All fine, the KVOs are triggered provided only array accessors or its wrappers are called by other programmers too.
Problem:
Some other developers may choose to perform:
[portfolioObject.portfolioItemArray addObject:xxxxx];

Instead of:
[portofolioObject addObjectToPortfolioItemArray:xxxxx];

This would screw the whole setup and it does not trigger the KVO. Is there a better mechanism of handling this? How to avoid programmers from opting direct insertion into the mutable array without using the array accessors?
Edit: Forgot to mention, I would have to expose the array because it can be set from outside (part of requirement). I am updating my KVO observation by overriding the setter for -portfolioItemArray.

A: Don't expose the mutable array. Expose an immutable array and a few methods to mutate the portfolio.


text:
Q: Integers representation in Haskell Define recurrent type of Integers representation to work like so:
data Integers = Zero | Next Integers | Prev Integers

and make this representation, the instance of class Num, it means that You should can use (+), (*), (==), abs, signum, show on Integers
Till now i defined sth like this:
data Integers = Zero | Integers Int deriving (Show)

next :: Integers -> Integers
next Zero = Integers 1
next (Integers a) = Integers a + Integers 1

prev :: Integers -> Integers
prev (Integers 1) = Zero
prev (Integers a) = Integers a - Integers 1

instance Eq Integers where
    Zero == Zero = True
    Integers a == Integers b = a == b
    _ == _ = False

instance Num Integers where
    Integers a + Integers b = Integers (a + b)
    Integers a - Integers b = Integers (a - b)
    Integers a * Integers b = Integers (a * b)
    abs (Integers a) = Integers (abs a)
    signum (Integers a) = Integers (signum a)
    fromInteger a = Integers (fromInteger a)

But it doesn't fit the data Integers = Zero | Next Integers | Prev Integers expectations

A: data Integers = Zero | Next Integers | Prev Integers

I'm going to show you +, the rest should be easy enough.
Zero + y = y
x + Zero = x

Well, that was easy!
Oh. There are some other cases.
Still, we've handled all the Zero cases, so now we only have to deal with Prev and Next. They're opposites of each other, aren't they? So if we're given one of each, they'll cancel each other out.
Next x + Prev y = x + y
Prev x + Next y = x + y

Now we only have to worry about the cases where the numbers we're given both have the same sign.
Next x + Next y = Next (Next (x + y))
Prev x + Prev y = Prev (Prev (x + y))

(These last two equations are not the most efficient implementation, but they are straightforward to understand.)
And we're done defining +.
Some of the other functions are easier, some are harder (and should reuse some of the easier functions), but they all involve pattern matching on the/either/both parameter(s) and doing the appropriate thing. And mostly they involve recursion, usually inescapable at some level when given a recursive data structure.


text:
Q: Extract row from pandas dateframe I have a data frame as the image below. I want to extract the rows of data frame which are having year and month as '1395/01'. I used the code below, but I know it is not correct because we can use string slice on a series of strings. Can anyone show me a way without using nested for loops?
df[df['Date'][:7] == '1395/01']

A: I might use str.match here:
df[df['Date'].str.match(r'^1395/01')]

But in general it is usually preferable to store dates as datetime and not text.  Also, the year 1395 seems dubious.

A: You can use loc and startswith to filter your dataframe.
Sample:
df = pd.DataFrame({'Date': ['1395/01/01', '1395/02/01', '1395/01/01', '1395/05/01']})
print(df)

          Date
0   1395/01/01
1   1395/02/01
2   1395/01/01
3   1395/05/01

Solution:
print(df.loc[df['Date'].str.startswith('1395/01'), :])

          Date
0   1395/01/01
2   1395/01/01

If you would like to extract year and month for all rows, you can use str.slice:
df['Extracted Date'] = df['Date'].str.slice(0, 7)
print(df)

          Date  Extracted Date
0   1395/01/01         1395/01
1   1395/02/01         1395/02
2   1395/01/01         1395/01
3   1395/05/01         1395/05


text:
Q: RavenDB - One client can't see changes from a different client I'm running two instances of my application. In one instance, I save one of my entities. When I check the RavenDB (http://localhost:8080/raven), I can see the change. Then, in my other client, I do this (below), but I don't see the changes from the other application. What do I need to do in order to get the most recent data in the DB?
public IEnumerable<CustomVariableGroup> GetAll()
{
    return Session
        .Query<CustomVariableGroup>()
        .Customize(x => x.WaitForNonStaleResults());
}

Edit: The code above works if I try to make a change and get a concurrency exception. After that, when I call refresh (which invokes the above code), it works.
Here is the code that does the save:
public void Save<T>(T objectToSave)
{
    Guid eTag = (Guid)Session.Advanced.GetEtagFor(objectToSave);
    Session.Store(objectToSave, eTag);
    Session.SaveChanges();
}

And here is the class that contains the Database and Session:
public abstract class DataAccessLayerBase
{
    /// <summary>
    /// Gets the database.
    /// </summary>
    protected static DocumentStore Database { get; private set; }

    /// <summary>
    /// Gets the session.
    /// </summary>
    protected static IDocumentSession Session { get; private set; }

    static DataAccessLayerBase()
    {
        if (Database != null) { return; }

        Database = GetDatabase();
        Session = GetSession();
    }

    private static DocumentStore GetDatabase()
    {
        string databaseUrl = ConfigurationManager.AppSettings["databaseUrl"];

        DocumentStore documentStore = new DocumentStore();

        try
        {
            //documentStore.ConnectionStringName = "RavenDb";  // See app.config for why this is commented.
            documentStore.Url = databaseUrl;
            documentStore.Initialize();
        }
        catch
        {
            documentStore.Dispose();
            throw;
        }

        return documentStore;
    }

    private static IDocumentSession GetSession()
    {
        IDocumentSession session = Database.OpenSession();

        session.Advanced.UseOptimisticConcurrency = true;

        return session;
    }
}

A: Lacking more detailed information and some code, I can only guess...
Please make sure that you call .SaveChanges() on your session. Without explicitly specifiying an ITransaction your IDocumentSession will be isolated and transactional between it's opening and the call to .SaveChanges. Either all operations succeed or none. But if you don't call it all your previous .Store calls will be lost.
If I was wrong, please post more details about your code.

EDIT: Second answer (after additional information):
Your problem has to do with the way RavenDB caches on the client-side. RavenDB by default caches every GET request throughout a DocumentSession. Plain queries are just GET queries (and no, it has nothing to do wheter your index in dynamic or manually defined upfront) and therefore they will be cached. The solution in your application is to dispose the session and open a new one.
I suggest you rethink your Session lifecycle. It seems that your sessions live too long, otherwise this concurrency wouldn't be an issue. If you're building a web-application I recommend to open and close the session with the beginning and the end of your request. Have a look at RaccoonBlog to see it implemented elegantly.

A: Bob,
It looks like you have but a single session in the application, which isn't right. The following article talks about NHibernate, but the session management parts applies to RavenDB as well:
http://archive.msdn.microsoft.com/mag200912NHibernate
This code is meaningless:
Guid eTag = (Guid)Session.Advanced.GetEtagFor(objectToSave);
Session.Store(objectToSave, eTag);

It basically a no op, but one that looks important. You seems to be trying to work with a model where you have to manually manage all the saves, don't do that. You only need to manage things yourself when you create a new item, that is all.
As for the reason you get this problem, here is a sample:
var session = documentStore.OpenSession();
var post1 = session.Load<Post>(1);
// change the post by another client
post2 = session.Load<Post>(1); // will NOT go to the server, will give the same instance as post1

Assert.ReferenceEquals(post1,post2);

Sessions are short lived, and typically used in the scope of a single form / request.


text:
Q: How can we extract values from a raster and put it in a shapefile? I just started using QGIS for a research project and I am not at all familiar with the software nor the formats used. I have a shapefile representing the different departments of France, delimited by borders, and a TIFF file with data points from all over the world that I want to extract and put in the shapefile.
I would like to capture the data from the TIFF file and compute an average for each department (from the shapefile), and put the results in a table (one average data point for each department).
How to do that?

A: Welcome to gis.stackexchange!
You are looking for the Zonal statistics raster analysis tool:

Under Raster layer select your raster, while Vector layer containing zones is your departments shapefile :)


text:
Q: Play Framework 2.3 Scala - Serialize Map[(String,CaseClass1),(CaseClass2,CaseClass3)] to JSon I have a Map which consists of tuple (String,CaseClass1) as a key and tuple (CaseClass2,CaseClass3) as value.
I created implicit Writers for each case class:
  implicit val caseClass1Writes = Json.writes[CaseClass1]
  implicit val caseClass2Writes = Json.writes[CaseClass2]
  implicit val caseClass3Writes = Json.writes[CaseClass3]

I tries to create another case class which contains all those tuples
TupleCaseClass(key:(String,CaseClass1),value:(CaseClass2,CaseClass3)) and then create implicit writer for this class, but the result is still the same :(
No Json serializer found for type Map[(String,CaseClass1),(CaseClass2,CaseClass3)]. Try to implement an implicit Writes or Format for this type.

A: Since you have tuples in your TupleCaseClass, Play does not implicitly understand how to write this (there's no obvious way to write a tuple of two custom objects).  You have to provide two more implicits to handle the tuples, e.g.
implicit val keyWrites = new Writes[(String, CaseClass1)]{
  def writes(o: (String, CaseClass1)) = Json.obj(o._1 -> o._2)
}

implicit val valueWrites = new Writes[(CaseClass2, CaseClass3)]{
  def writes(o: (CaseClass2, CaseClass3)) = Json.obj("caseClass2" -> o._1, "caseClass3" -> o._2)
}

A: Unfortunately, I had no other choice, but writing an implicit method which will transform Map[(String,CaseClass1),(CaseClass2,CaseClass3)] to List[TupleCaseClass]
val map:Map[(String,CaseClass1),(CaseClass2,CaseClass3)] = some map

can be easily converter to List of case Classes using foldLeft method
val list:List[TupleCaseClass] = map.foldLeft(List[TupleCaseClass]()){(l,t)=>l :+ ToupleCaseClass(t._1,t._2)}

and then Json.toJson(list)
This solution is ugly, I would expect Json parser to take care of such primitve structures like Tuples or Maps.
Hope it would be helpful for someone in the future.


text:
Q: Reassemble RAID 1 array from old system I recently upgraded my OS from RHEL 5 to 6. To do so, I installed the new OS on new disks, and I want to mount the old disks. The old disks are listed as /dev/sdc and sdd in the new system, they were created as a RAID 1 array using LVM, using the default setup from the RHEL install GUI.
I managed to mount the old disks and use them for the last two weeks, but after a reboot, they did not remount, and I can't figure out what to do to get them back on line. I have no reason to believe there is anything wrong with the disks.
(I'm in the process of doing dd copy of the disks, I have an older backup, but I hope I don't have to use either of these...)
Using fdisk -l :
# fdisk -l

Disk /dev/sdb: 300.1 GB, 300069052416 bytes
255 heads, 63 sectors/track, 36481 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00042e35

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1   *           1       30596   245760000   fd  Linux raid autodetect
/dev/sdb2           30596       31118     4194304   fd  Linux raid autodetect
/dev/sdb3           31118       36482    43080704   fd  Linux raid autodetect

Disk /dev/sda: 300.1 GB, 300069052416 bytes
255 heads, 63 sectors/track, 36481 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00091208

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1       30596   245760000   fd  Linux raid autodetect
/dev/sda2           30596       31118     4194304   fd  Linux raid autodetect
/dev/sda3           31118       36482    43080704   fd  Linux raid autodetect

Disk /dev/sdc: 640.1 GB, 640135028736 bytes
255 heads, 63 sectors/track, 77825 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00038b0e

   Device Boot      Start         End      Blocks   Id  System
/dev/sdc1               1       77825   625129281   fd  Linux raid autodetect

Disk /dev/sdd: 640.1 GB, 640135028736 bytes
255 heads, 63 sectors/track, 77825 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00038b0e

   Device Boot      Start         End      Blocks   Id  System
/dev/sdd1               1       77825   625129281   fd  Linux raid autodetect

Disk /dev/md2: 4292 MB, 4292804608 bytes
2 heads, 4 sectors/track, 1048048 cylinders
Units = cylinders of 8 * 512 = 4096 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/md1: 251.7 GB, 251658043392 bytes
2 heads, 4 sectors/track, 61439952 cylinders
Units = cylinders of 8 * 512 = 4096 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/md127: 44.1 GB, 44080955392 bytes
2 heads, 4 sectors/track, 10761952 cylinders
Units = cylinders of 8 * 512 = 4096 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

And then
# mdadm --examine /dev/sd[cd]
mdadm: /dev/sdc is not attached to Intel(R) RAID controller.
mdadm: /dev/sdc is not attached to Intel(R) RAID controller.
/dev/sdc:
          Magic : Intel Raid ISM Cfg Sig.
        Version : 1.1.00
    Orig Family : 8e7b2bbf
         Family : 8e7b2bbf
     Generation : 0000000d
     Attributes : All supported
           UUID : c8c81af9:952cedd5:e87cafb9:ac06bc40
       Checksum : 014eeac2 correct
    MPB Sectors : 1
          Disks : 2
   RAID Devices : 1

  Disk01 Serial : WD-WCASY6849672
          State : active
             Id : 00010000
    Usable Size : 1250259208 (596.17 GiB 640.13 GB)

[Volume0]:
           UUID : 03c5fad1:93722f95:ff844c3e:d7ed85f5
     RAID Level : 1
        Members : 2
          Slots : [UU]
    Failed disk : none
      This Slot : 1
     Array Size : 1250258944 (596.17 GiB 640.13 GB)
   Per Dev Size : 1250259208 (596.17 GiB 640.13 GB)
  Sector Offset : 0
    Num Stripes : 4883824
     Chunk Size : 64 KiB
       Reserved : 0
  Migrate State : idle
      Map State : uninitialized
    Dirty State : clean

  Disk00 Serial : WD-WCASY7183713
          State : active
             Id : 00000000
    Usable Size : 1250259208 (596.17 GiB 640.13 GB)
mdadm: /dev/sdd is not attached to Intel(R) RAID controller.
mdadm: /dev/sdd is not attached to Intel(R) RAID controller.
/dev/sdd:
          Magic : Intel Raid ISM Cfg Sig.
        Version : 1.1.00
    Orig Family : 8e7b2bbf
         Family : 8e7b2bbf
     Generation : 0000000d
     Attributes : All supported
           UUID : c8c81af9:952cedd5:e87cafb9:ac06bc40
       Checksum : 014eeac2 correct
    MPB Sectors : 1
          Disks : 2
   RAID Devices : 1

  Disk00 Serial : WD-WCASY7183713
          State : active
             Id : 00000000
    Usable Size : 1250259208 (596.17 GiB 640.13 GB)

[Volume0]:
           UUID : 03c5fad1:93722f95:ff844c3e:d7ed85f5
     RAID Level : 1
        Members : 2
          Slots : [UU]
    Failed disk : none
      This Slot : 0
     Array Size : 1250258944 (596.17 GiB 640.13 GB)
   Per Dev Size : 1250259208 (596.17 GiB 640.13 GB)
  Sector Offset : 0
    Num Stripes : 4883824
     Chunk Size : 64 KiB
       Reserved : 0
  Migrate State : idle
      Map State : uninitialized
    Dirty State : clean

  Disk01 Serial : WD-WCASY6849672
          State : active
             Id : 00010000
    Usable Size : 1250259208 (596.17 GiB 640.13 GB)

Trying to assemble:
# mdadm --assemble /dev/md3 /dev/sd[cd]
mdadm: no RAID superblock on /dev/sdc
mdadm: /dev/sdc has no superblock - assembly aborted

I've tried:
# mdadm --examine --scan /dev/sd[cd]
ARRAY metadata=imsm UUID=c8c81af9:952cedd5:e87cafb9:ac06bc40
ARRAY /dev/md/Volume0 container=c8c81af9:952cedd5:e87cafb9:ac06bc40 member=0 UUID=03c5fad1:93722f95:ff844c3e:d7ed85f5

And adding this to the /etc/mdadm.conf file, but it doesn't seem to help. I'm not sure what to try next. Any help would appreciated.
EDIT 1: Does "Magic : Intel Raid ISM Cfg Sig." indicate that I need to use dmraid?
EDIT 2: As suggested below, I tried dmraid, but I don't know what the response means:
# dmraid -ay
RAID set "isw_cdjaedghjj_Volume0" already active
device "isw_cdjaedghjj_Volume0" is now registered with dmeventd for monitoring
RAID set "isw_cdjaedghjj_Volume0p1" already active
RAID set "isw_cdjaedghjj_Volume0p1" was not activated

EDIT 2b: So, now I can see something here:
# ls /dev/mapper/
control  isw_cdjaedghjj_Volume0  isw_cdjaedghjj_Volume0p1

but it doesn't mount:
# mount /dev/mapper/isw_cdjaedghjj_Volume0p1 /mnt/herbert_olddrive/
mount: unknown filesystem type 'linux_raid_member'

EDIT 2c: Ok, maybe this might help:
# mdadm -I /dev/mapper/isw_cdjaedghjj_Volume0
mdadm: cannot open /dev/mapper/isw_cdjaedghjj_Volume0: Device or resource busy.

# mdadm -I /dev/mapper/isw_cdjaedghjj_Volume0p1
#

The second command returns nothing. Does this mean anything or am I way off track?
EDIT 3: /proc/mdstat:
# cat /proc/mdstat
Personalities : [raid1]
md127 : active raid1 sda3[1] sdb3[0]
      43047808 blocks super 1.1 [2/2] [UU]
      bitmap: 0/1 pages [0KB], 65536KB chunk

md1 : active raid1 sda1[1]
      245759808 blocks super 1.0 [2/1] [_U]
      bitmap: 2/2 pages [8KB], 65536KB chunk

md2 : active raid1 sda2[1]
      4192192 blocks super 1.1 [2/1] [_U]

unused devices: <none>

md1 and md2 are raid arrays on sda and sdb, which are used by the new OS.

A: A bit confused here - is it mdadm raid or lvm raid? In the question you mention lvm raid, yet keep trying to use mdadm raid.
for lvm - first use
pvscan -u

possibly
pvscan -a --cache /dev/sdc /dev/sdd

would be enough to recreate your device. if not, use
vgchange -ay VolGroup00

or
vgcfgrestore VolGroup00

The other possibility is that you used dmraid - can you try
dmraid -ay

but the disks must be connected to the intel fakeraid controller (make sure raid is enabled in bios for the ata slots the disks are connected to)

A: It appears that I had a conflict between the dmraid setup and the mdadm setup. I don't understand the details, but what I finally did to fix it was stop the dmraid
dmraid -an

and then assemble the drives to a whole new md device:
mdadm --assemble /dev/md4 /dev/sdc /dev/sdd

When I did this, /dev/md126 and /dev/md126p1 mysteriously appeared (mysterious to me, but I'm sure someone can explain it), and I mounted md126p1:
mount /dev/md126p1 /mnt/olddrive

And voilà: my data reappeared! There were a couple of corrupted files, but no data loss.
Thank you @Dani_l and @MadHatter for your help!


text:
Q: Usual arithmetic conversion -- a better set of rules? Consider the following code:
void f(byte x) {print("byte");}
void f(short x) {print("short");}
void f(int x) {print("int");}

void main() {
    byte b1, b2;
    short s1, s2;

    f(b1 + b2); // byte + byte = int
    f(s1 + s2); // short + short = int
}

In C++, C#, D, and Java, both function calls resolve to the "int" overloads... I already realize this is "in the specs", but why are languages designed this way? I'm looking for a deeper reason.
To me, it makes sense for the result to be the smallest type able to represent all possible values of both operands, for example:
byte + byte --> byte
sbyte + sbyte --> sbyte
byte + sbyte --> short
short + short --> short
ushort + ushort --> ushort
short + ushort --> int
// etc...

This would eliminate inconvenient code such as short s3 = (short)(s1 + s2), as well as IMO being far more intuitive and easier to understand.
Is this a left-over legacy from the days of C, or are there better reasons for the current behavior?

A: Quoted from this MSDN blog post:

byte b = 32; byte c = 240; int i = b +
  c; // what is i?
In this fantasy world, the value of i
  would be 16! Why? Because the two
  operands to the + operator are both
  bytes, so the sum "b+c" is computed as
  a byte, which results in 16 due to
  integer overflow. (And, as I noted
  earlier, integer overflow is the new
  security attack vector.)
Similarly,
int j = -b;
would result in j having the value 224
  and not -32, for the same reason.
Is that really what you want?
...
So no matter how you slice it, you're
  going to have to insert annoying
  casts. May as well have the language
  err on the side of safety (forcing you
  to insert the casts where you know
  that overflow is not an issue) than to
  err on the side of silence (where you
  may not notice the missing casts until
  your Payroll department asks you why
  their books don't add up at the end of
  the month).

Also, it's worth noting that adding in these casts only means extra typing, and nothing more. Once the JIT (or possibly the static compiler itself) reduces the arithmetic operation to a basic processor instruction, there's nothing clever going on - it's just whether the number gets treated as an int or byte.
This is a good question, however... not at all an obvious one. Hope that makes the reasons clear for you now.

A: A better set of rules IMHO, if one provided that the shifting operators could only be used with constant shift values (use shifting functions for variable shift amounts), would be that the results of any arithmetic expression should always evaluate as though it were processed with the largest possible signed or unsigned type, provided either could be statically guaranteed to give correct results (slightly tricky rules would apply in cases where the largest signed type might not be sufficient).  Provided shift operands are only allowed to be constants, one could determine pretty easily at compile time what the largest meaningful value of any operand could be, so I don't see any good reason for compilers not to look at how an operator's result is used in deciding on the implementation of the operator.