text:
Q: Find the upper value and lower value of a row using match function in excel Hi I am trying to find the upper and lower limit of the values in a row using MATCH function, I don't want to use VBA for this. My requirement is as if I give a value the function should return the lower value and upper value from a specific row.
For example, row values are defined in a row as: 100, 115, 200, 267, 392, 420, 487, 499, 520, 550. If I used the MATCH function to get the lower value but am not getting the upper value what is wrong I am doing. The function I used is:

*

*To get the lower value
=INDEX($A$1:$J$1,MATCH(I10,$A$1:$J$1,1))

this works good if I give the value as 118 as search criteria it returns "115"

*To get the upper value
=INDEX($A$1:$J$1,MATCH(I10,$A$1:$J$1)+1,1)

this formula is suppose to return 200 if I give the search as "118"

A: Did you mean:
=INDEX($A$1:$J$1,MATCH(I10,$A$1:$J$1,1)+1)


text:
Q: How to merge numerical and alphabet VBA? I GET VBA ERROR 13, TYPE MISMATCH ON THIS LINE:
rngCell.Offset(, 2).Value = m5 + " " + m3 'ALPHA-NUMERICAL VALUE
OTHERWISE EVERYTHING IS WORKING FINE.
CODE MENTIONED BELOW
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rngCell As Range, m1 As Variant, m2 As Variant
Check1:
    If Application.Intersect(Target, Range("C11")) Is Nothing Then GoTo Check2
Application.EnableEvents = False
    For Each rngCell1 In Range("C11")
        v1 = rngCell1.Value
        If Len(v1) > 0 Then

            'See if the value is in your lookup table
            m1 = Application.VLookup(v1, ThisWorkbook.Sheets("PARTY DETAILS").Range("D4:E10001"), 2, False)

            'If found a match then replace wiht the vlookup result
            If Not IsError(m1) Then rngCell1.Value = m1

        End If
        Range("C11").Value = UCase(Range("C11").Value)
        Next
       Application.EnableEvents = True
'On Error GoTo hell
'If Target.Address(False, False) = "C11" And Target.Validation.Type = 3 Then
'    Range("D19:D28").Value = ""
'End If
HI:
Check2:
'On Error GoTo HELL:
If Application.Intersect(Target, Range("C18:C37")) Is Nothing Then GoTo Check3:
Dim m3 As Variant
Dim m5 As String
Dim m4 As Variant

For Each rngCell In Intersect(Target, Range("C18:C37"))
    If Len(rngCell.Value) > 0 Then
        m1 = Application.VLookup(rngCell.Value, ThisWorkbook.Sheets("Item Names").Range("D4:E10001"), 2, False) 'TEXT VALUE
        m2 = Application.VLookup(rngCell.Value, ThisWorkbook.Sheets("Item Names").Range("D4:K10001"), 3, False) 'NUMERIC VALUE
        m3 = Application.VLookup(rngCell.Value, ThisWorkbook.Sheets("Item Names").Range("D4:E10001"), 4, False) 'TEXT VALUE
        m5 = "1"
        m4 = Application.VLookup(rngCell.Value, ThisWorkbook.Sheets("Item Names").Range("D4:K10001"), 5, False) 'NUMERIC VALUE
        If Not IsError(m1) Then
            Application.EnableEvents = False
            rngCell.Value = m1  'TEXT VALUE
            rngCell.Offset(, 1).Value = m2  'NUMERIC VALUE
            rngCell.Offset(, 2).Value = m5 + " " + m3 'ALPHA-NUMERICAL VALUE
            rngCell.Offset(, 3).Value = m4  'NUMERIC VALUE
            Application.EnableEvents = True
        End If
    End If
Next
If m1 = "" Then
            rngCell.Offset(, 2).Value = ""
End If

'HELL:
Check3:
Calculate
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub

I CANT FIND OUT WHERE I AM DOIND WRONG.
ANY HELP WILL MAKE MY DAY.

A: Concatenation operator in VBA is &, not +.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why breaking the link between two list nodes when partitioning a list? I was trying to solve the Partition List problem on LeetCode. The problem asks to sort an linked list given a target list node, so that all the list nodes having smaller value than the target will come before the target, while their original relative order remains unchanged.
I was able to come up a straightforward algorithm and to pass the online judge, basically creating two pointers and using them each to link either nodes < target or >= target while traversing the list.
public ListNode partition(ListNode head, int x) {
    ListNode ptr = head;
    ListNode small = new ListNode(0);
    ListNode big = new ListNode(0);
    ListNode dummy_1 = big;
    ListNode dummy_2 = small;
    int i = 1;
    while (ptr != null) {
        if (ptr.val < x) {
          small.next = ptr;
          small = small.next;
        } else {
          big.next = ptr;
          big = big.next;
        }
        ListNode help = ptr.next;
        ptr.next = null;
        ptr = help;
    }
    small.next = dummy_1.next;
    return dummy_2.next;
}

the following codes breaks the the link between ptr and ptr.next, and move the
ptr to original ptr.next.
ListNode help = ptr.next;
ptr.next = null;
ptr = help;

What I haven't quite figured out yet is that why this step is necessary, as we can move ptr to its next and directly update the reference later using small.next = ptr and big.next = ptr in the while-loop;
However when I simply used ptr = ptr.next instead of the three lines of code above, the online judge responded with error Memory Limit Exceeded.
I would really appreciate if anyone can explain this for me. What may cause the Memory Limit error as any cycled-list has seemed to be already avoided?

A: An object will not be eligible for Garbage Collection if it is pointed to by at least one reference. You may follow this post to build a brief understanding around this concept
Here is what happens in both cases
Case 1:
ptr = ptr.next

Assume the Linked List is in following state during first iteration

ptr is advanced, but the previous node having value 7 is still being referenced by head

ptr is advanced, but the previous node having value 1 is still being referenced by its previous node

ptr is advanced, but the previous node having value 3 is still being referenced by its previous node

And it continues till the end of loop while. If the list is of very huge size, then memory is not reclaimed. Like your judge said, it would result in error like Memory Limit Exceeded
Case 2:
    ListNode help = ptr.next;
    ptr.next = null;
    ptr = help;

Assume the Linked List is in following state during first iteration.

*

*help points to next node pointed by ptr

*ptr is re-referenced to point to help, in next step

*Hence the node earlier pointed to by ptr (the one which had value 7) is eligible for Garbage Collection

*And memory is reclaimed

*

*help points to next node pointed by ptr

*ptr is re-referenced to point to help, in next step

*Hence the node earlier pointed to by ptr (the one which had value 1) is eligible for Garbage Collection

*And memory is reclaimed

*

*help points to next node pointed by ptr

*ptr is re-referenced to point to help, in next step

*Hence the node earlier pointed to by ptr (the one which had value 3) is eligible for Garbage Collection

*And memory is reclaimed

*

*help points to next node pointed by ptr

*ptr is re-referenced to point to help, in next step

*Hence the node earlier pointed to by ptr (the one which had value 2) is eligible for Garbage Collection

*And memory is reclaimed

A: As commented, just setting big.next = null is working (I ran this using netbeans / java).
static ListNode partition(ListNode head, int x) {
    ListNode ptr = head;
    ListNode small = new ListNode(0);
    ListNode big = new ListNode(0);
    ListNode dummy_1 = big;
    ListNode dummy_2 = small;
    while (ptr != null) {
        if (ptr.val < x) {
          small.next = ptr;
          small = small.next;
        } else {
          big.next = ptr;
          big = big.next;
        }
        ptr = ptr.next;
    }
    small.next = dummy_1.next;
    big.next = null;
    return dummy_2.next;
}


text:
Q: Как эмулировать плавное передвижение курсора по экрану? Pyautogui Можно ли реализовать (с применением pyautogui) плавное передвижение курсора от точки до точки, с неодинаковой скоростью передвижения, с ускорениями примерно как это делает человек мышкой?
Как это лучше сделать?
Есть мысль генерировать список точек определенным алгоритмом а потом двигать курсор по нему.
Справится ли Pyautogui с плавностью?
Или надо поискать другую библиотеку для решения такой задачи?


text:
Q: Sending Data from iOS to java socket server Hi I have the next issue, why when I send data like this
uint8_t buffer[11] = "I send this";

NSInteger nwritten = [outputStream write:buffer maxLength:sizeof(buffer)];

if (-1 == nwritten) {
    NSLog(@"Error writing to stream %@: %@", outputStream, [outputStream streamError]);
}else{
    NSLog(@"Wrote %i bytes to stream %@.", nwritten, outputStream);
}

in the other side in the java socket server
connection = new Socket(Constants.HOST, Constants.CHAT_LISTENER_PORT);
_in = new DataInputStream(connection.getInputStream());
String data = _in.readUTF();

But nothing appear like as if it had not sent anything.
I read to much and I found the problem is from platforms because java byte works with big-endians and iOS with little-endians but I don't found information about how do to this.
uint8_t buffer[11] = "I send this"; to big-Endians format
Please heellppp, thanks.
Sorry my English is very but there is nothing in spanish :/ thaks.

A: On the server side in the next Line in java code:
DataInputStream.readUTF();

this .readUTF() expect a UTF java native type what is not the same with objective-c type, and the solution was send the string codifying in UTF native java like this.
NSString *msg = @"initChat_";
NSString *messageToSend  = [NSString stringWithFormat:@"%@", msg];
NSData *data = [self convertToJavaUTF8:messageToSend];

int dataLenght = [data length];

int num = [outputStream write:(const uint8_t *)[data bytes] maxLength:dataLenght];

if (-1 == num) {
    NSLog(@"Error writing to stream %@: %@", outputStream, [outputStream streamError]);
}else{
    NSLog(@"Wrote %i bytes to stream %@.", num, outputStream);
}

