text:
Q: Table generated by shiny with incorrect order This question is similiar to How adjust order output table
However, for the shiny it didn't work, only if I make it out of the shiny.
Could you help me understand why the table is being generated with the wrong order? Note from the attached image that I'm showing the table from 11/07 (Sunday) to 11/13 (Saturday), but notice that the order is wrong (figure below). It would have to show the dates from Sunday to Saturday.
Executable code below:
library(shiny)
library(shinythemes)
library(dplyr)
library(DT)

Test <- structure(list(date1 = as.Date(c("2021-11-01","2021-11-01","2021-11-01","2021-11-01","2021-11-01","2021-11-01","2021-11-01")),
                      date2 = as.Date(c("2021-10-18","2021-10-19","2021-10-20","2021-10-21","2021-10-22","2021-10-23","2021-10-24")),
                       Week = c("Monday", "Tuesday", "Wednesday", "Thursday","Friday","Saturday","Sunday"),
                      Category = c("FDE", "FDE", "FDE", "FDE","FDE","FDE","FDE"),
                       time = c(4, 6, 3, 2,3,3,4)), class = "data.frame",row.names = c(NA, -7L))

ui <- fluidPage(

    shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                      br(),
                      tabPanel("",
                               sidebarLayout(
                                   sidebarPanel(
                                       uiOutput('daterange')
                                   ),
                                   mainPanel(
                                       dataTableOutput('table')

                                   )
                               ))
    ))

server <- function(input, output,session) {

  data <- reactive(Test)

  output$daterange <- renderUI({
    dateRangeInput("daterange1", "Period you want to see:",
                   min   = min(data()$date1))
  })

  observe({updateDateRangeInput(session,"daterange1",start = NA, end = NA)})

  wk_port2eng <- data.frame(
    WeekE = c("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"),
    WeekP = c("segunda-feira", "terça-feira", "quarta-feira", "quinta-feira",  "sexta-feira", "sábado", "domingo")
  )

  data_subset <- reactive({
    req(input$daterange1)
    req(input$daterange1[1] <= input$daterange1[2])
    days <- seq(input$daterange1[1], input$daterange1[2], by = 'day')
    Test1 <- dplyr::filter(data(), date1 %in% days)
    weeks_inp <- unique(weekdays(days))
    wk <- wk_port2eng[wk_port2eng$WeekP %in% weeks_inp,]  ###  if weekday is in Portuguese in your notebook
    #wk <- wk_port2eng[wk_port2eng$WeekE %in% weeks_inp,]  ###  if weekday is in English in your notebook

    weeks_ine <- wk$WeekE
    meanTest1 <- data() %>%
      group_by(Week = tools::toTitleCase(Week), Category) %>%
      summarise(mean = mean(time, na.rm = TRUE), .groups = 'drop')
    meanTest <- meanTest1[meanTest1$Week %in% as.character(weeks_ine),]
    left_join(meanTest, wk_port2eng, by = c("Week" = "WeekE")) %>%
    arrange(match(WeekP, weekdays(input$daterange1))) %>%
    arrange(lubridate::wday(data()$date2))%>%
    select(-WeekP)

  })

  output$table <- renderDataTable({
    data_subset()
  })

}

shinyApp(ui = ui, server = server)

Output table

A: When you use match, you need to either (a) give it every possible distinct value, or (b) know that a returned NA is inherently what you want/need.
In the use of
arrange(match(WeekP, weekdays(input$daterange1)))

it is matching the values of several values again the values of just two things. You aren't telling it to sort based on a full sequence of things, you are telling R "please sort this vector of things based on two strings". You are assuming that R will infer what those two strings are, and how to project that inference onto the rest of your data.
In this case, since weekdays(input$..) only includes two days of the week, everything else in your match(.) will be NA, which is obviously broken. Had you further debugged your code and looked at the output of just match(.., weekdays(..)) (assign to some column), you would see
    left_join(meanTest, wk_port2eng, by = c("Week" = "WeekE")) %>%
      select(-WeekP) %>%
      mutate(sortcol = match(Week, weekdays(input$daterange1)))
# # A tibble: 7 x 4
#   Week      Category  mean sortcol
#   <chr>     <chr>    <dbl>   <int>
# 1 Friday    FDE          3      NA
# 2 Monday    FDE          4      NA
# 3 Saturday  FDE          3       2
# 4 Sunday    FDE          4       1
# 5 Thursday  FDE          2      NA
# 6 Tuesday   FDE          6      NA
# 7 Wednesday FDE          3      NA

for which arrange will not magically infer your needs.
Use seq on your input range.
    left_join(meanTest, wk_port2eng, by = c("Week" = "WeekE")) %>%
      select(-WeekP) %>%
      mutate(sortcol = match(Week, unique(weekdays(seq(input$daterange1[1], input$daterange1[2], by = "day")))))
# # A tibble: 7 x 4
#   Week      Category  mean sortcol
#   <chr>     <chr>    <dbl>   <int>
# 1 Friday    FDE          3       6
# 2 Monday    FDE          4       2
# 3 Saturday  FDE          3       7
# 4 Sunday    FDE          4       1
# 5 Thursday  FDE          2       5
# 6 Tuesday   FDE          6       3
# 7 Wednesday FDE          3       4

So that one reactive block should be:
  data_subset <- reactive({
    req(input$daterange1)
    req(input$daterange1[1] <= input$daterange1[2])
    days <- seq(input$daterange1[1], input$daterange1[2], by = 'day')
    Test1 <- dplyr::filter(data(), date1 %in% days)
    weeks_inp <- unique(weekdays(days))
    # wk <- wk_port2eng[wk_port2eng$WeekP %in% weeks_inp,]  ###  if weekday is in Portuguese in your notebook
    wk <- wk_port2eng[wk_port2eng$WeekE %in% weeks_inp,]  ###  if weekday is in English in your notebook

    weeks_ine <- wk$WeekE
    meanTest1 <- data() %>%
      group_by(Week = tools::toTitleCase(Week), Category) %>%
      summarise(mean = mean(time, na.rm = TRUE), .groups = 'drop')
    meanTest <- meanTest1[meanTest1$Week %in% as.character(weeks_ine),]
    left_join(meanTest, wk_port2eng, by = c("Week" = "WeekE")) %>%
      select(-WeekP) %>%
      arrange(match(Week, unique(weekdays(seq(input$daterange1[1], input$daterange1[2], by = "day")))))
  })

Producing:

BTW, this works fine as long as you are always summarizing by day-of-week, in which case weekdays(.) should always return a unique vector.


text:
Q: How to create minimalistic map for ios app How can I implement the same map as on screenshot?
I found out about custom overlays for MKMapView but I'm not sure it's a good way for change all maps.
Probably you have some ideas about this?

A: I am not familiar with if there is any better solution to achieve this.
I am using Overlays as you have mentioned in your question.
You can customize the Overlay with your own beautiful style at https://mapstyle.withgoogle.com/
You will get the JSON for the customization, include your App Key and you are ready to use in your App.
In your App
import GoogleMaps

@IBOutlet weak var viewMap: GMSMapView!
public let kMapStyle = "[{\"elementType\": \"geometry\", \"stylers\": [ { \"color\": \"#f5f5f5\" } ] },{\"elementType\": \"labels.icon\",\"stylers\": [{\"visibility\": \"on\"}]},{\"elementType\": \"labels.text.fill\",\"stylers\": [{\"color\": \"#616161\"}]},{\"elementType\": \"labels.text.stroke\",\"stylers\": [{\"color\": \"#f5f5f5\"}]},{\"featureType\": \"administrative.land_parcel\",\"elementType\": \"labels.text.fill\",\"stylers\": [{\"color\": \"#bdbdbd\"}]},{\"featureType\": \"poi\",\"elementType\": \"geometry\",\"stylers\": [{\"color\": \"#eeeeee\"}]},{\"featureType\": \"poi\",\"featureType\":\"poi.business\",\"stylers\": [{\"visibility\": \"on\"}],\"elementType\": \"labels.text.fill\",\"stylers\": [{\"color\": \"#757575\"}]},{\"featureType\": \"poi.park\",\"elementType\": \"geometry\",\"stylers\": [{\"color\": \"#e5e5e5\"}]},{\"featureType\": \"poi.park\",\"elementType\": \"labels.text.fill\",\"stylers\": [{\"color\": \"#9e9e9e\"}]},{\"featureType\": \"road\",\"elementType\": \"geometry\",\"stylers\": [{\"color\": \"#ffffff\"}]},{\"featureType\": \"road.arterial\",\"elementType\": \"labels.text.fill\",\"stylers\": [{\"color\": \"#757575\"}]},{\"featureType\": \"road.highway\",\"elementType\": \"geometry\",\"stylers\": [{\"color\": \"#dadada\"}]},{\"featureType\": \"road.highway\",\"elementType\": \"labels.text.fill\",\"stylers\": [{\"color\": \"#616161\"}]},{\"featureType\": \"road.local\",\"elementType\": \"labels.text.fill\",\"stylers\": [{\"color\": \"#9e9e9e\"}]},{\"featureType\": \"transit.line\",\"elementType\": \"geometry\",\"stylers\": [{\"color\": \"#e5e5e5\"}]},{\"featureType\": \"transit.station\",\"elementType\": \"geometry\",\"stylers\": [{\"color\": \"#eeeeee\"}]},{\"featureType\": \"water\",\"elementType\": \"geometry\",\"stylers\": [{\"color\": \"#c9c9c9\"}]},{\"featureType\": \"water\",\"elementType\": \"labels.text.fill\",\"stylers\": [{\"color\": \"#9e9e9e\"}]}]"
//YOUR JSON FOR STYLE

override func viewDidLoad() {
    super.viewDidLoad()
    do {
        viewMap.mapStyle = try GMSMapStyle(jsonString: kMapStyle)
    } catch {
        NSLog("One or more of the map styles failed to load. \(error)")
    }
}

Please let me know if this helps or you face any other issue while implementation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set variable by just mentioning the number on command line I want to make a script where I can mention the matchid in argument and then it selects to value of variable like below
1=IND vs PAK
2=SA vs SL
3=AUS vs ENG

So like when I run the script as
./match.sh --matchid 2

It gives output as
SA vs SL

Edit:
what if instead of output I have to assign it to a variable?

A: Sounds like you want to refer to a variable by its name stored in another variable. Here's a question I've found on Stack Overflow.
In a nutshell:
$ FOO='value of foo'
$ BAR='value of bar'
$ NAME=FOO
$ echo ${!NAME}
value of foo

