text:
Q: Object reference not set to an instance of an object. Dropdownlist I'm getting the following error:

Object reference not set to an instance of an object.
Server Error in '/WebSite3' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Here is my code
Partial Class frmChoseIncident
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles      Me.Load

    Dim objCDBGuest As New CDBGuestProfile
    Dim objCGuest As New CGuestProfile

    Dim arrList As New ArrayList

    If Page.IsPostBack = False Then

        Dim intGuestID1 As Integer
        intGuestID1 = Request.QueryString("id")
        objCGuest = objCDBGuest.getOneIncident(intGuestID1)

        txtIncidentName.Text = objCGuest.IncidentName
        txtIncidentSummary.Text = objCGuest.IncidentSummary
        txtRoomRate.Text = objCGuest.RoomRate
        txtArrivalDate.Text = objCGuest.ArrivalDate
        txtDepartureDate.Text = objCGuest.DepartureDate
        txtGuestName.text = objCGuest.GuestName
        txtCompany.Text = objCGuest.GuestCompany
        txtIncidentDate.Text = objCGuest.IncidentDate
        txtAddedDate.Text = objCGuest.AddedDate
        txtRoomID.Text = objCGuest.RoomId
        txtPreparedBy.Text = objCGuest.PreparedBy
        txtDepartment.Text = objCGuest.Department
        txtGuestTime.Text = objCGuest.GuestTime

        lstHotel.SelectedItem.Value = objCGuest.Hotel
        txtAction.Text = objCGuest.Action
        txtCost.Text = objCGuest.Cost
        txtComplimentary.Text = objCGuest.Complimentary
        txtAmount.Text = objCGuest.Amount
        lstGlitchStatus.SelectedItem.Value = objCGuest.GlitchStatus
        lstGuestHistory.SelectedItem.Value = objCGuest.GuestHistory
        txtComments.Text = objCGuest.Comments

        lstHotel.SelectedItem.Enabled = False
        txtAction.ReadOnly = True
        txtCost.ReadOnly = True
        txtComplimentary.ReadOnly = True
        txtAmount.ReadOnly = True
        lstGlitchStatus.SelectedItem.Enabled = False
        lstGuestHistory.SelectedItem.Enabled = False
        txtComments.ReadOnly = True

        txtIncidentName.ReadOnly = True
        txtIncidentSummary.ReadOnly = True
        txtRoomRate.ReadOnly = True
        txtArrivalDate.ReadOnly = True
        txtDepartureDate.ReadOnly = True
        txtGuestName.ReadOnly = True
        txtCompany.ReadOnly = True
        txtIncidentDate.ReadOnly = True
        txtRoomID.ReadOnly = True
        txtPreparedBy.ReadOnly = True
        txtDepartment.ReadOnly = True
        txtGuestTime.ReadOnly = True
    End If

End Sub

The Function
 Public Function getOneIncident(ByVal pintGuestID1 As Integer) As CGuestProfile
    Dim objCmd As New MySqlCommand
    Dim objCn As New MySqlConnection(connectionString)
    Dim objAdapter As New MySqlDataAdapter
    Dim strSQL As String = ""
    Dim objDs As New DataSet
    Dim objDataRow As DataRow

    strSQL = "SELECT * FROM tblGuestProfile WHERE strGuestCodeTI=" & pintGuestID1
    objCmd.CommandText = strSQL
    objCmd.Connection = objCn
    objAdapter.SelectCommand = objCmd

    objCn.Open()

    objAdapter.Fill(objDs, "tblGuestProfile")
    objDataRow = objDs.Tables("tblGuestProfile").Rows(0)
    Dim objCGuestProfile As New CGuestProfile

    objCGuestProfile.GuestName = objDataRow.Item("strGuestNameTI")
    objCGuestProfile.GuestCompany = objDataRow.Item("strGuestCompanyTI")
    objCGuestProfile.ArrivalDate = objDataRow.Item("strArrivalDateTI")
    objCGuestProfile.DepartureDate = objDataRow.Item("strDepartureDateTI")
    objCGuestProfile.IncidentDate = objDataRow.Item("strIncidentDateTI")
    objCGuestProfile.AddedDate = objDataRow.Item("strAddedDateTI")
    objCGuestProfile.RoomRate = objDataRow.Item("strRoomRateTI")
    objCGuestProfile.RoomId = objDataRow.Item("intRoomTI")
    objCGuestProfile.PreparedBy = objDataRow.Item("strPreparedByTI")
    objCGuestProfile.Department = objDataRow.Item("strDepartmentTI")
    objCGuestProfile.GuestTime = objDataRow.Item("strTimeTI")
    objCGuestProfile.IncidentName = objDataRow.Item("strIncidentNameTI")
    objCGuestProfile.IncidentSummary = objDataRow.Item("strIncidentSummaryTI")

    objCGuestProfile.Hotel = objDataRow.Item("intHotelTI")
    objCGuestProfile.Action = objDataRow.Item("strActionTI")
    objCGuestProfile.Cost = objDataRow.Item("strCostTI")
    objCGuestProfile.Complimentary = objDataRow.Item("strComplimentaryTI")
    objCGuestProfile.Amount = objDataRow.Item("strAmountTI")
    objCGuestProfile.GlitchStatus = objDataRow.Item("intGlitchStatusTI")
    objCGuestProfile.GuestHistory = objDataRow.Item("intGuestHistoryTI")
    objCGuestProfile.Comments = objDataRow.Item("strCommentsTI")
    objCn.Close()
    Return objCGuestProfile
End Function

The CGuestProfile
Imports Microsoft.VisualBasic

Public Class CGuestProfile
Private strGuestCodeTI As String
Private strGuestNameTI As String
Private strGuestCompanyTI As String
Private strArrivalDateTI As String
Private strDepartureDateTI As String
Private strIncidentDateTI As String
Private strAddedDateTI As String
Private intRoomTI As String
Private strRoomRateTI As String
Private strPreparedByTI As String
Private strDepartmentTI As String
Private strTimeTI As String
Private strIncidentNameTI As String
Private strIncidentSummaryTI As String
Private intHotelTI As Integer
Private intGuestHistoryTI As Integer
Private strComplimentaryTI As String
Private intGlitchStatusTI As Integer
Private strActionTI As String
Private strCostTI As String
Private strAmountTI As String
Private strCommentsTI As String

Public Property GuestId() As String
    Get
        Return strGuestCodeTI
    End Get
    Set(ByVal value As String)
        strGuestCodeTI = value
    End Set
End Property

Public Property GuestName() As String
    Get
        Return strGuestNameTI
    End Get
    Set(ByVal value As String)
        strGuestNameTI = value
    End Set
End Property

Public Property GuestCompany() As String
    Get
        Return strGuestCompanyTI
    End Get
    Set(ByVal value As String)
        strGuestCompanyTI = value
    End Set
End Property

Public Property ArrivalDate() As String
    Get
        Return strArrivalDateTI
    End Get
    Set(ByVal value As String)
        strArrivalDateTI = value
    End Set
End Property

Public Property DepartureDate() As String
    Get
        Return strDepartureDateTI
    End Get
    Set(ByVal value As String)
        strDepartureDateTI = value
    End Set
End Property

Public Property IncidentDate() As String
    Get
        Return strIncidentDateTI
    End Get
    Set(ByVal value As String)
        strIncidentDateTI = value
    End Set
End Property
Public Property AddedDate() As String
    Get
        Return strAddedDateTI
    End Get
    Set(ByVal value As String)
        strAddedDateTI = value
    End Set
End Property

Public Property RoomId() As Integer
    Get
        Return intRoomTI
    End Get
    Set(ByVal value As Integer)
        intRoomTI = value
    End Set
End Property

Public Property RoomRate() As String
    Get
        Return strRoomRateTI
    End Get
    Set(ByVal value As String)
        strRoomRateTI = value
    End Set
End Property

Public Property PreparedBy() As String
    Get
        Return strPreparedByTI
    End Get
    Set(ByVal value As String)
        strPreparedByTI = value
    End Set
End Property

Public Property Department() As String
    Get
        Return strDepartmentTI
    End Get
    Set(ByVal value As String)
        strDepartmentTI = value
    End Set
End Property

Public Property GuestTime() As String
    Get
        Return strTimeTI
    End Get
    Set(ByVal value As String)
        strTimeTI = value
    End Set
End Property
Public Property IncidentName() As String
    Get
        Return strIncidentNameTI
    End Get
    Set(ByVal value As String)
        strIncidentNameTI = value
    End Set
End Property
Public Property IncidentSummary() As String
    Get
        Return strIncidentSummaryTI
    End Get
    Set(ByVal value As String)
        strIncidentSummaryTI = value
    End Set
End Property
Public Property Hotel() As Integer
    Get
        Return intHotelTI
    End Get
    Set(ByVal value As Integer)
        intHotelTI = value
    End Set
End Property

Public Property Action() As String
    Get
        Return strActionTI
    End Get
    Set(ByVal value As String)
        strActionTI = value
    End Set
End Property

Public Property Cost() As String
    Get
        Return strCostTI
    End Get
    Set(ByVal value As String)
        strCostTI = value
    End Set
End Property
Public Property Complimentary() As String
    Get
        Return strComplimentaryTI
    End Get
    Set(ByVal value As String)
        strComplimentaryTI = value
    End Set
End Property

Public Property Amount() As String
    Get
        Return strAmountTI
    End Get
    Set(ByVal value As String)
        strAmountTI = value
    End Set
End Property
Public Property GlitchStatus() As Integer
    Get
        Return intGlitchStatusTI
    End Get
    Set(ByVal value As Integer)
        intGlitchStatusTI = value
    End Set
End Property

Public Property GuestHistory() As Integer
    Get
        Return intGuestHistoryTI
    End Get
    Set(ByVal value As Integer)
        intGuestHistoryTI = value
    End Set
End Property
Public Property Comments() As String
    Get
        Return strCommentsTI
    End Get
    Set(ByVal value As String)
        strCommentsTI = value
    End Set
End Property
End Class

If i take away the
lstHotel.SelectedItem.Value = objCGuest.Hotel
lstGlitchStatus.SelectedItem.Value = objCGuest.GlitchStatus
lstGuestHistory.SelectedItem.Value = objCGuest.GuestHistory
lstHotel.SelectedItem.Enabled = False
lstGlitchStatus.SelectedItem.Enabled = False
lstGuestHistory.SelectedItem.Enabled = False

Then i can load the page, however the dropdownlist is empty.
Hotel function
Public Function getAllHotelDropDownList() As ArrayList
    Dim objCn As New MySqlConnection(connectionString)
    Dim objCmd As New MySqlCommand
    Dim objAd As New MySqlDataAdapter

    Dim objDs As New DataSet
    Dim objDr As DataRow

    Dim strSQL As String = "SELECT * FROM tblHotel"

    Dim objArrayList As New ArrayList
    Dim objHotel As New CHotel

    objCmd.Connection = objCn
    objAd.SelectCommand = objCmd
    objCmd.CommandText = strSQL
    objCn.Open()
    objAd.Fill(objDs, "tblHotelData")

    For Each objDr In objDs.Tables("tblHotelData").Rows
        objHotel = New CHotel
        objHotel.Hotel = objDr.Item("intHotelHO")
        objHotel.strHotel = objDr.Item("strHotelHO")
        objArrayList.Add(objHotel)
    Next
    Return objArrayList

