text:
Q: Sincronizar atributos componente angular Estoy utilizando un componente bower "externo" (aunque si es necesario lo puedo modificar) para la subida de ficheros a un servidor. Este componente cuando finaliza la subida notifica a un método de mi controlador y establece en el modelo un identificador de subida. La cuestión es que desde mi controlador cuando tengo más de un elemento no funciona.
El componente al enviar hace:
function ctoUpload() {
    return {
        restrict: 'E',
        scope: {
            identificador: '=',
            identificadorObj: '=',
            onSuccess: '&'
        },
        controller: UploadFilesController,
        controllerAs: 'uploadController',
        templateUrl: '{{lang}}/upload.html',
        bindToController: true
    };
}

  function uploadFile() {
        var inputArchivo =document.getElementById('file' + uploadController.identificadorObj);
        var formData = new FormData();
        formData.append('file', inputArchivo.files[0]);
         var onsuccess = uploadController.onSuccess;

        uploadService.subirFichero(formData,  onsuccess).success(function (response, status) {
            if (_.isFunction(onsuccess)) {
                uploadController.identificador = response.id;//id correcto
                            result = $q.when(uploadController.onSuccess.apply(this));

result.then(function () {...
Mi "callback" hace lo siguiente:
vm.upload = function(file) {
     var id = vm.identificador;//aquí id vale erróneamente el anterior
     ...

El jade:
cto-upload(id="opt"+"vm.identificador",identificador="vm.identificador",
           on-success="vm.upload(file)"..

El resultado es que al subir un fichero vm.identificador vale "" al subir el segundo coge el anterior y así sucesivamente. He probado con $scope.apply y $scope.$evalAsync sin éxito. Depurando veo que al componente llegan todos los datos correctamente pero no se actualiza en mi modelo. ¿alguna idea?

A: Prueba realizar la logica que interactúa con componentes angular dentro de una función manejada por el ciclo de vida de angular, como $timeout
uploadService.subirFichero(formData,  onsuccess).success(function (response, status) {
    if (_.isFunction(onsuccess)) {
        $timeout(function (){
            /* tu logica aqui*/
        });
    }
});

Esto porque la asignación que haces:
uploadController.identificador = ...

No es visible en un ciclo de digest


text:
Q: ExponentialBackoff job Reload function Error: Call to undefined method I'm getting the following fatal error when running the php script below:
Waiting for job to complete
**Fatal error: Uncaught Error: Call to undefined method
Google\Cloud\BigQuery\CopyJobConfiguration::*reload()*
 in /opt/bitnami/apache2/htdocs/test.php:53 Stack trace: #0 [internal function]:
 {closure}() #1 /opt/bitnami/apache2/htdocs/vendor/google/cloud/src/Core/ExponentialBackoff.php(74):
 call_user_func_array(Object(Closure), Array) #2 /opt/bitnami/apache2/htdocs/test.php(58):
 Google\Cloud\Core\ExponentialBackoff->execute(Object(Closure)) #3 /opt/bitnami/apache2/htdocs/test.php(36):
 copy_table('aaaa', 'bbbb', 'cccc', 'dddd', 'eeee') #4 {main} thrown in /opt/bitnami/apache2/htdocs/test.php on line 54**

.
<?php

header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Pragma: no-cache"); // HTTP/1.0
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

# Includes the autoloader for libraries installed with composer

require "vendor/autoload.php";

use Google\Cloud\BigQuery\BigQueryClient;
use Google\Cloud\ServiceBuilder;
use Google\Cloud\Core\ExponentialBackoff;

$client = new Google_Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS='.dirname(__FILE__) . '/.ssh/xxx.json');
$client->useApplicationDefaultCredentials();

# Your Google Cloud Platform project stuff
$projectId = 'aaaa';
$datasetIdin = 'bbbb';
$datasetIdout = 'cccc';
$tableIdin = "dddd";
$tableIdout = "eeee";

$gcloud = new ServiceBuilder([
    'projectId' => $projectId
]);

copy_table($projectId, $datasetIdin, $datasetIdout, $tableIdin, $tableIdout);

function copy_table($projectId, $datasetIdin, $datasetIdout, $tableIdin, $tableIdout)
{
    $bigQuery = new BigQueryClient([
        'projectId' => $projectId,
    ]);
    $datasetin = $bigQuery->dataset($datasetIdin);
    $datasetout = $bigQuery->dataset($datasetIdout);
    $sourceTable = $datasetin->table($tableIdin);
    $destinationTable = $datasetout->table($tableIdout);
    $job = $sourceTable->copy($destinationTable);

    // poll the job until it is complete
    $backoff = new ExponentialBackoff(10);
    $backoff->execute(function () use ($job) {
        print('Waiting for job to complete' . PHP_EOL);
        $job->reload();
        if (!$job->isComplete()) {
            throw new Exception('Job has not yet completed', 500);
        }
    });
    // check if the job has errors
    if (isset($job->info()['status']['errorResult'])) {
        $error = $job->info()['status']['errorResult']['message'];
        printf('Error running job: %s' . PHP_EOL, $error);
    } else {
        print('Table copied successfully' . PHP_EOL);
    }

echo "table copied";
}

?>

It looks as 'though the appropriate class has not been loaded? The composer.json I am using is:
{
    "require": {
        "google/cloud": "^0.47.0",
        "google/apiclient": "^2.0"
    }
}

Any ideas as to why I'm hitting this error? Thanks!

A: Something is off in your approach.
$job = $sourceTable->copy($destinationTable);

this doesn't return a Job.
Returns a copy job configuration to be passed to either Google\Cloud\BigQuery\Table::runJob() or Google\Cloud\BigQuery\Table::startJob().
so you further need to add code to pass this conf to the above functions.
http://googlecloudplatform.github.io/google-cloud-php/#/docs/google-cloud/v0.47.0/bigquery/table?method=copy

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android Unicode Gender Symbols I'm trying to print the male and female symbols in an Android TextView.  In the preview of the layout, it works just fine.  But when I run the application on my phone, they are replaced by blue and pink images.  How can I override this so it just displays them as basic text?

A: For maximum compatibility you will need to find a font/typeface (.ttf file) that supports these unicode characters.
Once you find said file, place it in the assets folder in fonts/typeface_file.ttf
Then you load the Typeface:
Typeface.createFromAsset(assets, "fonts/typeface_file.ttf");

Next apply it to your TextView:
textView.setTypeface(typeface);

The advantage to loading your own typeface is that it won't matter what the system font of the device is, it will always be available and include those unicode characters because it is packaged into your app.


text:
Q: Fetching by associative array If you fetch the following data via an associative array in php:
SELECT thread.id, thread.title, thread.content, author.username, author.id
FROM thread INNER JOIN author
ON author_id = author.id

How can you differentiate between author.id and thread.id?
$threads = select_Query('SELECT thread.id, thread.title, thread.content, author.username, author.id
                         FROM thread INNER JOIN author
                         ON author_id = author.id', $link);

A: You can use column aliases to resolve column name ambiguities:
SELECT thread.id AS t_id, thread.title, thread.content, author.username, author.id AS a_id
FROM thread INNER JOIN author
ON author_id = author.id

Then reference the aliases in your PHP array, as $row['t_id'] and $row['a_id'] respectively.


text:
Q: R: List key value mappings switched Right now, I'm using lists as dictionaries mapping basketball team names to win rates). Somehow, after I'm finished processing the data I have, the key/value mappings are switched, so that the values themselves are correct, but keys don't map to their correct values. Is there any common mistake that might cause this to happen?
Here's some of the code I'm using, where the csv has the information in names(games).
games <- read.csv(game_pathname, header = FALSE)
names(games) <- c("GameDate", "DateCount", "HomeID", "AwayID", "HomePts", "AwayPts", "HomeAbbr", "AwayAbbre", "HomeName", "AwayName")
wins <- list()

for (team in unique(games$HomeName)) {
    wins[[team]] <- 0
}

for (i in 1:nrow(games)) {
    if (games$HomePts[i] > games$AwayPts[i]) {
        wins[[games$HomeName[[i]]]] <- wins[[games$HomeName[[i]]]] + 1
    } else {
        wins[[games$AwayName[[i]]]] <- wins[[games$AwayName[[i]]]] + 1
    }
}

>str(games)
'data.frame':   10303 obs. of  10 variables:
 $ GameDate : chr  "2008-11-10" "2008-11-10" "2008-11-11" "2008-11-11" ...
 $ DateCount: int  0 0 1 1 1 2 2 2 2 3 ...
 $ HomeID   : int  113 76 113 76 124 168 312 329 272 329 ...
 $ AwayID   : int  98 234 234 98 204 204 233 167 160 233 ...
 $ HomePts  : int  63 80 76 97 60 76 82 66 80 78 ...
 $ AwayPts  : int  65 49 57 54 73 56 58 70 73 68 ...
 $ HomeAbbr : chr  "ham" "dau" "ham" "dau" ...
 $ AwayAbbre: chr  "gab" "paq" "paq" "gab" ...
 $ HomeName : chr  "Houston" "Duke" "Houston" "Duke" ...
 $ AwayName : chr  "Georgia Southern" "Presbyterian" "Presbyterian" "Georgia Southern" ...

A: Use
str(yourbasketballdataset)

to check whether there are any factors in your dataset. Make also sure to check
?relevel
?levels
?as.factor

when trying to learn a bit about factors. Are you a Python guy (I mean since you use the term dictionary)? Even though I don't understand why you use lists (probably data.frame would be sufficient) you might want to look at lapply for processing lists.
Note that factors are not implicit within list, but are often created when data occurs that can easily be interpreted as categorical data – factor is just the R term for categorical. Maybe, you can try to post a reproducible example. I know it's some work to create one – but it's worth the hustle – particularly if you are a beginner. And cause it's basketball I might even have intrinsic motivation to check it on a sunday :)


text:
Q: How to get list of common elements of 2 array in Swift? I have two arrays:
fruitsArray = ["apple", "mango", "blueberry", "orange"]
vegArray = ["tomato", "potato", "mango", "blueberry"]

How can I get the list of common items in those two array which gives
ouptput = ["mango", "blueberry"]

I can't use if contains(array, string) as I want to compare 2 arrays.

A: A generic method, inspired by The Swift Programming Language (Swift 3) exercise:
func commonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> [T.Iterator.Element]
    where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
        var common: [T.Iterator.Element] = []

        for lhsItem in lhs {
            for rhsItem in rhs {
                if lhsItem == rhsItem {
                    common.append(lhsItem)
                }
            }
        }
        return common
}

Then, use it like this:
var a = [3,88,74]
var b = [1,3,88]

print("commons: \(commonElements(a, b))")

--> commons: [3, 88]

A: The following works with swift 4:
   let fruitsArray = ["apple", "mango", "blueberry", "orange"]
   let vegArray = ["tomato", "potato", "mango", "blueberry"]

   var someHash: [String: Bool] = [:]

   fruitsArray.forEach { someHash[$0] = true }

   var commonItems = [String]()

   vegArray.forEach { veg in
    if someHash[veg] ?? false {
        commonItems.append(veg)
    }
   }

   print(commonItems)

A: Convert them to Set and use intersect() function:
let fruitsArray = ["apple", "mango", "blueberry", "orange"]
let vegArray = ["tomato", "potato", "mango", "blueberry"]
let fruitsSet = Set(fruitsArray)
let vegSet = Set(vegArray)
let output = Array(fruitsSet.intersection(vegSet))

A: The following works with swift 4,5
let fruitsArray = ["apple", "mango", "blueberry", "orange"]
let vegArray = ["tomato", "potato", "mango", "blueberry"]

//You can using filter function
let commonArray = fruitsArray.filter { fruit in
    vegArray.contains(fruit)
}

print(commonArray)

Output: ["mango", "blueberry"]

A: You don't need a Set (as the comments above have mentioned).
You could instead use a generic function, similar to the one Apple use in their Swift Tour, and thus avoid casting:
func anyCommonElements <T, U where T: SequenceType, U: SequenceType, T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, rhs: U) -> Bool {
    for lhsItem in lhs {
        for rhsItem in rhs {
            if lhsItem == rhsItem {
                return true
            }
        }
    }
    return false
}

This function can take any two arrays (SequenceTypes) and if any of their elements are the same it returns true.
You could simply modify this generic function to package up an array of strings and return that instead.
For example like this:
func arrayOfCommonElements <T, U where T: SequenceType, U: SequenceType, T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, rhs: U) -> [T.Generator.Element] {
    var returnArray:[T.Generator.Element] = []
    for lhsItem in lhs {
        for rhsItem in rhs {
            if lhsItem == rhsItem {
                returnArray.append(lhsItem)
            }
        }
    }
    return returnArray
}

Usage like this:
var one = ["test2", "dog", "cat"]
var other = ["test2", "cat", "dog"]

var result = arrayOfCommonElements(one,other)

print(result) //prints [test2, dog, cat]

The added benefit here is that this function also works with all same typed arrays. So later if you need to compare two [myCustomObject] arrays, once they both conform to equatable, you're all set! (pun intended)
Edit: (For non common elements) you could do something like this
func arrayOfNonCommonElements <T, U where T: SequenceType, U: SequenceType, T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, rhs: U) -> [T.Generator.Element] {

    var returnArray:[T.Generator.Element] = []
    var found = false

    for lhsItem in lhs {
        for rhsItem in rhs {
            if lhsItem == rhsItem {
                found = true
                break
            }
        }

        if (!found){
            returnArray.append(lhsItem)
        }

        found = false
    }
    for rhsItem in rhs {
        for lhsItem in lhs {
            if rhsItem == lhsItem {
                found = true
                break
            }
        }

        if (!found){
            returnArray.append(rhsItem)
        }

        found = false
    }
    return returnArray
}

This implementation is ugly though.

A: You can also use filter and contains in conjunction:
let fruitsArray = ["apple", "mango", "blueberry", "orange"]
let vegArray = ["tomato", "potato", "mango", "blueberry"]

// only Swift 1
let output = fruitsArray.filter{ contains(vegArray, $0) }

// in Swift 2 and above
let output = fruitsArray.filter{ vegArray.contains($0) }
// or
let output = fruitsArray.filter(vegArray.contains)

Set vs Array for a single computation of common elements
We consider the following code snippet:
let array1: Array = ...
let array2: Array = ...

// `Array`
let commonElements = array1.filter(array2.contains)

// vs `Set`
let commonElements = Array(Set(array1).intersection(Set(array2)))
// or (performance wise equivalent)
let commonElements: Array = Set(array1).filter(Set(array2).contains)

I have made some (artificial) benchmarks with Int and short/long Strings (10 to 100 Characters) (all randomly generated). I always use array1.count == array2.count
I get the following results:
If you have more than critical #(number of) elements converting to a Set is preferable
data         |  critical #elements
-------------|--------------------
         Int |        ~50
short String |       ~100
 long String |       ~200

Explanation of the results
Using the Array approach uses "Brute force"-search which has time complexity O(N^2) where N = array1.count = array2.count which is in contrast to the Set approach O(N). However the conversion from Array to Set and back is very expensive for large data which explains the increase of critical #elements for bigger data types.

Conclusion
For small Arrays with about 100 elements the Array approach is fine but for larger ones you should use the Set approach.
If you want to use this "common elements"-operation multiple times it is advisable to use Sets only if possible (the type of the elements has to be Hashable).
Final Remarks
A conversion from Array to Set is kind of expensive while the conversion from Set to Array is in contrast very inexpensive.
Using filter with .filter(array1.contains) is performance wise faster than .filter{ array1.contains($0) } since:

*

*the last one creates a new closure (only once) whereas the first one passes only a function pointer

*for the last one the call of the closure creates an additional stack frame which costs space and time (multiple times: O(N))

A: Using Set and also intersection as follows:
func findIntersection (firstArray : [Int], secondArray : [Int]) -> [Int]
{
    return [Int](Set<Int>(firstArray).intersection(secondArray))
}

print (findIntersection(firstArray: [2,3,4,5], secondArray: [1,2,3]))


text:
Q: Issue with Google calendar ICS file import I'm trying to create a program which help me to import programmatically my school event. The output file (calendarXXXXX...ics) looks like this:
BEGIN:VCALENDAR
PRODID:xxx
VERSION:2.0
CALSCALE:GREGORIAN
BEGIN:VEVENT
DTSTART:20171023T140000Z
DTEND:20171023T160000Z
UID:xxx
CREATED:20171017T165457Z
DESCRIPTION:xxx
LOCATION:xxx
STATUS:CONFIRMED
SUMMARY:xxx
END:VEVENT
BEGIN:VEVENT
DTSTART:20171025T090000Z
DTEND:20171025T130000Z
UID:xxx
CREATED:20171017T165457Z
DESCRIPTION:xxx
LOCATION:xxx
STATUS:CONFIRMED
SUMMARY:xxx
END:VEVENT
END:VCALENDAR

When I try to import this file in Google Calendar it told me that it had elaborated all Y events, but only one was imported. Someone can help me with some suggest?

A: A event UID is important - it's a unique identifier.  If you used xxx for all of them, google probably treated it all as relating the same event.
Try validating your ics files.  The validators are not perfect but they help.
https://icalendar.org/validator.html  and http://severinghaus.org/projects/icv/ say missing DTSTAMPs
http://ical-validator.herokuapp.com/ says:
! CRLF should be used for newlines
Related RFC 5545 section: 3.1
! UID [xxx] encountered multiple times
Related RFC 5545 section: 3.8.4.7


text:
Q: Using Spring Cloud Data Flow with Azure Service Bus I am trying to find some examples of Spring Cloud Data Flow and Azure Service Bus setup. .
I have found https://github.com/microsoft/spring-cloud-azure/tree/master/spring-cloud-azure-stream-binder/spring-cloud-azure-servicebus-topic-stream-binder but it is still in RC and I do not see any examples (which cover Spring Cloud Data Flow) there.
Could you please help me to understand if I can use Spring Cloud Data Flow and Azure Service Bus together?
I was able to run examples with Kafka and RabbitMQ, but I cannot find anything about Azure Service Bus that can be used as the integration solution for Spring Cloud Data Flow

A: Spring Cloud Data Flow doesn't necessarily need to know what messaging layer you choose to run your applications on. Hence, your question is more likely related to how one can run the application with Azure Service Bus using Spring Cloud Stream.
This is one such a sample: https://learn.microsoft.com/en-us/java/azure/spring-framework/configure-spring-cloud-stream-binder-java-app-azure-event-hub?view=azure-java-stable
Once the application is built using Spring Cloud Stream (using the Azure event hub binder), you can then manage these applications using Spring Cloud Data Flow as Streaming applications.


text:
Q: Rscript: Define path file as argument I try this command :
Rscript "/Users/test/Scripts/arg_test.R" "path_in=/Users/test/GR/web-app/Rproject/Inputs/Rmerge/Description.csv" path_in2="/Users/test/IdeaProjects/Rproject/Inputs/Rmerge/Template_Auto.csv"

but I have this error :
Error in parse(text = args[[i]]) : unexpected '/' in "path_in=/"
Part of Rscript :
args=(commandArgs(TRUE))

if(length(args)==0){
    print("No arguments supplied.")
}else{
    for(i in 1:length(args)){
         eval(parse(text=args[[i]]))
    }
}

path_out = "/Users/test/Rproject/Results/"

annotation = read.csv(paste(path_in, sep=""))

modules = read.csv(paste(path_in2, sep=""))

merge_output = merge(annotation, modules, by = "Module")

How can I define path_in as argument(args) ?
Thank you.

A: Replacing the = with the proper assignment operator <- and protecting each argument with single quotes works for me:
Rscript /tmp/RscriptArgs.R  \
  'path_in<-"/Users/test/GR/web-app/Rproject/Inputs/Rmerge/Description.csv"'  \
  'path_in2<-"/Users/test/IdeaProjects/Rproject/Inputs/Rmerge/Template_Auto.csv"'

where /tmp/RscriptArgs.R is what you showed from your script.

A: You have path_in= inside the double quotes, but path_in2= outside. Could this be the problem?

A: Thank you, I just fix my problem !
I should use "path_in='/Users/test/...'" and not "path_in=/Users/test/...".
Works fine with quote.
Rscript "/Users/test/Scripts/arg_test.R" "path_in='/Users/test/GR/web-app/Rproject/Inputs/Rmerge/Gene-level Description for Modules.csv'" "path_in2='/Users/test/IdeaProjects/Rproject/Inputs/Rmerge/Template_Auto.csv'"

Fix add by Dirk works fine too (thanks) !


text:
Q: PayPal Java NVP API GetExpressCheckoutDetails - Missing Data I'm calling the PayPal sandbox with a 'express checkout' process from a java web application. The first call ('SetExpressCheckout') succeeds and I receive a Token as expected.
The second call ('GetExpressCheckoutDetails') succeeds as well in regard to getting an ACK=Success answer. But there is all the payer information data like FIRSTNAME, LASTNAME or SHIPTOCITY missing.
Here's the URL I'm calling with parameters:
https://api-3t.sandbox.paypal.com/nvp?TOKEN=__MY_TOKEN__&VERSION=106.0&SIGNATURE=__MY_SIGNATURE__&METHOD=GetExpressCheckoutDetails&PWD=__MY_PASSWORD__&USER=__MY_USERNAME__

Here's the response's body I get:
TOKEN=__MY_TOKEN__&CHECKOUTSTATUS=PaymentActionNotInitiated&TIMESTAMP=2013%2d09%2d11T20%3a56%3a36Z&CORRELATIONID=bb3916c14aa78&ACK=Success&VERSION=106%2e0&BUILD=7645184&CURRENCYCODE=USD&AMT=12%2e00&SHIPPINGAMT=0%2e00&HANDLINGAMT=0%2e00&TAXAMT=0%2e00&INSURANCEAMT=0%2e00&SHIPDISCAMT=0%2e00&PAYMENTREQUEST_0_CURRENCYCODE=USD&PAYMENTREQUEST_0_AMT=12%2e00&PAYMENTREQUEST_0_SHIPPINGAMT=0%2e00&PAYMENTREQUEST_0_HANDLINGAMT=0%2e00&PAYMENTREQUEST_0_TAXAMT=0%2e00&PAYMENTREQUEST_0_INSURANCEAMT=0%2e00&PAYMENTREQUEST_0_SHIPDISCAMT=0%2e00&PAYMENTREQUEST_0_INSURANCEOPTIONOFFERED=false&PAYMENTREQUEST_0_ADDRESSNORMALIZATIONSTATUS=None&PAYMENTREQUESTINFO_0_ERRORCODE=0

If I put the same request URL into Firefox I receive the response I would expect:
TOKEN=__MY_TOKEN__&CHECKOUTSTATUS=PaymentActionNotInitiated&TIMESTAMP=2013%2d09%2d11T20%3a37%3a31Z&CORRELATIONID=7804316ba643d&ACK=Success&VERSION=106%2e0&BUILD=7645184&EMAIL=mne%2dcustomer2%40m%2dn%2de%2ede&PAYERID=QRZ57KR8PHVF4&PAYERSTATUS=verified&FIRSTNAME=Frank&LASTNAME=Forest&COUNTRYCODE=US&SHIPTONAME=Frank%20Forest&SHIPTOSTREET=1%20Main%20St&SHIPTOCITY=San%20Jose&SHIPTOSTATE=CA&SHIPTOZIP=95131&SHIPTOCOUNTRYCODE=US&SHIPTOCOUNTRYNAME=United%20States&ADDRESSSTATUS=Confirmed&CURRENCYCODE=USD&AMT=15%2e00&SHIPPINGAMT=0%2e00&HANDLINGAMT=0%2e00&TAXAMT=0%2e00&INSURANCEAMT=0%2e00&SHIPDISCAMT=0%2e00&PAYMENTREQUEST_0_CURRENCYCODE=USD&PAYMENTREQUEST_0_AMT=15%2e00&PAYMENTREQUEST_0_SHIPPINGAMT=0%2e00&PAYMENTREQUEST_0_HANDLINGAMT=0%2e00&PAYMENTREQUEST_0_TAXAMT=0%2e00&PAYMENTREQUEST_0_INSURANCEAMT=0%2e00&PAYMENTREQUEST_0_SHIPDISCAMT=0%2e00&PAYMENTREQUEST_0_INSURANCEOPTIONOFFERED=false&PAYMENTREQUEST_0_SHIPTONAME=Frank%20Forest&PAYMENTREQUEST_0_SHIPTOSTREET=1%20Main%20St&PAYMENTREQUEST_0_SHIPTOCITY=San%20Jose&PAYMENTREQUEST_0_SHIPTOSTATE=CA&PAYMENTREQUEST_0_SHIPTOZIP=95131&PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE=US&PAYMENTREQUEST_0_SHIPTOCOUNTRYNAME=United%20States&PAYMENTREQUEST_0_ADDRESSSTATUS=Confirmed&PAYMENTREQUEST_0_ADDRESSNORMALIZATIONSTATUS=None&PAYMENTREQUESTINFO_0_ERRORCODE=0

This expected answer contains PAYERID, FIRSTNAME, LASTNAME, SHIPTOSTREET, SHIPTOCITY etc.
I tried calling the PayPal sandbox from java using

*

*Apache HttpClient GET request

*Apache HttpClient POST request

*javax.net.ssl.HttpsURLConnection

*java.net.URLConnection

I tried running the webapp in JBoss 7.1.1 on mac OS X and JBoss 7.2.0 on win8.
I also tried putting the port number in the URL explicitly (https://api-3t.sandbox.paypal.com:443)
The result is always the same. The payer information (name, address) is missing when I call it from java.
Has anyone got an idea what is wrong?
UPDATE: Calling the PayPal sandbox from Eclipse (Apache HttpClient GET request) returns the correct response. So I assume this might have something to do with JBoss AS.

A: After you call SetExpressCheckout, you have to redirect the buyer to PayPal (https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=__MY_TOKEN__) and have them log in and approve the payment.  After they've done that and returned to your website, then call GetExpressCheckoutDetails to retrieve their information.


text:
Q: LiveCharts re-renders the entire plot when changing axis (MinValue and MaxValue) or adding new data I've created a LineChart that has 5 charts. Each has 250 points: 1 point every 1 min. I have a button which moves MinValueX and MaxValueX. And an event UserControl_MouseDown which adds new data to 1 chart. But when I invoke this it needs 15-20 seconds to move or add data to the plot. I think 1250 point isn't a lot. It looks like it draws the entire graph again instead of moving it, or adding new data.
Can I somehow change the rendering behavior to be more optimal?
Here is my LineChart control:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using LiveCharts;
using LiveCharts.Defaults;
using LiveCharts.Wpf;

namespace Chart
{
    /// <summary>
    /// Interaction logic for LineChart2.xaml
    /// </summary>
    public partial class LineChart2 : UserControl, INotifyPropertyChanged
    {
        #region properties
        public SeriesCollection SeriesCollection { get; set; }
        private Dictionary<string, List<DateTimePoint>> SeriesFullCollection { get; set; }
        public Func<double, string> XFormatter { get; set; }
        public long AxisStep { get; set; }
        public double MinValueX { get; set; }
        public double MaxValueX { get; set; }

        private DateTime minValueXDate;
        public DateTime MinValueXDate
        {
            get { return minValueXDate; }
            set { minValueXDate = value;
                MinValueX = value.Ticks;
                OnPropertyChanged("MinValueX");
            }
        }
        private DateTime maxValueXDate;
        public DateTime MaxValueXDate
        {
            get { return maxValueXDate; }
            set
            {
                maxValueXDate = value;
                MaxValueX = value.Ticks;
                OnPropertyChanged("MaxValueX");
            }
        }
        public double MinValueY { get; set; }
        public double MaxValueY { get; set; }
        public int ChartButtonsId { get; set; }
        #endregion
        public LineChart2()
        {
            SeriesFullCollection = new Dictionary<string, List<DateTimePoint>>();
            SeriesCollection = new SeriesCollection();
            this.Loaded += ControlLoaded;
            DataContext = this;
            InitializeComponent();
        }

        private void ControlLoaded(object sender, RoutedEventArgs e)
        {
            MinValueXDate = DateTime.Now.AddHours(-3.5);
            MaxValueXDate = DateTime.Now.AddHours(0.5);
            AxisStep = TimeSpan.FromMinutes(15).Ticks;
            XFormatter = val => new DateTime((long)val).ToString("HH:mm");

            MinValueY = 0;            //Test
            MaxValueY = 20;            //Test
            //Test
            Text2Add("A");
            Text2Add("B");
            Text2Add("C");
            Text2Add("D");
            Text2Add("E");
            RefreshCollection();
        }

        #region Add/Update/Remove
        public void AddChart(string title, Dictionary<DateTime, double> data)
        {
            List<DateTimePoint> dateTimePoints = new List<DateTimePoint>();
            foreach (var item in data)
                dateTimePoints.Add(new DateTimePoint(item.Key, item.Value));

            SeriesFullCollection.Add(title, dateTimePoints);
            AddToCollection(title);
        }
        public void UpdateChart(string title, Dictionary<DateTime, double> data)
        {
            var series = SeriesCollection.FirstOrDefault(x => x.Title == title);
            var seriesfull = SeriesFullCollection.FirstOrDefault(x => x.Key == title);
            if (series != null)
                foreach (var item in data)
                {
                    series.Values.Add(new DateTimePoint(item.Key, item.Value));
                    seriesfull.Value.Add(new DateTimePoint(item.Key, item.Value));
                }
        }
        public void RemoveChart(string title)
        {
            var series = SeriesCollection.FirstOrDefault(x => x.Title == title);
            var seriesfull = SeriesFullCollection.FirstOrDefault(x => x.Key == title);
            if (series != null)
            {
                SeriesCollection.Remove(series);
                SeriesFullCollection.Remove(seriesfull.Key);
            }
            RefreshCollection();
        }

        private void AddToCollection(string title)
        {
            var seriesfull = SeriesFullCollection.FirstOrDefault(x => x.Key == title);
            var l = new LineSeries();
            l.Title = seriesfull.Key;
            l.Values = new ChartValues<DateTimePoint>();
            l.PointGeometrySize = 2;
            l.Values.AddRange(seriesfull.Value.Where(x => x.DateTime >= MinValueXDate && x.DateTime <= MaxValueXDate));
            SeriesCollection.Add(l);
        }
        #endregion
        #region EventsMethod
        public void MoveNext()
        {
            MinValueXDate = MinValueXDate.AddTicks(AxisStep * 2);
            MaxValueXDate = MaxValueXDate.AddTicks(AxisStep * 2);
            //RefreshCollection();
        }
        public void MovePrevious()
        {
            MinValueXDate = MinValueXDate.AddTicks(-AxisStep * 2);
            MaxValueXDate = MaxValueXDate.AddTicks(-AxisStep * 2);
            //RefreshCollection();
        }
        public void ZoomIn()
        {
            MinValueXDate = MinValueXDate.AddTicks(AxisStep);
            MaxValueXDate = MaxValueXDate.AddTicks(-AxisStep);
            //RefreshCollection();
        }
        public void ZoomOut()
        {
            MinValueXDate = MinValueXDate.AddTicks(-AxisStep);
            MaxValueXDate = MaxValueXDate.AddTicks(AxisStep);
            //RefreshCollection();
        }
        public void ChangeDate()
        {

        }
        #endregion
        private void RefreshCollection()
        {
            SeriesCollection.Clear();
            foreach (var item in SeriesFullCollection)
            {
                var l = new LineSeries();
                l.Title = item.Key;
                l.Values = new ChartValues<DateTimePoint>();
                l.PointGeometrySize = 2;
                l.Values.AddRange(item.Value.Where(x => x.DateTime >= MinValueXDate && x.DateTime <= MaxValueXDate));
                SeriesCollection.Add(l);
            }
        }
        #region Test
        private void Text2Add(string name)
        {
            var d = new Dictionary<DateTime, double>();
            int last = 0;
            Random r = new Random();
            for (int i = 0; i < 250; i++)
            {
                var next = r.Next(last == 0 ? 0 : last - 1, last == 20 ? 20 : last + 2);
                last = next;
                d.Add(DateTime.Now.AddMinutes(-250+ i), next);
            }
            AddChart(name, d);
        }
        private int aaaa = 0;

        public event PropertyChangedEventHandler PropertyChanged;

        private void UserControl_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var d = new Dictionary<DateTime, double>();
            int last = 0;
            Random r = new Random();
            for (int i = 0; i < 10; i++)
            {
                var next = r.Next(last == 0 ? 0 : last - 1, last == 20 ? 20 : last + 2);
                last = next;
                d.Add(DateTime.Now.AddMinutes(aaaa + i), next);
            }
            aaaa += 10;
            UpdateChart("A", d);
        }
        #endregion
        protected void OnPropertyChanged(string name)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MinValueXDate = MinValueXDate.AddTicks(AxisStep * 2);
            MaxValueXDate = MaxValueXDate.AddTicks(AxisStep * 2);
        }
    }
}

And Xaml:
<UserControl x:Class="Chart.LineChart2"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
         xmlns:local="clr-namespace:Chart"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="800" MouseDown="UserControl_MouseDown">
    <Grid Background="White">
        <lvc:CartesianChart Series="{Binding SeriesCollection}" LegendLocation="Right" >
            <lvc:CartesianChart.AxisY>
                <lvc:Axis Title="Value" MinValue="{Binding MinValueY}" MaxValue="{Binding MaxValueY}"></lvc:Axis>
            </lvc:CartesianChart.AxisY>
            <lvc:CartesianChart.AxisX>
                <lvc:Axis LabelFormatter="{Binding XFormatter}" MinValue="{Binding MinValueX}" MaxValue="{Binding MaxValueX}">
                    <lvc:Axis.Separator>
                        <lvc:Separator Step="{Binding AxisStep}" />
                    </lvc:Axis.Separator>
                </lvc:Axis>
            </lvc:CartesianChart.AxisX>
        </lvc:CartesianChart>
        <Button Height="20" Width="50" Click="Button_Click" Margin="740,10,10,270"/>
    </Grid>
</UserControl>

A: There is a link to page with peformance tips.
Suggested posibilities for better performance are:

*

*Disable Animations <lvc:CartesianChart DisableAnimations="True" />

*Reduce the number of shapes in chart

*Freeze all you can

*Avoid calling .Add() multiple times

So in your case, I would try at least first and last suggestion.


text:
Q: TS2339: Property 'closest' does not exist on type 'EventTarget'. - How do I get native event.target in React? I am trying to construct an event listener callback that detects where it has been invoked from, similar to this:
import { TouchEvent } from 'react'

const isInvokedFromInsideContainer = (event: TouchEvent<HTMLElement>) => {
  parentContainer = event.target.closest('#container')
  console.log('isInvokedFromInsideContainer: ' + !!parentContainer)
}

but I get

TS2339: Property 'closest' does not exist on type 'EventTarget'

event.nativeEvent.target.closest doesn't work either
event.currentTarget.closest works, but I obviously don't want that
Casting target as HTMLElement works:
const target = (event.target as HTMLElement)
const parentContainer = target.closest('#container')

What is the correct way to do this?

A: You can make Typescript understand which type the target is by asserting its constructor:
if (event.target instanceof HTMLElement) {
  const container = event.target.closest('#container')
}

A: I fixed this error by directly casting event.target as HTMLElement
So in your case:
...
  parentContainer = (event.target as HTMLElement).closest('#container')
...


text:
Q: underline color of LanguageTool in TeXstudio I am asking the same question as in here since I have the same problem but the solution does not work for me. I am using language tool to verify the grammar, but it is almost impossible to see the underlined grammar mistake(it is gray). On the other hand, it overwrites the spelling of texstudio; hence, it is impossible to find spelling mistakes as well. Here are my questions:

*

*How to fix the color problem? (texstudio preferences -> syntax highlighting does not work for me.)

*Is it possible to force texstudio to use its own dictionary?
I am running Texstudio 12.6 on windows 10.

A: Found the solution:
Somehow, language tool considers the spelling mistake as a grammar mistake, hence you need to change the color of grammerMistake in Language checking section of the Syntax Highlighting.


text:
Q: Linux Images wont show up on main root folder but will on a subfolder I have playing with some docker containers with LAMP.
The issue I am facing is that if I put my webpage to the www folder the page is showing up but the images from the folder www/icons/test.png wont show up. (http://192.168.123.123:8082/icons/test.png)
I get
Not Found
The requested URL was not found on this server.
Apache/2.4.38 (Debian) Server at 192.168.123.123 Port 8082

I made a copy of the icons folder to a subfolder www/test/icons/test.png and its working fine!
If I change path on the webpage all good.(http://192.168.123.123:8082/test/icons/test.png)
I checked the permissions for both folders and subfiles and they are the same!
drwxr-xr-x 11 userwh2 userwh2 4096 Aug  2 08:53 www

drwxr-xr-x 2 userwh2 userwh2   4096 Aug  1 10:19 www/icons
-rw-r--r-x 1 userwh2 userwh2  12145 Jul 24  2020 www/icons/test.png

drwxr-xr-x 3 userwh2 userwh2   4096 Aug  2 08:52 www/test
drwxr-xr-x 2 userwh2 userwh2 4096 Aug  1 10:19 www/test/icons
-rw-r--r-x 1 userwh2 userwh2  12145 Jul 24  2020 www/test/icons/test.png

I cant figure it out....
Any ideas anyone?
Edit:
Found this in the log:
Cannot serve directory /usr/share/apache2/icons/: No matching DirectoryIndex (index.php,index.html) found, and server-generated directory index forbidden by Options directive

A: Actually I was able to find an answer
https://forum.getkirby.com/t/subpage-not-working-after-digital-ocean-deployment/16083/41
Seems like the /icons folder name its used by apache2 when doing a lookup and that is why its getting confused. Its like a common name probably in apache (ex, root, etc)


text:
Q: wget -0 creating empty file in the file is not present I am using wget command with the if like this:
if (wget -O file)

If the file is not present it creates and empty file, how can stop this from happening?
What are the alternatives to remove this?


text:
Q: Is it possible to install and work on CUDA Toolkit on ElementaryOS or Deepin? And as far as I know that they're based on Ubuntu 16.04 LTS. I'm I right?

A: elementary OS is based on ubuntu, it should work without problems


text:
Q: prevent a regex to modify all a string Currently, l'm programming a small application and the future users of it will be able to write messages which will be parsed by a function (some regex).
For example, when the user write
":)"

it's transformed into

And in the same way, when he write
[code]my code :)[/code]

it's transformed into

my code

here is an example :
http://www.legeekcafe.com/upload/img/4298Capture.PNG
It's a big problem as you can see. So how can I prevent the regex to parse the smilies for example inside my code blocks ?
Thanks you

A: Take preg_replace_callback and put the code block detection in a subpattern and everything that appears before the code block subpattern into a another subpattern.
Then replace inside of the callback just the first subpattern (so not the code block) with your smiley regex.


text: Q: How to debug a gtk application using gdb? I'm trying to debug a gtk program by attaching it to gdb debugger but when I did the, gtk app freeze unless I execute next instruction or continue the program. It's annoying. I tried using ltrace but it is fill with gtk functions. How am I gonna debug this?


text:
Q: ArrayList> has no values My ArrayList<HashMap<String, String>> songslist has no values in it. In my doInBackground method i have for-loop that should fill this ArrayList. The Strings "id", "interpret"... have also values in it. Where is the problem? Here the code:
JSONArray charts = json.getJSONArray(TAG_CHARTS);

                // looping through All Products
                for(int i=0;i<charts.length();i++) {
                    JSONObject json_data = charts.getJSONObject(i);

                    String id = json_data.getString(TAG_ID);
                    String interpret = json_data.getString(TAG_INTERPRET);
                    String titel = json_data.getString(TAG_TITEL);
                    String album = json_data.getString(TAG_ALBUM);
                    String albumcover = json_data.getString(TAG_ALBUMCOVER);
                    String likes = json_data.getString(TAG_LIKES);

                    HashMap<String, String> map = new HashMap<String, String>();

                    map.put(TAG_ID, id);
                    map.put(TAG_INTERPRET, interpret);
                    map.put(TAG_TITEL, titel);
                    map.put(TAG_ALBUM, album);
                    map.put(TAG_ALBUMCOVER, albumcover);
                    map.put(TAG_LIKES, likes);

                    songslist.add(map);

                }

but List is empty. The JSONArray includes the values.

A: The code that creates the map and puts the elements in the list is ok.  So its either
1) songslist is messed up.  You don't show where/how its created
2) you think charts has items in it, but it doesn't.

A: You're not entering into the loop. Your posted code its OK. charts.length() == 0


text:
Q: How to schedule a task at go periodically? Is there any native library or third party support like ScheduledExecutorService by java native library at go lang for production use case?
Please find the code snippet in java 1.8 :
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TaskScheduler {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Runnable runnable = ()-> {
                // task to run goes here
                System.out.println("Hello !!");
        };
        ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
        service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);

    }

}

It will print Hello !! in every one second.

A: No need to use 3rd party library to achieve that. Simply take the advantage of goroutine and use available time.Sleep() API from time package, then the very same result can be achieved.
Example:
go func() {
    for true {
        fmt.Println("Hello !!")
        time.Sleep(1 * time.Second)
    }
}()

Playground: https://play.golang.org/p/IMV_IAt-VQX

Example using ticker #1
As per suggestion from Siddhanta. Here is one example to achieve the same result by using ticker (taken from go documentation page of ticker, with some modifications following your requirement).
done := make(chan bool)
ticker := time.NewTicker(1 * time.Second)

go func() {
    for {
        select {
        case <-done:
            ticker.Stop()
            return
        case <-ticker.C:
            fmt.Println("Hello !!")
        }
    }
}()

// wait for 10 seconds
time.Sleep(10 *time.Second)
done <- true

The ticker time information (the time when the Hello !! executed) can be taken from ticker.C channel.
case t := <-ticker.C:
    fmt.Println(t)

Playground: https://play.golang.org/p/TN2M-AMr39L

Example using ticker #2
Another simplified example of ticker, taken from https://gobyexample.com/tickers
ticker := time.NewTicker(1 * time.Second)
go func() {
    for range ticker.C {
        fmt.Println("Hello !!")
    }
}()

// wait for 10 seconds
time.Sleep(10 *time.Second)
ticker.Stop()


text:
Q: End If without block If error I Wrote this code. I dont understand why I got error : End If without block If
Sub mytest()

Dim i As Integer
Dim s As Integer
Dim j As Integer
Dim p As Integer
Dim k As Integer
s = 0

With Worksheets("mysheet")
.Range("B28:B75").Select

For i = 28 To 75
        If Cells(i, 2).Value > 0 Then Cells(i, 2).Interior.Color = RGB(255, 255, 255)
        s = s + 1
        End If
Next i

.Range("A28:A75").Select

For j = 28 To 75

    If Cells(i, 2).Value = 0 Then Cells(i, 2).Interior.Pattern = xlPatternLightDown
    Cells(i, 2).Interior.Color = RGB(255, 255, 255)
    End If

Next j

p = 75 - s
For k = 1 To s
    Cells(s + k, 1).Interior.Color = RGB(18, 0, 0)
Next k

End With

The End If clause wasnt omitted. I dont understand why I got error

A: If you write an If statement on a single line this:
If Foo = Bar Then FooBar()

You don't need to use an End If because the action is executed on the same line and so the end of the statement is implied (The compiler knows anything after Then on the same line is conditional, so you don't need to tell it where your conditional code ends)
If you place the action on a separate line:
If Foo = Bar Then
    FooBar()