And the Magic come from:
- (NSData*) convertToJavaUTF8 : (NSString*) str {
NSUInteger len = [str lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
Byte buffer[2];
buffer[0] = (0xff & (len >> 8));
buffer[1] = (0xff & len);
NSMutableData *outData = [NSMutableData dataWithCapacity:2];
[outData appendBytes:buffer length:2];
[outData appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
return outData;}

A: readUTF expects a specific format, you need to send the length as a big-endian 16-bit unsigned short, followed by the text UTF encoded.  I suspect its taking the first bytes as the length which works out to a large number so it is waiting for this many characters to be read.
UTF-8 is not big endian or little endian, so this is not a problem for you. If you are sending 16-bit, 32-bit or 64-bit data values, then you could have a problem with endianness.

A: At your request string end add \n
For example uint8_t buffer[] = "I send this\n",it may work.

A: The swift4 version of the answer.
extension String {
    func javaUTF8() -> Data? {
        guard let data = self.data(using: .utf8) else {
            return nil
        }
        let length = self.lengthOfBytes(using: .utf8)
        var buffer = [UInt8]()
        buffer.append(UInt8(0xff & (length >> 8)))
        buffer.append(UInt8(0xff & length))
        var outdata = Data()
        outdata.append(buffer, count: buffer.count)
        outdata.append(data)
        return outdata
    }
}

you can use it, as below.
let data = "hello word".javaUTF8()


text:
Q: MapView isn't instanciated in function I'm working on an app which uses MKMapView and I wish to place annotations based on a PHP file which loads data from a MySQL. I'm not that experienced with iOS programming but I'm learning and I can't put my head on the problem that occurs for me.
I've managed to get the data to a MSMutableArray and converts it to a NSDirctionary and are using an object class for each object. When I'm trying to place a pin (Annotation) on the map I get the error fatal error: unexpectedly found nil while unwrapping an Optional value I've looked through the debug and find that the mapView is nil and came to the conclusion that when I try to place a annotation the program don't have a reference to where it should place the annotation.
I've managed to get the annotations to show when I place the creation of the object and call for the mapView.addAnnotation(object) in the viewDidLoad() function/method. But whenever I'm nesting the mapView into another function within the class (ViewController) it breaks.
The forwardGeoCoding method is to convert the address which i get in plain text to coordinates to be able to place them correctly on the map. The setArray is fetching the data from the MySQL/PHP class and makes an array available in the ViewController (Bad name standard as the annotation takes place inside as well)

*

*I've tried to send the mapView to the function without result

*I've tried without and calling the mapView form the ViewController
within the function self.mapView.addAnnotation(test) without
result

*I've tried doing it from the SQL retrieving class without result

Break point - The error occurs where I'm calling the forwardGeocoding function because the mapView control is nil.

ViewController.swift
//  Created by Tony Langlet on 2016-05-18.
//  Copyright © 2016 Tony Langlet. All rights reserved.
//

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, HomeModelProtocal {

    var feedItems: NSArray = NSArray()
    var selectedLocation : LocationModel = LocationModel()
    var popViewController : PopUpViewControllerSwift! = PopUpViewControllerSwift(nibName: "PopUpViewController", bundle: nil)

    @IBOutlet weak var mapView: MKMapView!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let deviceItem = UIScreen.mainScreen().traitCollection.userInterfaceIdiom

        switch (deviceItem) {
        case .Phone:
            if UIScreen.mainScreen().scale == 3 {
                popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController_iPhone6Plus", bundle: nil)
            } else {
                popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController_iPhone6", bundle: nil)
            }
        case .Pad:
            popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController_iPad", bundle: nil)
        case .Unspecified:
            popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController", bundle: nil)
        default:
            popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController", bundle: nil)
        }

        mapView.delegate = self

        let homeModel = HomeModel()
        homeModel.delegate = self
        homeModel.downloadItems()

    }

    func itemsDownloaded(items: NSArray) {
        feedItems = items

        //self.listTableView.reloadData()
    }

    func setArray(array: NSMutableArray) {
        var jsonElement: NSDictionary = NSDictionary()

        for item in array {
            jsonElement = item as! NSDictionary
            let id = jsonElement["id"] as? String
            let name = jsonElement["name"] as? String
            let address = jsonElement["address"] as? String
            let city = jsonElement["city"] as? String
            let country = jsonElement["country"] as? String
            let typ = jsonElement["typ"] as? String
            let lastresult = jsonElement["lastresult"] as? String

            let myaddress = ("\(address), \(city), \(country)")
            //print(array)
            forwardGeocoding(self.mapView, coordAddress: myaddress, id: id!, name: name!, address: address!, typ: typ!, lastresult: last result!) // <-- This is where it breaks.

        }
    }

    func forwardGeocoding(mv: MKMapView, coordAddress: String, id: String, name: String, address: String, typ: String, lastresult: String) {

        CLGeocoder().geocodeAddressString(coordAddress, completionHandler: { (placemarks, error) in
            if error != nil {
                print(error)
                return
            }

            if placemarks?.count > 0 {
                let placemark = placemarks?[0]
                let location = placemark?.location
                let coordinate = location?.coordinate
                //print("\(name) \n\(address) \n\(typ) \n\(lastresult) \nlat: \(coordinate!.latitude), long: \(coordinate!.longitude)")

                let test = restObject(id: id, name: name, address: address, coordinate: CLLocationCoordinate2D(latitude: (coordinate!.latitude), longitude: (coordinate!.longitude)), typ: typ, lastresult: lastresult)

                mv.addAnnotation(test)

            }
        })
    }

    func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
        let identifier = "restObject"

        if annotation.isKindOfClass(restObject.self) {
            if let annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) {
                annotationView.annotation = annotation
                return annotationView
            } else {
                let annotationView = MKPinAnnotationView(annotation:annotation, reuseIdentifier:identifier)
                annotationView.enabled = true
                annotationView.canShowCallout = true

                let btn = UIButton(type: .DetailDisclosure)
                annotationView.rightCalloutAccessoryView = btn
                return annotationView
            }
        }

        return nil
    }

    func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
        let restaurant = view.annotation as! restObject
        let name = restaurant.name
        let address = restaurant.address
        let typ = restaurant.typ
        let lastresult = restaurant.lastresult

        popViewController.title = title
        popViewController.showInView(self.view, argStatusImg: UIImage(named: "icon-nogood"), argTitle: name, argAddress: address, argType: typ, argLastresult: lastresult, argDate: "2016-01-01", animated: true)

    }
}

HomeModel.swift (Retrieving of the data from PHP/MYSQL)
//  Created by Tony Langlet on 2016-06-10.
//  Copyright © 2016 Tony Langlet. All rights reserved.
//

import Foundation

protocol HomeModelProtocal: class {
    func itemsDownloaded(items: NSArray)
}

class HomeModel: NSObject, NSURLSessionDataDelegate {

    weak var delegate: HomeModelProtocal!

    var data : NSMutableData = NSMutableData()

    let urlPath: String = "path to PHP file"

    func downloadItems() {

        let url: NSURL = NSURL(string: urlPath)!
        var session: NSURLSession!
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()

        session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)

        let task = session.dataTaskWithURL(url)

        task.resume()
    }

    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
        self.data.appendData(data)
    }

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?){
        if error != nil {
            print("Failed to download data")
        } else {
            print("Data downloaded")
            var jsonResult: NSMutableArray = NSMutableArray()

            do {
                jsonResult = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as! NSMutableArray
            } catch let error as NSError {
                print(error)
            }

            let VC = ViewController()
            VC.setArray(jsonResult)

        }
    }
}

restObject.swift (Object class)
//  Created by Tony Langlet on 2016-05-18.
//  Copyright © 2016 Tony Langlet. All rights reserved.
//

import MapKit
import UIKit

class restObject: NSObject, MKAnnotation {
    var id: String
    var name: String
    var address: String
    var coordinate: CLLocationCoordinate2D
    var typ: String
    var lastresult: String

    init(id: String, name: String, address: String, coordinate: CLLocationCoordinate2D, typ: String, lastresult: String) {

        self.id = id
        self.name = name
        self.address = address
        self.coordinate = coordinate
        self.typ = typ
        self.lastresult = lastresult

    }
}