A: A small example of catching command line parameters that you can build from:
#!/bin/bash
firstparam=$1
secondparam=$2
if [[ $firstparam = "--matchid" ]]; then
   echo -e "You selected to match the id\r"
fi

case $secondparam in
    1) echo -e "Samson VS Goliath\r"
    ;;
    2) echo -e "Peanuts VS GArfield\r"
    ;;
esac

Just use in the prompt like: yourscript.sh --matchid 1


text:
Q: Spivak - Calculus. Chapter 1 Problem 21 - what is the point of the theorem?
I proved it but I don't understand what was the point of proving it.
I can rephrase this theorem:
If you have a rectangle with sides lengths $x_0$ and $y_0$ and you want to lengthen or shorten each side in such way that area of the rectangle changes by no more than $\epsilon$, then you can do so by changing $x_0$ side by less than $\text{min}(1, \frac{\epsilon}{2(y_0 + 1)})$ and $y_0$ by less than $\frac{\epsilon}{2(x_0 + 1)}$.
Spivak Answers book says "See chapter 5" which is about limits, so I would guess it's a way for us ot define $\delta(\epsilon)$ to prove that $\forall \epsilon \exists \delta$ something something.

A: Without going into too much detail (which will come in chapter 5), this is proving that the limit of the product is the product of the limits.


text:
Q: (Answerd by self)Swift array returns 0 count in function numberofRows(in tableView but anywhere else it returns correct amount of array.count I have a project that loads JSON file from internet and stores it in an array and a dictionary. When i print the count of the Array or Dict in viewDitload or viewDidDisappear i get a correct count of 50 thats in the JSON file. But in the numberOfRows and objectForValue calls for the tableViewDataSource it returns 0 for the count. i am overlooking something but at opening and closing of window there is information in the array but when the tableView is reloading somehow the array is empty. Here is my code any help is really appreciated
import Cocoa

class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {

    var coursesDict = [String: Course]()
    var coursesArray = [Course]()

    @IBAction func refreshTable(_ sender: Any) {
        table.reloadData()
    }
    @IBOutlet weak var table: NSTableView!

    func numberOfSectionsInTableView(tableView: NSTableView) -> Int {
        return 1
    }

    func numberOfRows(in tableView: NSTableView) -> Int {

        let numOfRows = coursesArray.count
        print(numOfRows)

        return numOfRows

    }

    func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
        return coursesArray[row]
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        if let data = UserDefaults.standard.data(forKey: "courses"),
            let savedCourses = NSKeyedUnarchiver.unarchiveObject(with: data) as? [String: Course] {
            self.coursesDict = savedCourses
            loadDataFromURL()

            self.coursesArray = Array(coursesDict.values)
            print(coursesDict.count, " appLaunch")
        } else {
            print("There is an issue")
        }
    }

        override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    override func viewDidDisappear() {
        let encodedData = NSKeyedArchiver.archivedData(withRootObject: coursesDict)
        UserDefaults.standard.set(encodedData, forKey: "courses")
        print(coursesDict.count, "viewUnload")
    }

    func loadDataFromURL() {
        // Fetch URL
        let url = URL(string: "https://www.apple.com/nl/today/static/data/hub/1101000001001110001.json")!

        // Load Data
        let data = try! Data(contentsOf: url)

        // Deserialize JSON
        let json = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject]

        let coursesJSON = json?["courses"] as? [AnyObject]

        for object in coursesJSON! {
            let id = object["id"] as! String
            if coursesDict[id] == nil {
                let name = object["shortName"] as! String
                let program = object["programName"] as! String
                let shortDescription = object["shortDesc"] as! String
                let mediumDescription = object["mediumDesc"] as! String
                let longDescription = object["longDesc"] as! String
                let imageURL = object["image"] as! String

                let tempCourse = Course(id: id, name: name, program: program, shortDescription: shortDescription, mediumDescription: mediumDescription, longDescription: longDescription, imageURL: imageURL)

                coursesDict[id] = tempCourse
            }
        }
        print(coursesDict.count, "loadURL")
    }

}

I even have a button on my view that reloads the tableView in case the information is not loaded before the tableView reloads automaticaly

A: The problem was not i my code. The problem was in the fact that i had two instances of the viewController in my Xib so when i hard coded things in to the array it was working because both instances would have that info but the viewDidload from the second viewcontroller was never calded because it was not connected to to any view

A: I guess that numberOfRows is being called before you retrieve the data from the internet. One way to solve that is by setting a listener in coursesArray, try replacing this:
var coursesArray: [Course] = []

With this:
var coursesArray: [Course] = [] {
    didSet {
        table.reloadData()
    }
}

A: func loadDataFromURL() {
        // Fetch URL
        let url = URL(string: "https://www.apple.com/nl/today/static/data/hub/1101000001001110001.json")!

        // Load Data
        let data = try! Data(contentsOf: url)

        // Deserialize JSON
        let json = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject]

        let coursesJSON = json?["courses"] as? [AnyObject]

        for object in coursesJSON! {
            let id = object["id"] as! String
            if coursesDict[id] == nil {
                let name = object["shortName"] as! String
                let program = object["programName"] as! String
                let shortDescription = object["shortDesc"] as! String
                let mediumDescription = object["mediumDesc"] as! String
                let longDescription = object["longDesc"] as! String
                let imageURL = object["image"] as! String

                let tempCourse = Course(id: id, name: name, program: program, shortDescription: shortDescription, mediumDescription: mediumDescription, longDescription: longDescription, imageURL: imageURL)

                coursesDict[id] = tempCourse
table.reloadData()
            }
        }
        print(coursesDict.count, "loadURL")
    }

}


text:
Q: Java 8 Lambda expression - Method overloading doubts I'm trying to learn Lambda expressions,
interface MathOperartor has operate() overloaded for types int and float, I'm sure this should be possible to do using Lambda expressions, but can't quite seem to figure out what the issue is here:
public static void main(String[] args) {
    LambdaLearning lb = new LambdaLearning();

    MathOperartor add = (a , b )->  a + b;  // error: The target type of this expression must be a functional interface
    MathOperartor sub = (a , b) -> a - b;   // same error
    MathOperartor mul = (a , b) -> a * b;   //  ''
    MathOperartor div = (a , b) -> a / b;   //  ''

    System.out.println(lb.operate(10, 15, add));
    System.out.println(lb.operate(10.5f, 15.5f, sub));
    System.out.println(lb.operate(10, 15, mul));
    System.out.println(lb.operate(10, 15, div));

}

interface MathOperartor{
    public Object operate(int a, int b);
    public Object operate(float a, float b);
}

private Object operate(int a, int b, MathOperartor math){
    return math.operate(a,b);
}
private Object operate(float a, float b, MathOperartor math){
    return math.operate(a,b);
}

Please let me know what I'm doing wrong here and suggest a fix...
Update:
Ok, so I understood the concept of Functional Interface, My question was also about achieving what I was trying to do in the above code and I found couple of ways to do it.
Thank you every one for your valuable answers!

A: A functional interface must is a SAM interface:

a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.

your interface has declared 2 abstract methods that the lambda expression don't know where to going, and the lambda expression is an instance of that interface which means that must implements all the abstract methods declared in the interface. but you can adding default method to solve your problem in this case, for example:
interface MathOperartor{
  //it also can be removed, since a int can cast to a float automatically
  default Object operate(int a, int b){
     return operate((float)a, (float)b);
  }
  public Object operate(float a, float b);
}

A: Generally the other answers are right, that a @FunctionalInterface is one that has a single abstract method, besides those that are declared in Object. This is still legal:
    @FunctionalInterface
    static interface Testable {

       public abstract String toString();

       public abstract void test();
    }

A: The target for lambda in the functional interface which is also known as SAM (Single Abstract Method) Interface.
Following is how you can run your example:
@FunctionalInterface
public interface MathOperator<T> {
     T operate(T a,T b);
}

public class MathOperations {
    public static void main(String[] args) {

        MathOperator<Integer> add = (a, b) -> a + b;
        MathOperator<Integer> sub = (a, b) -> a - b;

        System.out.println(add.operate(1, 2));
        System.out.println(sub.operate(2, 1));

    }

}

Hope it will help you

A: Functional Interface can have a single abstract method not more than that.

A: An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface.
Functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.
Example:
@FunctionalInterface
public interface SimpleFuncInterface {
  public void doWork();
}

But an interface can have one abstract method but any number of default methods and the interface would still be called an functional interface.
Example:
So, your code will be converted to:
interface MathOperartor {

    default Object operate(int a, int b) {
        return operate((float) a, (float) b);
    }

    public Object operate(float a, float b);

}

Instances of functional interfaces can be created with lambda expressions, method references, or constructor references.
However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.

A: Basically, your interface can have only one method. You can't overload them

*

*What is use of Functional Interface

*Oracle docs

*short dzone tutorial

*Oracle lambda expressions


text:
Q: Python change a single character of a string I have a string named userName in my program. It holds a users name and I want to be able to change it's first letter to a capital if not already.
For example if userName = "john"
I want it to change too "John"
I attempted this:
userClass[1] = userClass[1].upper()

That does not work.
Any ideas?


text:
Q: IBM Worklight - Adapter procedure response returns "zero results" from Google Places I am getting status "ZERO RESULTS" when I invoke HTTP Adapter using Indian latitude and longitude to search for any service like food, malls etc.
Here is my adapter implementation:
 function getGooglePlaces(location,name) {

    var input = {
        method : 'get',
        returnedContentType : 'json',
        path : 'maps/api/place/search/json',
        headers: {
            Host: 'maps.googleapis.com'
        },
        parameters : {
            'key'       :   My Key,
            'location'  :  location,
            'radius'    :   '10000',
            'sensor'    :   'false',
            'name'      :  name
        }
    };

    var response = WL.Server.invokeHttp(input);
    return response;

}

}
The JSON response for indian coordinates.
results is the array of places searched
{
 "html_attributions": [
  ],
 "isSuccessful": true,
 "responseHeaders": {
  "Alternate-Protocol": "443:quic",
  "Cache-Control": "public, max-age=300",
  "Content-Type": "application\/json; charset=UTF-8",
  "Date": "Wed, 12 Feb 2014 15:06:33 GMT",
  "Expires": "Wed, 12 Feb 2014 15:11:33 GMT",
  "Server": "mafe",
  "Transfer-Encoding": "chunked",
  "Vary": "Accept-Language",
  "X-Frame-Options": "SAMEORIGIN",
  "X-XSS-Protection": "1; mode=block"
   },
  "responseTime": 609,
  "results": [
   ],
   "status": "ZERO_RESULTS",
   "statusCode": 200,
   "statusReason": "OK",
   "totalTime": 609
   }