End If

Then you have to explicitly tell the compiler where the conditional code ends by using an End If because there is no other way for it to know.

A: Move statements after Then on new line. IMHO VBA expects single line statement if you use it with code after then, so next line with code without end if throws this error. I also recomends you to read more about VBA here for better range and cell specification.
but for your error use something like this
Sub mytest()

Dim i As Integer
Dim s As Integer
Dim j As Integer
Dim p As Integer
Dim k As Integer
s = 0

With Worksheets("mysheet")
.Range("B28:B75").Select

For i = 28 To 75
        If Cells(i, 2).Value > 0 Then
        Cells(i, 2).Interior.Color = RGB(255, 255, 255)
        s = s + 1
        End If
Next i

.Range("A28:A75").Select

For j = 28 To 75

    If Cells(i, 2).Value = 0 Then
    Cells(i, 2).Interior.Pattern = xlPatternLightDown
    Cells(i, 2).Interior.Color = RGB(255, 255, 255)
    End If

Next j

p = 75 - s
For k = 1 To s
    Cells(s + k, 1).Interior.Color = RGB(18, 0, 0)
Next k

End With


text:
Q: How to solve too many soql query error? I am getting error at following line
 List<Group> groupMembers = [SELECT Id, RelatedId, Type FROM Group WHERE RelatedId IN: sRoleIds AND Type =: 'Role'];