A: EDIT 2:
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?){
    if error != nil {
        print("Failed to download data")
    } else {
        print("Data downloaded")
        var jsonResult: NSMutableArray = NSMutableArray()

        do {
            jsonResult = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as! NSMutableArray
        } catch let error as NSError {
            print(error)
        }

        //let VC = ViewController()
        //VC.setArray(jsonResult)
        // Here you are creating new view controller, it's not same controller which you are seeing on screen, and in this init controllers view is not loaded from xib and that's why mapView is nil
        delegate?.itemsDownloaded()

    }

EDIT: add breakpoint in the forwardGecoding and check all variables, coordinate might be nil, and there it crashed.
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

You should pass the name of your xib file in this method so it loads view.
super.init(nibName: NAME_OF_XIB, bundle: nibBundleOrNil)


text:
Q: Backbone - Geolocation I'am a new Backbone user and started to implement Google Maps in it. I set this up in de View object. I works all fine, but when i go to another page (template with the navigator object) and go back to the page with Google Maps, the current position dont market on the Google Map.
Below my code from my View
DFM.MapView = Backbone.View.extend({

el: $("#content"),

template: $("#rankings_template").html(),

// Initialiseren
initialize: function(){

    self = this;
    this.render();

    var location_destiny = new google.maps.LatLng(52.476716,4.799623);

    var map = new google.maps.Map(document.getElementById('google_maps'), {
        center: location_destiny,
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        panControl: false,
        zoomControl: false,
        mapTypeControl: false,
        scaleControl: false,
        streetViewControl: false,
        overviewMapControl: false

    });

    if(navigator.geolocation){

        navigator.geolocation.watchPosition(update_user_location, error_handler, {
            enableHighAccuracy: true,
            frequency: 3000
        });

    } else {
        console.error('Geolocation: 0 - Geotracking not available');
    }

    // Update user location
    function update_user_location(position){
        location_user = new google.maps.LatLng(52.474716,4.798623);

        var marker_user = new google.maps.Marker({
             title: 'Gebruiker',
             position: location_user,
             map: map,
             draggable: true,
        });
    }

    // Error handler
    function error_handler(error){
        console.error('Geolocation: ' + error.code + ' - ' + error.message);
    }

    var marker_destiny = new google.maps.Marker({
         title: 'Bestemming',
         position: location_destiny,
         map: map,
         draggable: true,
    });
},

render: function(){

    this.$el.html(_.template(this.template));

    return this;
}

});

A: Not sure if I got the question right but for me it helped calling google.maps.event.trigger(map,'resize'); every time after triggering the map route.
PS: a bit late, but maybe it helps someone in the future


text:
Q: AppDelegate: Show blocking view when something changes I want something similar as the view shown in the "Friends" app when the iPhone is in flight mode. So my app shouldn't be usable when there is no internet and/or GPS so an empty view with an info message should pop up telling this the user. And of course vanish as soon as the internet/GPS is recovered. How can I do this?
EDIT: I know the reachabiljty class I only wonder how can I show and hide a view created in Storyboard directly from the app delegate?


text:
Q: Needing to parse out data I am trying to parse out certain data from a string and I am having issues.
Here is the string:
1=BETA.1.0^2=175^3=812^4=R^5=N^9=1^12=1^13=00032^14=REP NOT FOUND ON REP TABLE, CANNOT INSERT TO REPRGR.^10=107~117~265~1114~3143~3505~3506~3513~5717^11=SA16~1~WY~WY~A~S~20100210~001~SE62^-omitted due to existing Rep Not Found
I need to return this "REP NOT FOUND ON REP TABLE, CANNOT INSERT TO REPRGR."
Here is my query SELECT CONVERT(VARCHAR(5000),CHARINDEX('14=',Column))FROM Table

A: If you're parsing, can we assume that you don't know what might come after the '^14=', but you need to capture whatever does? So searching for a particular string won't work because anything could come after '^14='. The best approach is to identify the longest reliable specific string that gives you a "foothold" to find the data you're looking for. What you don't want to do is accidentally capture the wrong data if the '^14=' appears more than once in your string. It looks like the '^' is your delimiter, since I don't see one at the start of the string. So you were actually on the right track, you just need to use SUBSTRING as a commenter mentioned. You also need to identify a marker for the end of the error message, which looks like it might be the next occurring '^', correct? Check several samples to be sure of this, and make sure the end marker doesn't at any point exist before your start marker or you'll get an error.
SELECT CAST((SUBSTRING(Column,CHARINDEX('14=',Column,0),CHARINDEX('^',Column,CHARINDEX('14=',Column,0) + 1) - CHARINDEX('14=',Column,0))) AS VARCHAR(5000)) FROM Table

You may need to increment or decrement the start position and end position by doing a +1 or -1 to fully capture your error message. But this should dynamically grab any length error message provided you are positive of your starting and ending markers.
I also have here a table-valued parsing function, where you would pass it the string and the '^' and it will return a table of data with not only the 14=, but everything.
CREATE   function [dbo].[fn_SplitStringByDelimeter]
(
     @list      nvarchar(8000)
    ,@splitOn   char(1)
)
returns @rtnTable table
(

    id int identity(1,1)
    ,value nvarchar(100)
)
as
    begin
        declare @index int
        declare @string nvarchar(4000)
        select @index = 1
        if len(@list) < 1 or @list is null  return
       --
         while @index!= 0
         begin
              set @index = charindex(@splitOn,@list)
              if @index!=0
                    set @string = left(@list,@index - 1)
              else
                    set @string = @list

              if(len(@string)>0)
                    insert into @rtnTable(value) values(@string)
                --
              set @list = right(@list,len(@list) - @index)
              if len(@list) = 0 break
         end

        return
    end

A: You could try to use a Case When statement with wildcards to find the value that you want.
Example:
SELECT
 CASE
    WHEN x LIKE '%REP Not Found%'
        THEN 'REP NOT FOUND ON REP TABLE, CANNOT INSERT TO REPRGR'
 ELSE
    ''
END AS x

FROM
    #T1

A: You could use this query (assuming MySQL database):
-- item is the column that contains the string
select SUBSTR(item, LOCATE('REP',item), LOCATE('REPRGR.',item) + LENGTH('REPRGR.') - LOCATE('REP', item)) info_msg from Table;

Illustration:
create table parsetest (item varchar(5000));

insert into parsetest values('1=BETA.1.0^2=175^3=812^4=R^5=N^9=1^12=1^13=00032^14=REP NOT FOUND ON REP TABLE, CANNOT INSERT TO REPRGR.^10=107~117~265~1114~3143~3505~3506~3513~5717^11=SA16~1~WY~WY~A~S~20100210~001~SE62^-omitted due to existing Rep Not Found');

select * from parsetest;
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| item                                                                                |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| 1=BETA.1.0^2=175^3=812^4=R^5=N^9=1^12=1^13=00032^14=REP NOT FOUND ON REP TABLE, CANNOT INSERT TO REPRGR.^10=107~117~265~1114~3143~3505~3506~3513~5717^11=SA16~1~WY~WY~A~S~20100210~001~SE62^-omitted due to existing Rep Not Found |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

select SUBSTR(item, LOCATE('REP',item), LOCATE('REPRGR.',item) + LENGTH('REPRGR.') - LOCATE('REP', item)) info_msg from parsetest;
+------------------------------------------------------+
| info_msg                                             |
+------------------------------------------------------+
| REP NOT FOUND ON REP TABLE, CANNOT INSERT TO REPRGR. |
+------------------------------------------------------+

A: It sounds like you're trying to get the value of argument 14.  This should do it:
select substring(
  someData
  , charindex('^14=',someData) + 4
  , charindex('^',someData, charindex('^14=',someData) + 4) - charindex('^14=',someData) - 4
) errorMessage
from myData
where charindex('^14=',someData) > 0
and charindex('^',someData, charindex('^14=',someData) + 4) > 0

Try it here: http://sqlfiddle.com/#!18/22f23/2
This gets a substring of the given input.
The substring starts at the first character after the string ^14=; i.e. we get the index of ^14= in the string, then add 4 to it to skip over the matched characters themselves.
The substring ends at the first ^ character after the one in ^14=.  We get the index of that character, then subtract the starting position from it to get the length of the desired output.
Caveats:  If there is no parameter (^) after ^14= this will not work.  Equally if there is no ^14= (even if the string starts 14=) this will not work.  From the information available that's OK; but if this is a concern please say and we can provide something to handle that more complex scenario.

Code to create table & populate demo data
create table myData (someData nvarchar(256))
insert myData (someData)
values ('1=BETA.1.0^2=175^3=812^4=R^5=N^9=1^12=1^13=00032^14=REP NOT FOUND ON REP TABLE, CANNOT INSERT TO REPRGR.^10=107~117~265~1114~3143~3505~3506~3513~5717^11=SA16~1~WY~WY~A~S~20100210~001~SE62^-omitted due to existing Rep Not Found')
 , ('1xx^14=something else.^10=xx')


text:
Q: Hash or dict of Classes in Jars that needs folding I have a dictionary that contains a list of expanded classnames as the keys with each key pointing to an list containing the number of times the class appears in different jars and what jars it appears in.
For example:

classToJars = {
  'com.sun.xml.ws.policy.PolicyMapKey.class' :  [ 1, 'policy-2.3.1.jar'],
  'com.sun.xml.ws.policy.PolicyMerger.class' :  [ 1, 'policy-2.3.1.jar'],
  'com.sun.xml.ws.policy.PolicyAssertion.class' : [ 1,  'policy-2.3.1.jar' ],

  'com.sun.xml.bind.AccessorFactory.class'     : [1, 'jaxb-impl-2.2.6.jar'],
  'com.sun.xml.bind.AccessorFactoryImpl.class' : [1, 'jaxb-impl-2.2.6.jar'],
  'com.sun.xml.bind.AnyTypeAdapter.class'      : [1, 'jaxb-impl-2.2.6.jar' ],

  'org.apache.mina.integration.jmx.IoSessionManager.class' :      [1, 'mina-integration-jmx-1.1.7.jar'],
  'org.apache.mina.integration.jmx.IoServiceManager.class' :      [1, 'mina-integration-jmx-1.1.7.jar'],

  'org.apache.log4j.Appender.class' : [2, 'log4j-1.2.14.jar', 'log4j-1.2.15.jar'],
  'org.apache.log4j.AppenderSkeleton.class' : [2, 'log4j-1.2.14.jar', 'log4j-1.2.15.jar'],

  'com.sun.activation.registries.LineTokenizer.class' : [1, 'activation-1.1.jar'],
  'com.sun.activation.registries.LogSupport.class' : [1, 'activation-1.1.jar'],

  'com.sun.istack.Builder.class' : [2, 'jaxb-impl-2.2.6.jar istack-commons-runtime-2.4.jar'],
  'com.sun.istack.ByteArrayDataSource.class' : [2, 'jaxb-impl-2.2.6.jar istack-commons-runtime-2.4.jar'],

  'com.reuters.rfa.ansipage.Page.class' : [1, 'rfa-7.2.0.E2.jar'],
  'com.reuters.rfa.ansipage.PageUpdate.class' : [1, 'rfa-7.2.0.E2.jar'],

  'org.apache.http.impl.io.AbstractMessageWriter.class' : [1, 'rfa-7.2.0.E2.jar'],
  'org.apache.http.impl.io.ChunkedOutputStream.class' : [1, 'rfa-7.2.0.E2.jar']
}

The is a large dict with thousands of keys and values looped over a large set of jars. The idea is to to be able to fold the dict where if the values are the same, then fold it to the largest common substring.
For example: when I run the folding function, the above hash should be reduced to 4 lines as follows:

'com.sun.xml.ws.policy'    :  [ 1, 'policy-2.3.1.jar'],
'com.sun.xml.bind'         :  [1, 'jaxb-impl-2.2.6.jar'],
'org.apache.mina.integration.jmx'  :  [1, 'mina-integration-jmx-1.1.7.jar'],
'org.apache.log4j'      :  [2, 'log4j-1.2.14.jar', 'log4j-1.2.15.jar'],
'com.sun.activation.registries'  :  [1, 'activation-1.1.jar'],
'com.sun.istack'      :  [2, 'jaxb-impl-2.2.6.jar istack-commons-runtime-2.4.jar'],
'com.reuters.rfa.ansipage'    :  [1, 'rfa-7.2.0.E2.jar'],
'org.apache.http.impl.io'    :  [1, 'rfa-7.2.0.E2.jar'],

and so on.
since there is nothing common between com.reuters.rfa and org.apache.http, it will come back with an empty key if you go for largest common substring.
In a case like that, it should simply paste com.reuters.rfa and org.apache.http separately.
Any ideas on how to achieve this?

A: Is this what you want?
import os

classToJars = {
  'com.sun.xml.ws.policy.PolicyMapKey.class' :  [ 1, 'policy-2.3.1.jar'],
  'com.sun.xml.ws.policy.PolicyMerger.class' :  [ 1, 'policy-2.3.1.jar'],
  'com.sun.xml.ws.policy.PolicyAssertion.class' : [ 1,  'policy-2.3.1.jar' ],

  'com.sun.xml.bind.AccessorFactory.class'     : [1, 'jaxb-impl-2.2.6.jar'],
  'com.sun.xml.bind.AccessorFactoryImpl.class' : [1, 'jaxb-impl-2.2.6.jar'],
  'com.sun.xml.bind.AnyTypeAdapter.class'      : [1, 'jaxb-impl-2.2.6.jar' ],

  'org.apache.mina.integration.jmx.IoSessionManager.class' :
      [1, 'mina-integration-jmx-1.1.7.jar'],
  'org.apache.mina.integration.jmx.IoServiceManager.class' :
      [1, 'mina-integration-jmx-1.1.7.jar'],
  'org.apache.mina.integration.jmx.IoSessionManagerMBean.class' :
      [1, 'mina-integration-jmx-1.1.7.jar' ],

  'org.apache.log4j.Appender.class' : [2, 'log4j-1.2.14.jar', 'log4j-1.2.15.jar'],
  'org.apache.log4j.AppenderSkeleton.class' : [2, 'log4j-1.2.14.jar', 'log4j-1.2.15.jar'],
  'org.apache.log4j.AsyncAppender.class' : [2, 'log4j-1.2.14.jar log4j-1.2.15.jar'],
  # ...
  }

#
# from http://stackoverflow.com/a/21419164/866915
#
def common_prefix(names):
  prefix = os.path.commonprefix( [ n.split('.') for n in names ] )
  return '.'.join(prefix)

# return the first 3 components of a class name
def min_prefix(name):
  return '.'.join( name.split('.')[0:3] )

jarsForKey = {}
keyForClass = {}

for c in classToJars:
  jars = classToJars[c]
  s = '|'.join(jars[1:])
  jarsForKey[s] = classToJars[c]
  keyForClass[c] = s

# group together classes based on their key

sameKey = {}
for c in classToJars:
  s = keyForClass[c]
  sameKey.setdefault(s,[]).append(c)

# for each group of classes with the same key, find the largest common substring

for s in sameKey:
  cls = sameKey[s]  # all of the classes with the same key
  jars = jarsForKey[s]

  # partition cls into groups having at least 3 components in common

  group = {}
  for c in cls:
    m = min_prefix(c)
    group.setdefault(m, []).append(c)

  # find the common prefix for each group

  for m in group:
    cls = group[m]
    prefix = common_prefix(cls)
    print prefix, "==>", jars


text:
Q: How to know the folder paths to code bits assembled with includes? The problem:
An "index.php" is built using three pieces of code: "header", "content" & "footer", when I use "view page source", I'll see only the fully assembled index.php code, not to what file part belongs the header, content or footer and what is the path of the inspected element.
The question:
 Is there some way to trace to what file and source path the inspected element is from using some feature of google dev tools or any other method?
I'm trying to edit a wordpress theme and it is split into so many parts that finding one specific line of code to fix the property that I want seems as hard as looking for a needle in the haystack.
I've tried to download the whole project locally and go through files one-by-one on the visual studio code file browser but this still seems so inefficient.
I'm trying to find to what file this line belongs so i can add to it an aria-label attribute:

the original source code belongs to this blog:
https://blog.fdsm.edu.br/


text:
Q: how is current measured through ammeter? If we join a shunt through a galvanometer,it makes an ammeter.but in parallel arrangement voltage is same and only some amount of current is passed and not the total current of circuit.so how does the ammeter gives the value of total current in circuit????

A: As you said in shunt the galvanometer is connected in series, this makes it an ammeter, An ammeter has very minimal resistance (ideally zero), So it lets all the current pass through it, causing very minimal (ideally zero) voltage drop across it


text:
Q: Talking about feelings after a regular event For example,

*

*I go to the meditation class every week and I feel a lot more calm after class.

*I go to the meditation class every week and I felt a lot more calm after class.

I think I should use the present tense in the first half of the sentence because I am talking about something that I do regularly.
But at the same time, I felt calm every time after that class (it already happened many times in the past), so I am going to go to the classes and I believe I will still feel calm every time after going to the class (which makes it a regular event too?). So I'm confused about whether I should use the past tense in the second half of the sentence.
I did look up for the usage of simple past and it doesn't explain this situation.

A: The first statement is correct. You go to meditation class every week (though number of days you go is not defined). And you do feel calm after the classes. That should also be in simple present tense. Because you feeling calm is not completed in the past yet. You will continue to feel calm after the classes going to be held in the future also. Hence,
"I go to meditation class every week and I feel a lot more calm after class." Is correct.
However if you do want to use past tense, the action must have completed in the past. "I had been going to meditation class every week and I felt a lot more calm after class."


text:
Q: GitHub Action error: "Top level 'runs:' section is required" I am trying to get a private GitHub action to work within my private GitHub org. The private repo that contains these workflow 'templates' has this simple file structure as I'm just trying to get the bare minimum to work:
.
├── .git
├── test
│   ├── action.yml

And the action.yml file contents are:
name: Test

on: push

jobs:
  test:
    name: Test
    runs-on: ubuntu-latest
    steps:

    - name: Echo
      run: |
        echo Heyyyyy

I am trying to use this action in another private repo with a workflow file with these contents:
name: Test

on:
  push:
    branches:
      - master

jobs:
  test:
    name: Test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        with:
          repository: <private-actions-repo>
          token: ${{ secrets.REPO_TOKEN }}
          path: github-actions
      - name: Test private action
        uses: ./github-actions/test

When this action runs, I get the following error:
##[error]Top level 'runs:' section is required for /home/runner/work/<private-repo>/./github-actions/test/action.yaml
Trying to debug this, I updated the workflow that uses the template to cat the file contents of this file:
      - name: Test private action
        run: |
          cat ./github-actions/test/action.yml

..and I get the contents I would expect:
> Run cat ./github-actions/test/action.yml
name: Test

on: push

jobs:
  test:
    name: Test
    runs-on: ubuntu-latest
    steps:

    - name: Echo
      run: |
        echo Heyyyyy

Why would this not be working when using it from the action repo, but the exact same content works in the target repo?

A: You have to differentiate between workflows, actions, and different action types.
Workflows are toplevel elements and not composable. Actions are building blocks that can be used in workflows. The action you defined in action.yml is actually a workflow but should be a composite run steps action, i.e. a specific type of action, that has to follow the rules given in:
https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#runs-for-composite-run-steps-actions
You can find an example for a composite run steps action here:
https://docs.github.com/en/actions/creating-actions/creating-a-composite-run-steps-action#creating-an-action-metadata-file
If you use the following as action.yaml, it should work:
name: Test
description: 'composite run action'

runs:
  using: "composite"
  steps:
    - name: Echo
      shell: bash
      run: |
        echo Heyyyyy


text:
Q: ggplot legend - how to change the colour spread? I would like to change the spread display of the legend bar as on the jpeg below. In example 1, I'd like to display the "100" threshold value in the middle of the legend bar. In example 2, I'd like to display the mean value (white colour) in the middle of the legend bar. I suspect both would require similar line of code. Could someone very kindly help me with this?
#library
library(raster)
library(ggplot2)

#sample raster
r <- raster(ncol=36, nrow=18)
r[] <- (-ncell(r)/2+1):(ncell(r)/2)
r[1,] <- 5000
plot(r)

var_df <- as.data.frame(rasterToPoints(r))

### example 1
p <- ggplot()
p <- p + geom_raster(data = var_df , aes(x = x, y = y, fill = layer))
p <- p + coord_equal()
p <- p + scale_fill_gradientn(
  colours=c("red", "yellow", "skyblue", "darkblue"),
  values = rescale(c(min(var_df$layer),
                     100,
                     100.01,
                     max(var_df$layer))))
p
### example 2
meanval <- mean(var_df$layer)
p <- ggplot()
p <- p + geom_raster(data = var_df , aes(x = x, y = y, fill = layer))
p <- p + coord_equal()

p <- p + scale_fill_gradient2(low = muted("red"), mid = "white",
                              high = muted("blue"), midpoint = meanval)
p


text:
Q: Find transcription start sites with biomaRt I am using biomaRt in R to query ensembl's hsapiens database of human genes. I am using the function getBM to get all genes' name, start position and stop position, but I cannot find the right attribute for retrieving the TSS (transcription start site). Is it maybe because it is considered the same as the seqType= c("3utr", "5utr")?

A: A complete list of queriable attributes can be retrieved in a data frame using listAttributes. Then it's just a matter of searching it for the attributes you want.
mart <- useDataset("hsapiens_gene_ensembl", useMart("ensembl"))
att <- listAttributes(mart)
grep("transcript", att$name, value=TRUE)

will get you a rather long list, begining like this
 [1] "ensembl_transcript_id"
 [2] "transcript_start"
 [3] "transcript_end"
 [4] "external_transcript_id"
 [5] "transcript_db_name"
 [6] "transcript_count"
 [7] "transcript_biotype"
 [8] "transcript_status"
 [9] "clone_based_ensembl_transcript_name"
[10] "clone_based_vega_transcript_name"

Then you can go ahead and query using these names
getBM(attributes=c("transcript_start", "transcript_end"),
      filters="hgnc_symbol", values="foxp2", mart=mart)

and you get
   transcript_start transcript_end
1         113726382      114330960
2         113726494      114271639
3         113726615      114330155
4         113728221      114066565
5         113728221      114271650
6         114054329      114330218
7         114055052      114139783
8         114055052      114333827
9         114055110      114330155
10        114055113      114330200
11        114055275      114269037
12        114055374      114285885
13        114055378      114330012
14        114066555      114294198
15        114066557      114271754
16        114066557      114282629
17        114066570      114294198
18        114055052      114333823
19        114268613      114329981
20        113726615      114310038

If you want all the transcripts of all genes remove the filter and values arguments, but be aware that you will get a lot of data coming your way.

A: There is now a specific attribute for the transcription start site that can be downloaded: transcription_start_site.
library("biomaRt")
ensembl = useMart("ensembl", dataset = "hsapiens_gene_ensembl")
attributes = listAttributes(ensembl, page = "structure")
attributes[grep("transcript", attributes$description, ignore.case = TRUE), ]
#                         name                                description
# 178    ensembl_transcript_id                      Ensembl Transcript ID
# 183         transcript_start                      Transcript Start (bp)
# 184           transcript_end                        Transcript End (bp)
# 185 transcription_start_site             Transcription Start Site (TSS)
# 186        transcript_length Transcript length (including UTRs and CDS)
# 195         transcript_count                           Transcript count
# 201                     rank                    Exon Rank in Transcript

As an example, here is the result for the gene BTC. Note that because it is on the reverse strand (strand == -1), the value for transcription_start_site is the same as the value for transcript_end. Basically, downloading transcription_start_site is a shortcut so that you don't have to determine which end of the transcript is the TSS based on which strand the gene is on.
tss <- getBM(attributes = c("transcription_start_site", "chromosome_name",
                            "transcript_start", "transcript_end",
                            "strand",  "ensembl_gene_id",
                            "ensembl_transcript_id", "external_gene_name"),
             filters = "external_gene_name", values = "BTC",
             mart = ensembl)
tss
# transcription_start_site chromosome_name transcript_start transcript_end strand
# 1                 75635873     HG706_PATCH         75612096       75635873     -1
# 2                 75660403     HG706_PATCH         75610476       75660403     -1
# 3                 75719896               4         75669969       75719896     -1
# 4                 75695366               4         75671589       75695366     -1
# ensembl_gene_id ensembl_transcript_id external_gene_name
# 1 ENSG00000261530       ENST00000567516                BTC
# 2 ENSG00000261530       ENST00000566356                BTC
# 3 ENSG00000174808       ENST00000395743                BTC
# 4 ENSG00000174808       ENST00000512743                BTC

A: I believe the "transcript_start" and "transcript_end" are the translation start and stop site, but not necessarily the TSS (transcription start site).
Looking at the "start_position" and "end_position" attributes, these seem to be the TSS (start_position for + strand and end_position for - strand), because they are always the smallest number of the transcript_start options for different transcript for the + strand and the largest number of the transcript_end options for the - strand.


text:
Q: Send Python information to a JavaScript file I am new to Python and JavaScript and (attempting) to use cola.js. My HTML form sends information to Python, which turns it into an array of dictionaries.
Class_Name(ndb.Model):
    class_title = ndb.JsonProperty()
def post(self):
    classname = self.request.get('classname') #user inputs 1 classname
    prereq = self.request.get('prereq') #user inputs 1 prereq
    new_dictionary = {}
    new_dictionary [classname] = prereq
    new_class = Class_Name(class_title = new_dictionary) #stores as a dictionary
    new_class.put()

    Class_data = Class_Name.query().fetch() #gets all instances of Class_Name

   *** code that goes in b/w sends back to input form if want to add more classes, else, goes to below code

        output = []
        for a in Class_data:
            jsonprop = a.class_title
            extracted_output = json.dumps(jsonprop)
            output.append(extracted_output)
        template_vars= {'Class_data': output}
        template = jinja2_environment.get_template('template/post.html')
        self.response.write(template.render(template_vars))

This is my basic code so far. I want to use cola.js to turn my information into a graph, basically mapping out each class with its prerequisites. However, the cola.js format is a JavaScript file that looks like this:
graph = {
  nodes: [
  {
    id: 'A'
  }, {
    id: 'B'
  }, {
    id: 'C'
  }
],

links: [
  {
    id: 1,
    source: 'A',
    target: 'B'
  }, {
    id: 2,
    source: 'B',
    target: 'C'
  }, {
    id: 3,
    source: 'C',
    target: 'A'
  }
]
};

Is there any way I can tell JavaScript to get my Python array, and enter the info into the JavaScript file like this?
graph = {
  nodes: [
  {
    id: 'Class1' **will put actual class name
  }, {
    id: 'Class2'
  }
],

links: [
  {
    id: 1,
    source: 'Class1',
    target: 'prereq'
  }, {
    id: 2,
    source: 'Class2',
    target: 'prereq'
  }
]
};

This is a rough code for turning my Python information into the JavaScript format.
nodes_array = []
nodes_dict = {}
links_array = []
links_dict = {}
graph_array = []

#loops through every element
for a in Class_data:
    jsonprop = a.class_title
    extracted_output = json.loads(jsonprop)

for c_class, prereq in extracted_output.iteritems():
    # for the links dictionary
    counter_link = 1
    # creates {'id':'class1'}
    nodes_dict['id'] = c_class
    #creates [ {'id':'class1'},  {'id':'class2'}]
    nodes_array.append(nodes_dictionary)
    # creates {'id': 'counter', 'source': 'class1', 'target': 'prereq'}
    links_dictionary[id] = counter_link
    counter_link++
    links_dictionary[source] = c_class
    links_dictionary[target] = prereq
    # creates [{'id': 'counter', 'source': 'class1', 'target': 'prereq'}]
    links_array.append(links_dictionary)
    #creating the format --> 'nodes': [  {id: class1}, {id:class2},  {id:class3} ]"
    #creating the format --> 'links': [  {id: 1, source :class2, target :class3} ]"
    graph[nodes] = nodes_array
    graph[links] = links_array

A: Your Python script can use the json module to write the graph to a file in a format that JavaScript understands.
If you do this in Python:
import json

graph = {
    'nodes': [ {'id': 'Class1'}, {'id': 'Class2'} ],
    'links': [
        { 'id': 1, 'source': 'Class1', 'target': 'prereq' },
        { 'id': 2, 'source': 'Class2', 'target': 'prereq' }
    ]
}

with open('graph.js', 'w') as out_file:
  out_file.write('var graph = %s;' % json.dumps(graph))

The result is a file named graph.js, containing this:
var graph = {"links": [{"target": "prereq", "source": "Class1", "id": 1}, {"target": "prereq", "source": "Class2", "id": 2}], "nodes": [{"id": "Class1"}, {"id": "Class2"}]};

If you load graph.js before loading your own JavaScript file, you can refer to the variable graph to use your graph.


text:
Q: The unequal width between axes causes non-diagonal lines import numpy as np
import matplotlib.pyplot as plt
x=np.arange(-2,4,0.1)
y1=x
y2=-x
fig=plt.figure(figsize=(8,8))
plt.plot(x,y1)
plt.plot(x,y2)

Now I have drawn a graph of y=x and y=-x.

It's known to all that y=x and y=-x should be diagonal lines. However, because of the inequality of width between x axis and y axis with the same 1 unit distance, the lines are not diagonal.
That's a wrong graph.
I have also set the canvas to be a square to avoid such problem. It doesn't work.
How to draw a correct y=x and y=-x?
Thanks for your help!

A: It looks like you are looking for an equal aspect ratio:
plt.axis("equal")


text:
Q: Gulp + Sass + Git Workflow I'm working on a project (by myself, and in two different machines) where I'm using Gulp, and the gulpfile has two main goals - generate the build (default task) and compile SASS to CSS, within the /app (source) folder.
Any advice on avoiding people (me included) to update a .css file that would be eventually overwritten by a compiled .scss file with gulp-watch?
I'm also using Git and recently I lost some changes I've made to a CSS file for that reason. I'm not sure what happened, but when I merged commits, some CSS was lost and I had to look for it in previous commits. No big deal, and it was actually my fault, because I made some commits without checking out the origin, and then pushed them.
A part from the CSS issue, does it sounds like a good workflow? It feels good to work with that level of organisation and make profit of Sass, Gulp and Git, but sometimes it feels I'm making things too complex, not sure if that's the case, or if I'm doing something wrong or if it's just a matter of familiarisation.

A: First of all, if you are using SCSS, why are you editing CSS files?
I would recommend adding your CSS files to .gitignore so that they are not committed and only commit your scss files. You just have to remember to use gulp to generate new css files whenever you checkout your repo into a fresh project.
As far as, keeping people (including you) from editing a css file... just don't do it. You and anyone else familiar with a project should know that your css is overwritten by scss compiling.


text:
Q: jQuery total amount of elements in an array Seems like a simple thing but I cant find anything on it!
var cookie = [1,2,3],
    total  = cookie.magicMethodThatICantFindThatTotalsTheElements();

total = 3

A: Property length specifies the number of elements in array:
var total = cookie.length;


text:
Q: What is an efficient way to find disjoint elements in two arrays? I have the following arrays:
A = [1,2,3,4,5]
B = [2,6,7,1]

I want to find the disjoint elements, which are as follows:
output = [3,4,5,6,7]

I was able to achieve this as follows,
output = A + B - (A & B)

but it is inefficient, as I'm adding two arrays and then removing common elements. It is similar to finding non-intersecting elements. Can I do it better than this? If so, how?

A: How about just selecting elements in A not in B and elements in B not in A.
(A - B) + (B - A)

A: You could use Set
A = Set[1,2,3,4,5]
 => #<Set: {5, 1, 2, 3, 4}>
B = Set[2,6,7,1]
 => #<Set: {6, 1, 7, 2}>
C = A ^ B
 => #<Set: {5, 6, 7, 3, 4}>
C.to_a
 => [5, 6, 7, 3, 4]

A: Another one:
(A | B) - (A & B)

But you probably want to use your own version:
require 'benchmark'
n = 50000
A = (1..1000).to_a
B = [2,6,7,1]
Benchmark.bm do |x|
  x.report { n.times do; (A + B) - (A & B); end }
  x.report { n.times do; (A - B) + (B - A); end }
  x.report { n.times do; (A | B) - (A & B); end }
  x.report { n.times do; (Set[*A] ^ Set[*B]).to_a; end }
end

       user     system      total        real
   2.200000   0.000000   2.200000 (  2.208357)
   9.600000   0.010000   9.610000 (  9.591845)
  10.630000   0.000000  10.630000 ( 10.621927)
  31.420000   0.000000  31.420000 ( 31.418155)


text:
Q: Is there a way to have json.Unmarshal() select struct type based on "type" property? I have some JSON of the form:
[{
    "type": "car",
    "color": "red",
    "hp": 85,
    "doors": 4
}, {
    "type": "plane",
    "color": "blue",
    "engines": 3
}]

I have types car and plane that satisfy a vehicle interface; I'd like to be able to write:
var v []vehicle
e := json.Unmarshal(myJSON, &v)

... and have JSON fill my slice of vehicles with a car and a plane; instead (and unsurprisingly) I just get "cannot unmarshal object into Go value of type main.vehicle".
For reference, here are suitable definitions of the types involved:
type vehicle interface {
    vehicle()
}

type car struct {
    Type  string
    Color string
    HP    int
    Doors int
}

func (car) vehicle() { return }

type plane struct {
    Type    string
    Color   string
    Engines int
}

func (plane) vehicle() { return }

var _ vehicle = (*car)(nil)
var _ vehicle = (*plane)(nil)

(Note that I'm actually totally uninterested in the t field on car and plane - it could be omitted because this information will, if someone successfully answers this question, be implicit in the dynamic type of the objects in v.)
Is there a way to have the JSON umarhsaller choose which type to use based on some part of the contents (in this case, the type field) of the data being decoded?
(Note that this is not a duplicate of Unmarshal JSON with unknown fields because I want each item in the slice to have a different dynamic type, and from the value of the 'type' property I know exactly what fields to expect—I just don't know how to tell json.Unmarshal how to map 'type' property values onto Go types.)

A: JSON decoding and encoding in Go is actually surprisingly well at recognizing fields inside embedded structs. E.g. decoding or encoding the following structure works when there is no overlapping fields between type A and type B:
type T struct{
    Type string `json:"type"`
    *A
    *B
}

type A struct{
    Baz int `json:"baz"`
}

type B struct{
    Bar int `json:"bar"`
}

Be aware that if both "baz" and "bar" are set in the JSON for the example above, both the T.A and T.B properties will be set.
If there is overlapping fields between A and B, or just to be able to better discard invalid combinations of fields and type, you need to implement the json.Unmarshaler interface. To not have to first decode fields into a map, you can extend the trick of using embedded structs.
type TypeSwitch struct {
    Type string `json:"type"`
}

type T struct {
    TypeSwitch
    *A
    *B
}

func (t *T) UnmarshalJSON(data []byte) error {
    if err := json.Unmarshal(data, &t.TypeSwitch); err != nil {
        return err
    }
    switch t.Type {
    case "a":
        t.A = &A{}
        return json.Unmarshal(data, t.A)
    case "b":
        t.B = &B{}
        return json.Unmarshal(data, t.B)
    default:
        return fmt.Errorf("unrecognized type value %q", t.Type)
    }

}

type A struct {
    Foo string `json:"bar"`
    Baz int    `json:"baz"`
}

type B struct {
    Foo string `json:"foo"`
    Bar int    `json:"bar"`
}

For marshaling back, json.Marshaler must also be implemented if there is overlapping fields.
Full example: https://play.golang.org/p/UHAdxlVdFQQ

A: Taking the answers from the similar question: Unmarshal JSON with unknown fields, we can construct a few ways to unamrshal this JSON object in a []vehicle data structure.
The "Unmarshal with Manual Handling" version can be done by using a generic []map[string]interface{} data structure, then building the correct vehicles from the slice of maps. For brevity, this example does leave out the error checking for missing or incorrectly typed fields which the json package would have done.
https://play.golang.org/p/fAY9JwVp-4
func NewVehicle(m map[string]interface{}) vehicle {
    switch m["type"].(string) {
    case "car":
        return NewCar(m)
    case "plane":
        return NewPlane(m)
    }
    return nil
}

func NewCar(m map[string]interface{}) *car {
    return &car{
        Type:  m["type"].(string),
        Color: m["color"].(string),
        HP:    int(m["hp"].(float64)),
        Doors: int(m["doors"].(float64)),
    }
}

func NewPlane(m map[string]interface{}) *plane {
    return &plane{
        Type:    m["type"].(string),
        Color:   m["color"].(string),
        Engines: int(m["engines"].(float64)),
    }
}

func main() {
    var vehicles []vehicle

    objs := []map[string]interface{}{}
    err := json.Unmarshal(js, &objs)
    if err != nil {
        log.Fatal(err)
    }

    for _, obj := range objs {
        vehicles = append(vehicles, NewVehicle(obj))
    }

    fmt.Printf("%#v\n", vehicles)
}

We could leverage the json package again to take care of the unmarshaling and type checking of the individual structs by unmarshaling a second time directly into the correct type. This could all be wrapped up into a json.Unmarshaler implementation by defining an UnmarshalJSON method on the []vehicle type to first split up the JSON objects into raw messages.
https://play.golang.org/p/zQyL0JeB3b
type Vehicles []vehicle

func (v *Vehicles) UnmarshalJSON(data []byte) error {
    // this just splits up the JSON array into the raw JSON for each object
    var raw []json.RawMessage
    err := json.Unmarshal(data, &raw)
    if err != nil {
        return err
    }

    for _, r := range raw {
        // unamrshal into a map to check the "type" field
        var obj map[string]interface{}
        err := json.Unmarshal(r, &obj)
        if err != nil {
            return err
        }

        vehicleType := ""
        if t, ok := obj["type"].(string); ok {
            vehicleType = t
        }

        // unmarshal again into the correct type
        var actual vehicle
        switch vehicleType {
        case "car":
            actual = &car{}
        case "plane":
            actual = &plane{}
        }

        err = json.Unmarshal(r, actual)
        if err != nil {
            return err
        }
        *v = append(*v, actual)

    }
    return nil
}

A: The two passes approach works fine, but there is also the option of the mapstructure package, that was created to do exactly this.

A: I was facing the same problem.
I'm using the lib github.com/mitchellh/mapstructure together the encoding/json.
I first, unmarshal the json to a map, and use mapstructure to convert the map to my struct, e.g.:
type (
  Foo struct {
    Foo string `json:"foo"`
  }
  Bar struct {
    Bar string `json:"bar"`
  }
)

func Load(jsonStr string, makeInstance func(typ string) any) (any, error) {
    // json to map
    m := make(map[string]any)
    e := json.Unmarshal([]byte(jsonStr), &m)
    if e != nil {
        return nil, e
    }

    data := makeInstance(m["type"].(string))

    // decoder to copy map values to my struct using json tags
    cfg := &mapstructure.DecoderConfig{
        Metadata: nil,
        Result:   &data,
        TagName:  "json",
        Squash:   true,
    }
    decoder, e := mapstructure.NewDecoder(cfg)
    if e != nil {
        return nil, e
    }
    // copy map to struct
    e = decoder.Decode(m)
    return data, e
}

Using:
f, _ := Load(`{"type": "Foo", "foo": "bar"}`, func(typ string) any {
        switch typ {
        case "Foo":
            return &Foo{}
        }
        return nil
    })

A: If the property is a string you can use .(string) for casting the property because the origin is an interface.
You can use it the next way:
v["type"].(string)


text:
Q: Error while importing gobblin gradle project into IDE I am getting this error while I try to import the gobblin distribution into my IDE , I have tried both inteliJ and eclipse , not able to find any luck.
Below are the errors which I get when I try to import.
In Eclipse the error is:
*org.gradle.tooling.BuildException: Could not run build action using Gradle distribution 'https://services.gradle.org/distributions/gradle-3.3-bin.zip'.
*
For InteliJ
*Cause: startup failed: build file 'C:\Users\sayyad.ghazi\Desktop\gob\gobblin-master\gobblin-restli\gobblin-throttling-service\gobblin-throttling-service-api\build.gradle': 1: unexpected token: .. @ line 1, column 1. ../../api.gradle ^ 1 error*

A: This is because on Windows, Git can not create symbolic link file on non-admins mode. Symbolic link file is created as text file, containing a symbolic link.
Try the following command in Administrator Mode:
git clone -c core.symlinks=true <URL>

Then check the content of symbolic link file, such as "build.gradle" in your description. It should be the same as the content of "../../api.gradle", not just a symbolic link.
See git-for-windows-wiki-Symbolic-Links for more details.


text:
Q: Pandas rolling but involves last rows value I have this dataframe
hour = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]
visitor = [4,6,2,4,3,7,5,7,8,3,2,8,3,6,4,5,1,8,9,4,2,3,4,1]
df = {"Hour":hour, "Total_Visitor":visitor}
df = pd.DataFrame(df)
print(df)

I applied 6 window rolling sum
df_roll = df.rolling(6, min_periods=6).sum()
print(df_roll)

The first 5 rows will give you NaN value,
The problem is I want to know the sum of total visitor from 9pm to 3am, so I have to sum total visitor from hour 21 and then back to hour 0 until 3
How do you do that automatically with rolling?

A: I think you need add last N values, then using rolling and filter by length of Series:
N = 6
df_roll = df.iloc[-N:].append(df).rolling(N).sum().iloc[-len(df):]
print (df_roll)
     Hour  Total_Visitor
0   105.0           18.0
1    87.0           20.0
2    69.0           20.0
3    51.0           21.0
4    33.0           20.0
5    15.0           26.0
6    21.0           27.0
7    27.0           28.0
8    33.0           34.0
9    39.0           33.0
10   45.0           32.0
11   51.0           33.0
12   57.0           31.0
13   63.0           30.0
14   69.0           26.0
15   75.0           28.0
16   81.0           27.0
17   87.0           27.0
18   93.0           33.0
19   99.0           31.0
20  105.0           29.0
21  111.0           27.0
22  117.0           30.0
23  123.0           23.0

Check original solution:
df_roll = df.rolling(6, min_periods=6).sum()
print(df_roll)
     Hour  Total_Visitor
0     NaN            NaN
1     NaN            NaN
2     NaN            NaN
3     NaN            NaN
4     NaN            NaN
5    15.0           26.0
6    21.0           27.0
7    27.0           28.0
8    33.0           34.0
9    39.0           33.0
10   45.0           32.0
11   51.0           33.0
12   57.0           31.0
13   63.0           30.0
14   69.0           26.0
15   75.0           28.0
16   81.0           27.0
17   87.0           27.0
18   93.0           33.0
19   99.0           31.0
20  105.0           29.0
21  111.0           27.0
22  117.0           30.0
23  123.0           23.0

Numpy alternative with strides is complicated, but faster if large one Series:
def rolling_window(a, window):
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

N = 3
x = np.concatenate([fv[-N+1:], fv.to_numpy()])
cv = pd.Series(rolling_window(x, N).sum(axis=1), index=fv.index)
print (cv)
0    5
1    4
2    4
3    6
4    5
dtype: int64

A: Though you have mentioned a series, see if this is helpful-
import pandas as pd

def cyclic_roll(s, n):
    s = s.append(s[:n-1])
    result = s.rolling(n).sum()
    return result[-n+1:].append(result[n-1:-n+1])

fv = pd.DataFrame([1, 2, 3, 4, 5])
cv = fv.apply(cyclic_roll, n=3)
cv.reset_index(inplace=True, drop=True)
print cv

Output
      0
0  10.0
1   8.0
2   6.0
3   9.0
4  12.0


text:
Q: Spring security UserDetailsService not working Ok guys, I hope you can help me, this is my last attempt. I am quite new to this spring security world and I cant get this to work. I tried many things, followed many tutorials and nothing.
The problem is as you saw in the title, make a custom user details service to work. It just not logs in, It appears that the customuserdetailsservice is not being called, as the sysouts are not showing in the console...
It works as a charm with spring security in memory features. Below are my codes.
Spring Security Config:
@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = CustomUserDetailsService.class)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
UserDetailsService userDetailsService;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    //auth.inMemoryAuthentication().withUser("ram").password("ram123").roles("ADMIN");
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordencoder());
}