A: I have used the following and got a valid response, using a Worklight adapter.

*

*Note that I passed name and location as part of the parameters object and not like you did (just for the sake of simplification)

*I added a type parameter for "restaurant"

*I increased the radius
With the above, I got results.
Looks to me like this is a matter of tweaking the request parameters. Nothing related to Worklight adapters here, as it works.

*

*https://www.google.com/search?q=google+places+returns+zero+results
GooglePlaces-impl.js
function getPlaces() {
    var input = {
            method : 'get',
            returnedContentType : 'json',
            path : 'maps/api/place/search/json',
            headers: {
                Host: 'maps.googleapis.com'
            },
            parameters : {
                'key'       : 'make-sure-to-place-here-your-SERVER-KEY-generated-by-Google-GCM-console',
                'location'  : '27.173033, 78.042133',
                'radius'    : '30000',
                'sensor'    : 'false',
                'name'      : 'Taj Mahal',
                'type'      : 'restaurant',
            }
        };

        var response = WL.Server.invokeHttp(input);
        return response;
}

Procedure response
{
   "html_attributions": [
   ],
   "isSuccessful": true,
   "responseHeaders": {
      "Alternate-Protocol": "443:quic",
      "Cache-Control": "public, max-age=300",
      "Content-Type": "application\/json; charset=UTF-8",
      "Date": "Fri, 14 Mar 2014 05:45:41 GMT",
      "Expires": "Fri, 14 Mar 2014 05:50:41 GMT",
      "Server": "mafe",
      "Transfer-Encoding": "chunked",
      "Vary": "Accept-Language",
      "X-Frame-Options": "SAMEORIGIN",
      "X-XSS-Protection": "1; mode=block"
   },
   "responseTime": 662,
   "results": [
      {
         "geometry": {
            "location": {
               "lat": 27.175015,
               "lng": 78.042155
            }
         },
         "icon": "http:\/\/maps.gstatic.com\/mapfiles\/place_api\/icons\/generic_business-71.png",
         "id": "dcc9586b99ab0f0471fccecbe2dbb40fdc1fc2b5",
         "name": "Taj Mahal",
         "photos": [
            {
               "height": 853,
               "html_attributions": [
               ],
               "photo_reference": "CnRnAAAAojrNNKpH2yqjmiph_kNBxiT5DaK_g3N05YtE_mPP5tBrYD8XjyAAz_xEvWAJymfGOeeOTlVgzFUxUeOMQspvoPGogDQyWomDeZsNP7XEW3JsmzmYakDk_vyJBwajiamhluypx6rCDqDCnBWb6JnCLBIQRuBibftSN9xruu2eeZEm5xoUksG5kyFbtZULWpZceNvNhyl72tQ",
               "width": 1280
            }
         ],
         "rating": 4.6,
         "reference": "CnRrAAAA8n6I_Dnlm9UzwTiaTntjcxR-FysL5Ya26Fdcsdb48XOIxiJDGdd3AiK6iUUti41d1BQ1XnBfZoVMKWZ5QOyVZAW8QyH-xqSY8eaQXuxH0atjzXtuaplht-ww76JtbxQLkJ4SUtFrmrs7ZjmZn-_RhBIQmYTB0_yGd_4hm2bHoIKt5xoULaBq-FsZo51jFdxLV377nHM0cCI",
         "types": [
            "establishment"
         ],
         "vicinity": "Agra"
      },
     ...
     ...
     "status": "OK",
       "statusCode": 200,
       "statusReason": "OK",
       "totalTime": 1088
    }


text:
Q: Infer class generics when using `instanceof` Assuming we have the following code:
class Foo<T = number> {
  foo: T;

  constructor(foo: T) {
    this.foo = foo;
  }
}

const F: typeof Foo<number> = Foo;

let f: unknown;

if (f instanceof F) {
  f.foo; // 'any', why is this not a 'number'?
}

Playground
Why is f of type Foo<any> and not Foo<number>? And can I make this work only using instanceof or do I have to use a type predicates function?

A: You could use typeguards e.g
function isF(isF: unknown): isF is Foo<number>{
  return isF instanceof F;
}

if (isF(f)) {
  f.foo; // Foo<number>
}

A: It is not safe to assume that f is of type Foo<number> by checking f instanceof F. The instanceof operator does not care about generics as they are erased at runtime.
We can instantiate f with new Foo("a string") without an issue. f instance F will return true, even though f is of type Foo<string>.
const F: typeof Foo<number> = Foo;

let f: unknown = new Foo("a string")

console.log(f instanceof F)
// true

if (f instanceof F) {
  console.log(f.foo);
  // "a string"
}

The only safe way to check if f is Foo<number> is to use a type guard which both checks if f is instanceof Foo and typeof f.foo === "number".
const isFooNumber = (arg: unknown): arg is Foo<number> => {
  return arg instanceof Foo && typeof arg.foo === "number"
}

if (isFooNumber(f)) {
  console.log(f.foo);
}

Playground

A: As @TobiasS. and @MuratKaragöz pointed out, the instanceof operator can not distinguish Foo and F at runtime, hence the generics are not passed down.
There are two paths to fixing this:
Using instanceof only
Unsafe at runtime
Instead of typing F with typeof Foo<number> as I did. We can create a new constructor type which return an instance of Foo<number>:
class Foo<T = number> {
  foo: T;

  constructor(foo: T) {
    this.foo = foo;
  }
}

const F: new (...args: ConstructorParameters<typeof Foo<number>>) => Foo<number> = Foo

let f: unknown = new F(0)

if (f instanceof F) {
  f.foo; // number
}

This is a very simple way of typing F, but it IS unsafe at runtime because it tricks Typescript into thinking Foo and F are not the same class, even thought (new Foo()) instanceof F returns true at runtime (see the safer method below).
Although, this trick can still be useful in few niche cases (I personally ended up using a combination of the safe and unsafe methods).
Safe at runtime
This is most likely the preferred solution, as it does not suffer from the same caveat as the unsafe solution above.
Put simply, we can create a new class F which extends Foo<number>:
class Foo<T = number> {
  foo: T;

  constructor(foo: T) {
    this.foo = foo;
  }
}

class F extends Foo<number> {
  constructor(...args: ConstructorParameters<typeof Foo<number>>) {
    super(...args)
  }
}

let f: unknown;

if (f instanceof F) {
  f.foo; // number
}

This IS safer because (new Foo()) instanceof F will return false at runtime, on the opposite of the unsafe solution.
Using type guards
See @TobiasS.'s and @MuratKaragöz's answers.

*

*https://stackoverflow.com/a/74626164/8990411

*https://stackoverflow.com/a/74626118/8990411


text:
Q: Missing Closing Tag on Dynammically Generated React Component I'm building a react component with a render function that should return a list of posts that will be styled with element-ui's layout scheme.  The element returned should end up looking something like this:
render(){
   return <Layout.Row gutter="20">
          <Layout.Col span="6"><Post id=1/></Layout.Col>
          <Layout.Col span="6"><Post id=2/></Layout.Col>
          <Layout.Col span="6"><Post id=3/></Layout.Col>
          <Layout.Col span="6"><Post id=4/></Layout.Col>
        </Layout.Row>
}

I'm trying to achieve this by mapping the posts listed in state to columns.
Edit: updated class to remove typo and updated error message
class PostList extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            posts: [{id: 1}, {id: 2}]
        };
    }
    render(){
        let posts = this.state.posts.map((post, index)=>{
            var el = <Layout.Col span="6">{post.id}</Layout.Col>;
            var result
            if(index%4===0){
                result=<Layout.Row>{el}

            }
            if((index+1)%4===0){
                result={el}</Layout.Row>
            }
            return result
        });
        return (

{posts}

        );
    }
}

But this doesn't compile:
 Line 20:  Parsing error: Unterminated regular expression

  18 |      }
  19 |      if((index+1)%4===0){
> 20 |          result={el}</Layout.Row>
     |                       ^
  21 |      }
  22 |      return result
  23 |  });

Can anyone help me figure out how to achieve this format using React?

A: You need to wrap the column components in rows :
let posts = this.state.posts.map((post, index)=>{
            var el = <Layout.Col span="6">{post.id}</Layout.Col>; //here col to Col
            if(index%4===0){
                return <Layout.Row>{el}</Layout.Row> //here

            }
            if((index+1)%4===0){
                return <Layout.Row>{el}</Layout.Row> //and here
            }

        });

EDIT:
Following comment, easiest way to both simplify your code and fix your error might be:
let posts = <Layout.Row>
  {
    this.state.posts.map((post)=> (
      <Layout.Col span="6">{post.id}</Layout.Col>
    ))
  }
  </Layout.Row>;

A: you have a typo:
 <Layout.Col span="6">{post.id}</Layout.col>;

should be
 <Layout.Col span="6">{post.id}</Layout.Col>;

A: I suppose the problem is that you wrote </Layout.col> instead of </Layout.Col>.
EDIT:
Based on your comments, the code should look something like this:
render() {
  const { posts } = this.state;
  const cols = posts.map(post => <Layout.Col span="6">{post.id}</Layout.Col>);
  const columnsPerRow = 4;
  const rows = [];
  for (let i = 0; i < cols.length; i += columnsPerRow) {
    let cols = cols.slice(i, i + columnsPerRow);
    rows.push(<Layout.Row>{cols}</Layout.Row>);
  }
  return
{rows}
;
}


text:
Q: How to subtract two vectors' elements one by one? I have these two vectors:
first<-c(1,2,2,2,3,3,4)
second<-c(1,2)

now I want first without second elements to get result like this:(2,2,3,3,4); indeed,
I don't want all 2s removed and only want one by one subtracting.
I have tried this (from here):
'%nin%' <- Negate('%in%')
first<-first[first %nin% second]

but it removes all 2s from first and gives this result: (3,3,4)
How can I do that?

A: Try this:
first[-sapply(second, function(x) head(which(is.element(el=first, x)), 1))]
## [1] 2 2 3 3 4

This won't work if you have duplicate elements in second. In that case, I think you'll need a loop:
first2 <- first
for(i in seq_along(second)) {
    first2 <- first2[-head(which(is.element(el=first2, second[i])), 1)]
}
first2
# [1] 2 2 3 3 4

first2 <- first
second <- c(1,2,2)
for(i in seq_along(second)) {
    first2 <- first2[-head(which(is.element(el=first2, second[i])), 1)]
}
first2
## [1] 2 3 3 4

A: How about
second<-c(1, 2)
first[-match(second, first)]
## [1] 2 2 3 3 4