A: There are only two (out of 100) SQOL queries in your code, so we can exclude a governor limits problem with it.
Most simple solution would be to look at the relative debug log (if your code runs only with partner users you can set up one of them to generate a debug log for you in setup > debug logs). Look at the end of the log and you should see a list of all governor limits, along with your usage. You should be able to notice that the 100 limit on SOQL queries has been reached.
Look in the log file to spot which other Apex classes/methods are running besides the one you posted, either one of them has a SOQL query in a loop (most likely) or you are recursively calling this - or another SOQL containing - class.
In both cases you have to refactor the offending class/method, there's no avoidance of a Too many SOQL error just by editing shareEndCustomersWithPartnerCommunity.

A: You're building a collection and then inserting it - are there any triggers on the inserted object that may be firing SOQL calls?


text:
Q: How do I enable more than 8-bit colors in Terminal.app? In the Vim and Emacs terminal apps, the color schemes look horrid. How do I enable the colors to be as vibrant as the GUI version (or more than 8 colors for that matter)?
Should I just give up, and move over to their respective GUI applications? And if so, which?

A: You can't have more colors in the terminal, because there are only ANSI codes for 8 colors (16 if you count bold/light).  If you want to customize the colors, you can use the TerminalColours plugin from http://ciaranwal.sh/2007/11/01/customising-colours-in-leopard-terminal
Personally, I prefer to use the so-called Carbon Emacs on my Mac.  There are several builds available; Google is your friend.  I get mine from http://www.porkrind.org/emacs/