@Override
public void configure(WebSecurity web) throws Exception {
  web
    .ignoring()
       .antMatchers("/bower_components/**", "/resources/**", "/img/**"); // #3
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().csrf().disable()
    .authorizeRequests()
      .antMatchers("/", "/home", "/call").permitAll() // #4
      .antMatchers("/resource", "/video").hasRole("USER") // #6
      .anyRequest().authenticated();
}

@Bean(name="passwordEncoder")
public PasswordEncoder passwordencoder(){
    return new BCryptPasswordEncoder();
}

}

CustomUserDetailsService
@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService{

private UserService userService;

@Override
public UserDetails loadUserByUsername(String ssoId)
        throws UsernameNotFoundException {
    User user = userService.findByUsername(ssoId);
    System.out.println("User : "+user);
    if(user==null){
        System.out.println("User not found");
        throw new UsernameNotFoundException("Username not found");
    }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
             user.isEnabled(), true, true, true, getGrantedAuthorities(user));
}

private List<GrantedAuthority> getGrantedAuthorities(User user){
    List<GrantedAuthority> authorities = new ArrayList<>();

    authorities.add(new SimpleGrantedAuthority(user.getRole()));

    System.out.print("authorities :"+authorities);
    return authorities;
}
}

Initializer Class
@SpringBootApplication
@EnableWebSocket
public class One2OneCallApp implements WebSocketConfigurer {

@Bean
public CallHandler callHandler() {
  return new CallHandler();
}

@Bean
public UserRegistry registry() {
  return new UserRegistry();
}

@Bean
public KurentoClient kurentoClient() {
  return KurentoClient.create();
}

@Bean
public UiApplication uiApplication(){
  return new UiApplication();
}

@Bean
public CustomUserDetailsService customUserDetailsService(){
  return new CustomUserDetailsService();
}

@Bean
public SecurityConfig securityConfig(){
  return new SecurityConfig();
}

@Bean
public EncryptPassword encryptPassword(){
  return new EncryptPassword();
}

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry   registry) {
  registry.addHandler(callHandler(), "/call");
}

