text:
Q: Hash string with SHA512 in Swift Anyone knows how to reproduce PHP hashing method hash('SHA512', $value, true) in swift ? I tried to use CommonCrypto C library with this code :
extension String {
    func digest(length:Int32, gen:(data: UnsafePointer<Void>, len: CC_LONG, md: UnsafeMutablePointer<UInt8>) -> UnsafeMutablePointer<UInt8>) -> String {
        var cStr = [UInt8](self.utf8)
        var result = [UInt8](count:Int(length), repeatedValue:0)
        gen(data: &cStr, len: CC_LONG(cStr.count), md: &result)
        let output = NSMutableString(capacity:Int(length))
        for r in result {
            output.appendFormat("%02x", r)
        }
        return String(output)
    }
}

and used it like this :
var digest = salted.digest(CC_SHA512_DIGEST_LENGTH, gen: {(data, len, md) in CC_SHA512(data,len,md)})

But I don't get the right output
EDIT :
I have some PHP code :
echo base64_encode(hash('sha512', '8yOrBmkd', true)); // output: rlltLWeWaQCrfNTYMa0CcIs0mfLoHGAynrd+d8H65+rGAzHS/BSWsumwSmcxF9aAG9TIzXx+HOjArPyLL3herg==

And I want my swift code to output the same. The Base64 encoding is ok :
let utf8str = input.dataUsingEncoding(NSUTF8StringEncoding)!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
                let base64Encoded = utf8str!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
                print("Encoded:  \(base64Encoded)")

But the hashing part return an output the same value as this PHP code :
echo base64_encode(hash('sha512', '8yOrBmkd', false)); // output: YWU1OTZkMmQ2Nzk2NjkwMGFiN2NkNGQ4MzFhZDAyNzA4YjM0OTlmMmU4MWM2MDMyOWViNzdlNzdjMWZhZTdlYWM2MDMzMWQyZmMxNDk2YjJlOWIwNGE2NzMxMTdkNjgwMWJkNGM4Y2Q3YzdlMWNlOGMwYWNmYzhiMmY3ODVlYWU=

A: Swift 3 implementatiomn at bottom.
The code does not need to be so complex or an extension:
func sha512Hex(string string: String) -> String {
    var digest = [UInt8](count: Int(CC_SHA512_DIGEST_LENGTH), repeatedValue: 0)
    if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
        CC_SHA512(data.bytes, CC_LONG(data.length), &digest)
    }

    var digestHex = ""
    for index in 0..<Int(CC_SHA512_DIGEST_LENGTH) {
        digestHex += String(format: "%02x", digest[index])
    }

    return digestHex
}

//Test:
let hexDigest = sha512Hex(string:"8yOrBmkd")
print("hexDigest:\n\(hexDigest)")

Output:

hexDigest:
  ae596d2d67966900ab7cd4d831ad02708b3499f2e81c60329eb77e77c1fae7eac60331d2fc1496b2e9b04a673117d6801bd4c8cd7c7e1ce8c0acfc8b2f785eae

Just returing the byte array:
func sha512(string string: String) -> [UInt8] {
    var digest = [UInt8](count: Int(CC_SHA512_DIGEST_LENGTH), repeatedValue: 0)
    let data = string.dataUsingEncoding(NSUTF8StringEncoding)!
    CC_SHA512(data.bytes, CC_LONG(data.length), &digest)

    return digest
}

//Test:
let digestRaw = sha512(string:"8yOrBmkd")
print("decimal array:\n\(digestRaw)")
print("hexadecimal:\n\(NSData(bytes:digestRaw, length:digestRaw.count).description)")

Output:

decimal array:
  [174, 89, 109, 45, 103, 150, 105, 0, 171, 124, 212, 216, 49, 173, 2, 112, 139, 52, 153, 242, 232, 28, 96, 50, 158, 183, 126, 119, 193, 250, 231, 234, 198, 3, 49, 210, 252, 20, 150, 178, 233, 176, 74, 103, 49, 23, 214, 128, 27, 212, 200, 205, 124, 126, 28, 232, 192, 172, 252, 139, 47, 120, 94, 174]
hexadecimal:
  ae596d2d67966900ab7cd4d831ad02708b3499f2e81c60329eb77e77c1fae7eac60331d2fc1496b2e9b04a673117d6801bd4c8cd7c7e1ce8c0acfc8b2f785eae

Base64 output:
func sha512Base64(string string: String) -> String {
    let digest = NSMutableData(length: Int(CC_SHA512_DIGEST_LENGTH))!
    if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
        CC_SHA512(data.bytes, CC_LONG(data.length), UnsafeMutablePointer<UInt8>(digest.mutableBytes))
    }
    return digest.base64EncodedStringWithOptions(NSDataBase64EncodingOptions([]))
}

//Test:
let digestBase64 = sha512Base64(string:"8yOrBmkd")
print("Base64:\n\(digestBase64)")

Output:
Base64:
rlltLWeWaQCrfNTYMa0CcIs0mfLoHGAynrd+d8H65+rGAzHS/BSWsumwSmcxF9aAG9TIzXx+HOjArPyLL3herg==

Swift 3

func hashSHA512(data:Data) -> String? {
    var hashData = Data(count: Int(CC_SHA512_DIGEST_LENGTH))

    _ = hashData.withUnsafeMutableBytes {digestBytes in
        data.withUnsafeBytes {messageBytes in
            CC_SHA512(messageBytes, CC_LONG(data.count), digestBytes)
        }
    }

    // For hexadecimal output:
    return hashData.map { String(format: "%02hhx", $0) }.joined()
    // For Base64 output use this instead of the above:
    // return data.base64EncodedString()
}

Example from deprecated documentation section:
HMAC with MD5, SHA1, SHA224, SHA256, SHA384, SHA512 (Swift 3+)

These functions will hash either String or Data input with one of eight cryptographic hash algorithms.

The name parameter specifies the hash function name as a String
Supported functions are MD5, SHA1, SHA224, SHA256, SHA384 and SHA512
This example requires Common Crypto
It is necessary to have a bridging header to the project:
#import <CommonCrypto/CommonCrypto.h>
Add the Security.framework to the project.
These functions takes a hash name, message to be hashed, a key and return a digest:

hashName: name of a hash function as String
message:  message as Data
key:      key as Data
returns:  digest as Data

func hmac(hashName:String, message:Data, key:Data) -> Data? {
    let algos = ["SHA1":   (kCCHmacAlgSHA1,   CC_SHA1_DIGEST_LENGTH),
                 "MD5":    (kCCHmacAlgMD5,    CC_MD5_DIGEST_LENGTH),
                 "SHA224": (kCCHmacAlgSHA224, CC_SHA224_DIGEST_LENGTH),
                 "SHA256": (kCCHmacAlgSHA256, CC_SHA256_DIGEST_LENGTH),
                 "SHA384": (kCCHmacAlgSHA384, CC_SHA384_DIGEST_LENGTH),
                 "SHA512": (kCCHmacAlgSHA512, CC_SHA512_DIGEST_LENGTH)]
    guard let (hashAlgorithm, length) = algos[hashName]  else { return nil }
    var macData = Data(count: Int(length))

    macData.withUnsafeMutableBytes {macBytes in
        message.withUnsafeBytes {messageBytes in
            key.withUnsafeBytes {keyBytes in
                CCHmac(CCHmacAlgorithm(hashAlgorithm),
                       keyBytes,     key.count,
                       messageBytes, message.count,
                       macBytes)
            }
        }
    }
    return macData

    }

hashName: name of a hash function as String
message:  message as String
key:      key as String
returns:  digest as Data

func hmac(hashName:String, message:String, key:String) -> Data? {
    let messageData = message.data(using:.utf8)!
    let keyData = key.data(using:.utf8)!
    return hmac(hashName:hashName, message:messageData, key:keyData)
}

hashName: name of a hash function as String
message:  message as String
key:      key as Data
returns:  digest as Data

func hmac(hashName:String, message:String, key:Data) -> Data? {
    let messageData = message.data(using:.utf8)!
    return hmac(hashName:hashName, message:messageData, key:key)
}

// Examples
let clearString = "clearData0123456"
let keyString   = "keyData8901234562"
let clearData   = clearString.data(using:.utf8)!
let keyData     = keyString.data(using:.utf8)!
print("clearString: \(clearString)")
print("keyString:   \(keyString)")
print("clearData: \(clearData as NSData)")
print("keyData:   \(keyData as NSData)")

let hmacData1 = hmac(hashName:"SHA1", message:clearData, key:keyData)
print("hmacData1: \(hmacData1! as NSData)")

let hmacData2 = hmac(hashName:"SHA1", message:clearString, key:keyString)
print("hmacData2: \(hmacData2! as NSData)")

let hmacData3 = hmac(hashName:"SHA1", message:clearString, key:keyData)
print("hmacData3: \(hmacData3! as NSData)")

Output:
clearString: clearData0123456
keyString:   keyData8901234562
clearData: <636c6561 72446174 61303132 33343536>
keyData:   <6b657944 61746138 39303132 33343536 32>

hmacData1: <bb358f41 79b68c08 8e93191a da7dabbc 138f2ae6>
hmacData2: <bb358f41 79b68c08 8e93191a da7dabbc 138f2ae6>
hmacData3: <bb358f41 79b68c08 8e93191a da7dabbc 138f2ae6>

MD2, MD4, MD5, SHA1, SHA224, SHA256, SHA384, SHA512 (Swift 3+)

These functions will hash either String or Data input with one of eight cryptographic hash algorithms.

The name parameter specifies the hash function name as a String
Supported functions are MD2, MD4, MD5, SHA1, SHA224, SHA256, SHA384 and SHA512
a
This example requires Common Crypto
It is necessary to have a bridging header to the project:
#import <CommonCrypto/CommonCrypto.h>
Add the Security.framework to the project.

This function takes a hash name and String to be hashed and returns a Data:

name: A name of a hash function as a String
string: The String to be hashed
returns: the hashed result as Data

func hash(name:String, string:String) -> Data? {
    let data = string.data(using:.utf8)!
    return hash(name:name, data:data)
}