For a more complected cases, here's an option using <<-
second <- c(1, 2, 2)
invisible(lapply(second, function(x) first <<- first[-match(x, first)]))
first
## [1] 2 3 3 4


text:
Q: Shader execution after writing to gl_FragDepth Given a fragment shader that modifies the original depth of the fragment and writes to gl_FragDepth.
Will the code after writing to gl_Fragdepth still be executed if the depth test fails at that point?
Example:
in float depth;
layout(depth_less) out float gl_FragDepth;
void main() {
  float newDepth = depth - someModification;
  gl_FragDepth = newDepth;
  A();
}

Will A be executed if newDepth is greater than the current value in gl_FragDepth?
If so, what would be the alternative to stop the shader from doing unneccessary computations in A - without using a custom depth buffer?

A: In your example, A() will always be executed as long as it contributes to any output value, e.g. a color (otherwise, the compiler will remove it as an optimization). The depth test is a per-sample operation usually performed after the fragment shader. Under special circumstances, it is possible to do this test before the fragment shader, but this requires that the fragment shader itself does not write to gl_FragDepth.
Is the modification you do a uniform one or is it different for each fragment? If it is uniform, you could do it in a geometry shader - just apply the depth modification to the whole primitive. Then you could use the early-z. If it's on per-fragment basis, you could try binding the current depth render target as a readonly image, fetch the stored depth value, perform a manual comparison in your shader and discard the fragment if it fails. However, I neither know whether you can actually bind the currently bound framebuffer's render targets as images, even as readonly, nor whether this would be more or less performant than just executing A().


text:
Q: System.Net.Mail.MailMessage does not release memeory after sending I'm developing an EmailService to read the new mails of Emails table(Sql). This is a Windows Service written in C# and .NET 4.0. Every email record has a size of mail body measured is about 12kb...after sending every an email my service calls MailMessage.Disposed() method and set SmtpClient to null. But the memory of my Service keeps increasing and not back to the started Service (takes about 7mb system memory) even no new email is read. It often consumses 70mb - 120mb system memory and this is so weird :(
Do you have any solution to decrease the memory for my case above?
Thank you and best regards,

A: I've seen this before, where system resources were not actually released until the .exe was closed (back in the 2.0 days with some windows forms programming).

A: You should use using for the SmtpClient and the MailMessage objects:
using(SmtpClient client = new SmtpClient("ipaddress")){
using(MailMessage message = new MailMessage()){

//Do something to fill the message...

client.Send(message);

}

}


text:
Q: At what point do the Input Parameters of a WCF Workflow Service get instantiated/set? I have a very simple XOML file with a single Code Activity inside the ReceiveActivity Handler.
The ReceiveActivity is mapped to an Interface called IRulesEngineService wih a single method on it.
void DoWork(int i);

the input parameter on the interface method is mapped to a property on the Xoml called I

I'm now trying to attempt to step into the Workflow Life Cycle at a point:

*

*just before the first (and in this case only) Code Activity gets executed

*just after the i parameter has been assigned to I on my Workflow.

I've tried overriding all the various methods and events on the XOML but in all cases I is always zero in all the events and overrides I've tried. And then is correctly set to the passed in Parameter within the first Code Activity. e.g. Imagine I passed in 8 to the ClientSide DoWork call.
    public int I {get; set;}

    protected override void Initialize(System.IServiceProvider provider)
    {
        I = I*10; //I is still 0
        base.Initialize(provider);
        I = I * 10; //I is still 0
    }

    //Event on Xoml Designer
    private void Pinnacle_Initialized(object sender, EventArgs e)
    {
        I = I * 10; //I is still 0
    }

    //Event on Xoml Designer
    private void receiveActivity1_OperationValidation(object sender, OperationValidationEventArgs e)
    {
        I = I * 10; //I is still 0
    }

    protected override void OnActivityExecutionContextLoad(IServiceProvider provider)
    {
        I = I * 10; //I is still 0
        base.OnActivityExecutionContextLoad(provider);
        I = I * 10; //I is still 0
    }

    private void codeActivity1_ExecuteCode(object sender, EventArgs e)
    {
        DataAccess.WriteToDummyData(ConnectionString, "Pinnacle From Code Activity " + I);
        //I is now magically '8' what the heck set this?
    }

Anyone got any ideas on where in the Workflow Lifecycle the instantiating/binding/setting of these parameters occurs.

A: Looking at the .NET framework source code, it's not possible to access your data inputs within the code activity before the execution. in the ReceiveActivity class in the System.Workflow.Activities namespace there's a exact point where the inputs are populated. I've taken the class source from this link
See the image below:

As you can see in the picture inputs are populated at this point:
this.OperationHelper.PopulateInputs(this, requestContext.Inputs);

The instruction above is called just before the ReceiveActivity class executes the activity. At this stage I don't think there's a public event that can be subscribed to manipulate your data before your codeActivity1_ExecuteCode gets executed.
Hope it helps.


text:
Q: Glossaries package incompatible with documentclass{lni} I have an issue with the latex glossary package, in that it is incompatible with the lni documenttype.
The following code
\documentclass{lni}
\usepackage[utf8]{inputenc}
\usepackage[]{glossaries}
\makeglossaries
\title{test}
\author{author}
\date{December 2020}
\begin{document}
\maketitle
\section{Introduction}
\end{document}

gets me especially this error:
You can't use `\let' after \the.

\new@ifnextchar #1#2#3->\let
\reserved@d = #1\def \reserved@a {#2}\def \rese...
l.15 \end{document}

I'm forgetting what you said and using zero instead.

as soon as I use anything that is not lni, or remove the \makeglossaries, it works no problem.
I am using the pdftex compiler.
Any ideas?

A: The class redefines \year to be used an normal macro, which is not a good idea, because its value is used by packages like glossaries. A workaround for your problem is to set the year explicitly in your document, e.g. \year=2020 and to revert \year to its original definition (which is saved as \@rigyear) after it has been used, i.e. after \maketitle:
\maketitle
\makeatletter\let\year\@rigyear\makeatother
...


text:
Q: Python- Count list of items in a text file I am new to Python. I am struggling to write the code to get the count of list of items
keywords = ['bed', 'slot', 'display pane', 'graph', 'bedsides', 'multiviewer display', 'bed1']

In a text file containing the below sample text.
 Verify that the Respiration waveform size can be modified.
 Verify that changed Respiration waveform size is updated in Central Station.
 Verify that the Respiration Lead Selection settings are displayed as read-only for the Telemetry Bed at the Central Station.
 Verify that the NBP Auto mode settings are displayed for the Telemetry Bed at the Central Station.
 Verify that the NBP cuff size settings are displayed as read-only for the Telemetry Bed at the Central Station.
 Verify that the ECG lead analysis options displayed for the Telemetry Bed at the Central Station include the following:
 Verify that the adjustment of the ECG Lead Analysis setting from Single-Lead and Multi-Lead is permitted for the Telemetry Bed at the Central Station.
 Verify that the ECG Detect Pace settings displayed for the Telemetry Bed at the Central Station include the following:
 Verify that the adjustment of the ECG Detect Pace setting from PACE1    PACE2 and OFF is permitted for the Telemetry Bed at the Central Station.
 Verify that the ECG Display Lead settings displayed for the Telemetry Bed at the Central Station include the following:
 Verify that the adjustment of ECG Display Lead setting from I   II  III     V   aVR     aVL and aVF for the Telemetry Bed is permitted at the Central Station.
 Verify that the SpO2 Waveform Size settings are displayed for the Telemetry Bed but it's read-only(grayed out).
 Verify that the Central Station shall display the NIBP auto mode setting as read only.
 Verify that the displayed NBP Stat mode settings are read-only for the Telemetry Bed at the Central Station.
 Verify that a means to clear the NBP message is provided for the Telemetry Bed at the Central Station.
 Verify that the message displayed for the Telemetry Bed in the Multiviewer  slot is cleared.
 Verify that the ECG Va Lead Selections displayed for the Telemetry Bed at the Central Station include the following:
 Verify that the adjustment of the ECG Va Lead Selection setting from V1     V2  V3  V4  V5 and V6 is permitted for the Telemetry Bed at the Central Station except for one of the Va lead which will be greyed out based on the Vb lead selected.
 Verify that the ECG Vb Lead Selections displayed for the Telemetry Bed at the Central Station include the following:
 Verify that the adjustment of the ECG Vb Lead Selection setting from V2     V3  V4  V5 and V6 is permitted for the Telemetry Bed at the Central Station except for one of the Vb lead which will be greyed out based on the Va lead selected.
 Verify that the NBP Stat Mode setting is displayed as a read-only value of either ON or OFF for the Telemetry Bed at the Central Station.
 Verify that the message displayed for the Telemetry Bed in the Multiviewer  slot is cleared.
 Verify that the adjustment of the SPO2 rate setting is permitted for the Telemetry Bed at the Central Station.

Note: I would also want to convert above text into lowercase before finding the count of list items.