public static void main(String[] args) throws Exception {
  System.out.println("Iniciando");
  new SpringApplication(One2OneCallApp.class).run(args);
}

}

I've also tested the communication with the database and it works perfectly fine. I'm seeking any help. Sorry for bad English. Thank you all!
Edit: Answered my own question down below.

A: In SecurityConfig class:
@Autowired
CustomUserDetailsService customUserDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService);
}

A: Change
@Autowired
UserDetailsService userDetailsService;

to
@Autowired
CustomUserDetailsService userDetailsService;

Also, import the security config in you web/socket config and move the component scan there, not on the security
@ComponentScan(basePackageClasses = CustomUserDetailsService.class)
@Import(value = { SecurityConfig.class })
public class WebConfig extends WebMvcConfigurerAdapter { /*...*/ }

A: You are setting hasRole(" ") in security config  and you are using authorities for authentication.
instead of using .antMatchers("/resource", "/video").hasRole("USER")
  use .antMatchers("/resource", "/video").hasAuthority("USER")

A: I ended up staying with the built in memory anthentication just for the presentation I had to do. I think my problem had to do with something in spring boot and the initialization in my application.


text:
Q: How would I make a scrolling camera in Pygame? I am asking the question I did because I need a scrolling camera. I already tried a few methods on a camera, but none of them worked. Or they said that there was a global name error. This is the code I used that has a globalname error
import pygame

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)