Examples:
let clearString = "clearData0123456"
let clearData   = clearString.data(using:.utf8)!
print("clearString: \(clearString)")
print("clearData: \(clearData as NSData)")

let hashSHA256 = hash(name:"SHA256", string:clearString)
print("hashSHA256: \(hashSHA256! as NSData)")

let hashMD5 = hash(name:"MD5", data:clearData)
print("hashMD5: \(hashMD5! as NSData)")

Output:
clearString: clearData0123456
clearData: <636c6561 72446174 61303132 33343536>

hashSHA256: <aabc766b 6b357564 e41f4f91 2d494bcc bfa16924 b574abbd ba9e3e9d a0c8920a>
hashMD5: <4df665f7 b94aea69 695b0e7b baf9e9d6>

A: Updating this with swift 4
func sha512Hex( string: String) -> String {
    var digest = [UInt8](repeating: 0, count: Int(CC_SHA512_DIGEST_LENGTH))
    if let data = string.data(using: String.Encoding.utf8) {
        let value =  data as NSData
        CC_SHA512(value.bytes, CC_LONG(data.count), &digest)

    }
    var digestHex = ""
    for index in 0..<Int(CC_SHA512_DIGEST_LENGTH) {
        digestHex += String(format: "%02x", digest[index])
    }

    return digestHex
}

func sha512(string: String) -> [UInt8] {
    var digest = [UInt8](repeating: 0, count: Int(CC_SHA512_DIGEST_LENGTH))
    let data = string.data(using: String.Encoding.utf8 , allowLossyConversion: true)
    let value =  data! as NSData
    CC_SHA512(value.bytes, CC_LONG(value.length), &digest)

    return digest
}

func sha512Base64(string: String) -> String {
    let digest = NSMutableData(length: Int(CC_SHA512_DIGEST_LENGTH))!
    if let data = string.data(using: String.Encoding.utf8) {

        let value =  data as NSData
        let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: digest.length)
        CC_SHA512(value.bytes, CC_LONG(data.count), uint8Pointer)

    }
    return digest.base64EncodedString(options: NSData.Base64EncodingOptions([]))
}

Testing
    let vad = sha512Hex(string: "8yOrBmkd")
    print(vad)

    let digestRaw = sha512(string:"8yOrBmkd")
    print("decimal array:\n\(digestRaw)")
    print("hexadecimal:\n\(NSData(bytes:digestRaw, length:digestRaw.count).description)")

    let digestBase64 = sha512Base64(string:"8yOrBmkd")
    print("Base64:\n\(digestBase64)")

A: With CryptoKit added in iOS13, we now have native Swift API:
import Foundation
import CryptoKit

// CryptoKit.Digest utils
extension Digest {
    var bytes: [UInt8] { Array(makeIterator()) }
    var data: Data { Data(bytes) }

    var hexStr: String {
        bytes.map { String(format: "%02X", $0) }.joined()
    }
}

func example() {
    guard let data = "hello world".data(using: .utf8) else { return }
    let digest = SHA512.hash(data: data)
    print(digest.data) // 64 bytes
    print(digest.hexStr) // 309ECC489C12D6EB4CC40F50C902F2B4D0ED77EE511A7C7A9BCD3CA86D4CD86F989DD35BC5FF499670DA34255B45B0CFD830E81F605DCF7DC5542E93AE9CD76F
}


text:
Q: Why GetType() of a class "sliced" by interface tell me its a class type that isn't? Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            ISampleInterface a = new A();
            ISampleInterface b = new B();

            a.SampleMethod();
            b.SampleMethod();

            //Console.WriteLine(a.myValue); // can't do it!! a is not A
            Console.WriteLine(a.GetType()); // uhm...
        }
    }

    interface ISampleInterface
    {
        void SampleMethod();
    }

    class A : ISampleInterface
    {
        public double myValue = 10.0;

        public void SampleMethod() {
            Console.WriteLine("A");
        }
    }

    class B : ISampleInterface
    {
        public double myValue = 20.0;

        public void SampleMethod() {
            Console.WriteLine("B");
        }
    }
}

I init a class by interface (implemented by the class).
Obviously, can't access to a.myValue, because correctly Rextester.ISampleInterface doesn't contain such a definition.
But if I ask to compiler which type is a, it outputs Rextester.A (which is not, I believe).
Why? And more important, which kind of class is a? A sort of hybrid-sliced class limited by its interface? Not sure how I would define it...