A: You are possibly being inhibited by the fact you are running in a VT100/WhateverItsCalled compatible terminal and it just doesn't have more than about 16 foreground and 16 background colours.   If it did, the lovely library "CaCa" ( ColourAsciiColourArt ) would be much more pleasing to watch than it is.
If you want more colours, you simply have to use more modern technology, and this generally means using X ( unless your loving pain and want to use directfb/framebuffer/svgalib ).
For vim, there is GVim ( GTK+Vim ). Emacs GUI version however displeases me much, but I'm not an emacs user.

A: Aquamacs and MacVim

A: Sounds like you want MacVim


text:
Q: CSS - I need to move some text so that text flows around an image I have an image that is positioned way over to the right side of the div. I want the text that is now being pushed below the image to rise up and wrap around the image, or ignore the image.
I've tried different floats and divs and wraps and overflows and all kinds of stuff but I can't get that text two rise up and fill the top left side of the box.
The image I am referring to is the "little red triangle" on right side of the page, in the very top box. There's only one of them.
Can you help me move that text into its proper place?
http://www.i-treadmillreviews.com/?1/treadmill-reviews-yowza

A: What you want to do is change the position to absolute class sale and make the parent div position: relative;
.PromoDiv {position: relative;}
.Sale {
position: absolute;
top: -6px;
left: 155px;
}