screen_width = 700
screen_height = 400

half_width = int(screen_width / 2)
half_height = int(screen_height / 2)

def main():
    screen = pygame.display.set_mode([screen_width, screen_height])

    pygame.display.set_caption("RPG")
    global cameraX, cameraY

    pygame.init()

    player = pygame.image.load("Textures(Final)\Whoo_For_Testing.bmp").convert()
    playerect = player.get_rect()
    player.set_colorkey(WHITE)

    grasstile = pygame.image.load("Textures(Final)\Grass_Tile.bmp").convert()
    watertile = pygame.image.load("Textures(Final)\Water_Tile.bmp").convert()
    waterbeach = pygame.image.load("Textures(Final)\Water_Beach.bmp").convert()
    grassrect = grasstile.get_rect()
    waterrect = watertile.get_rect()
    waterb = waterbeach.get_rect()

    TILE_WIDTH = 32
    TILE_HEIGHT = 32

    tilemap = [
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile]
            ]

    total_level_width = len(tilemap[0]) * 32
    total_level_height = len(tilemap)*32

    camera = Camera(simple_camera ,total_level_width, total_level_height)

    map_surface = pygame.Surface(( len(tilemap[0])*TILE_WIDTH, len(tilemap)*TILE_HEIGHT))

    for y,row in enumerate(tilemap):
        for x,tile_surface in enumerate(row):
            map_surface.blit(tile_surface,(x*TILE_WIDTH,y*TILE_HEIGHT))

    map_surface = pygame.transform.scale(map_surface, (1200, 800))
    player = pygame.transform.scale(player, (50, 100))

    done = False

    clock = pygame.time.Clock()

    move_speed = 5
    x, y = 100, 100

    entities = pygame.sprite.Group()

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            y -= move_speed
        elif keys[pygame.K_DOWN]:
            y += move_speed
        elif keys[pygame.K_LEFT]:
            x -= move_speed
        elif keys[pygame.K_RIGHT]:
            x += move_speed

        screen.fill(BLACK)

        screen.blit(map_surface, grassrect)
        screen.blit(player, (x,y))

        camera.update(player)

        clock.tick(20)

        pygame.display.flip()