A: What methods you can call (outside reflection/dynamic) are based on the compile-time type of the variable.
Reference casts (which is what casting an existing reference to an interface it implements is) don't change the type of the object at all. But if you're storing the result of that cast in a variable, the type of the variable is what matters.
There's nothing comparable to C++'s slicing (what I presume you're referring to by slicing) in the .NET world, that I can think of - certainly you wouldn't get it from writing straightforward code.
A variable that is declared to be of an interface type will never contain a reference to something that is "just" that interface. It'll always be an object of some specific concrete struct/class type.

A:
But if I ask to compiler which type is a, it outputs Rextester.A (which is not, I believe)

If by "asking the compiler" you mean calling a.GetType(), that's not what you're doing. You're asking the runtime for the actual type of the object that a references. The runtime correctly tells you that it is a Rextester.A.
The compiler on the other hand, does not know this. The variable is declared as an ISampleInterface, so all the compiler can safely do is bind to methods defined by the interface.
If you cast the variable to an A, then you can access its members:
A newA = a;
newA.myValue = 15;  // perfectly valid

Note that the actual object that a references has not changed  (meaning it's the same object - obviously you changed one of its member fields). You can still reference is as the interface through a or the class through newA.
If you had asked the compiler what type a is but using a method like this:
public Type GetCompileTimeType<T>(T inputObject)
{
    return typeof(T);
}

(credit to this answer)
and calling
Console.WriteLine(GetCompileTimeType(a));

you'd get Rextester.ISampleInterface

A: a.myValue cannot be accessed because it's in scope as ISampleInterface
a.GetType() correctly results in A because this is resolved at runtime to the instance of the type assigned to a, which is A. It's only in scope as ISampleInterface.
For example...
ISampleInterface a = new A();

You are creating an instance of A declared as ISampleInterface.
a.SampleMethod();

You can access things that are declared.
Console.WriteLine(a.myValue);

You can't access things that are not declared.
Console.WriteLine(a.GetType());

GetType is callable from System.Object which everything naturally extends, so you can call this, because it's declared from an implicit base type. In this context, GetType returns A because that's exactly what a is; an instance of A.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SFINAE to detect the explicitness of a CTAD deduction guide Little-known feature of CTAD (class template argument deduction) in C++17: you can mark user-defined deduction guides as explicit.
(Godbolt.)
template<class T> struct A { A(int); };           A(int) -> A<int>;
template<class T> struct B { B(int); };  explicit B(int) -> B<int>;

A<int> a = 1;  // OK, constructor of A<int> is implicit
B<int> b = 1;  // OK, constructor of B<int> is implicit

auto a = A(1);  // OK, deduction guide of A exists
auto b = B(1);  // OK, deduction guide of B exists

A a = 1;  // OK, deduction guide of A is non-explicit
B b = 1;  // ERROR!! deduction guide of B is explicit

So, class templates A and B have observably different behavior.
I'd like to write a unit test that static_asserts that one of my templates behaves like B, not like A.
static_assert(!has_properly_explicit_deduction_guide_v<A>);
static_assert(has_properly_explicit_deduction_guide_v<B>);

Is this possible in C++17 and/or C++20 and/or "C++future"?

A: No.
You can't check declarations, so you can't check the validity of A a = 1; or B b = 1;
And class template argument deduction isn't valid in any other copy-initialization contexts. So while you can check "implicitly convertible" by seeing if the expression [](To){}(from) is valid, you cannot check "implicitly class-template-argument-deducible" by seeing if the expression [](A){}(1) is valid, since you cannot just write A there.
The only thing that you can check is whether A(1) is valid or not, but that is direct initialization, and so would not be able to validate explicitness.

A: Currently, per [dcl.type.class.deduct], a placeholder for a deduced class type can appear in:

*

*the initializing declaration of a variable;

*a new-expression;

*explicit type conversion (functional notation); or

*a non-type template parameter [NTTP].

The first of these is not SFINAE-able (either classically or in a requires clause), since it is a declaration and not an expression; the next two invoke direct-initialization, not copy-initialization; and the last only works for structural types with constexpr constructors (although this isn't particularly clear from the Standard).
wrt. future direction, back in 2018 Mike Spertus was angling for CTAD on function template arguments: Improving function templates with Class Template Argument Deduction, How to make Terse Notation soar with Class Template Argument Deduction. There hasn't been much movement on this since then, but perhaps it could be resurrected.


text:
Q: What are the differences between PEGs and CFGs? From this wikipedia page:

The fundamental difference between
  context-free grammars and parsing
  expression grammars is that the PEG's
  choice operator is ordered. If the
  first alternative succeeds, the second
  alternative is ignored. Thus ordered
  choice is not commutative, unlike
  unordered choice as in context-free
  grammars and regular expressions.
  Ordered choice is analogous to soft
  cut operators available in some logic
  programming languages.

Why does PEG's choice operator short circuits the matching? Is it because to minimize memory usage (due to memoization)?
I'm not sure what the choice operator is in regular expressions but let's suppose it is this: /[aeiou]/ to match a vowel. So this regex is commutative because I could have written it in any of the 5! (five factorial) permutations of the vowel characters? i.e. /[aeiou]/ behaves the same as /[eiaou]/. What is the advantage of it being commutative? (c.f. PEG's non-commutativity)

The consequence is that if a CFG is
  transliterated directly to a PEG, any
  ambiguity in the former is resolved by
  deterministically picking one parse
  tree from the possible parses. By
  carefully choosing the order in which
  the grammar alternatives are
  specified, a programmer has a great
  deal of control over which parse tree
  is selected.

Is this saying that PEG's grammar is superior to CFG's?

A: A CFG grammar is non-deterministic, meaning that some input could result in two or more possible parse-trees. Though most CFG-based parser-generators have restrictions on the determinability of the grammar. It will give a warning or error if it has two or more choices.
A PEG grammar is deterministic, meaning that any input can only be parsed one way.
To take a classic example; The grammar
if_statement := "if" "(" expr ")" statement "else" statement
              | "if" "(" expr ")" statement;

applied to the input
if (x1) if (x2) y1 else y2

could either be parsed as
if_statement(x1, if_statement(x2, y1, y2))

or
if_statement(x1, if_statement(x2, y1), y2)

A CFG-parser would generate a Shift/Reduce-conflict, since it can't decide if it should shift (read another token), or reduce (complete the node), when reaching the "else" keyword. Of course, there are ways to get around this problem.
A PEG-parser would always pick the first choice.
Which one is better is for you to decide. My opinion is that often PEG-grammars is easier to write, and CFG grammars easier to analyze.

A: I think you're confusing CFG with LR and with ambiguity. Grammars are not deterministic/nondeterministic, though their parsers may be. An ambiguous grammar is still CFG if it complies with the definition, and a deterministic parser can be built for it doing what PEG does.

A: PEGs and CFGs are two different ways of specifying a language. If you write a parser by hand, chances are very good that you will write a so-called recursive descent parser. A recursive descent parser will automatically resolve any ambiguities in your grammar, but does so silently and likely not in the way you would have wanted. The problem with this is that you never find out that there were ambiguities that got automatically resolved, unless you thoroughly test your parser. PEGs are basically a formalization of recursive descent parsers, and so come with this problem. For examples of this problem see How does backtracking affect the language recognized by a parser?, and https://cs.stackexchange.com/questions/143480/dragon-book-4-4-5-exercise/143975.
CFGs have a lot of theory to back them up, but PEGs not so much. The set of languages that can be encoded by CFG and those that can be encoded by PEG partially overlap, but neither encompasses the other.
For a more thorough review of this I recommend the excellent essay Which Parsing Approach?


text:
Q: Render django formset with two forms per row I'm trying to render a particular field in each form where each pair of fields should  appear in a single row.
<form method="post" action="settings/developer" id="ipwhitelist-form">{% csrf_token %}
      <input type="hidden" name="action" value="whitelistips">
      <input type="hidden" name="apikey" value="{{apikey}}">
      {{ formset.management_form }}

          {{ formset.0.id }}
          {% bootstrap_field formset.0.ip_range placeholder="0.0.0.0/0" addon_after='' %}

          {{ formset.1.id }}
          {% bootstrap_field formset.1.ip_range placeholder="0.0.0.0/0" addon_after='' %}

          {{ formset.2.id }}
          {% bootstrap_field formset.2.ip_range placeholder="0.0.0.0/0" addon_after='' %}

          {{ formset.3.id }}
          {% bootstrap_field formset.3.ip_range placeholder="0.0.0.0/0" addon_after='' %}

  </form>

In the above, I just hard-coded the form number and accessed it through formset.form-num . What I want is to do iterate over forms  and then access two forms at a time .. Note that I want only one field from each form to get rendered...


text:
Q: How to build eclipse-plugin for CDH4 ( 4.2.0 ) is there any one know how to build eclipse-plugin for CDH4 ( 4.2.0 )?
I google it all the morning and only found some tips about 4.1.2 or older version.
My hadoop cluster is build by Cloudera Management, and the latest version of CDH is 4.2.0, I don't know how to build eclipse-plugin, or I should just roll back my CDH version to 4.1.2? if so, how to do that?


text:
Q: SSRS report "unable to load client print control" We're using SQL Server 2008 for a (third-party) web app, and they utilise SSRS for reporting.
Recently, so I'm assuming this is related in some way to an MS patch, whenever we click on the "print" icon in a report we get an error popup:
Message from webpage
Unable to load client print control.

*

*The web server is Windows Server 2003 R2 x32

*The SSRS server is Windows SQL Server 2008 10.0.2531.0

*The SQL server is Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)

*The clients are Windows 7 and Windows XP

All the servers are up-to-date according to Windows Update.
The SSRS server also has the "Security Update for Report Viewer Redistributable 2008 Service Pack 1 (KB971119) installed.

A: The report redist must also be installed on any application/web servers if the app is using the report viewer .net control.
Users also need admin rights to install the activeX in xp.
We automate the installation of these component to all users - similar to this:  http://www.kodyaz.com/articles/client-side-printing-silent-deployment-of-rsclientPrint.aspx
This was an enlightening post when I had this problem.


text:
Q: Automatic class type inferences based off properties If i have four classes: Library, Function, Display and Information.
And two properties: Requires and Provides.
Where the range of both properties is the class: Information.
How do i use protege to say that:

*

*If an object both Requires and Provides Information then it is an
instance of the class Function.

*If an object only Requires Information then it is an instance of the
class Display.

*If an object only Provides Information then it is an instance of the
class Library.


text:
Q: JQuery Image slider load pictures from json I am using a JQuery plugin tiksluscarousel. It works fines for static html code. which is shown in .

$('.page-content-area').ace_ajax('loadScripts', scripts, function() {

    jQuery(document).ready(function(){
        $("#fruits").tiksluscarousel({width:640,height:480,nav:'thumbnails',current:1});
    });
});

Then i want to load images from a JSON. Then the slider effects gone. which is

var data = {"data": [{
        "name": "Nike air foamposite \"hyper colbalt/ben gordan\" pre order 8/26",
        "imagepath": "http://tikslus.com/web/bundles/tikslustikslus/examples/carousel/fruits3.jpg"
    },
    {
        "name": "Nike air foamposite \"hyper colbalt/ben gordan\" pre order 8/26",
        "imagepath": "http://tikslus.com/web/bundles/tikslustikslus/examples/carousel/fruits2.jpg"
    },
    {
        "name": "Nike air foamposite \"hyper colbalt/ben gordan\" pre order 8/26",
        "imagepath": "http://tikslus.com/web/bundles/tikslustikslus/examples/carousel/fruits1.jpg"
    },
    {
        "name": "Nike air foamposite \"hyper colbalt/ben gordan\" pre order 8/26",
        "imagepath": "http://tikslus.com/web/bundles/tikslustikslus/examples/carousel/fruits4.jpg"
    }
]}
var node = document.getElementById("fruits1")
for (var i in data.data) {
    var newItem = document.createElement("li");
    var img = document.createElement("img");
    img.src = data.data[i].imagepath;
    newItem.appendChild(img);
    node.appendChild(newItem);
}

$('.page-content-area').ace_ajax('loadScripts', scripts, function() {

    jQuery(document).ready(function(){

$("#fruits1").tiksluscarousel({width:640,height:480,nav:'thumbnails',current:1});
    });
});

I can not find the reason why the effect gone.
Please help me.

A: var node = document.getElementById("fruits1") will return the div not the ul. you have to append the li to the ul child of div.
try
var node = document.getElementById("fruits1").child[0];

instead of var node = document.getElementById("fruits1")
hope this helps.


text:
Q: How to find a value by class name in WatiN? I have the below span in an HTML file:
page 5 of 9

How to find this span using WatiN selectors for classes?
the .Span() method of the ie object accepts only a spanId.
I'd need something like this:
ie.SpanByClasses(new[]{"pagenavigation", "pagecount"});

A: Assuming you want a C# solution, you can get the span using
Span sp = el.Span(Find.ByClass("pagenavigation pagecount"));

where el is the parent element such as a Div or even the full Document ie.


text:
Q: jQuery, Shadowbox and AJAX I would like to load some content using AJAX and Shadowbox
Basically I would like the user to goto a page in case javascript is off. So this is what I want to do :-
1) Cancel the click event i.e the User must not go to a different page.
2) Load content using ajax function in jQuery
3) Show the content inside a shadow box
My code works ok until loading content using ajax but the shadowbox is not displayed and the URL is gettin refreshed i guess, everything goes blank.
jQuery(document).ready(function($){
    // rounded corners
    $('img').addClass('corner iradius16');
    DD_roundies.addRule('#nav li a',4,true);
    DD_roundies.addRule('.grid',6,true);

    $('h2 a').bind('click', function() {
        var id = $(this).attr('id');
        $.ajax({
            url: "/ajax-post.php?p="+id,
            success: function(data){
                Shadowbox.open({
                    content:    data,
                    player:     "html",
                    height:     350,
                    width:      350
                });
            }
         });
        return false;
    });

UPDATE 1
tried this code, and as soon as the shadowbox loads, the document gets reloaded and white.
Shadowbox.init({
    skipSetup: true,
    players: ["html"]
});

  // LOAD
jQuery(document).ready(function($){
    // rounded corners
    $('img').addClass('corner iradius16');
    DD_roundies.addRule('#nav li a',4,true);
    DD_roundies.addRule('.grid',6,true);

    $('.post h2 a').bind('click', function() {
        var id = $(this).attr('id');
        $.ajax({
            url: "<?php bloginfo( 'template_directory'); ?>/ajax-post.php?p="+id,
            success: function(data){
                show_box(data);
            }
         });
        return false;
    });

});

//shadowbox
function show_box(html) {
    Shadowbox.open({
        content:    html,
        player:     "html",
        height:     350,
        width:      350
    });
}

UPDATE 2
Okay got the prbolem, the html that I am getting via ajax has some javascript in it and that is the reason for the page reload.
Why is this happening ? Any ideas ?

A: Since you're not getting any JavaScript errors try debugging by breaking it down:
Ensure that the binding to and overriding of the click event is functioning properly:
$('h2 a').bind('click', function() {
    alert('click even fired');
    return false;
});

If that works, check the data that your ajax request is returning:
$('h2 a').bind('click', function() {
    var id = $(this).attr('id');
    $.ajax({
        url: "ajax-post.php?p="+id,
        success: function(data){
           alert(data);
        }
     });
    return false;
});

The code looks like it should work, so I'm guessing there's either something wrong elsewhere (in which case the first test will likely fail) or you're getting some really odd data returned.

A: Need to run
Shadowbox.setup('h2 a');

This will reinitialise and bind it to any ajax loaded content


text:
Q: How to change unique key to new field and update all the documents without re-indexing? I want to change the unique key field of documents to a new field, and update documents without re-indexing. What are the options do we have to achieve this? Solr version 8.2 and using solr cloud.

A: If you change anything on the schema side, you need to reindex the data.
There is an alternative to it.
But the solr cloud has nice feature that can be used here without restarting the solr server.

*

*Create a new config set.

*Make all your changes in the newly created configSet.

*Upload the newly created configset as zookeper maintains all your configsets.

*Create a new collection using the new configset.

*Index your data in new collection.

*Once all the data is indexed, create an alias to new collection.

*Give the alias name same as the old collection.

*All your new request will be redirected to new collection.

*Once everything is set you can delete the old collection.


text:
Q: Python block thread if list is empty Is there a way to make a thread go to sleep if the list is empty and wake it up again when there are items? I don't want to use Queues since I want to be able to index into the datastructure.

A: Yes, the solution will probably involve a threading.Condition variable as you note in comments.
Without more information or a code snippet, it's difficult to know what API suits your needs.  How are you producing new elements?  How are you consuming them?  At base, you could do something like this:
cv = threading.Condition()
elements = []  # elements is protected by, and signaled by, cv

def produce(...):
  with cv:
    ... add elements somehow ...
    cv.notify_all()

def consume(...):
  with cv:
    while len(elements) == 0:
      cv.wait()
    ... remove elements somehow ...

A: I would go with this:
import threading

class MyList (list):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._cond = threading.Condition()

    def append(self, item):
        with self._cond:
            super().append(item)
            self._cond.notify_all()

    def pop_or_sleep(self):
        with self._cond:
            while not len(self):
                self._cond.wait()
            return self.pop()


text:
Q: Why is Puppeteer not displayed as a child process on IIS? I have a node.js server which runs a child process on the server when the user requests.
This child process is managed by npm package 'child_process' and running a 'Puppeteer' script.
The whole process works as expected on local.
The problem is when I check it on the server, and then - the process IS executed and logs are printed, BUT I don't see the browser of puppeteer even though it's in headless false.
The server uses IIS and I suspect that maybe it's related.
p.s. I also tried the npm package 'execa' for the execution of the child process, and nothing changed.
Any ideas?
Thanks


text:
Q: Amazon Mechanical Turk ExternalQuestions Image URL I'm trying to make an ExternalQuestion HIT and was wondering how I could pass S3 image URLs to the hit and display them.
I considered passing the URL as a url parameter but that doesn't make sense since it's a url.
Is it possible to do something like this?
<ExternalQuestion xmlns="[the ExternalQuestion schema URL]">
  <ExternalURL>http://tictactoe.amazon.com/gamesurvey.cgi?gameid=01523</ExternalURL>
  <FrameHeight>400</FrameHeight>
  <ImageURL1>[image_url]</ImageURL1>
  <ImageURL2>[image_url]</ImageURL2>
   ....
</ExternalQuestion>

A: It looks like you're trying to do something like what the Requester User Interface does when creating a batch, which involves building an HTMLQuestion out of a template HTML page with some named variables and a CSV file containing the values for each variable.
The ExternalQuestion only contains the ExternalURL and FrameHeight parameters. If you want to display different images, those need to be on their own pages (i.e., your server needs to decide what image to display to a given worker OR you have to create multiple HITs, one for each page that contains a distinct URL).


text:
Q: Верстка колонки строк с увеличением каждой новой строки на 30px Есть три строки, каждая новая увеличивается на 30px. Как такое можно реализовать? С помощью функции calc возможно или нет?

Код HTML:

Fully responsive design

Hihh quality code

Diffetent headers & layout

Или придется каждому присваивать класс и ставить ширину?

A: Если не пугает вложенность элементов, можно сделать вот так. Не надо высчитывать для каждого элемента отдельную ширину; ее легко изменить для всех строк, меняя только паддинг у .parent.

.container {width: 300px;}

.parent {
  padding-right: 30px;
}

.line {
  padding: 5px;
  background-color: coral;
  margin-bottom: 5px;
}

Line 1

Line 2

Line 3

Line 4

Line 5

Line 6

A: Можно вот так, например:

.list{
  width: 500px
}
.list > div{
  background: blue;
  margin-bottom: 10px;
  padding: 10px;
  color: white;
  width: 100%;
}
.list > div:nth-child(2){
  width: calc(100% - 30px)
}
.list > div:nth-child(3){
  width: calc(100% - 60px)
}

Fully responsive design

Hihh quality code

Diffetent headers & layout

A: Просто пропиши margin-right:

section {
  width: 50%;
  margin: auto;
  border: 1px dotted blue;
}

div {
  background: silver;
  padding: .5em;
}

div + div {
  margin-top: .5em;
}

Fully responsive design

Hihh quality code

Diffetent headers & layout


text:
Q: Connection not closed after transaction completion HikariCP Spring Boot Version :1.5.6 and Hikari Pool 2.7.3 And Hibernate

java.lang.Exception: Apparent connection leak detected    at
com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112)
at
org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at
org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:386)
at
org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:87)
at
org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:112)
at
org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:230)
at
org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.begin(LogicalConnectionManagedImpl.java:237)
at
org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.begin(JdbcResourceLocalTransactionCoordinatorImpl.java:214)
at
org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:52)
at
org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1512)
at
org.hibernate.jpa.internal.TransactionImpl.begin(TransactionImpl.java:45)
at
org.springframework.orm.jpa.vendor.HibernateJpaDialect.beginTransaction(HibernateJpaDialect.java:189)
at
org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:380)
at
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
at
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447)
at
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277)
at
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
at
ariba.sellerdirect.fileprocessor.processor.SingleItemProcessor$$EnhancerBySpringCGLIB$$a84b87d5.diffAndStoreMasterItem()
at
ariba.sellerdirect.fileprocessor.processor.csv.MasterContentCSVProcessor.processDiffAndStoreItem(MasterContentCSVProcessor.java:66)
at
ariba.sellerdirect.fileprocessor.processor.csv.MasterContentCSVProcessor.processSingleItem(MasterContentCSVProcessor.java:43)
at
ariba.sellerdirect.fileprocessor.processor.csv.GeneralCSVProcessor.processFile(GeneralCSVProcessor.java:109)
at
ariba.sellerdirect.fileprocessor.processor.csv.GeneralCSVProcessor$$FastClassBySpringCGLIB$$6777a9.invoke()
at
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at
ariba.sellerdirect.util.PerformanceMonitorInterceptor.invokeUnderTrace(PerformanceMonitorInterceptor.java:24)
at
org.springframework.aop.interceptor.AbstractTraceInterceptor.invoke(AbstractTraceInterceptor.java:129)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)