End Function
Public Function getOneHotel(ByVal pstrHotelTI As Integer) As CHotel
    Dim objCmd As New MySqlCommand
    Dim objCn As New MySqlConnection(connectionString)
    Dim objAdapter As New MySqlDataAdapter
    Dim strSQL As String = ""
    Dim objDs As New DataSet
    Dim objDataRow As DataRow

    strSQL = "SELECT * FROM tblHotel WHERE intHotelHO=" & pstrHotelTI
    objCmd.CommandText = strSQL
    objCmd.Connection = objCn
    objAdapter.SelectCommand = objCmd

    objCn.Open()

    objAdapter.Fill(objDs, "tblHotel")
    objDataRow = objDs.Tables("tblHotel").Rows(0)
    Dim objCHotel As New CHotel

    objCHotel.strHotel = objDataRow.Item("strHotelHO")

    objCn.Close()
    Return objCHotel
End Function
End Class

A: I am not 100% sure what you are trying to do with the ddlist, but if I understand it, you want to update the value of the list to be the current information.
If this is the case, then you should not be altering the SelectedItem, you should be setting the SelectedValue:
lstHotel.SelectedValue = objCGuest.Hotel
lstGlitchStatus.SelectedValue = objCGuest.GlitchStatus
lstGuestHistory.SelectedValue = objCGuest.GuestHistory

Likewise, if you are trying to disable the list rather than the item in the list, then you need:
lstHotel.Enabled = False
lstGlitchStatus.Enabled = False
lstGuestHistory.Enabled = False

You might want to look through the MSDN documentation for SelectedItem and its data type ListItem.
If it turns out that you do want to work directly with a SelectedItem, you will have to test it for existence first and, if needed, select an item in the list or add one.
If lstHotel.SelectedItem Is Nothing Then
   ' Nothing in the list, so add it
   If lstHotel.Items.Count = 0 Then
       lstHotel.Items.Add(New ListItem)
   End If
   ' Select the first item in the list
    lstHotel.SelectedIndex = 0
End If
lstHotel.SelectedItem.Value = objCGuest.Hotel
lstHotel.SelectedItem.Enabled = False


text:
Q: how to store jsx element to javascript variable I want to reuse my jsx element in multiple places.
const value=
some text<Link href="abc.com">text</Link>

and I want to call value in multiple places.
I tried adding ' ' for the div but not getting element properly. It is returing as string. Can someone explain me the correct syntax to render jsx element to JavaScript variable?

A:
I want to reuse my jsx element in multiple places.

You can't. It can only be used in one place. It would appear that you can, I stand corrected by Mosè Raguzzini, this works just fine::
const value=
some text<Link href="http://example.com">text</Link>
;

ReactDOM.render(

    {value}
    {value}
    {value}

,
  document.getElementById("root")
);

Live Example:

const value=
some texttext
;

ReactDOM.render(

    {value}
    {value}
    {value}

,
  document.getElementById("root")
);

Another approach is to have a function that creates identical copies of it:
const getValue = () =>
some text<Link href="abc.com">text</Link>
;

Then when you want one, use getValue() to get it.
Or even give that a capital letter so it's a functional component:
const Value = () =>
some text<Link href="abc.com">text</Link>
;

Live Example (of both):

const getValue = () =>
some texttext
;

const Value = () =>
some texttext
;

ReactDOM.render(

    {getValue()}
    {getValue()}
    <Value />
    <Value />

,
  document.getElementById("root")
);

how to store jsx element to javascript variable

You can't reuse a React element the way you've shown, but there's nothing wrong with:
const value=
some text<Link href="abc.com">text</Link>

(other than relying on ASI at the end, because there's no ;). That works just fine. But it doesn't make it reusable.
Here's an example doing that:

const value=
some texttext
;

ReactDOM.render(

    {value}

,
  document.getElementById("root")
);

A: You could create a stateless component to reuse said component:
  import React from "react"

  export const MyComponent = () => (

      some text <Link href="abc.com">text</Link>

  );

redpajama_set_name: RedPajamaStackExchange


text:
Q: Class variables in rails views? Is it possible to refer to ruby class variables in a view?

A: Unfortunately class (@@variables) are not copied into the view. You may still be able to get at them via:
controller.instance_eval{@@variable}

or
@controller.instance_eval{@@variable}

or something else less gross.
With Rails, 99.9 out of 100 people should never be doing this, or at least I can't think of a good reason.

A: The more common approach is to wrap the class variable in a helper method:
# in /app/controllers/foo_controller.rb:
class FooController < ApplicationController
  @@bar = 'baz'

  def my_action
  end

  helper_method :bar

  def bar
    @@bar
  end
end

# in /app/views/foo/my_action.html.erb:
It might be a class variable, or it might not, but bar is "<%= bar -%>."

A: Rosen's answer is nice because it hides what kind of variable "bar" is, but if you have a lot of such variables, the need to define a bunch of helper methods is unappealing.  I'm using the following in my controller:
@bar = @@bar ||= some_expensive_call

That way, "some_expensive_call" is only made once, and the result is copied into @bar for each instance (so the view can then access it as @bar).


text:
Q: Linq Join on Two Conditions I am having some trouble with a left join on two DataTables that uses multiple conditions. I am getting an error The type of one of the expressions in the join clause is incorrect.  Type inference failed in the call to 'Join'
The error shows up on the keyword join just before t2
var JoinedData= ((from t1 in TableOne.AsEnumerable()
    join t2 in TableTwo.AsEnumerable() on
        new { t1s = (string)t1["start_time"], t1r = (string)t1["reference_id"] }
        equals
        new { t2s = (string)t2["start_time"], t2r = (string)t2["reference_id"] }
    select new {
                 id= (string)t1["reference_id"]
               }
)).Distinct()

Everything works fine with one or the other, but when I combine them it gets the error.

A: Try replacing with anonymous objects with same properties names:
    new { start_time = (string)t1["start_time"], end_time = (string)t1["reference_id"] }
    equals
    new { start_time = (string)t2["start_time"], end_time = (string)t2["reference_id"] }


text:
Q: MySQL Join query for credit balance I'm trying to create mysql query to get balance (sum(col1)-Sum(col2)) from one table along with name of that userid from another table.
-------
table: user
--------
name userid
Kashif Mehmood U001
Kamran Ahmad33 U004
Junaid Akram U006
-------

table: taccbalance,
--------
userid amountin amountout
U001  5000.00 NULL
U001 NULL 1000.00
U001 10000.00 NULL
U001 NULL 9000.00
U002 10000.00 NULL
U002 NULL 9000.00
U002 5000.00 NULL
U002 NULL 3000.00
-----------------------

query to get balance is
SELECT userid, SUM(amountin)-SUM(amountout) AS balance
FROM taccbalance
GROUP BY userid;

However If I make join with it,it doesnt work
SELECT a.name, b.userid, b.balance
FROM user AS a
INNER JOIN
    (SELECT userid, SUM(amountin)-SUM(amountout) AS balance
     FROM taccbalance GROUP BY userid) AS b
ON a.userid = b.userid;

It just return only one row, rather it should return multiple rows.
Can someone help please?

A: try using left  join
    SELECT a.name, b.userid, b.balance
    FROM user AS a
    LEFT JOIN
        (SELECT userid, SUM(amountin)-SUM(amountout) AS balance
         FROM taccbalance
         GROUP BY userid
    ) AS b ON a.userid = b.userid;

and check for user U002 you have not this value in user table


text:
Q: How to POST data as JSON in the following format I need to send POST data in the following format.
{
  "buys": [
    {
      "productId": "1ae9ac1a37934fde92d7545cd6c93c13",
      "amount": 200.00
    }
  ]
}

Currently, my PHP script that the form submits to is.
<?php
$productId = $_POST['productId'];
$amount = $_POST['amount'];
$type = $_POST['name'];

//API Url
$url = 'https://********.com/post_test.php';

//Initiate cURL.
$ch = curl_init($url);

//The JSON data.
$jsonData = array(
    'type' => $type,
    'productId' => $productId,
    'amount' => $amount
);

//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);

//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);

//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

//Execute the request
$result = curl_exec($ch);

?>

This is the output after submitting to form on the frontend, which isn't correct. I thought it would redirect to the inputted URL but I assume it's not meant to and it only posts? (as I typed that I to wondered if the output I'm seeing is from the webpage that I am linking at the top of the script, as that page simply echos the JSON as a string).
{"type":"buys","productId":"2ed913357e8842e9a38f0a16eb9703a9","amount":"45866"}

I really don't have any idea what to do next, or what to google to find a tutorial.
Some more details, I have a form that submits to the PHP script above. The variable $name is the "buys" in the requested format, the other variables are self-explanatory.
I'm sure there is just a way I need to format the JSON using my variables but I have no idea where to begin.

A: your json data should be like this
$jsonData = array(
    $type => array(
       'productId' => $productId,
       'amount' => $amount
    )
);

output :

{"busy":{"productId":"1ae9ac1a37934fde92d7545cd6c93c13","amount":"200.00"}}

A: So you want buys to be an array :
//The JSON data.
$jsonData = array(
    $type =>
    array(
        'productId' => $productId,
        'amount' => $amount
    )
);

The output will be {"bugs":{"productId":"productId","amount":"amount"}}

A: Change your $jsonData:
$jsonData = array(
    'type' => $type,
    'productId' => $productId,
    'amount' => $amount
);

As follows:
$jsonData = array();
$jsonData[ $type ] = array();
$jsonData[ $type ][] = array(
    'productId' => $productId,
    'amount' => $amount
);

A: You can try this
   $jsonData['buys'][] = array(
         'productId' => $productId,
        'amount' => $amount
    );


text:
Q: Issue with understanding python bedmas I'm doing a mock test and I am getting most of these bedmas questions wrong...
a) 25 / 4 + 4 * 10 % 3

b) 25 - 7 * 3 + 12 / 3

c) 17 % 3 * 2 - 12 + 15

a)
6.25 + 4 * 1
10.25

b)
25 - 21 + 4
8

c)
2 * 2 - 12 + 15
4 + 3
7

I've only managed to get one right (c). Please help.

A: The problem is that you are dealing with integers not floats and so you must use integer math not float math.
In integer math: 5 / 2 is 2 not 2.5 since the .5 gets truncated. If you wanted to get 2.5, you would have to do: 5.0 / 2.0 or float(5) / float(2).
(Note: As @Grijesh pointed out, in python3 (5/2) actually yields 2.5). However, if you are using any other language, I believe it is as I have described above (python2.7 gives 2))
As follows:
a) 25 / 4 + 4 * 10 % 3
b) 25 - 7 * 3 + 12 / 3
c) 17 % 3 * 2 - 12 + 15

a)
6 + 4 * 1
10

b)
25 - 21 + 4
8

c)
2 * 2 - 12 + 15
4 + 3
7

Hope that helps.


text:
Q: Querying Cloud Datastore - Returning all submissions from currently logged in user I am trying to retrieve all entities that a user has submitted and have tried to do this by using the user's email address as the filter, but I receive this error when querying the datastore:
ValueError: Name 'test@example.com' cannot contain period characters
Query:
email = users.get_current_user().email()

q = WorkRequest.query().filter(email)
results = q.fetch(10)

Can anyone help?

A: You have not structured the query properly.  Try this:
mail = users.get_current_user().email()

q = WorkRequest.query(WorkRequest.email == mail)
results = q.fetch(10)