class Camera(object):
    def __init__(self, camera_func, width, height):
        self.camera_func = camera_func
        self.state = Rect(0, 0, width, height)

    def apply(self, target):
        return target.rect.move(self.state.topleft)

    def update(self, target):
        self.state = self.camera_func(self.state, target.rect)

def simple_camera(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera
    return Rect(-l+HALF_WIDTH, -t+HALF_HEIGHT, w, h)

def complex_camera(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera
    l, t, _, _ = -l+HALF_WIDTH, -t+HALF_HEIGHT, w, h

    l = min(0, l)                           # stop scrolling at the left edge
    l = max(-(camera.width-WIN_WIDTH), l)   # stop scrolling at the right edge
    t = max(-(camera.height-WIN_HEIGHT), t) # stop scrolling at the bottom
    t = min(0, t)                           # stop scrolling at the top
    return Rect(l, t, w, h)

if __name__ == "__main__":
    main()

pygame.quit()

So essentially what I am asking is how to fix this. Sorry, not that good at explaining stuff. Thank you!

A: There are a couple things to fix here. Firstly about the NameErrors, those were occurring because since Rect is from the imported pygame package, you have to either import Rect specifically: from pygame import Rect or write pygame.Rect. (Also watch out for capitals in your global variables!). Now, as for the actual camera problems, the main problem you had was that the player's rect which you pass to your camera function is not a moved rect, it is just the rect pygame uses to store the surface's size (so is topleft will always be (0,0)).  You were also not applying your camera to the rects of the surfaces when you actually drew them. Here is the code I got to work:
import pygame

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)

SCREEN_WIDTH = 700
SCREEN_HEIGHT = 400

HALF_WIDTH = int(SCREEN_WIDTH / 2)
HALF_HEIGHT = int(SCREEN_HEIGHT / 2)

def main():
    screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])

    pygame.display.set_caption("RPG")
    global cameraX, cameraY

    pygame.init()

    #player = pygame.image.load("Textures(Final)\Whoo_For_Testing.bmp").convert()
    player = pygame.Surface((40,40))
    player.fill((255,0,0))

    playerrect = player.get_rect()
    player.set_colorkey(WHITE)

    #grasstile = pygame.image.load("Textures(Final)\Grass_Tile.bmp").convert()
    #watertile = pygame.image.load("Textures(Final)\Water_Tile.bmp").convert()
    #waterbeach = pygame.image.load("Textures(Final)\Water_Beach.bmp").convert()
    grasstile = pygame.Surface((40,40))
    watertile = pygame.Surface((40,40))
    waterbeach = pygame.Surface((40,40))
    grasstile.fill((0,200,0))
    watertile.fill((0,0,200))
    waterbeach.fill((200,200,250))

    grassrect = grasstile.get_rect()
    waterrect = watertile.get_rect()
    waterb = waterbeach.get_rect()

    TILE_WIDTH = 32
    TILE_HEIGHT = 32

    tilemap = [
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile]
            ]

    total_level_width = len(tilemap[0]) * 32
    total_level_height = len(tilemap)*32

    camera = Camera(simple_camera ,total_level_width, total_level_height)

    map_surface = pygame.Surface(( len(tilemap[0])*TILE_WIDTH, len(tilemap)*TILE_HEIGHT))

    for y,row in enumerate(tilemap):
        for x,tile_surface in enumerate(row):
            map_surface.blit(tile_surface,(x*TILE_WIDTH,y*TILE_HEIGHT))

    map_surface = pygame.transform.scale(map_surface, (1200, 800))
    player = pygame.transform.scale(player, (50, 100))

    done = False

    clock = pygame.time.Clock()

    move_speed = 5
    x, y = 100, 100

    entities = pygame.sprite.Group()

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            y -= move_speed
        elif keys[pygame.K_DOWN]:
            y += move_speed
        elif keys[pygame.K_LEFT]:
            x -= move_speed
        elif keys[pygame.K_RIGHT]:
            x += move_speed

        screen.fill(BLACK)

        screen.blit(map_surface, camera.apply(grassrect))
        screen.blit(player, camera.apply(pygame.Rect(x,y,50,100)))

        camera.update(player.get_rect().move((x,y)))

        clock.tick(20)

        pygame.display.flip()

class Camera(object):
    def __init__(self, camera_func, width, height):
        self.camera_func = camera_func
        self.state = pygame.Rect(0, 0, width, height)

    def apply(self, rect):
        return rect.move(self.state.topleft)

    def update(self, target_rect):
        self.state = self.camera_func(self.state, target_rect)