text:
Q: Expandable TableView How to show table view in categories and when clicked on one row it will expand with content?
I've seen it in some apps and that's how I know it is possible but can't find any reference or tutorial regarding it.
I would appreciate if someone could help me even if I don't have example code, because I don't know how to start with it.

A: I think this should be done by means of table view. I personally did this the following way: at first there was a table view with 5 sections and every section had no rows in it, only a header. When the header is clicked the sections "expands" - I add the rows to the section (insertRowsAtIndexPaths). If the section header is clicked again, I delete the rows from datasourse (deleteRowsAtIndexPaths). Hope this is useful

A: Go through this sample code
https://github.com/adamhoracek/KOTree
The table view will look like this


text:
Q: Show formatted properties in Laravel's blade template Let's say, I have some Model with updated_at attribute. I want to show it in template like this
{{ $model->updated_at }}

This can be used in many places so I DO NOT do this
{{ $model->updated_at->format('d/m/Y H:i:s') }}

But instead
public function getUpdatedAtAttribute($value)
{
    return $value->format('d/m/Y H:i:s');
}

But there is one big problem with this solution, I can not use $model->updated_at in controllers anymore, because it returns string, not Carbon instance.
Two possible solutions
1.
public function getUpdatedAtFormatterAttribute($value)
{
    return $this->updated_at->format('d/m/Y H:i:s');
}

and in template
{{ $model->updated_at_formatted }}

2.
Use package like this
class ModelPresenter extends Presenter {

    public function updated_at()
    {
        return $this->updated_at->format('d/m/Y H:i:s');
    }
}

And
{{ $model->present()->updated_at }}

From architectural point view I think second version is cleaner but are there some proven solutions? This can be not about Laravel only but about any popular PHP framework.

A: The two methods described in the question are, in fact, the standard and widely-accepted approaches to adding DRY date-formatting on Laravel models:

*

*Add one or more accessors to a model for specific date formats

*Use a presenter that wraps the model with logic for display

Both approaches consolidate the formatting logic at one location so we can update the format later, if needed, without changing every line that outputs a date. Both also avoid overriding the source attribute so the functionality is available when needed.
Which to choose depends on the size and requirements of the application. Smaller applications with small teams can certainly justify the first approach, which avoids introducing complexity by adding a presenter layer. The second approach may suit larger teams that can benefit from the abstraction and seperation-of-concerns.
In some applications, I like to make a trait that we can add to any model which enables automatic date formatting attributes using the dates and date format declared on the model:
class User extends Model
{
    use FormatsDates;

    protected $dates = [ 'last_login_at' ];
    ...
}

$user->formatted_last_login_at; // mm/dd/yyyy

Because this question doesn't include such a trait in its scope, I'll leave the implementation as an exercise to the reader, but I'm happy to help if needed.

A: try this - don't forget call in model- use Carbon\Carbon;
Model:
public function getUpdatedAtAttribute($updated_at)
{
    return Carbon::parse($updated_at)->format('d/m/Y H:i:s');
}

In your blade view call like this
{{$model->getUpdatedAtAttribute($updated_at)}}


text:
Q: Airflow metrics with prometheus and grafana any one knows how to send metrics from airflow to prometheus, I'm not finding much documents about it, I tried the airflow operator metrics  on Grafana but it doesnt show any metrics and all it says no data points.

A: By default, Airflow doesn't have any support for Prometheus metrics. There are two ways I can think of to get metrics in Prometheus.

*

*Enable StatsD metrics and then export it to Prometheus using statsd exporter.

*Install third-party/open-source Prometheus exporter agents (ex. airflow-exporter).
If you are going with 2nd approach then the Airflow Helm Chart also provides support for that.
Edit
If you're using statsd exporter here is a good resource for Grafana Dashboard and exporter config.

A: This is how it worked for me -

*