text:
Q: Filtering out OLED electrical noise I have an OLED display and a high gain op-amp on the same circuit. When OLED is powered on and displaying something, it creates a electrical noise on the output of the opamp. Here is what I tried:

*

*Opamp and OLED power lines are decoupled with closely-positioned 100nf ceramic caps.

*The display is mounted directly behind of the said opamp. To determine if noise is not caused by radiated EMI by the display itself, I connected the display away from the PCB by running a wire. No change.

*Added an LC filter to op-amp supply (ferrite bead and 100n+10u after). No change.

*If I supply the OLED with a seperate power supply, the problem goes away (output looks same as if OLED disconnected).

Here is a scope capture. Please ignore the rising/falling edges.

The OLED driver internally generates ~9V for driving the display. It uses a capacitance multiplier for that and probably that's my problem.
Any help/idea on filtering this supply noise would be appreciated.
Edit 1:

*

*Current draw of the OLED: 10mA@5V

*What is opamp doing: It is MCP601 that I'm using as a thermocouple frontend. Output goes to an ADC (no load).

*Other noise sources: Circuit is supplied with (clean) 12V, goes through on-board 5V linear regulator (with its input and output caps). Everything (OLED, op-amp and MCU) is on the same supply.

*Routing: Two layer PCB with ground pour on each layer. I did not do star grounding though.

*Decoupling on OLED: I modded the OLED board with its supply passes through a ferrite+100n, no change.

*Ferrite bead: I tried what I have on hand, BLM21PG331SN1D and FBMJ2125HS250NT.

A: A large (330uF) capacitor between VDD,VSS is definitly worth doing but you should also investigate tweaking your OLED init code.  Many OLED's have lots of config options to do with voltages and frequencies that can really make a difference to the amount of electrical noise they make by reducing their overall current draw but also by altering the "pattern" of said current draw.
I had the same problem as you with SSD1327 OLED from waveshare. The default configs work great but produced a significant amount of noise in my audio output.  The main turned out to be the refresh rate that was well into the audible range at around 120Hz and much higher than actually necessary.  A bit of tweaking to the internal oscillator config reduced the frame rate to a much lower value leading to less noise in the audible range. Futher tweaking to drive voltages reduced the scale of that noise so much that is almost unnoticable in my application.
I wrote more about it over on the EEVblog


text:
Q: Overriding antd component style for just one component Working with antd components, if you have an Alert component, inside there is a tooltip that is given the styling through ant-alert-icon class. So, if we need to override the Tooltip color, you can have in your stylesheet a class to override the values. For example:
ant-alert-info {
  .ant-alert-icon {
    color: #3d6de7 !important;
  }
}

However, this will apply the color #3d6de7 to all Alerts type Info. How can I apply a different color to just one specific Alert type Info while keeping the styling above for the remaining Alert type Info components? Is this possible? What are the alternatives to doing something similar?
I am able to change the background of the Alert using the style field as follows:
 <Alert
    description={}
    type="info"
    showIcon
    style={!props.alert ? { backgroundColor: "#F4F0F0"} : { backgroundColor: "#fff2f0", border: "#ffccc7" }}
  />

However, I have not been able to change the Tooltip color.
Thanks!

A: You can set an additional className like ant-alert-info-custom this way:
<Alert
   description={}
   type="info"
   showIcon
   className="ant-alert-info-custom ant-alert-info-custom-with-red-icon"
/>

And use it like this:
.ant-alert-info.ant-alert-info-custom {
  // some shared styles by all custom alerts
  .ant-alert-icon {
    color: #3d6de7 !important;
  }
  // specific style for red icon
  &.ant-alert-info-custom-with-red-icon{
    .ant-alert-icon {
      color: red!important;
     }
  }
}

A: As you can see you can do this:
<ConfigProvider csp={{ nonce: 'YourNonceCode' }}>
 <Button>My Button</Button>
</ConfigProvider>

I think you can use ConfigProvider to overwrite Antdesign styles. Check out the link for more info:
ConfigProvider.


text:
Q: Dynamic CSS selector in Angular.js app I am working on an Angular.js app with a plane view that contains objects.
Each time when the user drags an item from the left menu bar on to the middle of the screen, a new object is initiated.
The CSS selector of each item looks like this:
  #drag-item-0

   #drag-item-1

   #drag-item-2

etc.
So basically, each instation of an object leeds to an new CSS selector. I need to give each object different CSS styling, but I don´t know, how the corresponding CSS selector would look like. Any help or hints would be appreciated, thanks!

A: If those are children elements of a, let's say <div Id="elid"><\div> you could use the nth-child(pos) where pos is the children element position.
Like #elid:nth-child(2) to get the second children element of the div.

A: You can target odd and even rows so that new rows are distinctive when added:
div:nth-child(even) {background: #CCC}
div:nth-child(odd) {background: #FFF}

You could also set up a repeater with SASS/LESS to target n number of objects, like this:
@iterations: 10;

.span-loop (@i) when (@i > 0) {
                #drag-item-@{i} {
                    background: rbga(@i * 10, 25,25,1);
                }

            .span-loop(@i - 1);
        }

        .span-loop (@iterations);*/

Which would create css selectors for #drag-item-0 through to #drag-item-10


text:
Q: Loading data from HDFS does not work with Elephantbird I am trying to process data with elephantbird in pig but I don't succeed in loading the data. Here is my pig script:
register 'lib/elephant-bird-core-3.0.9.jar';
register 'lib/elephant-bird-pig-3.0.9.jar';
register 'lib/google-collections-1.0.jar';
register 'lib/json-simple-1.1.jar';

twitter = LOAD 'statuses.log.2013-04-01-00'
          USING com.twitter.elephantbird.pig.load.JsonLoader('-nestedLoad');

DUMP twitter;

The output I get is
[main] INFO  org.apache.pig.Main - Apache Pig version 0.11.0-cdh4.3.0 (rexported) compiled May 27 2013, 20:48:21
[main] INFO  org.apache.pig.Main - Logging error messages to: /home/hadoop1/twitter_test/pig_1374834826168.log
[main] INFO  org.apache.pig.impl.util.Utils - Default bootup file /home/hadoop1/.pigbootup not found
[main] INFO  org.apache.pig.backend.hadoop.executionengine.HExecutionEngine - Connecting to hadoop file system at: hdfs://master.hadoop:8020
[main] INFO  org.apache.pig.backend.hadoop.executionengine.HExecutionEngine - Connecting to map-reduce job tracker at: master.hadoop:8021
[main] INFO  org.apache.pig.tools.pigstats.ScriptState - Pig features used in the script: UNKNOWN
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MRCompiler - File concatenation threshold: 100 optimistic? false
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MultiQueryOptimizer - MR plan size before optimization: 1
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MultiQueryOptimizer - MR plan size after optimization: 1
[main] WARN  org.apache.pig.backend.hadoop23.PigJobControl - falling back to default JobControl (not using hadoop 0.23 ?)
java.lang.NoSuchFieldException: jobsInProgress
    at java.lang.Class.getDeclaredField(Class.java:1938)
    at org.apache.pig.backend.hadoop23.PigJobControl.<clinit>(PigJobControl.java:58)
    at org.apache.pig.backend.hadoop.executionengine.shims.HadoopShims.newJobControl(HadoopShims.java:102)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler.compile(JobControlCompiler.java:285)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher.launchPig(MapReduceLauncher.java:177)
    at org.apache.pig.PigServer.launchPlan(PigServer.java:1266)
    at org.apache.pig.PigServer.executeCompiledLogicalPlan(PigServer.java:1251)
    at org.apache.pig.PigServer.storeEx(PigServer.java:933)
    at org.apache.pig.PigServer.store(PigServer.java:900)
    at org.apache.pig.PigServer.openIterator(PigServer.java:813)
    at org.apache.pig.tools.grunt.GruntParser.processDump(GruntParser.java:696)
    at org.apache.pig.tools.pigscript.parser.PigScriptParser.parse(PigScriptParser.java:320)
    at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:194)
    at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:170)
    at org.apache.pig.tools.grunt.Grunt.exec(Grunt.java:84)
    at org.apache.pig.Main.run(Main.java:604)
    at org.apache.pig.Main.main(Main.java:157)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:208)