def simple_camera(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera

    return pygame.Rect(-l+HALF_WIDTH, -t+HALF_HEIGHT, w, h)

def complex_camera(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera
    l, t, _, _ = -l+HALF_WIDTH, -t+HALF_HEIGHT, w, h

    l = min(0, l)                           # stop scrolling at the left edge
    l = max(-(camera.width-SCREEN_WIDTH), l)   # stop scrolling at the right edge
    t = max(-(camera.height-SCREEN_HEIGHT), t) # stop scrolling at the bottom
    t = min(0, t)                           # stop scrolling at the top
    return pygame.Rect(l, t, w, h)

if __name__ == "__main__":
    main()

pygame.quit()

This works with your simple_camera method, but not the complex_camera method, which I will leave to you to try and fix.


text:
Q: Neo4j 2.2.3 ClassNotFoundException: org.neo4j.kernel.impl.transaction.XaDataSourceManager This is my Maven config for Neo4j:
    <properties>
        <neo4j.version>2.2.3</neo4j.version>
    </properties>

    <!-- neo4j -->
    <dependency>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j-enterprise</artifactId>
        <version>${neo4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j-ha</artifactId>
        <version>${neo4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j-kernel</artifactId>
        <version>${neo4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j-kernel</artifactId>
        <version>${neo4j.version}</version>
        <classifier>tests</classifier>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j-io</artifactId>
        <version>${neo4j.version}</version>
        <classifier>tests</classifier>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j-lucene-index</artifactId>
        <version>${neo4j.version}</version>
    </dependency>

During the application startup I have a following exception:
Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.extension.KernelExtensions@30bb7d0d' failed to initialize. Please see attached cause exception.
    at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.init(LifeSupport.java:489)
    at org.neo4j.kernel.lifecycle.LifeSupport.init(LifeSupport.java:72)
    at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:106)
    at org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:331)
    ... 127 more
Caused by: java.lang.NoClassDefFoundError: org/neo4j/kernel/impl/transaction/XaDataSourceManager
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
    at java.lang.Class.privateGetPublicMethods(Unknown Source)
    at java.lang.Class.getMethods(Unknown Source)
    at sun.misc.ProxyGenerator.generateClassFile(Unknown Source)
    at sun.misc.ProxyGenerator.generateProxyClass(Unknown Source)
    at java.lang.reflect.Proxy$ProxyClassFactory.apply(Unknown Source)
    at java.lang.reflect.Proxy$ProxyClassFactory.apply(Unknown Source)
    at java.lang.reflect.WeakCache$Factory.get(Unknown Source)
    at java.lang.reflect.WeakCache.get(Unknown Source)
    at java.lang.reflect.Proxy.getProxyClass0(Unknown Source)
    at java.lang.reflect.Proxy.newProxyInstance(Unknown Source)
    at org.neo4j.kernel.extension.KernelExtensions.getKernelExtensionDependencies(KernelExtensions.java:119)
    at org.neo4j.kernel.extension.KernelExtensions.init(KernelExtensions.java:62)
    at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.init(LifeSupport.java:483)
    ... 130 more
Caused by: java.lang.ClassNotFoundException: org.neo4j.kernel.impl.transaction.XaDataSourceManager
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 145 more

I can't find where XaDataSourceManager is located.

A: Xadatasource is present in the neo4j-kernal jar, but with jar version before 2.2.2. Since you are using 2.2.3, you will not find the class in the jar. I think the jar versions you are using are not compatible. Try adding the parent jar and let it reference to the compatible ones.


text:
Q: Mapping through a multidimensional array containing arrays of objects in React I'm trying to merge a multidimensional array, each containing objects and map over them to display results.
Below is the JSON output i'm getting.
[[{"_id":"f6476f3e-4bdc-49fa-b5ae-c1c52a31582e","created_at":"2019-02-06T18:24:39.501Z","updated_at":"2019-02-06T18:24:39.501Z","channel_id":"104939804","content_type":"video","content_id":"376156249","content_offset_seconds":123.801,"commenter":{"display_name":"Qiio","_id":"188064613","name":"qiio","type":"user","bio":"[ITA//ENG//SPA] Rising Streamer full of mad ideas |◔◡◉|","created_at":"2017-12-30T20:08:25.700146Z","updated_at":"2019-02-20T17:50:48.904111Z","logo":"https://static-cdn.jtvnw.net/jtv_user_pictures/f2106422-63b5-4c2c-b3c1-f0002a49a0b2-profile_image-300x300.jpeg"},"source":"chat","state":"published","message":{"body":"first <3","emoticons":[{"_id":"9","begin":6,"end":7}],"fragments":[{"text":"first "},{"text":"<3","emoticon":{"emoticon_id":"9","emoticon_set_id":""}}],"is_action":false,"user_badges":[{"_id":"premium","version":"1"}],"user_color":"#DAA520"},"more_replies":false},{"_id":"b29cb481-a45c-4c49-bfee-38b39496be23","created_at":"2019-02-06T18:25:18.571Z","updated_at":"2019-02-06T18:25:18.571Z","channel_id":"104939804","content_type":"video","content_id":"376156249","content_offset_seconds":162.871,"commenter":{"display_name":"Qiio","_id":"188064613","name":"qiio","type":"user","bio":"[ITA//ENG//SPA] Rising Streamer full of mad ideas |◔◡◉|","created_at":"2017-12-30T20:08:25.700146Z","updated_at":"2019-02-20T17:50:48.904111Z","logo":"https://static-cdn.jtvnw.net/jtv_user_pictures/f2106422-63b5-4c2c-b3c1-f0002a49a0b2-profile_image-300x300.jpeg"},"source":"chat","state":"published","message":{"body":"PepoCheer PartyParrot","fragments":[{"text":"PepoCheer PartyParrot"}],"is_action":false,"user_badges":[{"_id":"premium","version":"1"}],"user_color":"#DAA520"},"more_replies":false},{"_id":"a075d861-1c60-4827-a422-0d5d00b13aaa","created_at":"2019-02-06T18:25:33.871Z","updated_at":"2019-02-06T18:25:33.871Z","channel_id":"104939804","content_type":"video","content_id":"376156249","content_offset_seconds":178.171,"commenter":{"display_name":"Eclips3tv","_id":"177243225","name":"eclips3tv","type":"user","bio":null,"created_at":"2017-10-10T18:35:05.378892Z","updated_at":"2019-02-20T19:22:12.214121Z","logo":"https://static-cdn.jtvnw.net/jtv_user_pictures/e4263564-6ab2-47fd-a524-c6f280cda2cb-profile_image-300x300.jpeg"},"source":"chat","state":"published","message":{"body":"heddo :)","emoticons":[{"_id":"1","begin":6,"end":7}],"fragments":[{"text":"heddo "},{"text":":)","emoticon":{"emoticon_id":"1","emoticon_set_id":""}}],"is_action":false,"user_badges":[{"_id":"vip","version":"1"},{"_id":"subscriber","version":"6"},{"_id":"bits","version":"1000"}],"user_color":"#00FF7F"},"more_replies":false},{"_id":"f02243ba-7109-4561-9fcf-251ea8a3ff76","created_at":"2019-02-06T18:26:50.785Z","updated_at":"2019-02-06T18:26:50.785Z","channel_id":"104939804","content_type":"video","content_id":"376156249","content_offset_seconds":255.085,"commenter":{"display_name":"golfarn","_id":"154985355","name":"golfarn","type":"user","bio":null,"created_at":"2017-04-28T22:48:12.649571Z","updated_at":"2019-02-20T22:32:12.696331Z","logo":"https://static-cdn.jtvnw.net/jtv_user_pictures/88c320dd-c279-42a2-abb1-3509139b43aa-profile_image-300x300.jpeg"},"source":"chat","state":"published","message":{"body":"HEJOOO nymnOkay","emoticons":[{"_id":"934675","begin":7,"end":14}],"fragments":[{"text":"HEJOOO "},{"text":"nymnOkay","emoticon":{"emoticon_id":"934675","emoticon_set_id":""}}],"is_action":false,"user_badges":[{"_id":"subscriber","version":"0"},{"_id":"bits-charity","version":"1"}],"user_color":"#FB00FF"},"more_replies":false},{"_id":"93a38c2f-93f3-4fea-b580-4a322e790897","created_at":"2019-02-06T18:27:00.282Z","updated_at":"2019-02-06T18:27:00.282Z","channel_id":"104939804","content_type":"video","content_id":"376156249","content_offset_seconds":264.582,"commenter":{"display_name":"enett_","_id":"169870938","name":"enett_","type":"user","bio":null,"created_at":"2017-08-14T17:12:32.948781Z","updated_at":"2019-02-16T21:11:19.872686Z","logo":"https://static-cdn.jtvnw.net/jtv_user_pictures/d6df7b53-6f66-4d4f-b6db-ea28714c17df-profile_image-300x300.jpg"},"source":"chat","state":"published","message":{"body":"HEJOOO","fragments":[{"text":"HEJOOO"}],"is_action":false},"more_replies":false},{"_id":"db8ccd92-898a-4a45-917e-a338739af461","created_at":"2019-02-06T18:27:34.269Z","updated_at":"2019-02-06T18:27:34.269Z","channel_id":"104939804","content_type":"video","content_id":"376156249","content_offset_seconds":298.569,"commenter":{"display_name":"Eclips3tv","_id":"177243225","name":"eclips3tv","type":"user","bio":null,"created_at":"2017-10-10T18:35:05.378892Z","updated_at":"2019-02-20T19:22:12.214121Z","logo":"https://static-cdn.jtvnw.net/jtv_user_pictures/e4263564-6ab2-47fd-a524-c6f280cda2cb-profile_image-300x300.jpeg"},"source":"chat","state":"published","message":{"body":"apex? PartyParrot","fragments":[{"text":"apex? PartyParrot"}],"is_action":false,"user_badges":[{"_id":"vip","version":"1"},{"_id":"subscriber","version":"6"},{"_id":"bits","version":"1000"}],"user_color":"#00FF7F"},"more_replies":false},{"_id":"469de973-b78e-4485-84e9-3804fca209f9","created_at":"2019-02-06T18:27:43.636Z","updated_at":"2019-02-06T18:27:43.636Z","channel_id":"104939804","content_type":"video","content_id":"376156249","content_offset_seconds":307.936,"commenter":{"display_name":"Qiio","_id":"188064613","name":"qiio","type":"user","bio":"[ITA//ENG//SPA] Rising Streamer full of mad ideas |◔◡◉|","created_at":"2017-12-30T20:08:25.700146Z","updated_at":"2019-02-20T17:50:48.904111Z","logo":"https://static-cdn.jtvnw.net/jtv_user_pictures/f2106422-63b5-4c2c-b3c1-f0002a49a0b2-profile_image-300x300.jpeg"},"source":"chat","state":"published","message":{"body":"PartyParrot","fragments":[{"text":"PartyParrot"}],"is_action":false,"user_badges":[{"_id":"premium","version":"1"}],"user_color":"#DAA520"},"more_replies":false},{"_id":"607eb9d8-6b66-4a0a-b3bd-b70044fdc5ab","created_at":"2019-02-06T18:27:57.206Z","updated_at":"2019-02-06T18:27:57.206Z","channel_id":"104939804","content_type":"video","content_id":"376156249","content_offset_seconds":321.506,"commenter":{"display_name":"definitelyhonestlynotfeta","_id":"218337485","name":"definitelyhonestlynotfeta","type":"user","bio":null,"created_at":"2018-05-03T21:18:24.089913Z","updated_at":"2019-02-19T19:46:13.654084Z","logo":"https://static-cdn.jtvnw.net/jtv_user_pictures/38793c5a-d3a2-41e4-b345-21c120a3ff8c-profile_image-300x300.jpg"},"source":"chat","state":"published","message":{"body":"love dat ponytail still","fragments":[{"text":"love dat ponytail still"}],"is_action":false,"user_badges":[{"_id":"vip","version":"1"},{"_id":"subscriber","version":"6"}],"user_color":"#FF7300"},"more_replies":false},{"_id":"3407e5b5-5a57-4d74-84a8-05a89c07194c","created_at":"2019-02-06T18:27:57.533Z","updated_at":"2019-02-06T18:27:57.533Z","channel_id":"104939804","content_type":"video","content_id":"376156249","content_offset_seconds":321.833,"commenter":{"display_name":"Eclips3tv","_id":"177243225","name":"eclips3tv","type":"user","bio":null,"created_at":"2017-10-10T18:35:05.378892Z","updated_at":"2019-02-20T19:22:12.214121Z","logo":"https://static-cdn.jtvnw.net/jtv_user_pictures/e4263564-6ab2-47fd-a524-c6f280cda2cb-profile_image-300x300.jpeg"},"source":"chat","state":"published","message":{"body":"Queeen Ari PogChamp","emoticons":[{"_id":"88","begin":11,"end":18}],"fragments":[{"text":"Queeen Ari "},{"text":"PogChamp","emoticon":{"emoticon_id":"88","emoticon_set_id":""}}],"is_action":false,"user_badges":[{"_id":"vip","version":"1"},{"_id":"subscriber","version":"6"},{"_id":"bits","version":"1000"}],"user_color":"#00FF7F"},"more_replies":false},{"_id":"d343ea31-abd9-41c2-9872-1f60cf26357b","created_at":"2019-02-06T18:28:01.029Z","updated_at":"2019-02-06T18:28:01.029Z","channel_id":"104939804","content_type":"video","content_id":"376156249","content_offset_seconds":325.329,"commenter":{"display_name":"samuvaa","_id":"126636072","name":"samuvaa","type":"user","bio":null,"created_at":"2016-06-12T20:17:24.475086Z","updated_at":"2018-12-06T08:11:20.127314Z","logo":"https://static-cdn.jtvnw.net/user-default-pictures/0ecbb6c3-fecb-4016-8115-aa467b7c36ed-profile_image-300x300.jpg"},"source":"chat","state":"published","message":{"body":"hello","fragments":[{"text":"hello"}],"is_action":false},"more_replies":false}]]

Here is the mapping I'm doing, but it doesn't seem to be mapping over everything.
getComments(){
if(!this.state.value)
{
  const msg = 'This worked...';
}
else{
   let api = 'https://api.twitch.tv/v5/videos/'+ this.state.value +'/comments?client_id='+ this.state.cid +'&cursor='+this.state.after+'&limit=10000';
   fetch(api, {
     method: 'get',
     headers: {"Client-ID": this.state.cid}
   })
   .then((response) => response.text())
     .then((responseText) => {
       // add response untill you get all results
       if(responseText){
          //store array of response objects
          let next = JSON.parse(responseText)._next;

          if(next){
            this.setState({
             hits : [...this.state.hits, JSON.parse(responseText).comments],
             after : next });

             this.getComments()
          }
          else{
            this.mergeArrays(this.state.hits);
          }
       } else {

          return ;
       }

    });
  }
}

mergeArrays(arrays){
  const flattened = [].concat(...arrays);
  this.setState({
    hits : flattened
  })
}

     { hits && hits.comments && hits.comments.length !== 0 ?
          hits.comments.map(hit =>
            [{this.convertSeconds(hit.content_offset_seconds)}] - {hit.message.body}
          )
          :

No Comments Found

      }

I'm trying to get a full list of all the contents (objects) in the array.  Any help would be appreciated.
In this instance 'hit' is the state containing the multi-dimensional array
Thanks


text:
Q: What is Reset(handle,1)? I came across this code of Reset(elfhandle,1) and I don't know what the second input of 1 does. What does the second input of Reset specify?

A: The second parameter in the  System.Reset function is the record size to be read.
You can find more info in the Delphi online help.

RecSize is an optional expression that can be specified only if F is
  an untyped file. If F is an untyped file, RecSize specifies the record
  size to be used in data transfers. If RecSize is omitted, a default
  record size of 128 bytes is assumed.


text:
Q: Use another char than # in preprocessor directives Is there a way to use another char than # when defining preprocessor directives? Example:
Instead of:
#if 1
foo
#endif

Use ?, for example:
?if 1
foo
?endif

A: You have two options:

*

*Trigraphs: ??=if 1

*Digraphs: %:if 1
Both of these are 100% standard C, but at the same time considered very bad practice. However, mainstream compilers tend to warn against trigraphs but not for digraphs, so digraphs are perhaps the lesser evil.

A: There are trigraph sequences that exists to replace certain characters.  In particular, the # character can be replaced with ??=.  So the following code is valid:
??=if 1
foo
??=endif

You can't however put an arbitrary replacement in place.