*Running airflow in docker using this doc

*Added this configuration inside the docker-compose file downloaded in the previous step  AIRFLOW__SCHEDULER__STATSD_ON: 'true'
AIRFLOW__SCHEDULER__STATSD_HOST: statsd-exporter
AIRFLOW__SCHEDULER__STATSD_PORT: 9125
AIRFLOW__SCHEDULER__STATSD_PREFIX: airflow
Under environment section

*Now run the statsd_export

*docker run -d -p 9102:9102 -p 9125:9125 -p 9125:9125/udp \ -v $PWD/statsd_mapping.yml:/tmp/statsd_mapping.yml \ prom/statsd-exporter --statsd.mapping-config=/tmp/statsd_mapping.yml

*Get the statsd_mapping.yml contents from Here

*Now do docker-compose up to run the airflow and try to run some worflow and you should see logs at http://localhost:9102/metrics

A: If you installed your Airflow with statsd support:
pip install 'apache-airflow[statsd]'

you can expose Airflow statsd metrics in the scheduler section of your airflow.cfg file, something like this:
[scheduler]
statsd_on = True
statsd_host = localhost
statsd_port = 8125
statsd_prefix = airflow

Then, you can install a tool called statsd_exporter, that captures statsd-format metrics and converts them to Prometheus-format, making them available at the /metrics endpoint for Prometheus to scrape.
There is a docker image available on DockerHub called astronomerinc/ap-statsd-exporter that already maps Airflow statsd metrics to Prometheus metrics.
References:

*

*https://airflow.apache.org/docs/stable/metrics.html

*https://github.com/prometheus/statsd_exporter

*https://hub.docker.com/r/astronomerinc/ap-statsd-exporter/tags


text:
Q: "failed to receive handshake, SSL/TLS connection failed" only when trying to access T-Mobile.com I have 2 phones, 2 tablets, and 2 laptops can log into my account at T-Mobile with no issues.
My main PC, (Alienware R11 running Win11) cannot access my T-Mobile account. It gets an error when trying to access T-Mobile.

Hmmm… can't reach this page
It looks like the webpage at https://www.t-mobile.com/ might be having issues,
or it may have moved permanently to a new web address.
ERR_FAILED

I have tried Edge, Chrome, cURL, and openssl to connect. I have found no other URL that I cannot connect to. I have no issues connecting to T-Mobile on any other device.
Any suggestions to resolve?
C:\WINDOWS\system32>curl -v https://www.t-mobile.com
*   Trying 2a02:e980:e6::67:443...
* Connected to www.t-mobile.com (2a02:e980:e6::67) port 443 (#0)
* schannel: disabled automatic use of client certificate
* schannel: ALPN, offering http/1.1
* Send failure: Connection was reset
* schannel: failed to send initial handshake data: sent -1 of 202 bytes
* Closing connection 0
curl: (35) Send failure: Connection was reset

C:\WINDOWS\system32>openssl s_client -connect www.t-mobile.com:443 -tlsextdebug -showcerts
CONNECTED(0000019C)
write:errno=10054
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 322 bytes
Verification: OK
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 0 (ok)

No security software, vpn, ad/spyware installed (that I am aware of). System just has stock what Alienware installed, plus upgrade from Win 10 to 11.
Booting into "Safe Mode with Network" does not allow access to internet (cat5 or wifi).
Network controller is an Intel Killer E3000 2.5 Gigabit Ethernet Controller.
Every URL that I test works with no issue, except T-Mobile. And T-Mobile claims issue is on my end.


text:
Q: Unity Interception, Interceptor is called several times with partial classes mapping I've been looking around for a fix on this for a couple of days with no luck.
Basically we are using Unity for two things: dependency injection and more importantly for Interception.
What I want is that the interceptor is triggered each time a method inside the partial class is called, but I am seeing that the Interceptor is called several times depending on the number of Mappings I create on the web.config, meaning 2 mappings, 2 interceptions for each method called.
In the code samples below all partial classes have the same name but implement different interfaces and they all reside in different .cs files, this is because this library will be moved to WCF in the short term.
So we have several partial classes that look like this:
public partial class PartialClass : IInterface1
{
   ...
}
public partial class PartialClass : IInterface2
{
   ...
}

And the configuration file like this:
<alias alias="IInterface1"     type="MyProject.Interface.IInterface1, MyProjectAssembly" />
<alias alias="IInterface2"     type="MyProject.Interface.IInterface1, MyProjectAssembly" />
<alias alias="PartialClass" type="MyProject.Services.PartialClass , MyProjectAssembly" />
<alias alias="Interceptor" type="MyProject.Services.Interceptor, MyProjectAssembly" />

<container>
extension type="Interception" />

<register type="IInterface1" mapTo="PartialClass">
    <lifetime  type="ContainerControlledLifetimeManager" />
    <interceptor type="InterfaceInterceptor"/>
    <interceptionBehavior type="Interceptor" />
</register>

register type="IInterface2" mapTo="PartialClass">
    <lifetime  type="ContainerControlledLifetimeManager" />
    <interceptor type="InterfaceInterceptor"/>
    <interceptionBehavior type="Interceptor" />
</register>
</container>

Finally the constructor where an instance of either partial class is needed
public class MyClass()
{
    public MyClass(IInterface1 interface)
    {
         ...
    }
    public MyClass()
    :this(Microsoft.Practices.Unity.UnityContainerExtensions.Resolve<IInterface1>(Container))
    {

    }
}

The problem I am having is that the interceptor is being called TWO times per request, which means that if I add more mappings (Interface3, Interface4, etc) it will be called 3 or 4 times depending on the number of mappings I add.

A: If you use the isDefaultForType element on one of the registrations it will apply to all registrations of the type. This will prevent the duplicate calls to handlers.
For example
<register type="IInterface1" mapTo="PartialClass">
     <lifetime  type="ContainerControlledLifetimeManager" />
     <interceptor type="InterfaceInterceptor" isDefaultForType="True"/>
     <interceptionBehavior type="Interceptor" isDefaultForType="True"/>
</register>

<register type="IInterface2" mapTo="PartialClass">
     <lifetime  type="ContainerControlledLifetimeManager" />
</register>


text:
Q: How to unpack a pandas Panel created with a dictionary? I have several .txt files in a subdirectoy, /subdirect/
These files are
file1.txt
file2.txt
file3.txt
file4.txt
...

Using glob, I can put these into a three-dimensional panel, using the filename as the key for key-value pairs.
import glob
import pandas as pd

dataframe = {filename: pd.read_csv(filename) for filename in glob.glob('*.txt') # dictionary
data = pd.Panel.from_dict(dataframe) # create panel

Now, I would like to unpack these files to manipulate each DataFrame individually and plot data.
for fname in data:
    df = pd.read_csv(fname)
    df['total_sum'] = df[["column1", "column2", "column3"]].sum(axis=1)  # sum total reads
    df.plot(kind='bar')

However, I do not seem to be unpacking the panel correctly as the dimensions have completely changed.
How does one unpack a pandas Panel?

A: How about reading the data files individually instead, since you don't seem to be interested in the Panel structure per se:
import glob
import pandas as pd

for filename in glob.glob('*.txt'):
    df = pd.read_csv(filename)
    df['total_sum'] = df[["column1", "column2", "column3"]].sum(axis=1)  # sum total reads
    df.plot(kind='bar')

Alternatively, take a look at pd.Panel.to_frame() to convert Panel to DataFrame. For instance, with a Panel from a dict with two DataFrames:
df = pd.DataFrame(np.random.random(size=(20, 10)))

panel = pd.Panel.from_dict({'1': df, '2': df.add(10)})

<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 20 (major_axis) x 10 (minor_axis)
Items axis: 1 to 2
Major_axis axis: 0 to 19
Minor_axis axis: 0 to 9

Using to_frame() gets you a long-format DataFrame with two columns and a MultiIndex with length of row x column. To plot, you could iterate over the columns of data_frame using .items() and use .unstack() to convert into format suitable for plotting:
data_frame = panel.to_frame()

MultiIndex: 200 entries, (0, 0) to (19, 9)
Data columns (total 2 columns):
1    200 non-null float64
2    200 non-null float64
dtypes: float64(2)
memory usage: 4.7+ KB
None

for i, data in data_frame.items():
    data.unstack().plot()

On performance - if you start from a panel, summing there is faster than grouping and unstacking. It's also faster than summing an individual dataframe.
%timeit panel.sum(axis=1)
10000 loops, best of 3: 111 µs per loop

%timeit panel.to_frame().groupby(data_frame.columns, axis=1).apply(lambda x: x.unstack(0).sum(axis=1))
100 loops, best of 3: 3.63 ms per loop

df = data_frame.unstack(0)
%timeit df.loc[:, '1'].sum(axis=1)
1000 loops, best of 3: 409 µs per loop

A: I would unpack the files as a flat file and add the filename as a column.  You can now create a MultiIndex using the filename and whatever attributes you have in the dataframe.
Panels were used before MultiIndex functionality was improved.  Flat is better than nested.
import glob
import pandas as pd

dfs = []
for filename in glob.glob('*.txt'):
    df = pd.read_csv(filename)
    df['filename'] = filename
    dfs.append(df)
dfs = pd.concat(dfs, ignore_index=True)


text:
Q: Retrieving Stock Data using Google Finance 0.5 pypi I downloaded the Google Finance and was wondering how I could extract specific values versus all of them. This is the example given:
>>> from googlefinance import getQuotes
>>> print json.dumps(getQuotes('AAPL'), indent=2)

[
  {
    "Index": "NASDAQ",
    "LastTradeWithCurrency": "123.25",
    "LastTradeDateTime": "2015-03-27T16:03:28Z",
    "LastTradePrice": "123.25",
    "LastTradeTime": "4:03PM EDT",
    "LastTradeDateTimeLong": "Mar 27, 4:03PM EDT",
    "StockSymbol": "AAPL",
    "ID": "22144"
  }
]

What would the
>>> print json.dumps(get(…)('AAPL'), indent=2)

call be if I just wanted to call the stock dividend for example?

A:
was wondering how I could extract specific values versus all of them

If your call returns
x = [
  {
    "Index": "NASDAQ",
    "LastTradeWithCurrency": "129.09",
    "LastTradeDateTime": "2015-03-02T16:04:29Z",
    "LastTradePrice": "129.09",
    "Yield": "1.46",
    "LastTradeTime": "4:04PM EST",
    "LastTradeDateTimeLong": "Mar 2, 4:04PM EST",
    "Dividend": "0.47",
    "StockSymbol": "AAPL",
    "ID": "22144"
  }
]

Then x is a list, the first element in the list is e.g.stock = x[0], which is:
{
        "Index": "NASDAQ",
        "LastTradeWithCurrency": "129.09",
        "LastTradeDateTime": "2015-03-02T16:04:29Z",
        "LastTradePrice": "129.09",
        "Yield": "1.46",
        "LastTradeTime": "4:04PM EST",
        "LastTradeDateTimeLong": "Mar 2, 4:04PM EST",
        "Dividend": "0.47",
        "StockSymbol": "AAPL",
        "ID": "22144"
      }

So to get the dividend you can access the key 'Dividend', stock['Dividend'], that will get your the dividend value as a string, you can convert it to a float e.g. float(stock['Dividend'])
Also Try this yahoo-finance lib https://github.com/lukaszbanasiak/yahoo-finance, as it has a get_dividend_share() (dividends per share), and get_dividend_yield() (annual dividends / stock price, in %)

A: Assume stock = json.dumps(getQuotes('AAPL'), indent=2). Then, type(stock) returns type string.
What you need to do is skip encoding it as JSON since getQuotes('AAPL') already outputs what you want as a list. Instead, save the output like so:
stock=getQuotes('AAPL')

Then, as bakkal pointed out, you can address specific values of the list via indexing e.g. stock[0].
print  stock[0]
{u'Index': u'NASDAQ', u'LastTradeWithCurrency': u'113.40', u'LastTradeDateTime': u'2015-09-28T13:49:28Z', u'LastTradePrice': u'113.40', u'LastTradeTime': u'1:49PM EDT', u'LastTradeDateTimeLong': u'Sep 28, 1:49PM EDT', u'StockSymbol': u'AAPL', u'ID': u'22144'}

You'll want to drill down to 'dividends', or in my example, 'LastTradePrice' by using
stock[0]['LastTradePrice']

This returns:
u'113.40'

Now, also as bakkal pointed out, getting our value as a number is simply a question of using float(stock[0]['LastTradePrice'])
Update
The above was confirmed to work on a RaspberryPi Running Debian Wheezy. As demonstrated by bakkal (and confirmed on my Windows machine) stock['LastTradePrice'] may be the correct form of indexing your list depending on your platform.


text:
Q: cryptsetup: waiting for encrypted source device /swapfile, fstab empty On the bootscreen I get the message:
cryptsetup: waiting for encrypted source device /swapfile...

which then leaves me hanging for about 2 minutes followed by
Initramfs unpacking failed: Decoding failed.

I then get dropped to Initramfs.
This is on Ubuntu 20.04 with an encrypted home folder. I got the error after switching back to the nouveau driver in order to install cuda-10 (it was complaining about nvidia driver already being in use)
Other suggestions involve doing something with /etc/crypttab, but that file doesn't exist on my system. cat /etc/fstab also shows an empty file. Some reading suggests that in that case it would be using default settings but if so how does it know what disk should be used as a swapspace? Or is there something I can do with a live usb?
The output of mount is
none on / type rootfs (rw)
sysfs on /sys type sysfs (rw,nosuid, nodev, noexec, relatime)
proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)
udev on /dev type devtmpfs (rw,nosuid, noexec,relatime,size=32840428k,nr_inodes=8210107,mode=755)
devpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000)
tmpfs on/run type tmpfs (rw,nosuid,nodev,noexec,relatime,size=6583428k,mode=755)