A: You should have a look at the re.findall (https://docs.python.org/3.6/library/re.html#re.findall)
With re  you can ignore case, so you won't need to lowercase all your text before :)


text:
Q: Convert HTML to less/sass structure Quite often I create some html structure, and then I create less/sass styles for that. Usually every element in structure needs some styling and it requires me to 'rewrite' html structure to less/sass.
While rewriting there is only one rule - elements that appear multiple times in html are declared only once in less/sass.
Is there any tool that let me paste my HTML to it and that would generate corresponding less/sass structure that is ready for styling?
Example:
Such html:

Would result in such less:
.container {

    .elem {

        .sub {

        }
        img.other-sub {

        }
    }
}


text:
Q: How to update leaflet map with `getDerivedStateFromProps` from React 16.3? Now that componentWillReceiveProps is going to be deprecated how would you update a leaflet map with the new getDerivedStateFromProps workflow.
This is what I do now:

*

*I load the map in componentDidMount and draw elements

*If there is a prop update I clear the layers and redraw the elements in componentDidUpdate.

This is some sample code:
componentDidMount(){
  // load leaflet map and draw components
  var map = this.map = L.map('leafletmap');
  this.map.addData(geojsonData);
}

componentDidUpdate(prevProps,prevState) {
  // clear layers and redraw data
  if (prevProps.data !== this.props.data) {
      this.map.clearLayers();
      this.map.addData(geojsonData);
   }
 }

I have to do it this way since componentDidMount is only called once and componentDidUpdate is only called after a prop update. I think I could use either componentDidUpdate or componentWillReceiveProps in my workflow. Now that componentWillReceiveProps is deprecated and considering that getDerivedStateFromProps is always called I would like to know if I can draw all my leaflet stuff on this step and if this should be enough to update the map wherever props are changed.
static getDerivedStateFromProps(nextProps) {
  // draw stuff on map every time props change
  // (layers should be cleared as well)
  if (prevProps.data !== this.props.data) {
      this.map.clearLayers();
      this.map.addData(geojsonData);
   }
 }

componentDidMount(){
  // load leaflet map
  var map = this.map = L.map('leafletmap');
}

The problem I have is that I can't access this in getDerivedStateFromProps
Related: How do I force leaflet to update the map?

A: getDerivedStateFromProps is intended to only update/set the state based on prop and not to perform any side-effect,
The componentWillReceiveProps function can be broken down into
static getDerivedStateFromProps(nextProps, prevState) {
   //returning the updated state if you want
}

componentDidUpdate(prevProps, prevState) {
   //perform side-effects based on props or state change
}

In your case you would write
componentDidUpdate(prevProps, prevState) {
  if (prevProps.data !== this.props.data) {
      this.map.clearLayers();
      this.map.addData(geojsonData);
   }
}

A:
I think I could use either componentDidUpdate or componentWillReceiveProps in my workflow.

As Wazner's comment mentions above, this isn't quite right. Side effects (what you're describing) are not safe in componentWillReceiveProps or getDerivedStateFromProps. The StrictMode docs page has a section that goes into more detail on why this is.
For the case you're describing, it's unclear to me why you can't just continue to use componentDidMount and componentDidUpdate as your sample code shows. (Since you weren't using componentWillReceiveProps before- why change now?)


text:
Q: Cordova 3.3 to 3.4, iOS Plugins don't load I recently updated from Cordova 3.3 to 3.4 and had no trouble with my Android build, but the ios version no longer loads any plugins. I then removed all the plugins and re-added them and rebuilt and they still don't load. This is what Xcode says:
CDVPlugin class CDVLocation (pluginName: Geolocation) does not exist.
ERROR: Plugin 'Geolocation' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml.

Any thoughts, thank you!

A: Seems that deleting the ./plugins/ios.json file allowed the plugins to be reinstalled. Now it is all running again.


text:
Q: Microsoft Bot send the response twice in Teams I've used Microsoft bot framework SDKv4, and integrated to Teams channel. It is running well, but giving responses twice.

But, I didn't get the same behavior, while I tested it on Emulator and Web Chat in Azure Portal.
However, I can see below issue, while I ping the bot in web chat and get a response.

Further, I can also see, that its always 'sending' as a status although I got a valid response, and the status later changes to "Send Failed. Retry"

Is the issue related to my teams integration for getting message twice? and how, should I fix it!

A: Are you using webhooks? If so, having multiple webhooks with same ID could be the reason  for double messages. Hope this helps

A: I made my bot working. It was the issue of MS authentication!
I had a call with MS support person and the root cause appeared to be only the MS authentication. Had to reset app secret and then re-deloyment.
Its weird that, although it was not getting authenticated primarily yet it was returning me the response. This, I still haven't got it!


text:
Q: springboot error when launching application 'Error creating bean with name 'entityManagerFactory' ... [HibernateJpaConfiguration.class]' I am runnig for the first time a Springboot web api project and I have installed JPA/Hibernate dependency and the SQL Server driver, I am using windows authentication and LocalDb, but when I am launching the application it throws the following exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.18.jar:5.3.18]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.18.jar:5.3.18]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.18.jar:5.3.18]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.6.jar:2.6.6]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:740) ~[spring-boot-2.6.6.jar:2.6.6]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415) ~[spring-boot-2.6.6.jar:2.6.6]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) ~[spring-boot-2.6.6.jar:2.6.6]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312) ~[spring-boot-2.6.6.jar:2.6.6]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.6.jar:2.6.6]
    at com.RestApiTest.demo.RestApiTestApplication.main(RestApiTestApplication.java:10) ~[classes/:na]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:175) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:173) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:127) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1460) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1494) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.18.jar:5.3.18]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.18.jar:5.3.18]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.18.jar:5.3.18]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.18.jar:5.3.18]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.18.jar:5.3.18]
    ... 16 common frames omitted
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:138) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    ... 33 common frames omitted

the application.property is setup like this

spring.datasource.url=jdbc:sqlserver://(localdb)\\MSSQLLocalDB;databaseName=RestApiTestApplicationDb;integratedSecurity=true
spring.datasource.username=
spring.datasource.password=
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2016Dialect
spring.jpa.hibernate.ddl-auto = create-drop

A: You are using the wrong property to configure the dialect. It should be spring.jpa.properties.hibernate.dialect.


text:
Q: Glassfish 4.1 JMX: java.rmi.ConnectIOException: non-JRMP server at remote endpoint I've updated to Glassfish 4.1 from 4.0, and I can't access it from JConsole and VisualVM now (but I used to). JConsole outputs this before entering user/password:
java.io.IOException: Failed to retrieve RMIServer stub: javax.naming.CommunicationException [Root exception is java.rmi.ConnectIOException: non-JRMP server at remote endpoint]
    at javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:369)
    at javax.management.remote.JMXConnectorFactory.connect(JMXConnectorFactory.java:268)
    at sun.tools.jconsole.ProxyClient.tryConnect(ProxyClient.java:357)
    at sun.tools.jconsole.ProxyClient.connect(ProxyClient.java:313)
    at sun.tools.jconsole.VMPanel$2.run(VMPanel.java:292)
Caused by: javax.naming.CommunicationException [Root exception is java.rmi.ConnectIOException: non-JRMP server at remote endpoint]
    at com.sun.jndi.rmi.registry.RegistryContext.lookup(RegistryContext.java:118)
    at com.sun.jndi.toolkit.url.GenericURLContext.lookup(GenericURLContext.java:203)
    at javax.naming.InitialContext.lookup(InitialContext.java:411)
    at javax.management.remote.rmi.RMIConnector.findRMIServerJNDI(RMIConnector.java:1936)
    at javax.management.remote.rmi.RMIConnector.findRMIServer(RMIConnector.java:1903)
    at javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:286)
    ... 4 more
Caused by: java.rmi.ConnectIOException: non-JRMP server at remote endpoint
    at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:248)
    at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
    at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:341)
    at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
    at com.sun.jndi.rmi.registry.RegistryContext.lookup(RegistryContext.java:114)
    ... 9 more

I have this line in Glassfish's log:
JMXStartupService has started JMXConnector on JMXService URL service:jmx:rmi://Debian-70-wheezy-64-minimal:8686/jndi/rmi://Debian-70-wheezy-64-minimal:8686/jmxrmi

And I can connect using telnet. How can I solve this problem?


text:
Q: mysqli bind_result and fetch to PDO PostgreSQL I am trying to convert my mysqli to PDO using PostgreSQL and I am wondering what is the equivalent way of writing the following code in PDO
$result = $mysqli->prepare("SELECT FOUND_ROWS()");
$result->execute();
$result->bind_result($total_rows);
$result->fetch();

What I tried is the following:
$stmt = $this->pdo->prepare('SELECT FOUND_ROWS()');
$stmt->execute();

but I am not sure how to convert the rest of the my_sqli logic to my new PostgreSQL PDO, in particular the $result->bind_result($total_rows); and fetch().

A: PDO doesn't have anything equivalent to bind_result(). PDOStatement::fetch() returns the row as an array or object, and you extract the result columns from that. So instead of
$result->bind_result($total_rows);
$result->fetch();
echo $total_rows;

you use
$row = $stmt->fetch(PDO::FETCH_NUM);
echo $row[0];

It's generally easier if you assign aliases to the columns being selected, then you can fetch an associative array.
$stmt = $this->pdo->prepare('SELECT FOUND_ROWS() AS total_rows');
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo $row['total_rows'];


text:
Q: On Button Click Pause HTML Video (Which is in autoplay) I have a HTML 5 video, and it plays without audio on page load. It works how I wanted. But is there a way the user can press a button and the video will pause?
My Code in HTML is:
<video autoplay loop poster="" id="bgvid">
<source src="img/bg.mp4" type="video/webm">
<source src="img/bg.mp4" type="video/mp4">

and the CSS...
video#bgvid {
position: fixed;
top: 50%;
left: 50%;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
z-index: -100;
-ms-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
background: url(polina.jpg) no-repeat;
background-size: cover;

}

A: <video onclick="this.paused? this.play() : this.pause()">

As commented said. Via: How to pause a HTML5 video on an event?

A: $('.btn').click( function() {
   $('video').get(0).pause();
});

$('video').click( function() {
       this.pause();
});


text:
Q: tab bar panel not showing on all views.. My tab bar with icons at bottom of the is not showing on all views... like I will go to the following view on button tap... there the tab bar is not showing... this is my onbuttontap function
myAccFunction: function() {
  var MyUser=Ext.Viewport.add(Ext.create('Sample.view.Userinfo'));
  Ext.Viewport.animateActiveItem(MyUser, this.getSlideLeftTransition());
  console.log('UserinfoAction'); },

tab bar is showing when I go directly to the view using icon on the tab bar.. but when I go to the view using button tap tab bar is not showing ..

A: Viewport is the main view that takes usually full screen. Inside the viewport you normally have a panel with tabbars, navigation/title bar and if you want to present multiple pages there - you use cards layout. But the point would be - not to add these pages directly to the viewport, but rather add them to your main panel.


text:
Q: Embedding of rational number Q into real number R is dense and the embedding of Q into p-adic numbers $Q_p$ is dense too Q: If $p,q$ are different primes, show the embedding
$$\mathbb{Q} \rightarrow \mathbb{Q}_q \times \mathbb{Q}_p$$
$$x \rightarrow (x,x)$$
is dense in the product space $\mathbb{Q}_q \times \mathbb{Q}_p$.
Furthermore, show the embedding
$$\mathbb{Q} \rightarrow \mathbb{R} \times \mathbb{Q}_p$$
$$x \rightarrow (x,x)$$
is dense in the product space $\mathbb{R} \times \mathbb{Q}_p$.
My idea:
The professor gives us a hint to use Chinese Remainder Theorem. However, I still have no idea to start off my solutions...Can anyone help to explain how to do this proof? I am confused about this topic also. Thank you.