text:
Q: How do I connect to Oracle SQL using VBA? I'm a newbie with vba, and would appreciate help with connecting to Oracle SQL using VBA.
I have such code for MS Server, and need to modify it somehow (or create a new one) so it works with Oracle SQL.
Here's the code:
Public Const sConnect As String = "xxx; Initial Catalog=xxx; User ID=xxx;Password=xxx;"

Sub GetData1()

Sheets(1).Range("a1:ao20000").ClearContents

Dim rsConnection As ADODB.Connection
Dim rsRecordset As ADODB.Recordset
Dim sQuerry As String

sQuerry = "select * from xxx"

Set rsConnection = New ADODB.Connection
Set rsRecordset = New ADODB.Recordset

rsConnection.ConnectionString = sConnect
rsConnection.Open

Set rsRecordset = rsConnection.Execute(sQuerry)

Worksheets(1).Range("A2").CopyFromRecordset rsRecordset

rsConnection.Close

Set rsConnection = Nothing
Set rsRecordset = Nothing

End Sub

My questions are:
Do i need to install anything else than Oracle Developer? If so, what?
How to change the code to make it work?
Thanks a lot in advance!!
Regards,
Maciej

A: You need to install Oracle client software on your computer.  The smallest setup is to use Oracle instant client, see http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html.
The only thing you need to change in your program is the connection string


text:
Q: spacy matcher: detect first word of sentence if pattern is matched my spacy matcher shows unexpected behaviour and I cannot figure out why. Consider the following toy data:
# %% Load packages
import pandas as pd
import spacy

# %% toy data
df = \
    pd.DataFrame(columns=['date',         'ground_cat',   'ground_word',    'sentence'],
                  data = [["2009-09-01",  "a",            'wutschäumend'  , "Wutschäumend bin ich."], # in this line, "Wutschäumend" should match
                          ["2009-09-01",  "a",            'wutschäumend',   "Ich bin Wutschäumend."],
                          ["2009-09-01",  "neg_a",        'wutschäumend'  , "Ich bin nicht wutschäumend."],
                          ["2009-09-01",  "b",            'zweifelhaftes' , "Peter hat ein zweifelhaftes Verständnis von Gerechtigkeit."],
                          ["2009-09-01",  "c",            'unsittlich',     "Das ist unsittlich."],
                          ["2009-09-01",  "d",            'unsolidarisch' , "Niemand ist so unsolidarisch wie er."]])

df['processed_sentence'] = [doc for doc in nlp.pipe(df['sentence'].tolist())]

ground_x identify the ground_truth, e.g. in row one, category a should be matched by finding the word wutschäumend etc.
I now prepare the matcher and instantiate patterns. Basically, I want the words in matching_dict to match if they are either at the beginning of the sentence or if they are somewhere in the sentence but not preceded by one of the negation words.
These are the patterns:
# %% Prepare Matcher
nlp = spacy.load("de_core_news_lg")
matcher = spacy.matcher.Matcher(nlp.vocab)  # instantiate Matcher

negations = ["nicht", "nichts", "kein", "keine", "keinen", "keinem"] # negation words

matching_dict: dict = {"a": ['wutschäumend'],
                       "b": ['zweifelhaftes'],
                       "c": ["unsittlich"],
                       "d": ["unsolidarisch"]}

# patterns for non-negated words associated with each emotion
a = [[{"IS_SENT_START": True}, {"LOWER": {"IN": matching_dict['a']}}], [{"LOWER": {"NOT_IN": negations}}, {"LOWER": {"IN": matching_dict['a']}}]]
b = [[{"IS_SENT_START": True}, {"LOWER": {"IN": matching_dict['b']}}], [{"LOWER": {"NOT_IN": negations}}, {"LOWER": {"IN": matching_dict['b']}}]]
c = [[{"IS_SENT_START": True}, {"LOWER": {"IN": matching_dict['c']}}], [{"LOWER": {"NOT_IN": negations}}, {"LOWER": {"IN": matching_dict['c']}}]]
d = [[{"IS_SENT_START": True}, {"LOWER": {"IN": matching_dict['d']}}], [{"LOWER": {"NOT_IN": negations}}, {"LOWER": {"IN": matching_dict['d']}}]]

matcher.add(201, a)
matcher.add(202, b)
matcher.add(203, c)
matcher.add(204, d)

Now, when I apply this to the toy data, the first sentence is not matched although it should be, and I cannot figure out what is wrong with my pattern. Can someone point out my mistake?
df['matches'] = df['processed_sentence'].apply(matcher)  # match patterns

df['matches']
#                 [] # should be [(201, 0, 2)]!
# 1    [(201, 1, 3)]
# 2               []
# 3    [(202, 2, 4)]
# 4    [(203, 1, 3)]
# 5    [(204, 2, 4)]
# Name: matches, dtype: object

Thanks a lot in advance!

A: Let's look at these patterns. Keep in mind each dictionary is a token.
a = [
    [{"IS_SENT_START": True},
     {"LOWER": {"IN": matching_dict['a']}}],
    [{"LOWER": {"NOT_IN": negations}},
     {"LOWER": {"IN": matching_dict['a']}}]]