lsblk returns a non found error (this is in inframs so that might not work)
While mounting sdc1 on /mnt on a life usb I can get the following results:
cat /mnt/etc/fstab looks like
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/sdc1 during installation
UUID=5df229c0-be7c-43d7-b616-67ec15e2a6d3 /               ext4    errors=remount-ro 0       1
# /boot/efi was on /dev/nvme0n1p2 during installation
UUID=D23D-B0F6  /boot/efi       vfat    umask=0077      0       1
#/swapfile none            swap    sw              0       0
/dev/mapper/cryptswap1 none swap sw 0 0

.
cat /mnt/etc/crypttab
looks like
# <target name> <source device>     <key file>  <options>
cryptswap1 /swapfile /dev/urandom swap,offset=1024,cipher=aes-xts-plain64

and lsblk -o name, type, uuid, label looks like
NAME        TYPE UUID                                 LABEL
loop0       loop
loop1       loop
loop2       loop
loop3       loop
loop4       loop
loop5       loop
sda         disk
└─sda1      part 8C45-E3AC                            UBUNTU 20_0
sdb         disk
├─sdb1      part
└─sdb2      part
sdc         disk
└─sdc1      part 5df229c0-be7c-43d7-b616-67ec15e2a6d3
nvme0n1     disk
├─nvme0n1p1 part 60FC3C5FFC3C3220                     Recovery
├─nvme0n1p2 part D23D-B0F6
├─nvme0n1p3 part
└─nvme0n1p4 part

A: If I don't miss anything, everything seems fine with your configurations. However it might help to regenerate initramfs while disabling the /swap file encryption.
Boot up the system using a live Ubuntu disk. mount these two partitions:
$ sudo mount /dev/sdc1 /mnt
$ sudo mount /dev/nvme0n1p2 /mnt/boot/efi