[main] INFO  org.apache.pig.tools.pigstats.ScriptState - Pig script settings are added to the job
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - mapred.job.reduce.markreset.buffer.percent is not set, set to default 0.3
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - Using reducer estimator: org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.InputSizeReducerEstimator
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.InputSizeReducerEstimator - BytesPerReducer=1000000000 maxReducers=999 totalInputFileSize=656085089
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - Setting Parallelism to 1
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - creating jar file Job6015425922938886053.jar
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - jar file Job6015425922938886053.jar created
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - Setting up single store job
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - 1 map-reduce job(s) waiting for submission.
[JobControl] WARN  org.apache.hadoop.mapred.JobClient - Use GenericOptionsParser for parsing the arguments. Applications should implement Tool for the same.
[JobControl] INFO  org.apache.hadoop.mapreduce.lib.input.FileInputFormat - Total input paths to process : 1
[JobControl] INFO  org.apache.pig.backend.hadoop.executionengine.util.MapRedUtil - Total input paths (combined) to process : 5
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - 0% complete
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - HadoopJobId: job_201307261031_0050
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - Processing aliases twitter
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - detailed locations: M: twitter[10,10] C:  R:
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - More information at: http://master.hadoop:50030/jobdetails.jsp?jobid=job_201307261031_0050
[main] WARN  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - Ooops! Some job has failed! Specify -stop_on_failure if you want Pig to stop immediately on failure.
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - job job_201307261031_0050 has failed! Stop running all dependent jobs
[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - 100% complete
[main] ERROR org.apache.pig.tools.pigstats.SimplePigStats - ERROR 2997: Unable to recreate exception from backed error: Error: Found interface org.apache.hadoop.mapreduce.Counter, but class was expected
[main] ERROR org.apache.pig.tools.pigstats.PigStatsUtil - 1 map reduce job(s) failed!
[main] INFO  org.apache.pig.tools.pigstats.SimplePigStats - Script Statistics:

HadoopVersion   PigVersion  UserId  StartedAt   FinishedAt  Features
2.0.0-cdh4.3.0  0.11.0-cdh4.3.0 hadoop1 2013-07-26 12:33:48 2013-07-26 12:34:23 UNKNOWN

Failed!

Failed Jobs:
JobId   Alias   Feature Message Outputs
job_201307261031_0050   twitter MAP_ONLY    Message: Job failed!    hdfs://master.hadoop:8020/tmp/temp971280905/tmp1376631504,

Input(s):
Failed to read data from "hdfs://master.hadoop:8020/user/hadoop1/statuses.log.2013-04-01-00"

Output(s):
Failed to produce result in "hdfs://master.hadoop:8020/tmp/temp971280905/tmp1376631504"

Counters:
Total records written : 0
Total bytes written : 0
Spillable Memory Manager spill count : 0
Total bags proactively spilled: 0
Total records proactively spilled: 0

Job DAG:
job_201307261031_0050

[main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - Failed!
[main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 2997: Unable to recreate exception from backed error: Error: Found interface org.apache.hadoop.mapreduce.Counter, but class was expected
Details at logfile: /home/hadoop1/twitter_test/pig_1374834826168.log

The file exists and is accessible:
$ hdfs dfs -ls /user/hadoop1/statuses.log.2013-04-01-00
Found 1 items
-rw-r--r--   3 hadoop1 supergroup  656085089 2013-07-26 11:53 /user/hadoop1/statuses.log.2013-04-01-00

This seems to be a general problem with the pig version shipped with Cloudera 4.6.0: the problem seems to be the line that says
[main] ERROR org.apache.pig.tools.pigstats.SimplePigStats - ERROR 2997: Unable to recreate exception from backed error: Error: Found interface org.apache.hadoop.mapreduce.Counter, but class was expected

I got a similar error when running another user defined function for loading data:
[main] ERROR org.apache.pig.tools.pigstats.SimplePigStats - ERROR 2997: Unable to recreate exception from backed error: Error: Found interface org.apache.hadoop.mapreduce.TaskAttemptContext, but class was expected

When I force pig to local mode (''-x local'') I get the more obvious error
Caused by: java.lang.IncompatibleClassChangeError: Found interface org.apache.hadoop.mapreduce.TaskAttemptContext, but class was expected

So the version of Hadoop pig uses seems to be incompatible with the one shipped with Cloudera, I guess.

A: This is indeed a versioning problem: some libraries are not yet compatible with the new MapReduce API, see for example the issues #56, #247 and #308.
For ElephantBird the issue is solved in a recent version. Using ElephantBird 4.1 in the above code and adding the Hadoop compatibility module
register 'lib/elephant-bird-core-4.1.jar';
register 'lib/elephant-bird-pig-4.1.jar';
register 'lib/elephant-bird-hadoop-compat-4.1.jar';
register 'lib/google-collections-1.0.jar';
register 'lib/json-simple-1.1.jar';

solved the problem! :-)


text:
Q: how to count collection.defaultdict values? I have a file with type= collections.defaultdict
it is like this:
defaultdict(set,
            {'2712': {'java', 'manager', 'program', 'programme', 'senior'},
             '3193': {'agile', 'coach', 'master', 'scrum'},
             '2655': {'business', 'consultant', 'principal'})

I have never worked with this type. How I can count each elements for each keys? for example for '2712' is 5 for 3193 is 4 and for 2655 is 3.

A: As the docs for defaultdict say, you can use a default dict in the same way as a normal dict, using the square brackets for indexing for keys, and iterating through the list of keys with a for loop, as below:
d = defaultdict(
    set, {
        '2712': {'java', 'manager', 'program', 'programme', 'senior'},
        '3193': {'agile', 'coach', 'master', 'scrum'},
        '2655': {'business', 'consultant', 'principal'}
    })

for key in d:
    print(f"The set at key {key} is {len(d[key])} long.")

See repl here

A: for key, value in some_dict.items():
    print(f'{key}: {len(value)}')

where some_dict is your dict/defaultdict.


text:
Q: Условие в значении свойства JSON Я создал JSON используя Survey Creator:
{
 "pages": [
  {
   "name": "page1",
   "elements": [
    {
     "type": "radiogroup",
     "name": "question1",
     "choices": [
      "item1",
      "item2",
      "item3"
     ]
    },
    {
     "type": "text",
     "name": "question2",
     "visibleIf": "{question1} = \"item1\""
    }
  }
 ]
}

В зависимости от значения свойства visibleIf должен скрываться или показываться вопрос question2.
Что значит {question1} = \"item1\" в значении свойства visibleIf. Как это выразить в MySQL базе данных, чтобы получить это условие в свойстве visibleIf объекта JSON? Какой тип поля? Как это будет работать?


text:
Q: generic compareTo sorting different object classes I am trying to use compareTo to return the largest or maximum of various types of objects. This works for integers, strings, but I am having when I try to include circles...
How can I get one generic method to compare all objects? In this case circles only have one variable, radius, to compare...

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

 Integer[] numbers = {1, -2, 3, 0, -1, 2, -3};
 String[] colors = {"blue", "green", "white", "red", "black"};
 Circle[] circles = {new Circle(5.9), new Circle(.5), new Circle(1),
   new Circle(2.5), new Circle(.1)};

 System.out.println("Numerically, the maximum number is: " + max(numbers));
 System.out.println("Alphabetically, the maximum color is: " + max(colors));
 System.out.println("The largest circle has a radius of: " + max(circles);
 }

 public static <T extends Comparable<T>> T max(T[] list) {
  T currentMax = null;
  int currentMaxIndex;

  for (int i = 0; i < list.length - 1; i++) {
   currentMax = list[i];
   currentMaxIndex = i;

   for (int j = i + 1; j < list.length; j++) {
    if (currentMax.compareTo(list[j]) > 0) {
     currentMax = list[j];
     currentMaxIndex = j;
    }
   }

   if (currentMaxIndex != i) {
    list[currentMaxIndex] = list[i];
    list[i] = currentMax;
   }
  }
  return currentMax;
 }
}

A: "How can I get one generic method to compare all objects?"
There is no ONE generic way to compare objects , thats why compareTo and Comparable were made in the first place . Consider students in a class , i can compare them based on height , score , age ...
Just make a Class of w.e concept you want (say a circle) , implement Comparable and define compareTo to define the criteria for how u compare that Object. for example :
public class Circle implements Comparable<Circle> {
 int diameter;
 //constructor
 public int compareTo(Circle c) {
   if(c.diameter> this.diameter){
   return 1;
  }else if ....

A: You must implement Comparable interface in Circle.


text:
Q: strange error message in a complex, but legal Perl one-liner >perl -e '$_ = q(t b[\)sizeof];); s/(t?(\w)(?:\s(\w))?\s(\w)(\[([^\]]+)\]))/eval $1/e'
Bareword found where operator expected at (eval 1) line 1, near ")sizeof"
    (Missing operator before sizeof?)

This is legal Perl, then why the error message?  I have the latest Perl.
This is an SSCCE ; any one character less and the error message does not appear.

A: The Perl code is valid, but you are trying to eval a string which is not valid Perl code. When I run this code and swap eval for print, it prints the string:
t b[)sizeof]

Now if I try and run this as Perl code I get:
> perl -we't b[)sizeof]'
Bareword found where operator expected at -e line 1, near ")sizeof"
        (Missing operator before sizeof?)
Unquoted string "sizeof" may clash with future reserved word at -e line 1.
syntax error at -e line 1, near "[)"
Execution of -e aborted due to compilation errors.

(You should always use warnings -w, even with one-liners)
This code does exactly what your evaluation is trying to do: It's trying to run that string as Perl code, and it fails because that string is not valid Perl code.
Also you should be careful when using eval, as it can do unexpected and catastrophical things to your computer. Usually, this kind of double evaluation is written using two of the /e modifiers, e.g.:
s/.../.../ee

Which is a bit more convenient than
s/.../eval .../e


text:
Q: jackson deserialize object with list of spring's interface I need to save and load objects from redis.
The object contains list of GrantedAuthority (among other things) which is an interface:
public class UserAccountAuthentication implements Authentication {
    private List<GrantedAuthority> authorities;
    private boolean authenticated = true;
    ...
}

Jackson successfully serializes the object but fails to deserialize it with the following exception:
abstract types can only be instantiated with additional type information

I know that I can specify the type by adding:
@JsonTypeInfo(

But I can't do it in this case because the GrantedAuthority is an interface of Spring and I cannot change it.

the serialized json is:
{
"authorities": [
    {
        "authority": "ROLE_NORMAL_USER"
    }
],
"authenticated": true,
"securityToken": {
    "expiration": 1458635906853,
    "token": "sxKi3Pddfewl2rgpatVE7KiSR5qGmhpGl0spiHUTLAAW8zuoLFE0VLFYcfk72VLnli66fcVmb8aK9qFavyix3bOwgp1DRGtGacPI",
    "roles": [
        "ROLE_NORMAL_USER"
    ],
    "expired": false,
    "expirationDateFormatted": "2016-03-22 08:38:26.853 UTC"
},
"name": "admin",
"expired": false

}

the abstract GrantedAuthority is only filled with SimpleGrantedAuthority.
so i tried:
objectMapper.registerSubtypes(SimpleGrantedAuthority.class);

and still no luck.

A: I think you need to add a custom deserializer
public class UserAccountAuthenticationSerializer extends JsonDeserializer<UserAccountAuthentication> {

@Override
public UserAccountAuthentication deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
        throws IOException {

    UserAccountAuthentication userAccountAuthentication = new UserAccountAuthentication();

    ObjectCodec oc = jsonParser.getCodec();
    JsonNode node = oc.readTree(jsonParser);
    userAccountAuthentication.setAuthenticated(node.get("authenticated").booleanValue());

    Iterator<JsonNode> elements = node.get("authorities").elements();
    while (elements.hasNext()) {
        JsonNode next = elements.next();
        JsonNode authority = next.get("authority");
        userAccountAuthentication.getAuthorities().add(new SimpleGrantedAuthority(authority.asText()));
    }
    return userAccountAuthentication;
}

}
This is my json
{"authenticated":true,"authorities":[{"authority":"role1"},{"authority":"role2"}],"details":null,"principal":null,"credentials":null,"name":null}

Then at the top of your POJO
@JsonDeserialize(using = UserAccountAuthenticationSerializer.class)
public class UserAccountAuthentication  implements Authentication {

Here's the test
@Test
public void test1() throws IOException {

UserAccountAuthentication userAccountAuthentication = new UserAccountAuthentication();
userAccountAuthentication.setAuthenticated(true);
userAccountAuthentication.getAuthorities().add(new SimpleGrantedAuthority("role1"));
userAccountAuthentication.getAuthorities().add(new SimpleGrantedAuthority("role2"));

String json1 = new ObjectMapper().writeValueAsString(userAccountAuthentication);
UserAccountAuthentication readValue = new ObjectMapper().readValue(json1, UserAccountAuthentication.class);
String json2 = new ObjectMapper().writeValueAsString(readValue);
assertEquals(json1, json2);

}


text:
Q: How can I show mysql locks? Is there anyway to show all the locks that are active in a mysql database?

A: Reference taken from this post.
You can use below script:
SELECT
    pl.id
    ,pl.user
    ,pl.state
    ,it.trx_id
    ,it.trx_mysql_thread_id
    ,it.trx_query AS query
    ,it.trx_id AS blocking_trx_id
    ,it.trx_mysql_thread_id AS blocking_thread
    ,it.trx_query AS blocking_query
FROM information_schema.processlist AS pl
INNER JOIN information_schema.innodb_trx AS it
    ON pl.id = it.trx_mysql_thread_id
INNER JOIN information_schema.innodb_lock_waits AS ilw
    ON it.trx_id = ilw.requesting_trx_id
        AND it.trx_id = ilw.blocking_trx_id

A: Using this command
SHOW PROCESSLIST

will show all process currently running, including process that has acquired lock on tables.

A: AFAIK there's still no native way in MYSQL, but I use innotop. It's free and has plenty of other functionality as well.
Also see this link for more information on using the innotop tool.

A: See Marko's link for InnoDB tables and the caveats.
For MyISAM, there isn't a dead easy "this is the offending query" solution. You should always start with a processlist. But be sure to include the full keyword so that the printed queries aren't truncated:
SHOW FULL PROCESSLIST;

This will show you a list of all current processes, their SQL query and state. Now usually if a single query is causing many others to lock then it should be easy to identify. The affected queries will have a status of Locked and the offending query will be sitting out by itself, possibly waiting for something intensive, like a temporary table.
If it's not obvious then you will have to use your powers of SQL deduction to determine which piece of offending SQL may be the cause of your woes.

A: If you use InnoDB and need to check running queries I recommend
show engine innodb status;
as mentioned in Marko's link. This will give you the locking query, how many rows/tables are locked by it etc. Look under TRANSACTIONS.
The problem with using SHOW PROCESSLIST is that you won't see the locks unless other queries are queueing up.

A: Try SHOW OPEN TABLES:
show open tables where In_Use > 0 ;

A: None of the answers can show all the locks that are currently held.
Do this e.g. in mysql in a terminal.
start transaction;
update someTable set name="foobar" where ID=1234;
-- but no rollback or commit - just let it sit there

Clearly the transaction above holds a lock, because the transaction is still active. But no query is going on right now and nobody is waiting for a lock anywhere (yet at least).
INFORMATION_SCHEMA.INNODB_LOCKS is empty, which makes sense given the documentation, because there is only one transaction and currently nobody waiting for any locks. Also INNODB_LOCKS is deprecated anyway.
SHOW ENGINE INNODB STATUS is useless: someTable is not mentioned at all
SHOW FULL PROCESSLIST is empty, because the culprit is not actually running a query right now.
You can use INFORMATION_SCHEMA.INNODB_TRX, performance_schema.events_statements_history and performance_schema.threads to extract the queries that any active transactions have executed in the past as outlined in my other answer, but I haven't come across any way to see that someTable is locked in the above scenario.
The suggestions in the other answers so far won't help at least.
Disclaimer: I don't have innotop installed and I didn't bother. Perhaps that could work.


text:
Q: Path dependent Markov property Let's consider a function $\Psi\in \mathcal{C}_B(\mathcal{C}[t,T])$ continuous and bounded
\begin{align*}
    \Psi \colon \mathcal{C}[t,T]  \longrightarrow [0,+\infty)
\end{align*}
Then my question is: Is the following equality true?
\begin{align*}
\mathbb{E} \left [ \Psi\left(S_s, s\in [t,T]\right)  \big| \mathcal {F}_t \right ] = \mathbb{E} \left [ \Psi\left(S_s, s\in [t,T]\right)  \big| S_t \right ]
\end{align*}
where $S$ is the unique strong solution of a standar SDE with Lipschitz and sublinear coefficients $$dS_s=b(s,S_s)ds+\sigma(s,S_s)dW_s$$ with $S_t=\bar{s}$, $t\leq s \leq T$.
We obviously know $S$ is a Markov process by standard theory, so we have the standard Markov property:
let $s>t$
\begin{align*}
\mathbb{E} \left [ \Phi(S_s)  \big| \mathcal {F}_t \right ] = \mathbb{E} \left [ \Phi(S_s)  \big| S_t \right ]
\end{align*}
where $\mathcal{F}_t$ is the filtration with respect to $W$ is a brownian motion.
In other word the question is if this Markov property is preserved for a path-dependent process $\Psi=\Psi\left(S_s, s\in [t,T] \right)$ ?
Thanks everybody for your help.


text:
Q: Cannot clone git repo - Templates not found I am getting an error when attempting to clone a git repo using attlassian source tree stating
error: templates not found /usr/local/git/share/git-core/templates

A quick google search shows a few solutions to this issue, but none have worked for me.
When I do attempt to clone a repo, the installation will never complete.
Any ideas how I can fix this?
EDIT:
I tried all solutions stated in this post


text:
Q: Binary classifier of words in list I have extracted text using OCR from a number of stylized documents in Swedish. Now I want formalize the data and extract city names. Due to the OCR working imperfectly, the names are sometimes spelled wrong and shows up at semi-random positions in the text. Therefore regex does not work.
Is it a good procedure/possible to transform the text into bags of words and train an algorithm to binary categorize words as city vs not city?
Consider example data set:
Col1                                          Col2
['Hi', 'there', 'Haag']                      ['Haag']
['Paris, 'is', 'better', 'than', 'Osloe]     ['Paris', 'Oslo']
['My', 'hometown', 'is', 'New York']         ['New York']
...

I want to use Col1 as X variable and Col2 as Y variable. Is this a good procedure or should I use another method?

A: One possible way of dealing with spelling mistakes is to first collect your vocabulary (all words in the corpus) and to then select candidate OCR mistakes by their individual term frequencies (assuming that mistakes like "Osloe" are rare). In a second step you could use Edit distance to link candidate spelling mistakes to their correct word forms.
To extract cities you could, for example, take a look at spacy's pretrained models for named entity recognition.
Collocations like "New York" you could identify by contrasting the frequency of the terms to go together in sequence vs the individual term frequencies (depending on your corpus "York" might often go together with "New" much more often than one would assume under a hypothesis of the occurrence of "New" and "York" being independent).


text:
Q: PSModule provider is missing I recently installed Windows 10 on my laptop. Problem is that I cannot install apps from OneGet because I cannot install Chocolatey source because PSModule provider is missing. Screenshot:
Click for full size
I also screenshoted my main PC where everything works fine:
Click for full size
how can it be fixed?
Difference between PC: I have MSVS2015 installed on main PC, and it was updated from 8.1 against laptop clean install

A:
Currently, OneGet is in flux. The initial version of OneGet shipped
  with Chocolatey as its sole default repository, but Chocolatey has now
  been removed from the default configuration. A Chocolatey package
  source will soon be available for easy installation via OneGet. You
  can currently install the Chocolatey package source with a command,
  but Chocolatey's packages wouldn't actually install on our system
  after doing so. This is a minor roadbump in development.

Source: http://www.howtogeek.com/200334/windows-10-includes-a-linux-style-package-manager-named-oneget/?PageSpeed=noscript


text:
Q: API not available after custom build I successfully built the ClassicEditor from source with the inline widget plugin (https://ckeditor.com/docs/ckeditor5/latest/framework/guides/tutorials/implementing-an-inline-widget.html). If I include
ClassicEditor
    .create( document.querySelector( '#editor' ), {
...

in app.js, I am able to create an instance of the editor, with the plugin available. However, when I include ckeditor.js in my page, and try to run the same code to initialize an editor, I get
ReferenceError: Can't find variable: ClassicEditor

Any idea what the issue could be?

A: I found something that works here:
Getting ClassicEditor exported on custom build of CKEditor 5
Basically add window.ClassicEditor=ClassicEditor; to the bottom of app.js.
That doesn't make all the plugins available to reference when creating a ClassicEditor instance, but I can just specify those as default plugins in app.js. Not really sure if this is the way it's supposed to be done, since the samples from the online builder don't work this way, but there are no clear directions so this will work for my purposes.


text:
Q: Changing Heroku folder when creating app in Eclipse So I'm new to Heroku and I have a little problem. I use WAMPP to test my webapp in my local machine and as you know the project MUST be in the www folder. When I create an Heroku app in Eclipse it immediately is created in c:\users\myname\git\heroku\appname and I DON'T want that!
Is simple, I want to all my Heroku apps to be created in a folder in the WAMPP www folder and, if possible, to change the GIT folder to be inside that www folder so then I can test my project in my local machine also.
Thanks in advance!

A: You can just move the directory and then import an existing project in Eclipse.  Make sure you tell Eclipse not to copy the contents into the workspace.


text:
Q: Как определить, что checkBox активирован? Как определить, что CheckBox активирован?
Допустим, если checkBox активен, то выводилось 1, если не активно, то 2.
Как это сделать? Активным я считаю, если на виджете есть "галочка".
с = #определение состояния
if c == #есть "галочка":
   x = 5
elif c == #нет "галочки":
   x = 10
print(x)

#что-то не так
import subprocess
from PyQt5.QtWidgets import QApplication
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(959, 365)
        Form.setStyleSheet("")
        self.checkBox = QtWidgets.QCheckBox(Form)
        self.checkBox.setGeometry(QtCore.QRect(20, 230, 421, 41))
        self.checkBox.setObjectName("checkBox")
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(23, 30, 441, 41))
        self.label.setStyleSheet("font: 87 12pt \"Arial Black\";")
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(Form)
        self.label_2.setGeometry(QtCore.QRect(494, 20, 421, 61))
        self.label_2.setStyleSheet("font: 87 12pt \"Arial Black\";")
        self.label_2.setObjectName("label_2")
        self.lineEdit = QtWidgets.QLineEdit(Form)
        self.lineEdit.setGeometry(QtCore.QRect(20, 80, 421, 41))
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit_2 = QtWidgets.QLineEdit(Form)
        self.lineEdit_2.setGeometry(QtCore.QRect(490, 80, 431, 41))
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.label_3 = QtWidgets.QLabel(Form)
        self.label_3.setGeometry(QtCore.QRect(25, 164, 421, 21))
        self.label_3.setStyleSheet("font: 87 12pt \"Arial Black\";")
        self.label_3.setObjectName("label_3")
        self.label_4 = QtWidgets.QLabel(Form)
        self.label_4.setGeometry(QtCore.QRect(493, 160, 421, 31))
        self.label_4.setStyleSheet("font: 87 12pt \"Arial Black\";")
        self.label_4.setObjectName("label_4")
        self.lineEdit_3 = QtWidgets.QLineEdit(Form)
        self.lineEdit_3.setGeometry(QtCore.QRect(21, 190, 421, 41))
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.lineEdit_4 = QtWidgets.QLineEdit(Form)
        self.lineEdit_4.setGeometry(QtCore.QRect(489, 190, 431, 41))
        self.lineEdit_4.setObjectName("lineEdit_4")
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(20, 280, 901, 51))
        self.pushButton.setStyleSheet("font: 87 26pt \"Arial Black\";")
        self.pushButton.setObjectName("pushButton")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)
        self.checkBox.stateChanged.connect(
            lambda state=self.checkBox.isChecked(), no=1: self.selectBooks(state, no))

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.checkBox.setText(_translate("Form", "Использовать тот же путь"))
        self.label.setText(_translate("Form", "Введи путь до исходного файла"))
        self.label_2.setText(_translate("Form", "Введи название исходного файла"))
        self.label_3.setText(_translate("Form", "Введи путь до конечного файла"))
        self.label_4.setText(_translate("Form", "Введи название конечного файла"))
        self.pushButton.setText(_translate("Form", "Конвертировать"))

app = QApplication([])

class Main(QtWidgets.QWidget, Ui_Form):
    def __init__(self, parent=None):
        super(Main, self).__init__(parent)
        self.setupUi(self)
        file = str(self.lineEdit.text()) + "/" + str(self.lineEdit_2)
        def selectBooks(self, toggle, no):
            if toggle == QtCore.Qt.Checked:
                print('toggle=`{}`, checked_{}'.format(toggle, no))
                if no == 1:
                    print('checked_{} -> галочка поставлена выполнилось действие'.format(no))
            else:
                print('toggle=`{}`, unchecked_{}'.format(toggle, no))

mw = Main()
mw.show()

app.exec()

A: Никогда не изменяйте модуль созданный в QT Designer
selectBooks метод  class Main сдвинули на 4 позиции влево.
from PyQt5.QtWidgets import QApplication
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(959, 365)
        Form.setStyleSheet("")
        self.checkBox = QtWidgets.QCheckBox(Form)
        self.checkBox.setGeometry(QtCore.QRect(20, 230, 421, 41))
        self.checkBox.setObjectName("checkBox")
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(23, 30, 441, 41))
        self.label.setStyleSheet("font: 87 12pt \"Arial Black\";")
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(Form)
        self.label_2.setGeometry(QtCore.QRect(494, 20, 421, 61))
        self.label_2.setStyleSheet("font: 87 12pt \"Arial Black\";")
        self.label_2.setObjectName("label_2")
        self.lineEdit = QtWidgets.QLineEdit(Form)
        self.lineEdit.setGeometry(QtCore.QRect(20, 80, 421, 41))
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit_2 = QtWidgets.QLineEdit(Form)
        self.lineEdit_2.setGeometry(QtCore.QRect(490, 80, 431, 41))
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.label_3 = QtWidgets.QLabel(Form)
        self.label_3.setGeometry(QtCore.QRect(25, 164, 421, 21))
        self.label_3.setStyleSheet("font: 87 12pt \"Arial Black\";")
        self.label_3.setObjectName("label_3")
        self.label_4 = QtWidgets.QLabel(Form)
        self.label_4.setGeometry(QtCore.QRect(493, 160, 421, 31))
        self.label_4.setStyleSheet("font: 87 12pt \"Arial Black\";")
        self.label_4.setObjectName("label_4")
        self.lineEdit_3 = QtWidgets.QLineEdit(Form)
        self.lineEdit_3.setGeometry(QtCore.QRect(21, 190, 421, 41))
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.lineEdit_4 = QtWidgets.QLineEdit(Form)
        self.lineEdit_4.setGeometry(QtCore.QRect(489, 190, 431, 41))
        self.lineEdit_4.setObjectName("lineEdit_4")
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(20, 280, 901, 51))
        self.pushButton.setStyleSheet("font: 87 26pt \"Arial Black\";")
        self.pushButton.setObjectName("pushButton")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.checkBox.setText(_translate("Form", "Использовать тот же путь"))
        self.label.setText(_translate("Form", "Введи путь до исходного файла"))
        self.label_2.setText(_translate("Form", "Введи название исходного файла"))
        self.label_3.setText(_translate("Form", "Введи путь до конечного файла"))
        self.label_4.setText(_translate("Form", "Введи название конечного файла"))
        self.pushButton.setText(_translate("Form", "Конвертировать"))

class Main(QtWidgets.QWidget, Ui_Form):
    def __init__(self, parent=None):
        super(Main, self).__init__(parent)
        self.setupUi(self)
        file = str(self.lineEdit.text()) + "/" + str(self.lineEdit_2)

        # Никогда не изменяйте модуль созданный в QT Designer
        self.checkBox.stateChanged.connect(
            lambda state=self.checkBox.isChecked(), no=1: self.selectBooks(state, no))

#   <---- это метод  class Main сдвинули на 4 позиции влево
    def selectBooks(self, toggle, no):
        if toggle == QtCore.Qt.Checked:
            print('toggle=`{}`, checked_{}'.format(toggle, no))
            if no == 1:
                print('checked_{} -> галочка поставлена выполнилось действие'.format(no))
        else:
            print('toggle=`{}`, unchecked_{}'.format(toggle, no))

if __name__ == '__main__':
    app = QApplication([])
    mw = Main()
    mw.show()
    app.exec()


text:
Q: How do I fix key not found error in python? I'm new to coding and I'm trying to write a password manager program here. I decided to use sg.Frame instead of sg.Tab (Which worked just fine but I just don't like how it looked.) and ran into this problem where it has problem finding the key 'Login'. What made me confused is I already assigned the key in line 22 or am I doing something wrong? (Which is extremely likely.)
import random
import getpass
import PySimpleGUI as sg

us = '*'
pw = '**'

main_enabled=False

login_layout = [
        [sg.Text('Username'), sg.InputText(do_not_clear=False)],
        [sg.Text('Password'), sg.InputText(do_not_clear=False)],
        [sg.Button('OK')]
    ]

main_layout = [
        [sg.Button('Saved Passwords')],
        [sg.Button('Generate New Password')]
    ]

layout = [
    [sg.Frame('Login', login_layout, visible=True)],
    [sg.Frame('Main', main_layout, visible=False)]
]

window = sg.Window('PWKeep', layout, resizable=True)

while not window.was_closed():
    event, values = window.read()
    if event == 'OK':
        if values[0] == us and values[1] == pw:
            main_enabled=True
            window['Login'].update(visible=False)
            window['Main'].update(visible=True)
        else :
            sg.Popup('Wrong Username or Password. Please Try Again.')

window.close()

Don't worry about the hardcoded username and password, This program is far from finished as you may already have seen.
I also would love to hear about how I can optimize/improve this program further.

A: You need to assign the element a key attribute like this:
layout = [
    [sg.Frame('Login', login_layout, visible=True, key='Login')],
    [sg.Frame('Main', main_layout, visible=False, key='Main')]
]

Then you will have window['Login'] and window['Main'] working properly.


text:
Q: p:dataTable: How to sort only the data on the current page like Struts ? I am given the task to port an old Struts 1.3 application on Jetty 9.3 to JSF/Primefaces.
The well-know Struts <display:table>-component has a sort-attribute which can have either "list" or "page" as values, meaning either to sort the entire underlying data or just the visible part of it on the current page, respectively.
How can this be emulated with JSF <h:dataTable> or preferably Primefaces <p:dataTable>?
I have consulted the Primefaces 5.3 user guide, the showcase and many internet resources and of course stackoverflow search.
The lazy loading features of Primefaces could be a key I figured but no complete example was to be found.
Is there a complete example with say in-memory dummy data?,

A: PrimeFaces supports lazyloading for the datatable. The feature that you can do lazy loading (no need to fully load all data upfront),  is actually provided by  actually giving you full control of any aspect of sorting, paging and filtering.
Normally you would filter, sort and then page, but that could be done in any order.
So it is very simple to just sort after you e.g. loaded the data for the right page with the right filter instead of doing the sorting before the paging.
That way you achieve the behaviour you want.


text:
Q: Google Maps API & geoxml 3 - Zoom to placemark on click/Center placemark on map UPDATED SCRIPT - with click and zoom/center
Still not quite right, first click shows infoWindow put does not zoom/center
// When the window has finished loading create our google map below
    google.maps.event.addDomListener(window, 'load', initialize);

var geoXml = null;
var geoXmlDoc = null;
var map = null;
var myLatLng = null;
var myGeoXml3Zoom = false;
var sidebarHtml = "";
var infowindow = null;
var kmlLayer = null;
var filename = "test.kml.xml";

    function initialize() {
      myLatLng = new google.maps.LatLng(52.60426, 1.72764);
      // these set the initial center and zoom for the map
      // if it is not specified in the query string
      var lat = 52.60426;
      var lng = 1.72764;
      var zoom = 16;

      if (!isNaN(lat) && !isNaN(lng)) {
        myLatLng = new google.maps.LatLng(lat, lng);
      }
                var myOptions = {
                    zoom: zoom,
                    center: myLatLng,
                    streetViewControl: false,
                    mapTypeControl: false,
                    zoomControl: true,
                    // How you would like to style the map.
                    // This is where you would paste any style found on Snazzy Maps.
                    styles: [{"featureType":"all","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"administrative.country","elementType":"labels.text","stylers":[{"visibility":"off"}]},{"featureType":"administrative.province","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"administrative.locality","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"administrative.neighborhood","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"administrative.land_parcel","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"landscape.man_made","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"landscape.natural","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"on"}]},{"featureType":"road.arterial","elementType":"labels.text","stylers":[{"visibility":"on"}]},{"featureType":"transit","elementType":"labels","stylers":[{"visibility":"off"}]}]
                    // zoom: 16,
                    // center: myLatlng,
                };
                map = new google.maps.Map(document.getElementById("map"),
                      myOptions);
                infowindow = new google.maps.InfoWindow({});

   geoXml = new geoXML3.parser({
                    map: map,
                    infoWindow: infowindow,
                    singleInfoWindow: true,
                    zoom: myGeoXml3Zoom,
                    afterParse: useTheData
                });
                geoXml.parse(filename);
        };

function kmlClick(pm) {
       if (geoXml.docs[0].placemarks[pm].marker.getMap()) {
          google.maps.event.trigger(geoXml.docs[0].placemarks[pm].marker,"click");
       } else {
          geoXmlDoc.placemarks[pm].marker.setMap(map);
          google.maps.event.trigger(geoXmlDoc.placemarks[pm].marker,"click");
       }

    google.maps.event.addListener(geoXml.docs[0].placemarks[pm].marker, "click", function (e) {
        map.setZoom(19);
        //infoWindow.open(map, marker);

        map.panTo(geoXml.docs[0].placemarks[pm].marker.getPosition());
    });
}

function showAll() {
        map.setZoom(16);
        map.panTo(myLatLng);
}

// == builds the sidebar ==

function makeSidebarEntry(i) {
  var name = geoXmlDoc.placemarks[i].name;
   if (!name  || (name.length == 0)) name = "marker #"+i;
   // alert(name);
   sidebarHtml += '
	'+name+'
';
}

function makeSidebar() {
  sidebarHtml = '

';
  var currentBounds = map.getBounds();
// if bounds not yet available, just use the empty bounds object;
if (!currentBounds) currentBounds=new google.maps.LatLngBounds();
if (geoXmlDoc) {
  for (var i=0; i<geoXmlDoc.placemarks.length; i++) {
    if (geoXmlDoc.placemarks[i].marker) {
      if (currentBounds.contains(geoXmlDoc.placemarks[i].marker.getPosition())) {
         makeSidebarEntry(i);
      }
    }
  }
}
  sidebarHtml += "
";
  document.getElementById("sidebar").innerHTML = sidebarHtml;
}

function useTheData(doc){
  var currentBounds = map.getBounds();
  if (!currentBounds) currentBounds=new google.maps.LatLngBounds();
  // Geodata handling goes here, using JSON properties of the doc object
  sidebarHtml = '

';
//  var sidebarHtml = '
';
  geoXmlDoc = doc[0];
  for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
    // console.log(doc[0].markers[i].title);
    var placemark = geoXmlDoc.placemarks[i];
    if (placemark.marker) {
      if (currentBounds.contains(placemark.marker.getPosition())) {
         makeSidebarEntry(i);
      }
    }

/*    doc[0].markers[i].setVisible(false); */
  }
  sidebarHtml += "
";
  document.getElementById("sidebar").innerHTML = sidebarHtml;
};

XML:
<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2'>
    <Document>
        <name>Map</name>
        <description></description>
        <Folder>
            <name>Points</name>
            <Placemark>
                <name>Placemark 1</name>
                <description>Description</description>

                <Point>
                    <coordinates>1.7275818,52.6043317,0.0</coordinates>
                </Point>
            </Placemark>
            <Placemark>
                <name>Placemark 2</name>
                <description>Description</description>

                <Point>
                    <coordinates>1.73041,52.60436,0.0</coordinates>
                </Point>
            </Placemark>
        </Folder>

    </Document>
</kml>

Hi i'm trying to create a custom map using Google Maps API and geoxml3. I have managed to set up the map and add a custom sidebar with a list of placemarks which are loaded from an external KML.xml file.
I want to have it so when you click a placemark from the sidebar, or on the map itself, the map will auto center on the placemark and also zoom in.
Heres the HTML and Script I have so far,
HTML:

    <title>Test Map</title>
    <link rel="stylesheet" href="css/style.css" type="text/css">

Locations

*Click to show location on map

Script:
// When the window has finished loading create our google map below
    google.maps.event.addDomListener(window, 'load', initialize);

var geoXml = null;
var geoXmlDoc = null;
var map = null;
var myLatLng = null;
var myGeoXml3Zoom = false;
var sidebarHtml = "";
var infowindow = null;
var kmlLayer = null;
var filename = "test.kml.xml";

    function initialize() {
      myLatLng = new google.maps.LatLng(52.60426, 1.72764);
      // these set the initial center and zoom for the map
      // if it is not specified in the query string
      var lat = 52.60426;
      var lng = 1.72764;
      var zoom = 16;

      if (!isNaN(lat) && !isNaN(lng)) {
        myLatLng = new google.maps.LatLng(lat, lng);
      }
                var myOptions = {
                    zoom: zoom,
                    center: myLatLng,
                    streetViewControl: false,
                    mapTypeControl: false,
                    zoomControl: true,
                    // How you would like to style the map.
                    // This is where you would paste any style found on Snazzy Maps.
                    styles: [{"featureType":"all","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"administrative.country","elementType":"labels.text","stylers":[{"visibility":"off"}]},{"featureType":"administrative.province","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"administrative.locality","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"administrative.neighborhood","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"administrative.land_parcel","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"landscape.man_made","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"landscape.natural","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"on"}]},{"featureType":"road.arterial","elementType":"labels.text","stylers":[{"visibility":"on"}]},{"featureType":"transit","elementType":"labels","stylers":[{"visibility":"off"}]}]
                    // zoom: 16,
                    // center: myLatlng,
                };
                map = new google.maps.Map(document.getElementById("map"),
                      myOptions);
                infowindow = new google.maps.InfoWindow({});

   geoXml = new geoXML3.parser({
                    map: map,
                    infoWindow: infowindow,
                    singleInfoWindow: true,
                    zoom: myGeoXml3Zoom,
                    afterParse: useTheData
                });
                geoXml.parse(filename);
        };

function kmlClick(pm) {
   if (geoXml.docs[0].placemarks[pm].marker.getMap()) {
      google.maps.event.trigger(geoXml.docs[0].placemarks[pm].marker,"click");
   } else {
      geoXmlDoc.placemarks[pm].marker.setMap(map);
      google.maps.event.trigger(geoXmlDoc.placemarks[pm].marker,"click");
   }
}

// == builds the sidebar ==

function makeSidebarEntry(i) {
  var name = geoXmlDoc.placemarks[i].name;
   if (!name  || (name.length == 0)) name = "marker #"+i;
   // alert(name);
   sidebarHtml += '
	'+name+'
';
}

function makeSidebar() {
  sidebarHtml = '

';
  var currentBounds = map.getBounds();
// if bounds not yet available, just use the empty bounds object;
if (!currentBounds) currentBounds=new google.maps.LatLngBounds();
if (geoXmlDoc) {
  for (var i=0; i<geoXmlDoc.placemarks.length; i++) {
    if (geoXmlDoc.placemarks[i].marker) {
      if (currentBounds.contains(geoXmlDoc.placemarks[i].marker.getPosition())) {
         makeSidebarEntry(i);
      }
    }
  }
}
  sidebarHtml += "
";
  document.getElementById("sidebar").innerHTML = sidebarHtml;
}

function useTheData(doc){
  var currentBounds = map.getBounds();
  if (!currentBounds) currentBounds=new google.maps.LatLngBounds();
  // Geodata handling goes here, using JSON properties of the doc object
  sidebarHtml = '

';
//  var sidebarHtml = '
';
  geoXmlDoc = doc[0];
  for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
    // console.log(doc[0].markers[i].title);
    var placemark = geoXmlDoc.placemarks[i];
    if (placemark.marker) {
      if (currentBounds.contains(placemark.marker.getPosition())) {
         makeSidebarEntry(i);
      }
    }

/*    doc[0].markers[i].setVisible(false); */
  }
  sidebarHtml += "
";
  document.getElementById("sidebar").innerHTML = sidebarHtml;
};

Any help would be greatly appreciated.

A: To center the map on a marker clicked on the sidebar, add code to do that to the function that is called (kmlClick):
function kmlClick(pm) {
  // center the map on the marker and change the zoom to 18
  if (geoXml.docs[0].placemarks[pm].marker.getPosition){
     map.setCenter(geoXml.docs[0].placemarks[pm].marker.getPosition());
     map.setZoom(19);
  }

  if (geoXml.docs[0].placemarks[pm].marker.getMap()) {
    // if map is not null (marker is on the map), trigger a click on it
     google.maps.event.trigger(geoXml.docs[0].placemarks[pm].marker,"click");
  } else {
    // if map is null (marker is not on the map), add it to the map,
    // then trigger a click on it
    geoXmlDoc.placemarks[pm].marker.setMap(map);
    google.maps.event.trigger(geoXmlDoc.placemarks[pm].marker,"click");
  }
}

If you want it to center and zoom when the marker is clicked or the click is triggered from the sidebar, put that functionality in the marker click listener.  One way to do that would be to add a marker click listener to the markers in useTheData:
function useTheData(doc){
  var currentBounds = map.getBounds();
  if (!currentBounds) currentBounds=new google.maps.LatLngBounds();
  sidebarHtml = '

';
  geoXmlDoc = doc[0];
  for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
    var placemark = geoXmlDoc.placemarks[i];
    if (placemark.marker) {
      google.maps.event.addListener(placemark.marker,'click',function(evt) {
        this.getMap().setCenter(this.getPosition());
        this.getMap().setZoom(19);
      });
      if (currentBounds.contains(placemark.marker.getPosition())) {
         makeSidebarEntry(i);
      }
    }
  }
  sidebarHtml += "
";
  document.getElementById("sidebar").innerHTML = sidebarHtml;
};

proof of concept
code snippet:

google.maps.event.addDomListener(window, 'load', initialize);

var geoXml = null;
var geoXmlDoc = null;
var map = null;
var myLatLng = null;
var myGeoXml3Zoom = false;
var sidebarHtml = "";
var infowindow = null;
var kmlLayer = null;
var filename = "kml/SO_20160415_placemarks.kml";

function initialize() {
  myLatLng = new google.maps.LatLng(52.60426, 1.72764);
  var lat = 52.60426;
  var lng = 1.72764;
  var zoom = 16;

  if (!isNaN(lat) && !isNaN(lng)) {
    myLatLng = new google.maps.LatLng(lat, lng);
  }
  var myOptions = {
    zoom: zoom,
    center: myLatLng,
    streetViewControl: false,
    mapTypeControl: false,
    zoomControl: true
  };
  map = new google.maps.Map(document.getElementById("map"),
    myOptions);
  infowindow = new google.maps.InfoWindow({});

  geoXml = new geoXML3.parser({
    map: map,
    infoWindow: infowindow,
    singleInfoWindow: true,
    zoom: myGeoXml3Zoom,
    afterParse: useTheData
  });
  geoXml.parseKmlString(kmlStr);
  google.maps.event.addListener(map, "bounds_changed", makeSidebar);
  google.maps.event.addListener(map, "center_changed", makeSidebar);
  google.maps.event.addListener(map, "zoom_changed", makeSidebar);
  google.maps.event.addListenerOnce(map, "idle", makeSidebar);
};

function kmlClick(pm) {
  if (geoXml.docs[0].placemarks[pm].marker.getMap()) {
    google.maps.event.trigger(geoXml.docs[0].placemarks[pm].marker, "click");
  } else {
    geoXmlDoc.placemarks[pm].marker.setMap(map);
    google.maps.event.trigger(geoXmlDoc.placemarks[pm].marker, "click");
  }
}

function showAll() {
  map.setZoom(16);
  map.panTo(myLatLng);
}

// == builds the sidebar ==
function makeSidebarEntry(i) {
  var name = geoXmlDoc.placemarks[i].name;
  if (!name || (name.length == 0)) name = "marker #" + i;
  sidebarHtml += '
	' + name + '
';
}

function makeSidebar() {
  sidebarHtml = '

';
  var currentBounds = map.getBounds();
  // if bounds not yet available, just use the empty bounds object;
  if (!currentBounds) currentBounds = new google.maps.LatLngBounds();
  if (geoXmlDoc) {
    for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
      if (geoXmlDoc.placemarks[i].marker) {
        if (currentBounds.contains(geoXmlDoc.placemarks[i].marker.getPosition())) {
          makeSidebarEntry(i);
        }
      }
    }
  }
  sidebarHtml += "
";
  document.getElementById("sidebar").innerHTML = sidebarHtml;
}

function useTheData(doc) {
  var currentBounds = map.getBounds();
  if (!currentBounds) currentBounds = new google.maps.LatLngBounds();
  sidebarHtml = '

';
  geoXmlDoc = doc[0];
  for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
    var placemark = geoXmlDoc.placemarks[i];
    if (placemark.marker) {
      google.maps.event.addListener(placemark.marker, 'click', function(evt) {
        this.getMap().setCenter(this.getPosition());
        this.getMap().setZoom(19);
      });

      if (currentBounds.contains(placemark.marker.getPosition())) {
        makeSidebarEntry(i);
      }
    }
  }
  sidebarHtml += "
";
  document.getElementById("sidebar").innerHTML = sidebarHtml;
};

var kmlStr = "<?xml version='1.0' encoding='UTF-8'?><kml xmlns='http://www.opengis.net/kml/2.2'><Document><name>Map</name><description></description><Folder><name>Points</name><Placemark><name>Placemark 1</name><description>Description</description><Point><coordinates>1.7275818,52.6043317,0.0</coordinates></Point></Placemark><Placemark><name>Placemark 2</name><description>Description</description><Point><coordinates>1.73041,52.60436,0.0</coordinates></Point></Placemark></Folder></Document></kml>";
html,
body,
#map,
.map {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

Locations

*Click to show location on map

A: Test to change your function makeSidebar() as:
function makeSidebar() {
  sidebarHtml = '

';
  var currentBounds = map.getBounds();
if (!currentBounds) currentBounds=new google.maps.LatLngBounds();
if (geoXmlDoc) {
  for (var i=0; i<geoXmlDoc.placemarks.length; i++) {
    if (geoXmlDoc.placemarks[i].marker) {
  if (currentBounds.contains(geoXmlDoc.placemarks[i].marker.getPosition())) {
     makeSidebarEntry(i);

        google.maps.event.addListener(geoXmlDoc.placemarks[i].marker, "click", function (e) {
            map.setZoom(16);
            //infoWindow.open(map, marker);

            map.setCenter(marker.getPosition());
        });
  }
}
  }
}

A: Try to change your function Kmlclick as :
 function kmlClick(pm) {
    google.maps.event.addListener(geoXml.docs[0].placemarks[pm].marker, "click", function (e) {
                    map.setZoom(16);
                    //infoWindow.open(map, marker);

                    map.setCenter(marker.getPosition());
                });
       if (geoXml.docs[0].placemarks[pm].marker.getMap()) {
          google.maps.event.trigger(geoXml.docs[0].placemarks[pm].marker,"click");
       } else {
          geoXmlDoc.placemarks[pm].marker.setMap(map);
          google.maps.event.trigger(geoXmlDoc.placemarks[pm].marker,"click");
       }
    }

The approch is when you create your mark in map you must add a listner to it "click" i hop that help you

A: I've managed to get the centring and zoom almost working, with the help of @BLD_Sys
function kmlClick(pm) {
    google.maps.event.addListener(geoXml.docs[0].placemarks[pm].marker, "click", function (e) {
                    map.setZoom(19);
                    //infoWindow.open(map, marker);

                    map.panTo(geoXml.docs[0].placemarks[pm].marker.getPosition());
                });
       if (geoXml.docs[0].placemarks[pm].marker.getMap()) {
          google.maps.event.trigger(geoXml.docs[0].placemarks[pm].marker,"click");
       } else {
          geoXmlDoc.placemarks[pm].marker.setMap(map);
          google.maps.event.trigger(geoXmlDoc.placemarks[pm].marker,"click");
       }
    }

I had to add the geoXML.docs[0].placemarks[pm] bit because it was returning a Reference Error using just marker.getPosition()
Im still having an issue with it only working if you click the sidebar first and not if you click the placemarker on the map first.

A: test to move the code after your test as :
 function kmlClick(pm) {

          if (geoXml.docs[0].placemarks[pm].marker.getMap()) {
              google.maps.event.trigger(geoXml.docs[0].placemarks[pm].marker,"click");
           } else {
              geoXmlDoc.placemarks[pm].marker.setMap(map);
              google.maps.event.trigger(geoXmlDoc.placemarks[pm].marker,"click");
           }

        google.maps.event.addListener(geoXml.docs[0].placemarks[pm].marker, "click", function (e) {
                        map.setZoom(19);
                        //infoWindow.open(map, marker);

                        map.panTo(geoXml.docs[0].placemarks[pm].marker.getPosition());
                    });
        }

Tell me if he work for you and thank to mark vote in answer .

A: I try to test this code in my machine but i don't have "test.kml.xml";
any way you try to change  your function useTheData as :
function useTheData(doc){
  var currentBounds = map.getBounds();
  if (!currentBounds) currentBounds=new google.maps.LatLngBounds();
  // Geodata handling goes here, using JSON properties of the doc object
  sidebarHtml = '

';
//  var sidebarHtml = '
';
  geoXmlDoc = doc[0];
  for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
    // console.log(doc[0].markers[i].title);
    var placemark = geoXmlDoc.placemarks[i];
    if (placemark.marker) {
      if (currentBounds.contains(placemark.marker.getPosition())) {
         makeSidebarEntry(i);
 google.maps.event.addListener(placemark.marker, "click", function (e) {
        map.setZoom(19);
        //infoWindow.open(map, marker);

        map.panTo(geoXml.docs[0].placemarks[pm].marker.getPosition());

      }
    }

/*    doc[0].markers[i].setVisible(false); */
  }
  sidebarHtml += "
";
  document.getElementById("sidebar").innerHTML = sidebarHtml;
};

I hope that this is one is the best


text:
Q: VBA: How can I fill in cells in one column based on the collective information of iterative ranges? I need to fill in Col H (see red text in image for an example) as follows:

*

*There are 3 subjects listed (separated by grey background) (Col C for number)

*Each subject has multiple data points (one per row-Col D for data point "name")

*(not shown) each subject multiple data points is run on multiple tests and sorted by test, subject, timepoint. (See Col E for Test), which means each "unifying ID"/"Subject ID" is used more than once.  This data should be considered separately (for example, subject 8 Adiponectin results should not be compared with subject 8 Areg data)

*Some of the data is not detected by the test and is marked in both Col J ("<LLOQ") and Col I ("Yes" for <LLOQ aka not detected).

*I need help designing a program that answers if "all samples from this subject (and test) are below LLOQ?".  Thus the program needs to detect that each subject's data must be viewed in a chunk fill out Col H "All Samples below LLOQ?" before moving on to the next subject.  If there are no <LLOQ samples in the range, then each cell in Col H will be "No".  If there are some samples <LLOQ and some samples that are NOT <LLOQ, then each cell in Col H within the range will be "No" (see grey subject). However, if All samples for a subject are <LLOQ, then the values in H must be "Yes" for all cells within the range.

In another Sub() I figured out how to reset values for each new subject using "C01D01.00" as a reset cue.  This works to fill in data that is not reliant on the cells in a range (such as "Is the Baseline below LLOQ?" in col G.  But I cannot figure out how to "set" a range, read through the range, identify if any cells are "no" in Col I and then return "no" in Col H (or "yes" in Col H if there are no "no" in Col I with in the range, and then move onto the next "range").  Ideas?
See below for how I programmed Col G.

Sub BaselineBelowLLOQ()

    Sheets("Cyt-Data").Activate
    Dim NewSubject As String
    Dim SubjectBL As String
    Dim BaselineRow As Integer

    For i = 2 To 1000000
        If Sheets("Cyt-Data").Cells(i, 2).Value = "" Then
            Exit For
        End If

        NewSubject = Cells(i, 3).Value

        If Not SubjectBL = NewSubject And Cells(i, 4).Value = "C01D01.00" Then
            SubjectBL = NewSubject
            BaselineRow = i
        ElseIf Not SubjectBL = NewSubject And Not Cells(i, 4).Value = "C01D01.00" Then
            SubjectBL = ""
        End If

        If Not SubjectBL = "" Then
            If Cells(BaselineRow, 9).Value = "Yes" Then
                Cells(i, 7).Value = "Yes"
            Else
                Cells(i, 7).Value = "No"
            End If
        End If
    Next i

End Sub

A: Something like this should work:
Sub BaselineBelowLLOQ()

    Dim ws As Worksheet, i As Long, dict As Object, k As String
    Dim subjId, testName, num1 As Long, num2 As Long

    Set dict = CreateObject("scripting.dictionary")
    Set ws = ThisWorkbook.Worksheets("Cyt-Data") 'or ActiveWorkbook...

    For i = 2 To ws.Cells(Rows.Count, "B").End(xlUp).Row

        subjId = ws.Cells(i, "C").Value
        testName = ws.Cells(i, "E").Value
        k = subjId & "<>" & testName 'SubjectId<>TestName combination
        If Not dict.exists(k) Then   'new combination?

            'count all rows for this combo
            num1 = Application.CountIfs(ws.Columns("C"), subjId, _
                                        ws.Columns("E"), testName)
            'count rows for this combo with "Yes" in Col I
            num2 = Application.CountIfs(ws.Columns("C"), subjId, _
                                        ws.Columns("E"), testName, _
                                        ws.Columns("I"), "Yes")

            dict.Add k, IIf(num1 = num2, "Yes", "No") 'compare counts for this combo
                                                      'and store the Yes/No outcome
        End If
        'tag the row using the value we already figured out
        ws.Cells(i, "H").Value = dict(k)
    Next i

End Sub


text:
Q: Electric Car Charging Android App crashes on start - custom list item and Adapter I am doing a Udacity course on Android Development specifically in Networking atm. I am building an app that find the closest Electric Car Charging points and displays them in a listView. At the moment I am just trying to get the structure working before retrieving live data.
I am using a custom object - ChargePoint- which takes 5 inputs.
I am using a custom adapter - ChargePointAdapter - which translates the 5 bits of info onto the right places in a list_item.xml
My  - MainActivity - stores the placeholder data, creates an adapter with the data, finds the listView from activity_main.xml and sets the adapter.
I dont get any errors, however my app crashes on start.
Here is a link to the project: https://github.com/Kovah101/ChargeMyCar
EDIT: On further inspection the app runs when I comment out the line:
chargePointListView.setAdapter(adapter)

which I assume means my custom adapter class isnt to blame? The only difference in the Log outputs from the running to non running version is
09-21 18:08:54.533 20790-20790/com.example.android.chargemycar I/Process: Sending signal. PID: 20790 SIG: 9

Any help would be greatly appreciated!

A: So there were a few little errors, DroiDev was correct in saying the adapter had caused the error, since commenting out that line allowed the app to run.
I went through each part of my ChargePointAdapter and found TextView distanceTextView = (TextView) listItemView.findViewById(distance); which should have been R.id.distance, fixing that didnt solve my problem so I commented out the whole distance chunk to start a process of elmination through the app. First time and that solved the crash so the error was in
TextView distanceTextView = (TextView) listItemView.findViewById(R.id.distance);
        String distance = Double.toString(currentChargePoint.getDistance());
        distanceTextView.setText(distance);
theoretically that all worked so I looked at my xml and my parent View had the id/distance not my textView, correcting that fixed everything, the Github is updated with the working code now too.
Keep looking down the Rabit Hole (Thanks DroiDev)


text:
Q: list assignment index out of range by Python n=int(input())
m=int(input())
a=[n+1]
for i in range(n+1):
    a[i]=0
a[0]=a[1]=1
for i in range(n+1):
    a[i]=a[i-1]+a[i-2]
for i in range(n+1):
    sum+=a[i]*a[i]
print((sum+1)%m)

        a[i]=0

IndexError: list assignment index out of range

Can you help me ? list assignment index out of range. I can not fix.

A: Languages like Java require you to create an array of a specific length. Python lets you initialize a list, either empty or populated, and then you can simply append items to the list. If you want to create a list a of length n+1 containing a 0 in each element, you can do that with a list comprehension: a = [0 for item in range(n+1)].
You shouldn't use sum as a variable, as sum is a Python built-in function. However, if you do choose to override a built-in function, you have to actually assign something to it first. Adding a number to sum with sum+=a[i]*a[i] attempts to add the square of a[i] to a function, which doesn't work.
Keep in mind that a negative-numbered index in a Python list, as with a[i-2] when i is less than 2, starts from the end of the list: mylist[-1] is the last item in a list, mylist[-2] is the second to last item, and so on. So the first item in the list, a 1, is set to the sum of the last and second-to-last items, which is 0. The second item, also a 1, is set to the sum of the first item (now a 0) and the last item (still 0), which is also 0. Now your list is all zeros.
I've made a few changes to the parts of your code that produced errors, and added comments so that you can see what each part does, given reasonable inputs like n=3 and m=5:
n=int(input())
m=int(input())
a=[0 for item in range(n+1)] # initialize all to 0
mysum = 0 # initialize a sum that doesn't override the builtin
a[0]=a[1]=1 # set first 2 elements to 1
for i in range(n+1): # for every item in a,
    a[i]=a[i-1]+a[i-2] # this ends up setting everything to 0
for i in range(n+1): # for every item in a,
    mysum+=a[i]*a[i] # add 0*0 to the sum
print((mysum+1)%m) # 1 modulo anything greater than 1 is 1, so this prints 1

So this program doesn't do much more than print 1.

A: # Get input values
n = 10
m = 100

# Initialize list
fib = [1,1]
# Fibonacci sequence of length n
for i in range(2,n): # Adjust the number of iterations to your problem
    fib.append(fib[-1]+fib[-2])

# List comprehension for creating the "squares" list and getting its sum
result = sum([fib[i]**2 for i in range(len(fib))]) % m

print fib
print result


text:
Q: How can I get JupyterLite to work again as it has stopped working entirely? I have been using the browser version on JupyterLite for a few weeks. As of a few days ago, anything I type into a row does nothing when I select Run. Even entering a basic print() doesn't do anything. Can anyone help me? thanks.
I have tried opening up a new tab, entering many different things, and nothing seems to work?


text:
Q: Using DocumentDB change stream on multiple collections? I'm implementing python an application to capture change on DocumentDB using Change Stream feature my design is watching change on all collections in the target database and publish to some message queue to do some processing.
My question is currently DocumentDB support MongoDB API version 3.6 which not support watch change on DB level. Is there a way to watch the change stream on the DB level on the current DocumentDB version.

A: You can enable change streams at the collection, database, and cluster level.
However, at the moment to seek for the changes it happens at the collection level.
You need to setup your code to seek for changes in every collection that is being watched.

A: Since October/November 2020, Amazon DocumentDB supports change streams at the database level. The release notes were posted here and here.
The documentation has examples for how to watch changes for all collections in a database.