There are two patterns here.
In the first, you have the first word of the sentence, and the second word is in your a list.
In the second, you have a word that isn't a negation, followed by a word in the a list.
Your first pattern doesn't match the word at the start of a sentence, which is what you want it to do. You need to make one dictionary per token, so it should look like this:
[{"IS_SENT_START": True, "LOWER": {"IN": matching_dict['a']}]


text:
Q: StreamBridge bean not found in Spring context StreamBridge cannot be injected (using @Autowired) into a service and causes the following error:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.cloud.stream.function.StreamBridge' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

pom.xml (partial)
<repositories>
    <repository>
        <id>confluent</id>
        <url>https://packages.confluent.io/maven/</url>
    </repository>
</repositories>

<properties>
    <!-- Build properties -->
    <maven.version>3.2.5</maven.version>
    <java.version>11</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
    <maven.compiler.source>${java.version}</maven.compiler.source>
    <maven.compiler.target>${java.version}</maven.compiler.target>
    <start-class>com.smarthome.actuatorms.ActuatormsApp</start-class>
    <argLine>-Djava.security.egd=file:/dev/./urandom -Xmx1G</argLine>
    <m2e.apt.activation>jdt_apt</m2e.apt.activation>
    <run.addResources>false</run.addResources>
    <jhipster-dependencies.version>7.9.3</jhipster-dependencies.version>
    <spring-boot.version>3.0.2</spring-boot.version>
    <archunit-junit5.version>0.22.0</archunit-junit5.version>
    <mapstruct.version>1.5.2.Final</mapstruct.version>
    <!-- Plugin versions -->
    <maven-clean-plugin.version>3.2.0</maven-clean-plugin.version>
    <maven-site-plugin.version>3.12.1</maven-site-plugin.version>
    <maven-compiler-plugin.version>3.10.1</maven-compiler-plugin.version>
    <maven-javadoc-plugin.version>3.4.1</maven-javadoc-plugin.version>
    <maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version>
    <maven-enforcer-plugin.version>3.1.0</maven-enforcer-plugin.version>
    <maven-failsafe-plugin.version>3.0.0-M7</maven-failsafe-plugin.version>
    <maven-jar-plugin.version>3.2.2</maven-jar-plugin.version>
    <maven-idea-plugin.version>2.2.1</maven-idea-plugin.version>
    <maven-resources-plugin.version>3.3.0</maven-resources-plugin.version>
    <maven-surefire-plugin.version>3.0.0-M7</maven-surefire-plugin.version>
    <maven-war-plugin.version>3.3.2</maven-war-plugin.version>
    <maven-checkstyle-plugin.version>3.1.2</maven-checkstyle-plugin.version>
    <checkstyle.version>10.3.2</checkstyle.version>
    <nohttp-checkstyle.version>0.0.10</nohttp-checkstyle.version>
    <git-commit-id-plugin.version>5.0.0</git-commit-id-plugin.version>
    <modernizer-maven-plugin.version>2.4.0</modernizer-maven-plugin.version>
    <jacoco-maven-plugin.version>0.8.8</jacoco-maven-plugin.version>
    <properties-maven-plugin.version>1.1.0</properties-maven-plugin.version>
    <sonar-maven-plugin.version>3.9.1.2184</sonar-maven-plugin.version>

    <avro.version>1.11.1</avro.version>
    <avro-compiler.version>1.11.1</avro-compiler.version>
    <avro-maven-plugin.version>1.11.1</avro-maven-plugin.version>
    <kafka-avro-serializer.version>7.3.1</kafka-avro-serializer.version>
    <spring-cloud-stream-schema.version>2.2.1.RELEASE</spring-cloud-stream-schema.version>
    <spring-cloud-stream.version>4.0.1</spring-cloud-stream.version>

    <spring-boot-starter-validation.version>3.0.2</spring-boot-starter-validation.version>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring-boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>tech.jhipster</groupId>
            <artifactId>jhipster-dependencies</artifactId>
            <version>${jhipster-dependencies.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
        <version>${spring-boot-starter-validation.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-stream-kafka</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-stream</artifactId>
        <version>${spring-cloud-stream.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-stream-binder-kafka</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-stream-schema</artifactId>
        <version>${spring-cloud-stream-schema.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-bootstrap</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.avro</groupId>
        <artifactId>avro</artifactId>
        <version>${avro.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.avro</groupId>
        <artifactId>avro-compiler</artifactId>
        <version>${avro-compiler.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.avro</groupId>
        <artifactId>avro-maven-plugin</artifactId>
        <version>${avro-maven-plugin.version}</version>
    </dependency>
    <dependency>
        <groupId>io.confluent</groupId>
        <artifactId>kafka-avro-serializer</artifactId>
        <version>${kafka-avro-serializer.version}</version>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
            </exclusion>
            <exclusion>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <!-- Spring Cloud -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.retry</groupId>
        <artifactId>spring-retry</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
</dependencies>

Please note that these dependencies are not exhaustive and I've included the ones that are most relevant to Spring Cloud Stream.
In the application.yml properties I have included the properties for Spring Cloud stream.
spring:
  cloud:
    stream:
      kafka:
        binder:
          brokers:
            - localhost:9092
          producer-properties:
            key.serializer: io.confluent.kafka.serializers.KafkaAvroSerializer
            value.serializer: io.confluent.kafka.serializers.KafkaAvroSerializer
            schema.registry.url: http://localhost:8081
          consumer-properties:
            key.deserializer: io.confluent.kafka.serializers.KafkaAvroDeserializer
            value.deserializer: io.confluent.kafka.serializers.KafkaAvroDeserializer
            schema.registry.url: http://localhost:8081
            specific.avro.reader: true
      bindings:
        switchArrayStateProducer-out-0:
          destination: switch_array_state
          content-type: application/*+avro
          group: switch-array-state-group-0

I used Avro for this project and I have created a topic in Kafka with the name switch_array_state.
There is a service where I am injecting StreamBridge (I tried both constructor injection and autowiring). But this is where the dependency issue is found. It seems there is no bean of this type and I have no idea why this is not instantiated. I have used this approach before on a different application with a different Spring Boot version and it works.

A: I found out the cause of this. It is a mismatch in versions between Spring Cloud and Spring Boot.
Check this link for more information


text:
Q: Move elements in a grid (Combinatorics) Here's an interesting and fairly simple problem I encountered a couple of weeks ago.
There is a grid with 11 rows and 11 columns with a ball in every cell. Move every ball to an adjacent cell (up, down, left or right - diagonals are not allowed).
Show that no matter how you move the balls you will always end up with at least one cell with more than one balls in it.

A: Color the grid like a chessboard with alternating white and black squares. Let white be the color of the corners, so there are $61$ white squares and $60$ black squares. Notice that applying the move means balls that were on white squares are now on black squares, so since there were $61$ balls originally on white squares, but only $60$ black squares, by the pigeonhole principle after the move some (black) square must have more than $1$ ball.
Notice that this generalizes to any rectangular grid with an odd number of squares.

A: Colour the cells in checkerboard fashion.  The total number of cells is odd, so there is one more of one colour (say red) than the other (black).  All the balls from red cells go to black cells, so ...


text:
Q: NoClassDefFoundError: Crashlytics FirebaseInfo I am trying to enable minifyEnabled on my app and I have resolved all the compile time warnings but this happens when I run it:
java.lang.NoClassDefFoundError: Failed resolution of: Lio/fabric/sdk/android/services/common/FirebaseInfo;
at com.crashlytics.android.CrashlyticsInitProvider.onCreate(CrashlyticsInitProvider.java:22)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1917)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1892)
at android.app.ActivityThread.installProvider(ActivityThread.java:6239)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:5805)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5722)

This is my proguard-rules.pro:
-keepattributes *Annotation*
-keepattributes SourceFile,LineNumberTable
-keep public class * extends java.lang.
-keep class com.crashlytics.** { *; }
-dontwarn com.crashlytics.**


text:
Q: finding next sibling in a jquery accordian menu So, my problem is that I can't seem to find the next() sibling down to the following nested ul li. when set to hide. I can find it when it's not set to hide easily by:

*

*This works when I comment out the JS and nothing is hidden:
//$(".vertNavigation li ul a").hide();

*Add this to click function:
$(this).next().css("background", "yellow").slideToggle("normal");
Goal is to do the reverse, click on BUTTON ONE and slideDown nested ul and so on. What is it that I'm missing here?
HTML CODE:

BUTTON ONE

sub menu 1

sub menu 2

sub menu 3

sub menu 4

BUTTON TWO

sub menu 1

sub menu 2

sub menu 3

sub menu 4

BUTTON THREE

sub menu 1

sub menu 2

sub menu 3

sub menu 4

BUTTON FOUR

sub menu 1

sub menu 2

sub menu 3

sub menu 4

CSS CODE:
.vertNavigation ul {
    list-style-type: none;
    padding-left: 0;
    margin-lef: 0;
}

.vertNavigation li {
    display: inline;
}

.vertNavigation a { /*main menu*/
    display: block;
    width: 100px;
    text-decoration: none;
    margin: 2px 0px 2px 0px;
    padding: 6px 15px 3px 15px;
    background-color: #EAEAEA;
    color: #333;

    font-size: .8em;
}

.vertNavigation li ul a {  /*sub menu*/
    text-decoration: none;
    border-bottom: solid 1px #333;
    border-length: 50px;
    margin: 2px 0px 2px 0px;
    background-color: #FFF;
    color: #333;
}

JS CODE:
google.load("jquery", "1.6.2");

google.setOnLoadCallback(function(){

    $(".vertNavigation li ul a").hide();
    $(".vertNavigation ul li a").click(function()
    {
        //$(this).next().slideToggle("normal");
        $(this).next().slideDown("normal");

        return false;
    });

});

A: Try this:
$(".vertNavigation > ul > li > ul").hide();
$(".vertNavigation > ul > li > a").click(function(e){
    e.preventDefault();
    $(this).next('ul').slideToggle();
});

Check the live working solution


text:
Q: GetChanges REST call from java returning status 400 I'm trying to use the GetChanges REST API call in SharePoint 2013 from a standalone Java app using Apache HttpClient. The JSON body in the POST request body looks like this:
{"Web":true,"query":{"__metadata":{"type":"SP.ChangeQuery"}},"Update":true}

which matches the sample at:
http://msdn.microsoft.com/en-us/library/office/dn499819%28v=office.15%29.aspx
I'm setting the Accept and Content-type headers to:
"application/json;odata=verbose"

and also setting the X-RequestDigest header to the FormDigestValue from the contextinfo request.
But I get back a 400 response with this message:

"The parameter Web does not exist in method GetChanges."

If I omit the Web and Update properties from the request there is no error but I get an empty results array.

A: Figured out the issue: The parameters such as Web and Update must be inside the query object, not outside.

A: The JSON Body Should be
"{ 'query': { '__metadata': { 'type': 'SP.ChangeQuery' }, 'Web': true, 'Update': true } }"


text:
Q: How to Play Transparent background avi file in media element? I have a video with transparent background in .avi format (Made from Adobe After Effects), but the transparent background appears black in mediaelement. Media Player has no background property also.
What should i use so that this media element plays the file and when placed on an image takes that image as its background. (No i cannot embed that image in the avi file as my image keeps changing).
*If my approach is wrong please let me know.

A: I'm afraid using the normal wpf media player this can't be done.
The mediaplayer ignores the transparent regions, even with video formats that accept it.  From memory, i dont think AVI files support transparent regions.  MOV files do.
Having said that, and although it could be a very complicated task, it may be possible to enhance the WPFMediaKit mediaplayer to do what you want.
http://wpfmediakit.codeplex.com/
J Morrill the author of wpfmediakit may be able to let you know if it is possible or not.
I might add that i got around this problem in a project once by using a sequence of .png files that played a short 10 second movie.  Of course this is not an ideal solution, but it got me out of a jam

A: Another workaround is to use color keying - assing a color (or more colors) in your video, which you translate to the transparency by a WPF Effect(BitmapEffect or ShaderEffect).


text:
Q: Preventing duplicate form submissions I came up with a technique to prevent duplicate form submission by going back/forward or refreshing the page. And I thought about duscussing it here, I already tested a sample not in production environment, what is flaws that you can identify?
Please note that I am well aware of using Form Tokens, which will defend you against CSRF attacks, and wasn't added in the steps below.
-Generate Form ID for each form, and use it as hidden field in the form:
$formid = microtime(true)*10000;

-On form submit:

*

*Validate from data

*Calculate the hash of form fields data
$allvals = '';
foreach($_POST as $k=>$v){
    $allvals .= $v;
}
$formHash = sha1($allvals);

*Validate form hash by comparing with previously saved hashes. the session value is binded to each form by $formid variable.
$allowAction = true;
if(isset($_SESSION['formHash'][$_POST['formid']]) && ($_SESSION['formHash'][$_POST['formid']] == $formHash)){
     $allowAction = false;
}

*if form hash wasn't found, it means this is the first time form submitted or the form data is changed.

*If data saved ( to database, for example), save form hash to session:
$_SESSION['formHash'][$_POST['formid']] = $formHash;

Full version of the code:
http://thebusy.me/2011/01/06/preventing-duplicate-form-submissions/

A: A simpler way to achieve what you want is to use redirect on submit. After you process a POST request you redirect, possibly even to the same page. This is a common pattern called "Redirect after POST" or POST/Redirect/GET.
For example:
<?php
if($_POST) {
    // do something

    // now redirect
    header("Location: " . $_SERVER["REQUEST_URI"]);
    exit;
}
?>

<html> ...
<form method="post" action=""> ... </form>

By setting the action to "" then it will submit to itself, at which point the if($_POST) code block will validate to true and process the form, then redirect back to itself.
Of course you probably want to redirect to a different page that shows a "your form has been submitted" response or put the form on a different page and have the HTML of this page be the response.
The benefit of this method is that when you hit the back button it does a GET request so the form is not re-submitted.
On Firefox, it will actually take the submission to itself out of the browser history so when users browse across the web and then hit back, instead of seeing the "thank you" page they see the form page.

A: It looks like you are getting overly complicated with this. My favorite way, because it also prevents some session jacking hacks at the same time, is described here:
http://www.spotlesswebdesign.com/blog.php?id=11
It's simple and easy to impliment on any form. It uses a randomly generated page instance id to verify that the form submission received is identical to the last page served to that particular user.

A: Both solutions above are good but a bit short.
how about stopping further insertions in the next few minutes from the same user with perhaps minor changes in data?
this can be done by putting an md5 hash in a cookie on the users machine and storing a copy in the database - this way any further attempt from the same machine over a specified time can be ignored and stopped from being inserted into the database.
perhaps someone can comment on the validity and effectiveness of my suggestion or am i barking up the wrong tree ???


text:
Q: code fails to be wrapped with condition In the following example, I want the content in minipage is highlighted by \colorbox if the condition is true. If the condition is false, the content in minipage typeset directly.
The typeset of true-branch however, is not highlighted. I think it is because of \fi.
Then,how to modify this code to make it work as expected?
Code:
\documentclass{article}
\usepackage{xcolor}
\begin{document}

\ifnum 5>1 % or something like \ifx..., \if\empty..., and so on.
\colorbox{red} \fi
{\begin{minipage}{2in}The content maybe very large and complex, I don't want to duplicate it in both true-branch and false-branch\end{minipage}}

\end{document}

A: \documentclass{article}
\usepackage{xcolor}

\makeatletter
\newcommand\myConditionTF[1]{%
  #1% or something like \ifx..., \if\empty..., and so on.
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
}
\makeatother

\begin{document}

\myConditionTF{\ifnum 5>1\relax}
  {\colorbox{red}}
  {}
{\begin{minipage}{2in}The content maybe very large and complex, I don't want to duplicate it in both true-branch and false-branch\end{minipage}}
\qquad
\myConditionTF{\ifnum 5<1\relax}
  {\colorbox{red}}
  {}
{\begin{minipage}{2in}The content maybe very large and complex, I don't want to duplicate it in both true-branch and false-branch\end{minipage}}
\end{document}


text:
Q: passing parameter between HTML pages in Angular I am brand new to Angular, so forgive me if I use the wrong terms. An existing Component.HTML page includes a custom tag that is a menu.  Depending on where the tag is placed I want to pass a parameter that will be treated as a query parameter.  Ultimately, I'm passing that parameter to an API endpoint.  The parameter is optional so I don't want to (can't) use a router parameter.
The code below shows part of the component.html which contains the tag <home-loan-submenu style="display: contents;" [loanId]="loan.loanHeaderId" [source]=source ></home-loan-submenu>
in this tag I am trying to pass a "source" parameter

 0">Previous Loans

    <mat-expansion-panel *ngIf="history.length > 0">
        <mat-expansion-panel-header>
            <mat-panel-title>
                Previous Loan History
            </mat-panel-title>
        </mat-expansion-panel-header>

            <mat-card class="loan-history-item" *ngFor="let loan of history"  fxFlex="grow" fxLayout="column center" fxLayoutGap="0px">
                <mat-card-content fxLayout="column">

                            {{ loan.publicLoanId }}

                            Orig. Date: {{ loan.originationDate | date: 'M/d/yy' }}

                            Status: {{ loan.loanStatus }}

                        <home-loan-submenu style="display: contents;" [loanId]="loan.loanHeaderId" [source]="history" ></home-loan-submenu>

                </mat-card-content>
            </mat-card>

    </mat-expansion-panel>

In the home-loan-submenu.component.html I am creating the query parameter:
    <mat-menu #menu="matMenu">
    Contracts & Receipts

</mat-menu>

In the home-loan-submenu.component.ts I am subscribing to an observable to get query params:
    ngOnInit()
{
     this.route
    .queryParams
    .subscribe(params => {
        this.source = params['source'] || '';
    })

but it's not passing the value.
Note: if I hard code a string in the query parameter in loan-submenu.component.html, as in [queryParams]="{source: 'history'}" the parameter is passed correctly.  The issue is getting it from the containing page that holds the tag.
I appreciate any suggestions
Update
Based on the link ashwinlagji sent me, I confirmed I was using @input in my parent component.  However, the one change I did make was in the parent html, where the custom tag is used, i added the parameter name instead of a string as such:<home-loan-submenu [loanId]="loan.loanHeaderId" [source] = source></home-loan-submenu>
in the component file I assigned a value to "source" parameter and it is passed through as a query parameter as expected <yea!> However, there is one important point I didn't communicate.  there are two section to the HTML page, one is Active loans and the other is Loan History.  Both sections are identical in code structure.  I need to know which section the user clicked from, hence the name "source".  by hardcoding the value of "source" in the HTML, I was hoping it would pass that value back to the child page as the source value.

A: in addition to the updates above, in the end i created two variables in my parent component page and used each one in its appropriate section in the HTML.  I now have the right query string values showing up.


text:
Q: Analyze total error entry occurance in a time frame from log files with a hadoop mapreduce job I have a huge number of logfiles stored in HDFS which look like the following:
2012-10-20 00:05:00; BEGIN
...
SQL ERROR -678: Error message
...
2012-10-20 00:47:20; END

I'd like to know how often certain sql error codes occured during a time frame, e.g.:
How many 678 SQL ERRORs occured from 20 OCT 2012 0:00am until 20 OCT 2012 1:00am.
Since files are typically split into several blocks they could be distributed between all data nodes.
Is such a query possible? I'd like to use the hadoop mapreduce Java API or Apache Pig, but I don't know how to apply the time frame condition.

A: HDFS doesn't take care of new lines into consideration while splitting the file into blocks, so a single line might be split across two blocks. But, MapReduce does, so a line in the input file will be processed by a single mapper.

2012-10-20 00:05:00; BEGIN
  ...
  SQL ERROR -678: Error message
  ...
  2012-10-20 00:47:20; END

If the file is bigger than the block size then there is a better chance that the above lines will be in two blocks and processed by different mappers. The FileInputFormat.isSplitable() can be overwritten to make sure that a single log file is processed by a single mapper and not processed by multiple mappers.
Hadoop will invoke the user defined map function with the KV pairs, where K is the file offset and the value is the line in the input file. An instance variable would be required to store the BEGIN time to check against the END time in the later call to the user defined map function.
This is not an efficient way, since a single mapper is processing a particular map file and is not distributed.
Another approach is to pre-process the log files, by combining the the relevant lines into a single line. This way, the relevant lines in the log files will be processed by a single mapper only.
FYI, a more complex approach without using the FileInputFormat.isSplitable() is a also possbile, but that needs to be worked out.
The pros and cons have to be evaluated of each approach and the right one picked.


text:
Q: HTML5 - drawImage not drawing over other layer I am using drawImage trying to draw tiles and a player. It works however it draws the player first then the tiles.  This should be the opposite because now I can't see my player.
How do I know my player is being drawn? Because if I take out what draws the tiles (if (loadedImagesCount==NUM_OF_TILES) draw();) then I can see my player. Also the message that says the player is drawn always pops up.
Help?
Here's my code:
// HTML5 JS Tile Example
var canvas, context, board, imageObj, tiles;
var currentMap = 1;
var upMap = 0;
var rightMap = 0;
var leftMap = 0;
var downMap = 3;
var NUM_OF_TILES = 16; // starting from ZERO

    var spawnX = 9; // spawn on X position
    var spawnY = 7; // spawn on Y position
    var playerImg = new Image();
    var currX = 9; // current X position
    var currY = 7; // current Y position

// Set return 2D array of map
function loadMap(map) {
    if (map == 1) {
        return [
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1], [1, 13, 1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1], [1, 13, 1, 13, 1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1], [1, 13, 1, 13, 1, 13, 1, 13, 13, 13, 13, 13, 1, 13, 13, 1], [1, 13, 13, 13, 1, 13, 1, 13, 1, 13, 13, 13, 1, 13, 13, 1], [1, 13, 13, 13, 13, 13, 1, 13, 1, 13, 1, 13, 1, 13, 13, 1], [1, 13, 13, 13, 13, 13, 13, 13, 1, 13, 1, 13, 13, 13, 13, 1], [1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1, 13, 13, 13, 13, 1], [1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 13, 1, 1, 1, 1, 1, 1]
        ];
    }
}

var drawPlayer = function() {
        realSpawnX = spawnX * 32;
        realSpawnY = spawnY * 32;
        playerImg.src = "me.gif";
        context.drawImage(playerImg, realSpawnX, realSpawnY, 32, 32);
        console.log("Player drawn at (" + spawnX + "," + spawnY + ") Real spawn: X: " + realSpawnX + " Y: " + realSpawnY);
}

window.onload = function () {
    canvas = document.getElementById("canvas");
    context = canvas.getContext("2d");
    imageObj = new Image();
    tiles = [];
    board = loadMap(1);

    canvas.width = 512;
    canvas.height = 352;

    // Draw the player .,.. now
    drawPlayer();

    var draw = function() {
        var theX;
        var theY;
        // 3. DRAW MAP BY ROWS AND COLS
        for (x = 0; x <= 10; x++) {
            for (y = 0; y <= 15; y++) {

                theX = x * 32;
                theY = y * 32;
                context.drawImage(tiles[board[x][y]], theY, theX, 32, 32);
            }
        }
    }

    var loadedImagesCount = 0;

    // 2. SET UP THE MAP TILES

    for (x = 0; x <= NUM_OF_TILES; x++) {
        var imageObj = new Image(); // new instance for each image
        imageObj.src = "line_tile/t" + x + ".png";
        imageObj.onload = function() {
            loadedImagesCount++;
            if (loadedImagesCount==NUM_OF_TILES) draw();
        };
        tiles.push(imageObj);
    }

};

A: Here's what I meant, it should be obvious where I've made changes:
// HTML5 JS Tile Example
var canvas, context, board, imageObj, tiles;
var currentMap = 1;
var upMap = 0;
var rightMap = 0;
var leftMap = 0;
var downMap = 3;
var NUM_OF_TILES = 16; // starting from ZERO

    var spawnX = 9; // spawn on X position
    var spawnY = 7; // spawn on Y position
    var playerImg = new Image();
    var currX = 9; // current X position
    var currY = 7; // current Y position

// Set return 2D array of map
function loadMap(map) {
    if (map == 1) {
        return [
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1], [1, 13, 1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1], [1, 13, 1, 13, 1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1], [1, 13, 1, 13, 1, 13, 1, 13, 13, 13, 13, 13, 1, 13, 13, 1], [1, 13, 13, 13, 1, 13, 1, 13, 1, 13, 13, 13, 1, 13, 13, 1], [1, 13, 13, 13, 13, 13, 1, 13, 1, 13, 1, 13, 1, 13, 13, 1], [1, 13, 13, 13, 13, 13, 13, 13, 1, 13, 1, 13, 13, 13, 13, 1], [1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1, 13, 13, 13, 13, 1], [1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 13, 1, 1, 1, 1, 1, 1]
        ];
    }
}

var drawPlayer = function() {
        realSpawnX = spawnX * 32;
        realSpawnY = spawnY * 32;
        playerImg.src = "me.gif";
        context.drawImage(playerImg, realSpawnX, realSpawnY, 32, 32);
        console.log("Player drawn at (" + spawnX + "," + spawnY + ") Real spawn: X: " + realSpawnX + " Y: " + realSpawnY);
}

window.onload = function () {
    canvas = document.getElementById("canvas");
    context = canvas.getContext("2d");
    imageObj = new Image();
    tiles = [];
    board = loadMap(1);

    canvas.width = 512;
    canvas.height = 352;

    // Draw the player .,.. now
    //*************No, later

    var draw = function() {
        var theX;
        var theY;
        // 3. DRAW MAP BY ROWS AND COLS
        for (x = 0; x <= 10; x++) {
            for (y = 0; y <= 15; y++) {

                theX = x * 32;
                theY = y * 32;
                context.drawImage(tiles[board[x][y]], theY, theX, 32, 32);
            }
        }
    }

    var loadedImagesCount = 0;

    // 2. SET UP THE MAP TILES

    for (x = 0; x <= NUM_OF_TILES; x++) {
        var imageObj = new Image(); // new instance for each image
        imageObj.src = "line_tile/t" + x + ".png";
        imageObj.onload = function() {
            loadedImagesCount++;
            if (loadedImagesCount==NUM_OF_TILES) {
                draw();
                drawPlayer();
            }
        };
        tiles.push(imageObj);
    }
};

The problem was that tiles were being drawn in an onload event - that executes when the browser has finished fetching the images from the network.  So no matter where you put the call to drawPlayer if it took anything over a millisecond or so to load all the tile images they would be getting drawn last.  The solution was to expand the block of code in the onload handler where it tested to see if all the images were loaded (this bit: if (loadedImagesCount==NUM_OF_TILES) ) so that you could then draw the map and the player in order.


text:
Q: GitHub : API name/identity inside webhook payload? I'm writing a Github API client and a webhook.
Is there any way to distinguish if an event (i.e assignment, issue open, etc etc) is trigered by API or by user directly (i.e via git's web ui) ?
I read what payload github will send on it's webhook call, but could not find one.
sincerely
-bino-

A: I'm not sure what it looks on the server side, but at least when using the UI, the POST payload seems to be form-data, and with API it is JSON-formatted.
From my tests with UI:
...
Content-Disposition: form-data; name="issue[user_assignee_ids][]"

28
------

and from GitHub API documentation:
{
  "assignees": [
    "hubot",
    "other_user"
  ]
}

This also means that the requests content-type header is different: for form data it is content-type: multipart/form-data; ... and for JSON it should be content-type: application/json.


text:
Q: Xcode: Event not created in Calendar : issue With Timezone? ddI am facing issue while creating Event in Native CALENDAR, When i pass event.startDate anything other than present timestamp... also event.endDate not working with different value as below..
- (void)createEventInCalendar:(NSString *)calendarType withTitle:(NSString *)eventTitle startDate:(NSString *)stDate endDate:(NSString *)endDATE withNotes:(NSString *)paramNotes addAlarm:(BOOL)alarmNeeded {

EKEventStore *eventStore = [[EKEventStore alloc] init];

/* Are there any calendars available to the event store? */
if ([eventStore.calendars count] == 0){
    NSLog(@"No calendars are found.");
}

EKEvent *event  = [EKEvent eventWithEventStore:eventStore];
event.title     = [NSString stringWithFormat:@"%@ with Alarm", eventTitle];

//Convert String to DATE
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:SS"];

NSDate* date1 = [dateFormat dateFromString:stDate];
NSDate* date2 = [dateFormat dateFromString:endDATE];
//get Difference betwenn 2 DATE Values
NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2];

event.startDate = date1;
event.endDate   = [date1 initWithTimeInterval:distanceBetweenDates sinceDate:event.startDate];
event.notes = paramNotes;

/* The alarm goes off 2 seconds before the event happens */
EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:-2.0f];

[event addAlarm:alarm];

[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
NSLog(@"Error shows: %@", err);

//Show EVENT EDIT Screen to User.
EKEventEditViewController *controller = [[EKEventEditViewController alloc] init];

controller.eventStore       = eventStore;
controller.event            = event;
controller.editViewDelegate = self;

[self presentModalViewController:controller animated:YES];

}

After debug: Error Domain=EKErrorDomain Code=4 "The start date must be before the end date." UserInfo=0x223170 {NSLocalizedDescription=The start date must be before the end date.}
where as my Log: ST DATE: 2013-04-25 07:50:00
           & end DATE: 2013-04-29 07:50:00
but EVENT EDIT View shows END DATE value sometime before START DATE.. Its strange.
Can anyone guide me as to how to solve it ?
Thanks.

A: Issue Resolved:
one simple mistake:
//get Difference betwenn 2 DATE Values
NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2];

it should be
//get Difference betwenn 2 DATE Values
NSTimeInterval distanceBetweenDates = [date2 timeIntervalSinceDate:date1];

Thanks.


text:
Q: Gather dummy variables and recode factors I have
df<-data.frame(id=c(1,2,3,4,5),one=c(0,1,0,0,0), two=c(0,0,1,0,0), three=c(0,0,0,1,0), four=c(0,0,0,0,1))
df

I would like to gather the dummy variables one, two, three and four into the variable out and I would like to recode the levels of the out variable so that one="A", two="B", three="C" and four="D"
df.out<-data.frame(id=c(1,2,3,4,5),out=c(NA, "A","B","C","D" ))
df.out

is it possible to do it in dplyr? I tried gather but I get different lengths of the output data.frame and i think pivot wider and longer are not the right choice.
The df is part of a much larger, wider and longer data frame. I would like to be able to specify which colums to merge and how to recode. Ideally a tidyverse solution
I am looking for the exact opposite of this

A: You can do,
LETTERS[ifelse(rowSums(df[-1]) == 0, NA, max.col(df[-1]))]
#[1] NA  "A" "B" "C" "D"

A: You can write a function which returns NA when all the value are 0 or else index of max value.
library(dplyr)

return_value <- function(x) {
  if(all(x == 0)) return(NA)
  else which.max(x)
}

df %>%
  rowwise() %>%
  mutate(out = return_value(c_across(one:four)))

#     id   one   two three  four   out
#  <dbl> <dbl> <dbl> <dbl> <dbl> <int>
#1     1     0     0     0     0    NA
#2     2     1     0     0     0     1
#3     3     0     1     0     0     2
#4     4     0     0     1     0     3
#5     5     0     0     0     1     4

To get 'A', 'B' etc you may use inbuilt LETTERS.
df %>%
  rowwise() %>%
  mutate(out = return_value(c_across(one:four))) %>%
  ungroup %>%
  mutate(out = LETTERS[out])

A: Here's an idea:
library(tidyverse)
ids <- 1:nrow(df)
df %>%
    mutate(id = ids) %>%
    pivot_longer(cols = one:four) %>%
    filter(value == 1) %>%
    mutate(out = plyr::mapvalues(
        name,
        from = c("one", "two", "three", "four"),
        to = LETTERS[1:4])) %>%
    select(-name, -value) %>%
    right_join(tibble(id = ids)) %>%
    arrange(id)
#> Joining, by = "id"
#> # A tibble: 5 × 2
#>      id out
#>   <int> <chr>
#> 1     1 <NA>
#> 2     2 A
#> 3     3 B
#> 4     4 C
#> 5     5 D

Created on 2021-10-22 by the reprex package (v2.0.1)
Whether this is efficient, I'm not sure. I also needed to add an "id" variable to make it work this way.

A: A dplyr only solution:
df %>%
  rename_with(~ c("id", LETTERS[1:4], colnames(df))) %>%
  mutate(across(2:5, ~case_when(. == 1 ~ cur_column()))) %>%
  mutate(out = coalesce(A,B,C,D), .keep="unused")

output:
    id  out
1  1 <NA>
2  2    A
3  3    B
4  4    C
5  5    D

A: I couldn't find a one-step solution, but this appears solution appears to give you the flexibility you want.
recode_fn <- function(x) {
  case_when(x == "one" ~ "A", x == "two" ~ "B", x == "three" ~ "C", x == "four" ~ "D", TRUE ~ "!! Error")
}

df %>%
  pivot_longer(
    cols=c(one, two, three, four),
    names_to="Variable",
    values_to="Value"
  ) %>%
  mutate(
    Variable=recode_fn(Variable)
  )
# A tibble: 20 × 2
   Variable Value
   <chr>    <dbl>
 1 A            0
 2 B            0
 3 C            0
 4 D            0
 5 A            1
 6 B            0
 7 C            0
 8 D            0
 9 A            0
10 B            1
11 C            0
12 D            0
13 A            0
14 B            0
15 C            1
16 D            0
17 A            0
18 B            0
19 C            0
20 D            1


text:
Q: powershell: Append text before specific line instead of after I'm looking for a way to add text before a line.
To be more specific, Before a line and a blank space.
Right now the scripts adds my text after the line [companyusers].
But I'd like to add the line before [CompanytoEXT] and before the blank space above [CompanytoEXT].
Does any body know how to do this?
Visual representation of what I'd want to do: https://imgur.com/a/lgH5i
My current script:
$FileName = "C:\temptest\testimport - Copy.txt"
$Pattern = "[[\]]Companyusers"
$FileOriginal = Get-Content $FileName

[String[]] $FileModified = @()
Foreach ($Line in $FileOriginal)
{
    $FileModified += $Line
    if ($Line -match $pattern)
    {
        #Add Lines after the selected pattern
        $FileModified += "NEWEMAILADDRESS"

    }
    }

Set-Content $fileName $FileModified

Thanks for any advice!
Even if you're just pointing me where to look for answers it will be very much appreciated.

A: This might be easier using an ArrayList, that way you can insert new data easily at a specific point:
$FileName = "C:\temptest\testimport - Copy.txt"
$Pattern = "[[\]]Companyusers"
[System.Collections.ArrayList]$file = Get-Content $FileName
$insert = @()

for ($i=0; $i -lt $file.count; $i++) {
  if ($file[$i] -match $pattern) {
    $insert += $i-1 #Record the position of the line before this one
  }
}

#Now loop the recorded array positions and insert the new text
$insert | Sort-Object -Descending | ForEach-Object { $file.insert($_,"NEWEMAILADDRESS") }

Set-Content $FileName $file

First open the file into an ArrayList, then loop over it. Each time you encounter the pattern, you can add the previous position into a separate array, $insert. Once the loop is done, you can then loop the positions in the $insert array and use them to add the text into the ArrayList.

A: You need a little state machine here. Note when you have found the correct section, but do not insert the line yet. Insert only at the next empty line (or the end of the file, if the section is the last in the file).
Haven't tested, but should look like this:
$FileName = "C:\temptest\testimport - Copy.txt"
$Pattern = "[[\]]Companyusers"
$FileOriginal = Get-Content $FileName

[String[]] $FileModified = @()

$inCompanyUsersSection = $false

Foreach ($Line in $FileOriginal)
{
    if ($Line -match $pattern)
    {
        $inCompanyUsersSection = $true
    }

    if ($inCompanyUsersSection -and $line.Trim() -eq "")
    {
        $FileModified += "NEWEMAILADDRESS"
        $inCompanyUsersSection = $false
    }

    $FileModified += $Line
}

# Border case: CompanyUsers might be the last sction in the file
if ($inCompanyUsersSection)
{
    $FileModified += "NEWEMAILADDRESS"
}

Set-Content $fileName $FileModified

Edit: If you don't want to use the "insert at the next empty line" approach, because maybe your section may in clude empty lines, you can also trigger the insert at the beginning of the next section ($line.StartsWith("[")). However that would complicate things because now you have to look two lines ahead which means you have to buffer one line before writing it out. Doable but ugly.


text:
Q: Laravel 5 cacheTags path What is the use clause needed for cacheTags?
I have:
$categories = FinanceTransactionCategory::select('id')
            ->cacheTags(['cell-editors', 'categories'])
            ->remember(60)->get();
    $jsConfig['filters'] = [
        'category' => $categories
    ];

But it's not working because:
Call to undefined method Illuminate\Database\Query\Builder::cacheTags()

A: This has been removed in Laravel 5. See here:
https://github.com/laravel/framework/issues/7259
You'll want to use Cache directly now. This should help:
http://laravel.com/docs/5.0/cache#cache-tags
There's a discussion here that may be useful as well:
https://laracasts.com/index.php/discuss/channels/general-discussion/laravel-5-remember-missing-from-query-builder
So I believe this (untested) code may do what you want:
$categories = Cache::tags(['cell-editors', 'categories'])->remember('categories', 60, function() {
    return FinanceTransactionCategory::select('id')->get();
});

Or at least get you going in the right direction!


text:
Q: Changing Image url & 3D model for AR.js So I decided to add AR to a mobile app source code I have, but instead of changing my mobile app source code to do this I found a project online that would allow me to use the browser, AR.js.
Adding the test code works fine but when I try to add my own image url or 3D model it stops working, so I wanted to know if anyone can help by telling me how am I supposed to use the image url (which I think I am doing correctly) and the 3D model, the test url is very complex and the one I changed it to is a simple url from my website where I uploaded the new model.
Error is the url that loads stays stuck in "Loading, please wait" text. When it does manage to go pass it nothing happens.
Here is the original test source code.

Loading, please wait...

And then my code I just updated the image url as well as the 3D model url.

This is where I uploaded the file to open the camera to load the AR.
https://mobileappstarter.com/AR
Any help would be much appreciated.

A: So doing a lot of research on this I found a simple workaround, wish I knew about this sooner.
AR.js has a simple to follow doc and git page but if by any chance your like me and still have issues there is a great toll online here https://ar-js-org.github.io/studio/ this nifty tool will help you create the marker and upload the media you wish to edit.
Once done just download source code or upload directly on github.
Hope this helps!