Open /mnt/etc/fstab and comment this line (add a # at the beginning):
/dev/mapper/cryptswap1 none swap sw 0 0

Open /mnt/etc/crypttab and comment this line (add a # at the beginning):
cryptswap1 /swapfile /dev/urandom swap,offset=1024,cipher=aes-xts-plain64

Now we have to chroot into system and regenerate the initramfs:
$ sudo mount --bind /dev /mnt/dev
$ sudo chroot /mnt
# mount --type proc none /proc
# mount --type sysfs none /sys
# update-initramfs -k all -c

It's all done. exit from chroot environment:
# exit

Un-mount the mounted partitions and reboot:
$ sudo umount -R /mnt
$ sudo reboot

Now you lost the encryption on /swap. However I think you didn't want it in the first place. You might try these instructions without editing /etc/fstab and /etc/crypttab. That might work too.


text:
Q: callback with `this` confusion I have this clock object:
var Clock = {
    start: function () {
      $('#btnScrollPause').show();
      $('#btnScrollResume').hide();

      advance();
      this.interval = setInterval(function () {
        advance();
      }, 5000);
    },

    pause: function () {
      $('#btnScrollPause').hide();
      $('#btnScrollResume').show();
      this.reset();
    },

    resume: function () {
      if (!this.interval) {
        this.start();
      }
    },

    reset: function () {
      clearInterval(this.interval);
      delete this.interval;
    }
  };

I have two buttons that pause and resume automatic scrolling of an element, but my confusion is on the click handlers that I've attached to them.
If I call the pause function like this:
// 1
$('#btnScrollPause').click(function () {
  Clock.pause();
});

It works correctly, however if I try to reduce the code like so:
// 2
$('#btnScrollPause').click(Clock.pause);

It no longer works and I get the error "this.reset is not defined". Also, if I make a function and use that in the click handler instead:
// 3
$('#btnScrollPause').click(scrollPause);

function scrollPause() {
  Clock.pause();
}

It works! Can someone explain why 1 and 3 work, but 2 doesn't?

A: This is related to how this keyword works in JavaScript. When you pass a method as a callback to another function the method is detached from the object and the this  keyword doesn't refer to object. Additionally jQuery event methods modify the this value of callbacks to refer to the owner of the event, i.e. the DOM elements.
One option that you have is using the .bind function:
$('#btnScrollPause').click(Clock.pause.bind(Clock));

A related question: How does the "this" keyword work?

A: The this object binding is volatile in JavaScript...that is, it doesn't always point to the same object and its binding can change from one line of code to the very next. How you invoke the code that contains the word this determines what object it will bind to.
Had you made an instance of Clock (i.e. var c = new Clock()) and then said:
$('#btnScrollPause').click(c.pause);

It would have worked because this would be bound to the instance of the Clock referenced by the c variable.
But as it stands with your code, this is bound to your button because that is the object that initiated the code.
Here's a checklist that you can follow to know what this will bind to...
If the code that contains this is invoked:

*

*As a method or property of an object instance (through an instance variable):
var o = new Object();

// "this" will be bound to the "o" object instance
// while "someProperty" and "someMethod" code executes
o.someProperty = someValue;
o.someMethod();

*Via a .call(), .apply(), .bind() or Array.prototype.fn invocation:
// "this" will be bound to the object suppled as the "thisObjectBinding"
someFunction.call(thisObjectBinding, arg, arg);
someFunction.apply(thisObjectBinding, [arg, arg]);
var newFunc = someFunction.bind(thisObjectBinding, arg, arg);

Additionally, several Array.prototype methods allow for a thisObject to be passed which will alter the binding for the duration of the method call:
Array.prototype.every( callbackfn [ , thisArg ] )
Array.prototype.some( callbackfn [ , thisArg ] )
Array.prototype.forEach( callbackfn [ , thisArg ] )
Array.prototype.map( callbackfn [ , thisArg ] )
Array.prototype.filter( callbackfn [ , thisArg ] )

*If none of the other scenarios apply, Default binding occurs.
3a. With "use strict" in effect: this is undefined
3b. Without "use strict" in effect: this binds to the Global object
** NOTE: this binding can also be affected by using eval(), but as a general best practice, the use of eval() should be avoided.


text:
Q: Set ConnectionFactory for Camel JMS Producer: camel-jms Vs camel-sjms Ciao, my basic requirement is to have a route where I can send a message and this is put on a JMS Queue. The camel context run in a JavaEE 6 container namely JBoss AS 7.1.1 so it's HornetQ for JMS which ships with it; I start the context via bootstrap singleton but I don't use the camel-cdi. So far I've been using camel-jms component, but now I'm looking to migrate to the camel-sjms if possible because springless.
My question is: what is the proper way to configure the ConnectionFactory for camel-sjms in this JavaEE scenario, please?
With the camel-jms I could put this in the endpoint URL, as simple as .to("jms:myQueue?connectionFactory=#ConnectionFactory"). With the camel-sjms instead it seems to me that I need to create an instance of the SJMSComponent myself, set the connectionFactory, and set this instance in the camel context before starting it.
I have code below for the camel-jms Vs camel-sjms case, and I would like to know if I "migrated" the setting of the ConnectionFactory correctly. Thanks.

For camel-jms this was done as:

@Singleton
@Startup
public class CamelBootstrap {
    private CamelContext camelContext;
    private ProducerTemplate producerTemplate;

    public CamelContext getCamelContext() {
        return camelContext;
    }

    public ProducerTemplate getProducerTemplate() {
        return producerTemplate;
    }

    @PostConstruct
    public void init() throws Exception {
        camelContext = new DefaultCamelContext();
        camelContext.addRoutes(new MyCamelRoutes());
        camelContext.start();
        producerTemplate = camelContext.createProducerTemplate();
    }
}

Nothing special, and in the MyCamelRoutes I could do route configuration using:
.to("jms:myQueue?connectionFactory=#ConnectionFactory")

For camel-sjms now I have to modify the bootstrap singleton with:

@Singleton
@Startup
public class CamelBootstrap {

    @Resource(mappedName="java:/ConnectionFactory")
    private ConnectionFactory connectionFactory;

    private CamelContext camelContext;
    private ProducerTemplate producerTemplate;

    public CamelContext getCamelContext() {
        return camelContext;
    }

    public ProducerTemplate getProducerTemplate() {
        return producerTemplate;
    }

    @PostConstruct
    public void init() throws Exception {
        camelContext = new DefaultCamelContext();

        SjmsComponent sjms = new SjmsComponent();
        sjms.setConnectionFactory(connectionFactory);
        camelContext.addComponent("sjms", sjms);

        camelContext.addRoutes(new MyCamelRoutes());
        camelContext.start();
        producerTemplate = camelContext.createProducerTemplate();
    }
}

and please notice @Resource for the connectionFactory this is passed as a reference to the SjmsComponent instance, which is passed to the camelContext. And then in the MyCamelRoutes I could use the sjms while do route configuration using:
.to("sjms:myQueue")

The code seems to work correctly in both scenario, but as I understand the configuration of the ConnectionFactory is quite susceptible of performance issue if not done correctly, therefore I prefer to ask if I migrated to the camel-sjms correctly for my JavaEE scenario. Thanks again

A: Performance issues are likely to happend if you don't do caching/pooling of JMS resources. Caching is typically configured by wrapping a ConnectionFactory in some Caching ConnectionFactory library - or by handing over the control to the application server.
Camel SJMS includes built-in pooling. However, if you have a container managed resource to handle JMS connections, you should probably consider using it. SJMS has some facilities to deal with that, ConncetionResource instead of ConnectionFactory.


text:
Q: iisnode 404.0 ErrorCode: The operation completed succesfully node js API Buenos dias a todos y doy las gracias de antemano por la ayuda que me puedan brindar.
El detalle esta en que tengo mi API node js que no quiere correr en internet(me refiero a que no puedo realizarle peticiones), igual si intento abrir la pagina que contiene mi API me saca un error 404.
Tengo una imagen del Seguimiento de peticiones fallidas que tiene plesk,  y esta otra es de una peticion que le hice con postman.
En ambos casos obtengo el error 404, ahora, yo estoy seguro de que el API funciona porque lo tengo corriendo en heroku y ahi me funciona perfectamente y me trae la informacion de las peticiones que le hago desde el frontend.
No soy un experto porque es la primera vez que subo un proyecto a internet, me estoy familiarizando con plesk y hostgator, la verdad es que si quiero sacar este proyecto y me urge que corra el API en hostgator.
Estoy utilizando:
El gestor de plesk con un servidor dedicado(windows) de hostgator con gruporedhogar.com como dominio  principal
El stack MEAN con MySql
En mi API estoy utilizando TypeORM para realizar la conexion y las consultas a mi base de datos
En los permisos de la carpeta de mi proyecto le di permisos a los IIS_IUSRS
Mi proyecto lo tengo bien montado con dependencias instaladas y esta activo(es un compilado de typescript)

Estos son los archivos y carpetas que contiene mi proyecto, estan dentro de httpdocs/backendprueba

Todo esto es completamente nuevo para mi y siento que ya estoy a nada de que funcione pero nuevamente mi falta de experiencia no me ayuda, si me hace falta informacion la puedo proporcionar, y gracias otra vez.


text:
Q: Databinding fails with JAXB class not found exception during compilation (using kapt) I am following GithubBrowserSample. The only change I have made is not to use NavHostFragment. I am adding fragment at runtime but the code is not compiling and there is no such helpful error log
Application
open class SCApp : Application(), HasActivityInjector, HasServiceInjector {

    @Inject
    protected lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity>

    @Inject
    protected lateinit var dispatchingServiceInjector: DispatchingAndroidInjector<Service>

    override fun onCreate() {
        super.onCreate()

        AppInjector.init(this)
    }

    override fun activityInjector() = dispatchingAndroidInjector

    override fun serviceInjector() = dispatchingServiceInjector
}

Activity
class IncomingLeadActivity : AppCompatActivity(), HasSupportFragmentInjector {

    lateinit var binding: ActivityIncomingLeadBinding

    private lateinit var incomingLeadViewModel: IncomingLeadViewModel

    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory

    @Inject
    lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = DataBindingUtil.setContentView(this, R.layout.activity_incoming_lead)
        incomingLeadViewModel = ViewModelProviders.of(this, viewModelFactory).get(IncomingLeadViewModel::class.java)

        binding.viewModel = incomingLeadViewModel
        binding.setLifecycleOwner(this)

        supportFragmentManager
            .beginTransaction()
            .replace(android.R.id.content, LeadReceiverFragment.newInstance(), "")
            .commit()
    }

    override fun supportFragmentInjector() = dispatchingAndroidInjector
}

Fragment
class LeadReceiverFragment : Fragment(), Injectable {

    lateinit var binding: LeadReceiverFragmentBinding

    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory

    private lateinit var leadReceiverViewModel: LeadReceiverViewModel

    companion object {
        fun newInstance() = LeadReceiverFragment()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        binding = DataBindingUtil.inflate(
            inflater,
            R.layout.lead_receiver_fragment,
            container,
            false
        )
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        leadReceiverViewModel = ViewModelProviders.of(this, viewModelFactory).get(LeadReceiverViewModel::class.java)
        binding.setLifecycleOwner(viewLifecycleOwner)

        binding.viewModel = leadReceiverViewModel
    }
}

Error
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:kaptDebugKotlin'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:110)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:77)
        at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
        at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
        at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
        at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:91)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:59)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.run(EventFiringTaskExecuter.java:51)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46)
        at org.gradle.execution.taskgraph.LocalTaskInfoExecutor.execute(LocalTaskInfoExecutor.java:42)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:277)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:262)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:135)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:130)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.execute(DefaultTaskPlanExecutor.java:200)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.executeWithWork(DefaultTaskPlanExecutor.java:191)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.run(DefaultTaskPlanExecutor.java:130)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: org.gradle.api.GradleException: Internal compiler error. See log for more details
        at org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.throwGradleExceptionIfError(tasksUtils.kt:15)
        at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.run(GradleKotlinCompilerWork.kt:135)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:152)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:147)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runJvmCompilerAsync(GradleKotlinCompilerRunner.kt:87)
        at org.jetbrains.kotlin.gradle.internal.KaptWithKotlincTask.compile(KaptWithKotlincTask.kt:72)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.doExecute(StandardTaskAction.java:46)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:801)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:768)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:131)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:120)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:99)
        ... 31 more

Detailed Log
            ^
e: java.lang.IllegalStateException: failed to analyze: java.lang.reflect.InvocationTargetException
        at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:56)
        at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:128)
        at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:159)
        at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:57)
        at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:96)
        at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:52)
        at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:93)
        at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$1$2.invoke(CompileServiceImpl.kt:442)
        at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$1$2.invoke(CompileServiceImpl.kt:102)
        at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:1013)
        at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:102)
        at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
        at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:1055)
        at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:1012)
        at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:441)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:564)
        at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)
        at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
        at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
        at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:564)
        at org.jetbrains.kotlin.kapt3.base.AnnotationProcessingKt.doAnnotationProcessing(annotationProcessing.kt:55)
        at org.jetbrains.kotlin.kapt3.base.AnnotationProcessingKt.doAnnotationProcessing$default(annotationProcessing.kt:31)
        at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.runAnnotationProcessing(Kapt3Extension.kt:223)
        at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:187)
        at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:98)
        at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:96)
        at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:106)
        at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:82)
        at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:384)
        at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:70)
        at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:107)
        at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:375)
        at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:123)
        ... 30 more
Caused by: com.sun.tools.javac.processing.AnnotationProcessingError: java.lang.ExceptionInInitializerError
        at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:976)
        at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.java:881)
        at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment.access$2100(JavacProcessingEnvironment.java:110)
        at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1202)
        at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1311)
        at jdk.compiler/com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1250)
        at jdk.compiler/com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1149)
        ... 47 more
Caused by: java.lang.ExceptionInInitializerError
        at android.databinding.annotationprocessor.ProcessExpressions$IntermediateV2.appendTo(ProcessExpressions.java:326)
        at android.databinding.annotationprocessor.ProcessExpressions.onHandleStep(ProcessExpressions.java:117)
        at android.databinding.annotationprocessor.ProcessDataBinding$ProcessingStep.runStep(ProcessDataBinding.java:212)
        at android.databinding.annotationprocessor.ProcessDataBinding$ProcessingStep.access$000(ProcessDataBinding.java:197)
        at android.databinding.annotationprocessor.ProcessDataBinding.doProcess(ProcessDataBinding.java:98)
        at android.databinding.annotationprocessor.ProcessDataBinding.process(ProcessDataBinding.java:73)
        at org.jetbrains.kotlin.kapt3.base.ProcessorWrapper.process(annotationProcessing.kt:106)
        at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:964)
        ... 53 more