A: Let's look at the second one. Given $a\in \Bbb R$, $b\in\Bbb Q_p$ and
$\newcommand{\ep}{\varepsilon}\ep>0$ one needs to prove the existence of $x\in\Bbb Q$ with $|a-x|_\infty<\ep$ and $|b-x|_p<\ep$. There are certainly $a'$, $b'\in\Bbb Q$ with $|a-a'|_\infty<\ep/2$ and $|b-b'|_p<\ep/2$ so it suffices to
prove that there is $x\in\Bbb Q$ with
$|x-a'|_\infty<\ep/2$ and $|x-b'|_p<\ep/2$. Let $y=x-b'$ and $c=a'-b'$. Then
we want $y\in\Bbb Q$ with $|y-c|_\infty<\ep$ and $|y|_p<\ep/2$.
To achieve this, consider $u=p^N/(1+p^{2N})$ where $N$ is a sufficiently
large integer. Choosing $N$ large enough, gives $|u|_p<\ep/4$
and $|u|_\infty<\ep/4$ say. Then $|mu|_p<\ep/4$ for all integers $m$.
We can now take $m\in\Bbb Z$ so that $mu$ lies in the interval
$(c-\ep/4,c+\ep/4)$ inside $\Bbb R$.


text:
Q: Date label text overlapping in chronosys I'm attempting (with huge help from Hafid Boukhoulda who helped here) to utilise chronosys to construct a number of timelines, mostly on BC date ranges. Most data has been fixed-points, so not a problem, but some are events dated only to date ranges. I come across a problem when date ranges are close together:
\documentclass{article}
\usepackage{chronosys}