Caused by: java.lang.RuntimeException: Cannot create the xml marshaller
        at android.databinding.tool.store.ResourceBundle$LayoutFileBundle.<clinit>(ResourceBundle.java:730)
        ... 61 more
Caused by: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
 - with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory]
        at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:278)
        at javax.xml.bind.ContextFinder.find(ContextFinder.java:421)
        at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
        at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
        at android.databinding.tool.store.ResourceBundle$LayoutFileBundle.<clinit>(ResourceBundle.java:725)
        ... 61 more
Caused by: java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
        at javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:122)
        at javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:155)
        at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:276)
        ... 65 more

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.

A: After changing gradle version latest one, the compiler showed different errors which helped to solve the issue. In my case, the issue occured due to Dagger version 2.17, so downgrading to 2.16 solved the issue.
Reference: https://github.com/google/dagger/issues/1245


text:
Q: module.exports update array I'm trying to understand module.exports better.
As I understand it, it can be used as a two way communication (you can send and receive data to the module.
However, this is not working as I expected:
File1.js:
var Test = require("./Balances")
Test.push(12)

Balances.js:
var arrays = [10, 11];
module.exports = arrays

File2.js:
var Test = require("./Balances")
setInterval(function(){console.log(Test)},2000)

What I want is to be able to add to the array from File1, and read the output in File2.
File2 reads the initial array just fine, but the value I push never shows in File2.
However, if I add a console.log(Test) in File1, that pushed value does appear there.
Upon rerunning File1, I don't however see [12, 12] , only [ 12 ], which means the first push never got written in the Balances array.
Any idea why?

A: When you import a variable from another javascript module, you get that variable by value, not by reference (you create a copy of the value at the given memory address, you don't simply get a pointer to that same exact variable). Therefore, you have only mutated the Test variable in File1.js; to reflect those changes in your console.log in File2.js you would have to re-export your mutated variable from File1.js and import that into File2.js, and then do the log.

Here is analysis of your code:
File1.js:
// creates copy of the `Balance.js` `arrays` variable
// stores value in new variable `Test`
var Test = require("./Balances") // => [10, 11]
// pushes 12 to the copy
Test.push(12) // => [10, 11, 12]

File2.js:
// creates copy of the `Balance.js` `arrays` variable
// stores value in new variable `Test`
var Test = require("./Balances") // => [10, 11]
// This interval does nothing. The fact is, the mutated
// `arrays` var from `File1.js` does not effect the
// `arrays` var in any other modules scope.
setInterval(function(){console.log(Test)},2000) // => [10, 11]

This is all assuming you have additional code not seen here that is required and executed from an entry point. As Thomas said in the comments, there is no state persisted between running individual scripts.

To accomplish what you're attempting in your post:
Balances.js:
var arrays = [10, 11]
module.exports = arrays

File1.js:
var test = require('./Balances')
test.push(12)

module.exports = test

File2.js:
var test = require('./File1')
function action() {
  console.log(test)
}

module.exports = action

main.js (entry point):
var action = require('./File2')
action() // => [10, 11, 12]

run $ node main.js
Hope this helps!

A: It had to have never gotten pushed because you didn't actually require File1.js anywhere. This main.js works exactly as expected with the original File1.js, File2.js, and Balances.js files. (You probably wanted setTimeout, and as mentioned that had no effect anyhow, but it does work.)
require('./File1')
require('./File2')

Yes, modifying passed non-primitives updates the original item. They are not copied. Don't spend the next few years on a redundant construct to rebuild what is already happening.

A: Technically you can use modules like that, but I'd avoid that. Mutating state like that can lead to a lot of problems, especially if it is done in distributed modules.
And out of a sudden you have some error or unwanted behaviour that seems to come out of nowhere. Because its source is in an completely unrelated part of your app. Have fun, finding/debugging that.
I'd rather use modules as read-only sources for configs and stuff, or export a self-contained API that manages these mutations and everything else that happens in that module.

Back to you question
all you need is a common entry point that loads both modules in the same application.
That's probably ýour misconception. every time you call node ... you start a seperate application with seperate memory and state. It loads the files you tell it to, executes the code and eventually finishes. Like opening two sites in the browser, one loading File1, the other one loading File2.
So, you can create a common entry point like main.js
require("./File1");
require("./File2");

and then start the application at that common entry point node main.js
Or you can run node -i -r "./File1" -r "./File2" and start typing more JS.


text:
Q: Switch apps iOS can't change default launch icon How to change icon on switch apps on iOS (screenshot). I can't change this icon. I created cordova app, flutter app and clear swift iOS app. Every this solution don't change this icon.

A: Create icons using this link and try to add them to your app

A: For IOS you need to add your icon in the IOS Project (you have the XCTAsset file for add all icon), not in pubspec.yaml.


text:
Q: How to check which element is hovered using React 17.0.2 I am currently trying to make a webpage that displays multiple images, and when I hover on each image, they will display different text depending on the image. I was thinking of useState and useEffect, but I'm not entirely sure how to implement that. My current structure is that I have a list with an a tag and inside that i have an image.

A: You could probably use the built in onMouseEnter and onMouseLeave events and manage a state with an object containing an index of each image and its info through the events.
 //change the state} onMouseLeave={() => //return state back to default}>


text:
Q: Returning an array from C to .Net: What am I doing wrong? This is a follow on from this question.
I am trying to return an array of floating point numbers from C, to .Net. I will include some F# code, as well as C# code, so that people of either language can answer.
Unmanaged C code:
extern "C"
{
    __declspec(dllexport) void DisplayHelloFromDLL(c_float* P_x, c_float* x)
    {
        //printf("Hello from DLL !\n");
        //cout << "You gave me ... an int: " << i << endl;

        // Load problem data
        //c_float P_x[4] = { 4., 1., 1., 2., }; //covariance matrix
        c_int   P_nnz = 4; //number of non-zero elements in covar
        c_int   P_i[4] = { 0, 1, 0, 1, }; //row indices?
        c_int   P_p[3] = { 0, 2, 4}; //?
        c_float q[2] = { 1., 1., }; //linear terms
        c_float A_x[4] = { 1., 1., 1., 1., }; //constraint coefficients matrix
        c_int   A_nnz = 4; //number of non zero elements in constraints matrix
        c_int   A_i[4] = { 0, 1, 0, 2, }; //row indices?
        c_int   A_p[3] = { 0, 2, 4}; //?
        c_float l[3] = { 1., 0., 0., }; //lower bounds
        c_float u[3] = { 1., 0.7, 0.7, }; //upper bounds
        c_int n = 2; //number of variables (x)
        c_int m = 3; //number of constraints

        // Problem settings
        OSQPSettings *settings = (OSQPSettings *)c_malloc(sizeof(OSQPSettings));

        // Structures
        OSQPWorkspace *work; // Workspace
        OSQPData *data;      // OSQPData

        // Populate data
        data = (OSQPData *)c_malloc(sizeof(OSQPData));
        data->n = n;
        data->m = m;
        data->P = csc_matrix(data->n, data->n, P_nnz, P_x, P_i, P_p);
        data->q = q;
        data->A = csc_matrix(data->m, data->n, A_nnz, A_x, A_i, A_p);
        data->l = l;
        data->u = u;

        // Define Solver settings as default
        osqp_set_default_settings(settings);

        // Setup workspace
        work = osqp_setup(data, settings);

        // Solve Problem
        osqp_solve(work);

        //return the value
        OSQPSolution* sol = work->solution;
        x = sol->x;

        // Clean workspace
        osqp_cleanup(work);
        c_free(data->A);
        c_free(data->P);
        c_free(data);
        c_free(settings);
    }
}

So all I have done is declared a parameter 'x', and I am setting it after the results are calculated.
F# code
open System.Runtime.InteropServices

module ExternalFunctions =
    [<DllImport("TestLibCpp.dll")>]
    extern void DisplayHelloFromDLL(float[] i, [<In>][<Out>] float[] x)

[<EntryPoint>]
let main argv =
    let P_x = [|4.; 1.; 1.; 2.|]
    let mutable xResult:float[] = [|0.;0.|]
    ExternalFunctions.DisplayHelloFromDLL(P_x, xResult);

    printfn "This is x:%A" xResult
    0 // return an integer exit code

C# code
class Program
    {
        [DllImport("TestLibCpp.dll")]
        public static extern void DisplayHelloFromDLL(double[] i, [In, Out] double[] x);
        static void Main(string[] args)
        {
            Console.WriteLine("This is C# program");
            double[] P_x = new double[] {4.0, 1.0, 1.0, 2.0};
            double[] x = new double[] { 0.0, 0.0};
            DisplayHelloFromDLL(P_x, x);

            Console.WriteLine("Finished");
        }
    }

In both the F#, and C# cases, the value of x is unchanged.
I have tried other variations such as
open System.Runtime.InteropServices

module ExternalFunctions =
    [<DllImport("TestLibCpp.dll")>]
    extern void DisplayHelloFromDLL(float[] i, [<In>][<Out>] float[]& x)

[<EntryPoint>]
let main argv =
    let P_x = [|4.; 1.; 1.; 2.|]
    let mutable xResult:float[] = [|0.0; 0.0|]
    ExternalFunctions.DisplayHelloFromDLL(P_x, &xResult);

    printfn "This is x:%A" xResult

But I suspect the problem is the C code, not the .Net code. I think the problem is that work->solution->x is a pointer, not an array. I am guessing that I need to convert it from a pointer to an array, but can't work out how to do that. And again, not totally sure this is even the problem to begin with.

A: Thanks to PetSerAl for pointing (pun intended) me in the right direction.
All I needed to do was change part of the C code to
        //return the value
        OSQPSolution* sol = work->solution;
        for (int i = 0; i != n; ++i)
            x[i] = sol->x[i];


text:
Q: How Cooper pairs conduct curent we know that electrons in superconductor are coupled somehow (How does Cooper pairing work?)
  creating quasi-particles called cooper pairs which are Bosons and going to ground state ( do not obey Pauli exclusion anymore)
and that happen after this?.. how can be charge was cared without any dissipation?