\newcommand{\mychronodatestyle}[1]{

\pgfmathparse{equal(sign(#1),-1)? int(abs(#1)):#1 }
\pgfmathresult
\pgfmathparse{equal(sign(#1),-1)? "BC":}
 ~\pgfmathresult
 }

 \catcode`\!=11
 \def\eventyear{\!chreventyear}
 \catcode`\!=12

 \newcommand{\myeventdatestyle}[1]{
 \pgfmathparse{equal(sign(\eventyear),-1)? int(abs(\eventyear)):"#1"}
\pgfmathresult
 \pgfmathparse{equal(sign(\eventyear),-1)? "BC":}
 ~\pgfmathresult
 }

\begin{document}

\startchronology
[startyear=-800,stopyear=-14, arrow=false, height=0.2em, dateselevation=10pt,
datesstyle=\mychronodatestyle
]
\chronoevent[datestyle=\myeventdatestyle ]
{12/-753}{Rome's foundation}

\chronoperiode[datesstyle=\mychronodatestyle,dateselevation=2pt]{-350}{-320}{important event}
\stopchronology

\end{document}

A: Your datestyle was inadequate for the narrow date band provided.  So I created an alternate (vertical) date style (named \mychronovdatestyle, note the v) for such narrowly spaced events.
I also added a number of % chars at line end, to suppress stray spaces from getting introduced into the labels.
\documentclass{article}
\usepackage{chronosys}

\newcommand{\mychronodatestyle}[1]{%
\pgfmathparse{equal(sign(#1),-1)? int(abs(#1)):#1 }%
\pgfmathresult%
\pgfmathparse{equal(sign(#1),-1)? "BC":}%
 ~\pgfmathresult%
 }

\newcommand{\mychronovdatestyle}[1]{%
\pgfmathparse{equal(sign(#1),-1)? int(abs(#1)):#1 }%
\edef\tmp{\pgfmathresult}%
\pgfmathparse{equal(sign(#1),-1)? "BC":}%
 \kern-1.5pt\rotatebox[origin=left]{90}{--- \tmp~\pgfmathresult}%
 }

 \catcode`\!=11
 \def\eventyear{\!chreventyear}
 \catcode`\!=12

 \newcommand{\myeventdatestyle}[1]{%
 \pgfmathparse{equal(sign(\eventyear),-1)? int(abs(\eventyear)):"#1"}%
\pgfmathresult%
 \pgfmathparse{equal(sign(\eventyear),-1)? "BC":}%
 ~\pgfmathresult%
 }
\begin{document}
\startchronology
[startyear=-800,stopyear=-14, arrow=false, height=0.2em, dateselevation=10pt,
datesstyle=\mychronodatestyle
]
\chronoevent[datestyle=\myeventdatestyle ]
{12/-753}{Rome's foundation}

\chronoperiode[color=red,datesstyle=\mychronovdatestyle,dateselevation=-7pt]
  {-350}{-320}{important event}
\stopchronology

\end{document}

SUPPLEMENT
The OP asks if the vertical dates could be placed below the line, at the expense of omitting the label.
I took no effort to make it pretty, but just minimized the modifications necessary from the above MWE:

*

*removed "important event" text, leaving argument blank.

*changed the dateselevation from -7pt to -10pt.

*changed the \rotatebox angle from 90 to -90.

*changed the label pre-kern from -1.5pt to 1.5pt.
The new MWE:
\documentclass{article}
\usepackage{chronosys}

\newcommand{\mychronodatestyle}[1]{%
\pgfmathparse{equal(sign(#1),-1)? int(abs(#1)):#1 }%
\pgfmathresult%
\pgfmathparse{equal(sign(#1),-1)? "BC":}%
 ~\pgfmathresult%
 }

\newcommand{\mychronovdatestyle}[1]{%
\pgfmathparse{equal(sign(#1),-1)? int(abs(#1)):#1 }%
\edef\tmp{\pgfmathresult}%
\pgfmathparse{equal(sign(#1),-1)? "BC":}%
 \kern1.5pt\rotatebox[origin=left]{-90}{--- \tmp~\pgfmathresult}%
 }

 \catcode`\!=11
 \def\eventyear{\!chreventyear}
 \catcode`\!=12

 \newcommand{\myeventdatestyle}[1]{%
 \pgfmathparse{equal(sign(\eventyear),-1)? int(abs(\eventyear)):"#1"}%
\pgfmathresult%
 \pgfmathparse{equal(sign(\eventyear),-1)? "BC":}%
 ~\pgfmathresult%
 }
\begin{document}
\startchronology
[startyear=-800,stopyear=-14, arrow=false, height=0.2em, dateselevation=10pt,
datesstyle=\mychronodatestyle
]
\chronoevent[datestyle=\myeventdatestyle ]
{12/-753}{Rome's foundation}

\chronoperiode[color=red,datesstyle=\mychronovdatestyle,dateselevation=-10pt]
  {-350}{-320}{}
\stopchronology

\end{document}


text:
Q: Textfield client side validation How can I implement a validator that won't allow a use to type angled-brackets on the client side.
This, of course, only allows the use to type numbers:
{
xtype: 'numberfield',
hideTrigger: true,
name: 'tsId',
width: 120
}

But how would I have a textfield that allows a user to type anything other than angled-brackets. < >

A: Regex is your friend - here's the expression you'll need to test against
/<|>/g

You can use it as a function like so:
var str;

function evaluate() {
    str = $('#evaluationText').val();
    var evalTest = str.match(/<|>/g); // test for '<' or '>'
    if(evalTest){
        alert('illegal chars..');
    }else {
        alert('all good');
    }
}

$('#evalText').click(function() {
  evaluate();
});

Fiddle here - http://jsfiddle.net/ackerman/K6agg/


text:
Q: How to preserve an array across multiple executions of a method I have a rake task which I want to run daily. The rake task would return a value. Every 15 days I want to take the average of the values retured by the rake task in the last 15 days. The rake method corresponding to task:
class Admin::OrderQueryController < Admin::ResourceController
def get_conversion_rate
    amount = 1
    @dollars = GoogCurrency.inr_to_usd(amount)
    debugger
    if @values.size == 15
        sum = 0
        @values.each do |x|
            sum = sum + x
        end
        avg_value = sum/15
        CurrencyConversionFactor.create! :currency => "USD", :value => avg_sum
    else
        @values.push(@dollars)
        debugger
    end
end
end

env_setup.rake:
task :convert_to_dollars => :environment do
  Admin::OrderQueryController.new.get_conversion_rate
end

But I don't understand how and where I can declare the @values array, so that its not lost after the execution of the method.
Thanks


text:
Q: How do I fix other data not adding to previous data in react infinite scroll? This my first time implementing react infinite scrolling. I ran into difficulty where the initial array of data keep repeating.
function Details() {
const [facility, setFacility] = useState([]);
  const [loading, setLoading] = useState(true);

  const getFacility = useCallback(async () => {
    let skip = 0;
    setLoading(true)
    await Axios.get(
      `...apiUrl/${wardTitle}/ward/details?limit=${10}&skip=${skip}`
    ).then((response) => {
      const details = response.data.data;
      setFacility((prev) => [...prev, ...details]);
      setLoading(false)
    });

  }, [wardTitle]);

  const handleScroll =  (e) => {
    const { scrollTop, scrollHeight, clientHeight} = e.currentTarget;

    if(clientHeight + scrollTop + 1 >= scrollHeight ){
      getFacility();
    }
  };

  useEffect(() => {
    getFacility();

  }, [getFacility]);

return (
<>
  {facility.map((cur) => (

{curr}

 {loading &&
Loading ...

)
</>
)

}

Everything seems fine other than the data repetition. I dont know where i got it wrong in the call. I would appreciate any help.

A: i can see so many errors in your code check the spellings too.
You are not explaining what you really want to do?
infinite scrolling like facebook?


text:
Q: Content Resolver is null when called by second Application I am having an issues with Content Providers.
I am trying to retrieve data held in a SQLite database in Application 1 whilst in Application 2 but it is bringing back null. Where as when the exact same code is run in Application 1 it returns values.
I have also however given the correct permissions in the manifest for both Applications and the content provider itself is working fine on Application 1.
Application 1 Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.application1">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <permission
        android:name="LOCATION_PROVIDER_READ_PERMISSION"
        android:protectionLevel="normal" />
    <permission
        android:name="LOCATION_PROVIDER_WRITE_PERMISSION"
        android:protectionLevel="normal" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyTheme"
        android:usesCleartextTraffic="true">
        <activity
            android:name=".SplashActivity"
            android:theme="@style/Theme.MyTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity"
            android:theme="@style/Theme.MyTheme.NoActionBar"
            android:windowSoftInputMode="adjustPan" />

        <provider
            android:name=".LocationContentProvider"
            android:authorities="com.example.application1.LocationContentProvider"
            android:enabled="true"
            android:exported="true"
            android:grantUriPermissions="true"
            android:multiprocess="true"
            android:readPermission="LOCATION_PROVIDER_READ_PERMISSION"
            android:writePermission="LOCATION_PROVIDER_WRITE_PERMISSION" />
    </application>

</manifest>

Application 2 Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.application2">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="LOCATION_PROVIDER_WRITE_PERMISSION" />
    <uses-permission android:name="LOCATION_PROVIDER_READ_PERMISSION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyTheme"
        android:usesCleartextTraffic="true">
        <activity
            android:name=".SplashActivity"
            android:theme="@style/Theme.MyTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity"
            android:theme="@style/Theme.MyTheme.NoActionBar"
            android:windowSoftInputMode="adjustPan" />
    </application>

</manifest>

Content Resolver used in Application 2, which looks at Application 1.
  try {

        String URL = "content://com.example.application1.LocationContentProvider/location_table";
        Uri uri = Uri.parse(URL);
        ContentResolver cr = getContentResolver();
        Cursor c = cr.query(uri, null, null, null, null);

        if (c != null) {
            if (c.getCount() != 0) {
                c.moveToFirst();
                Toast.makeText(this, c.getString(c.getColumnIndex("ID")), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "its null", Toast.LENGTH_SHORT).show();
            }
        }
    } catch (Exception ex) {
        Toast.makeText(this, ex.toString(), Toast.LENGTH_SHORT).show();
    }

Can anyone suggest anything? I have honestly spent hours looking at everyone else's solutions, all of which i have tried and implemented into my own solution.


text:
Q: What's the preferred way to handle transactions in pyscopg2? According to psycopg2 documentation we should set autocommit to get the default PostgreSQL behaviour. This even seems to be the preferred approach according to some people. My question is, if this is the best approach in these circumstances, how do I start a transaction explicitly? Using cursor.execute("BEGIN")?
On another note, how do the context managers provided by psycopg2 work with this into account? Do they automatically start a transaction in the beginning of the block and commit on success?

A: Personally I never use autocommit and almost always use the with syntax.
with psycopg2.connect(DSN) as conn:
    with conn.cursor() as curs:
        curs.execute(SQL)

Which will get committed as soon as you exit the context manager.
Likewise,
with psycopg2.connect(DSN) as conn:
    with conn.cursor() as curs:
        curs.execute(SQL)
        raise Exception("I changed my mind")

will cause the SQL statement to be safely rolled back.
with is very useful in Python for the few occasions where you really do want tight control of object lifetime, for example when object creation and destruction is tied to transactional behaviour.

A: psycopg2's transaction model is a bit like that of JDBC.
To open a transaction, set autocommit off and just start doing work. No explicit BEGIN is required.
To commit, use conn.commit().
Autocommit is fine if each statement is a single transaction naturally. There's no need for explicit transaction management then.


text:
Q: .NET Resources & Dynamics NAV I have a Project that is meant to be used as an Add-In for Dynamics NAV.
It is supposed to be shown in the currently used language with english being the standard.
To ensure this I have a method that sets CurrentCulture and CurrentUICulture.
Inside a test project that runs outside Dynamics NAV, the forms are shown with the appropriate translations.
When using the add-In in Dynamics NAV though, the forms are always in english, dispite the current culture and current UI culture being set to the correct language (I checked this by debugging in multiple cases).
I have tried two setups:

*

*localizable forms, where form1 contains form1.resx and form1.de.resx

*resx-files resources.resx and resources.de.resx that are seperated from Form1 and called in the code right after InitializeComponent.

The result is the same in both cases:
Starting the program outside NAV: Translation succeeds
Starting the program from inside NAV: Always uses standard resources
Does anyone know if there is a detail i am missing?

A: The issue was a very common one: The de-resources were compiled into a "de" folder and as a result NAV - like so often - was unable to find the files.
AssemblyResolve fixed this issue:
Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    var location = Path.Combine(
        Path.GetDirectoryName(typeof(MyForm).Assembly.Location),
        CultureInfo.CurrentCulture.Parent.Name,
        args.Name.Substring(0, args.Name.IndexOf(",", StringComparison.OrdinalIgnoreCase)) + ".dll");

    if (File.Exists(location))
    {
        return Assembly.LoadFrom(location);
    }

    return null;
    }
}

The only detail to keep in mind is to subscribe to AssemblyResolve before the InitializeComponent function is executed.


text:
Q: OVH Public Cloud Storage, Duplicity, Openstack, Swfit REGION NAME issue Thanks for reading me !
I do daily backups of my OVH Public Cloud projects and other on OVH Swift/Openstack Public Cloud storages using Duplicity on Debian 8. Everything works fine except for the location of the containers that are created by my scripts.
Indeed, while I specify "export SWIFT_REGIONNAME ="GRA3"" so that the containers are created in Gravelines ("GRA3"), they are all without exception created in Warsaw ("WAW1").
I am copying you here my normalized Duplicity script, if more experienced OpenStack or Duplicity users do not pass there I hope they can help me!
Script Example :

SWIFT_USERNAME="xxxxxxxxxxxx"
export SWIFT_PASSWORD="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
export SWIFT_AUTHURL="https://auth.cloud.ovh.net/v2.0/"
export SWIFT_AUTHVERSION="2"
export SWIFT_TENANTNAME="xxxxxxxxxxxxxxxx"
export SWIFT_REGIONNAME="GRA3"

duplicity --verbosity notice \
--num-retries 1 \
--asynchronous-upload \
--cf-backend swift \
--full-if-older-than 7D \
--volsize 100 \
--encrypt-key "$enc_key" \
--sign-key "$sign_key" \
"${src}" "${dest}"

unset SWIFT_USERNAME SWIFT_PASSWORD SWIFT_AUTHURL SWIFT_AUTHVERSION SWIFT_TENANTNAME SWIFT_REGIONNAME PASSPHRASE SIGN_PASSPHRASE

am open to any trail or advices that would explain this problem, i'm new to duplicity so i think i did a mistake i just dont know what it is !
Thank you in advance for your help :)

A: I came across this problem and came with a solution, with an older version of duplicity the environment variable SWIFT_REGIONNAME wasn't working but with the lastest version 0.7.18.2 works perfectly. Maybe your issue is the same. Hope this help you. Greetings.


text:
Q: proper autocrlf setting for git We sometimes use SourceTree as client.
It handles various line endings OK, but the diff tool it uses does not.
It sees all lines ending in LF as one line.
As a result, we keep all source in our repository with CRLF.
I'm looking at installing a git client.
I can't find the correct setting for TEXT or AUTOCRLF.
It seems like they all want to "normalize" the file on check in to LF.
I want to
Convert to CRLF on checkout;
and either
Convert to CRLF on checkin;
or
Do nothing on checkin;
The best I can find so far is
-text: Do nothing on checkin or checkout;
Is there any hope?
Thanks,
Brad.

A: Git's native end-of-line settings are LF, and I'm not aware of any way to alter that behavior aside from recompiling it from source. However, you can force checkouts to use CRLF, which requires the creation of a .gitattributes file. For example:
# Force C# source files to be checked out using CRLF line endings,
# ignoring "core.eol" setting.
*.cs eol=crlf

# Don't apply CRLF conversion to PDF files, regardless of
# user settings including "core.autocrlf".
*.pdf -text

# All other files are subjected to the usual algorithm to determine
# whether a file is a binary file or a text file, respecting
# "core.eol" for all files detected as text files.
# "core.autocrlf", if set, will force the conversion to/from CRLF
# automatically as necessary for text files.
* text=auto

Note that if you created a new file with LF line endings (e.g. using Linux, Cygwin, or an application such as Notepad++ that defaults to LF line endings), you will get a warning when adding that file to the repository if it matches a pattern in the .gitattributes file where eol=crlf is used:
warning: LF will be replaced by CRLF in Example.cs.
The file will have its original line endings in your working directory.

Of course, if you later pull new changes, the original LF line endings will no longer be present.
Here's a list of the interactions between various EOL/text settings:

*

*.gitattributes file

*

*eol=...

*

*Possible values are lf and crlf.

*Files specified are always treated as text files and are checked out with the specified line endings.

*Ignores core.eol and core.autocrlf.

*text

*

*Files specified are always treated as text files.

*Respects core.eol and core.autocrlf.

*text=auto

*

*Files specified are subjected to automatic detection to determine whether they are text or binary files.

*Respects core.eol and core.autocrlf for text files.

*Ignores core.eol and core.autocrlf for binary files.

*-text

*

*Files specified are always treated as binary files.

*Ignores core.eol and core.autocrlf since they don't apply to binary files.

*core.autocrlf configuration setting

*

*input: any text files checked in will undergo conversion from CRLF to the native LF.

*true: any text files checked in/out undergo CRLF conversion.

*May be overridden by an eol=... rule applied to certain files in .gitattributes.

*core.eol configuration setting

*

*native (default): any text files checked out have native line endings (CRLF on Windows, LF elsewhere)

*lf: any text files checked out have LF line endings

*crlf: any text files checked out have CRLF line endings

*If core.autocrlf is set to true, this setting is ignored.

*May be overridden by an eol=... rule applied to certain files in .gitattributes.


text:
Q: Create and configure a CDN from Powershell I have a powershell script that must setup all my infrastructure with a single click, what I'm missing is a way to create and configure the CDN, this seems to be only possible from the management portal.
Thanks

A: According to this answer creating a CDN endpoint through Azure PowerShell is not supported yet.
Quoting the link's Q&A:

Q: [ViewRidge] How can I create a CDN endpoint using Azure PowerShell?
A: [Manling] -> [ViewRidge] We don't support it today but it's targeted to be
  supported in CY Q4.


text:
Q: Forms Auth: Where's my auth cookie gone? Where's my auth cookie gone?
When redirecting from my SSO to a client application, the .ASPXAUTH cookie is lost but only if the two sites are not on the same server.
In Fiddler, I can see the cookie being set by the SSO to the Response, in the correct cookie path for the client app.  Upon redirecting however, I see that the request does not bear the cookie.
Response after logging into SSO:

Request back to client application:

Relevant sections of the Login apps web.config:
<machineKey compatibilityMode="Framework20SP2"
                decryption="AES"
                decryptionKey="<a valid RSA key>"
                validation="SHA1"
                validationKey="<a valid HMACSHA256 hash>"
                />
    <!-- "SHA1" actually implements HMACSHA256, but for one reason or another, we can't specify it explicitly. -->

    <authentication mode="Forms">
      <forms loginUrl="Index"
             cookieless="UseCookies"
             requireSSL="false"
             name=".ASPXAUTH"
             path="/path/to/SSO-Virtual-Directory/"
             slidingExpiration="true"
             timeout="20"
             enableCrossAppRedirects="true"
             protection="All"
             ticketCompatibilityMode="Framework20"
             />
      <!-- set cookie path relative to virtual path of the application in IIS. See Application -> Advanced Settings to see the virtual path.
            Cookie Paths, Domains, and Names are all CASE SENSITIVE!!!!!
            Be sure to check the virtual path, as it doesn't update when you rename path tokens to change case. you will have to recreate the application to update the virtualpath-->
    </authentication>

    <!--SSOConfig Providers-->
    <membership defaultProvider="SqlMembershipProvider" >
      <providers>
        <clear />
        <add name="ADMembershipProvider"
             connectionStringName="ADConnectionString"
             attributeMapUsername="sAMAccountName"
             enableSearchMethods="false"
             connectionUsername="<a valid domain username"
             connectionPassword="<a valid password>"
             type="System.Web.Security.ActiveDirectoryMembershipProvider"
             />
        <!-- do not set applicationName= .-->

        <add name="SqlMembershipProvider"
             connectionStringName="SqlConnectionString"
             applicationName="SSO"
             enablePasswordRetrieval="false"
             enablePasswordReset="true"
             requiresQuestionAndAnswer="true"
             requiresUniqueEmail="true"
             passwordFormat="Hashed"
             minRequiredNonalphanumericCharacters="0"
             type="System.Web.Security.SqlMembershipProvider"
             />
        <!-- for some messed up reason applicationName is required.-->
      </providers>
    </membership>

    <roleManager defaultProvider="SqlRoleProvider"
                 enabled="true"
                 cacheRolesInCookie="true"
                 cookieName=".ASPROLES"
                 cookieTimeout="30"
                 cookiePath="/path/to/Virtual-Directory/"
                 cookieRequireSSL="false"
                 cookieSlidingExpiration="true"
                 cookieProtection="All"
                 >
      <!--set cookie path relative to virtual path of the application in IIS. See Application -> Advanced Settings to see the virtual path. eg: /secure/sso/CentralLogin/ on Exodus.
            Cookie Paths, Domains, and Names are all CASE SENSITIVE!!!!!
            Be sure to check the virtual path, as it doesn't update when you rename path tokens to change case. you will have to recreate the application to update the virtualpath-->
      <providers>
        <clear />
        <add name="SqlRoleProvider"
             type="System.Web.Security.SqlRoleProvider"
             connectionStringName="SqlConnectionString"
             applicationName="SSO"
             />
        <!-- set ApplicationName-->
      </providers>
    </roleManager>

Client Web.config:
<machineKey compatibilityMode="Framework20SP2"
                decryptionKey="<The same RSA key>"
                validation="SHA1"
                validationKey="<The same HMACSHA256 hash>"
     />

    <authentication mode="Forms" >
      <forms loginUrl="~/login/Index"
             name=".ASPXAUTH"
             path="/Payment/"
             requireSSL="false"
             slidingExpiration="true"
             timeout="20"
             cookieless="UseCookies"
             enableCrossAppRedirects="true"
             protection="All"
             ticketCompatibilityMode="Framework20"
             />
    </authentication>

    <membership defaultProvider="SqlMembershipProvider" >
      <providers>
        <clear />
        <add name="ADMembershipProvider"
             connectionStringName="ADConnectionString"
             attributeMapUsername="sAMAccountName"
             enableSearchMethods="true"
             connectionUsername="<a valid domain username"
             connectionPassword="<a valid password>"
             type="System.Web.Security.ActiveDirectoryMembershipProvider"
             />

        <add name="SqlMembershipProvider"
             connectionStringName="SqlSSOConnection"
             applicationName="SSO"
             enablePasswordRetrieval="false"
             enablePasswordReset="true"
             requiresQuestionAndAnswer="true"
             requiresUniqueEmail="true"
             passwordFormat="Hashed"
             minRequiredNonalphanumericCharacters="0"
             type="System.Web.Security.SqlMembershipProvider"
             />
      </providers>
    </membership>

    <roleManager defaultProvider="SqlRoleProvider"
                 enabled="true"
                 cacheRolesInCookie="true"
                 cookieName=".ASPROLES"
                 cookieTimeout="30"
                 cookiePath="/Payment/"
                 cookieRequireSSL="false"
                 cookieSlidingExpiration="true"
                 cookieProtection="All"
                  >
      <providers>
        <clear />
        <add name="SqlRoleProvider"
             type="System.Web.Security.SqlRoleProvider"
             connectionStringName="SqlSSOConnection"
             applicationName="SSO"
             />
      </providers>
    </roleManager>

Both sites are MVC5 on .Net 4.5.2.
Does anyone have any ideas as to whats going wrong, and what I can do about it?

A: So as we seems to found out in comments, the problem is SSO and client reside on different domains\ips and so cookie set for SSO will not be passed to client by browser. There are different ways to solve this, but they require change of how your general SSO process works.
As I understand you only have problem with that in development environment, not on production. If so, suppose your SSO is on 10.0.0.1 and your client is on 127.0.0.1. Then map client.yoursite.local domain (in your corporate DNS or just in /etc/hosts file) to 127.0.0.1 and yoursite.local to 10.0.0.1, and use domain names instead of raw ip addresses. Then in SSO set cookie with domain of ".yoursite.local". This then should be delivered correctly to your client application, and will not require significant changes to how your SSO process works.


text:
Q: Fastest way to find if element exists in an unsorted array? Is the fastest algorithm for searching an unsorted array for an element linear search? I mean I guess a combination of merge sort + binary search would be slower. Are there any other options? (in terms of algorithms not involving multithreading)?

A: Yes, if the array is unsorted and that's all you know about its structure then the fastest way to search for an element is to consider every one which takes linear time O(n).
If you are going to be searching the array a lot then you may want to consider an initial sort and then insert elements into their correct sorted index (using binary search). This means that you have your initial sort as O(n log n) but each insert and search takes O(log n). It's all about tradeoffs and whether that is better than O(1) insert and O(n) search.
You said no multithreading but that is an easy way to boost performance, have multiple threads look at different chunks in the list.

A: I have created a method for searching an element in an unsorted array.
#include <iostream>
#include <vector> // for 2D vector
#include<bits/stdc++.h>
using namespace std;

int main()
{
    vector<vector<int>> vect{ {0},{0},{0},{0},{0},{0},{0},{0},{0},{0} };
    int count[10];
    int min = INT_MAX;
    int max = INT_MIN;
    for (int i = 0; i < 10; i++)
    {
        count[i] = 0;
    }

    for (int i = 0; i < 7; i++)
    {
        //input 7 integers
        int ip,
            rem;
        cin >> ip;
        rem = ip % 10;
        if (ip > max)
            max = ip;
        if (min > ip)
            min = ip;
        if (vect[rem][0] == 0 && count[rem] == 0)
        {
            vect[rem][0] = ip;
            count[rem]++;
        }
        else
        {
            vect[rem].push_back(ip);
            count[rem]++;
        }
    }

    int find;
int flag = 0;
    cin >> find;
    int rem = find % 10;
    if (find>max || find<min || count[rem] == 0)
        cout<<"not present in the array";
    else
    {
        for (int i = 0; i < vect[rem].size(); i++)
        {
            if (vect[rem][i] == find)
            {
                cout << "found";flag = 1;
                break;
            }
        }
      if(flag == 0)
        cout<<"not present in the array";
    }

    return 0;
}

I see that this can be faster.
Basically I'm storing the elements in a 2D vector once I receive it.
I'm taking the remainder of the number (number % 10) as the index for the vector and pushing those elements.
Now to search the element, I'm traversing only the elements present in that specific index of the vector.
In this way, the number of comparisons are less.


text:
Q: Serialization Exception i am trying to save a state of a chessGameplay.
private void saveToolStripMenuItem_Click(object sender, EventArgs e)// menu strip control
{
    saveFileDialog1.InitialDirectory = @"c:\";

    DialogResult result= saveFileDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        saveToFile(saveFileDialog1.FileName);
    }

}

private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
    openFileDialog1.InitialDirectory = @"c:\";

    DialogResult result= openFileDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        openFile(openFileDialog1.FileName);
    }
}
GameSave game2 = new GameSave();
public void saveToFile(string s)
{
    game2.setLoadedPieces(codeFile.PieceState());// will pass the current pieces state. that is an array of all the chess pieces objects..which determine where each piece is on the board
    FileStream f = new FileStream(s, FileMode.Create);
    BinaryFormatter b = new BinaryFormatter();

    b.Serialize(f, game2);// throws here an exception.Type 'WindowsFormsApplication1.Pieces' in Assembly 'ChessBoardGame, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
    f.Close();
}

public void openFile(string s)
{
    FileStream f = new FileStream(s, FileMode.Open);// will open the file and the stream
    BinaryFormatter b = new BinaryFormatter();
    game2 = (GameSave)b.Deserialize(f);// will load the stream
    f.Close();
    codeFile.setPieces(game2.getLoadedPieces());// sets the board to the loaded pieces.
    PrintPieces(game2.getLoadedPieces());//prints the existing loaded pieces.
}

[Serializable]
class GameSave
{
    Pieces[,] pieces;

    public void setLoadedPieces(Pieces[,] serializedSavedPieces) // set the pieces array  to be saved
    {
        this.pieces = serializedSavedPieces;
    }
    public Pieces[,] getLoadedPieces() // returns the pieces array
    {
        return pieces;
    }

}

Type of exception:

Type 'WindowsFormsApplication1.Pieces' in Assembly 'ChessBoardGame, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

A: Perhaps you should mark WindowsFormsApplication1.Pieces as [Serializable] ? :)


text:
Q: How to change column name in pandas I am trying to get aws cost using cost explorer api, following is code I am using here.
The output I am getting in column name (2021-02-01) that I want to convert to (Feb-21). Can someone guide me what changes I have to make and in which line in following code
rows = []
    sort = ''
    for v in results:

        row = {'date':v['TimePeriod']['Start']}
        sort = v['TimePeriod']['Start']
        for i in v['Groups']:
            key = i['Keys'][0]
            if key in self.accounts:
                key = self.accounts[key][ACCOUNT_Name]
            row.update({key:int(float(i['Metrics']['UnblendedCost']['Amount']))})
        if not v['Groups']:
            row.update({'Total':int(float(v['Total']['UnblendedCost']['Amount']))})
        rows.append(row)

    df = pd.DataFrame(rows)

    df.set_index('date', inplace= True)

    df = df.fillna(0.0)

    if Style == 'Change':
        dfc = df.copy()
        lastindex = None
        for index, row in df.iterrows():
            if lastindex:
                for i in row.index:
                    try:
                        df.at[index,i] = dfc.at[index,i] - dfc.at[lastindex,i]
                    except:
                        logging.exception("Error")
                        df.at[index,i] = 0
            lastindex = index
    df = df.T
    df = df.sort_values(sort, ascending=False)
    self.reports.append({'Name':Name,'Data':df, 'Type':type})

Output that i get
2021-02-01      2021-02-01
xxxxxxx          xxxxxxx
output required
Jan-21           Feb-21
xxxxxxx          xxxxxxx

A: Try passing the format as below,
df['col1'] = df['col'].dt.strftime('%b-%y')