text:
Q: Content gets centered in PySimpleGui after hiding und unhiding content I am trying to hide and unhide content in PySimpleGui. Here's the example code.
How can I achieve, that the sg.Frame get's centered after hiding and unhiding the frame (by clicking the Checkbox in the top)?
import PySimpleGUI as sg

frameContent=[]
frameContent.append([sg.Text('Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. ')],)
frameContent.append([sg.Text('Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes,')],)
frameContent.append([sg.Text('nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. ')],)
frameContent2=[]
frameContent2.append([sg.Text('Nulla consequat massa quis enim.')],)
frameContent2.append([sg.Text('Donec pede justo, fringilla vel, ')],)
frameContent2.append([sg.Text('aliquet nec, vulputate eget, arcu.')],)
frameContent3=[]
frameContent3.append([sg.Text('In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. ')],)
frameContent3.append([sg.Text('Integer tincidunt. Cras dapibus.')],)
frameContent3.append([sg.Text('Vivamus elementum semper nisi. Aenean vulputate eleifend tellus.')],)
frameContent4=[]
frameContent4.append([sg.Text('In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. ')],)
frameContent4.append([sg.Text('Integer tincidunt. Cras dapibus.')],)
frameContent4.append([sg.Text('Vivamus elementum semper nisi. Aenean vulputate eleifend tellus.')],)
layout = [
            [sg.Checkbox('Tooltips', key="-showTooltips-", enable_events=True)],
            [sg.Frame('Frame',frameContent, key='-frame1-',visible=True)],
            [sg.Frame('Frame',frameContent2, key='-frame2-',visible=True  )],
            [sg.Frame('Frame',frameContent3, key='-frame1Tooltips-',visible=False)],
            [sg.Frame('Frame',frameContent4, key='-frame2Tooltips-',visible=False  )]
        ]

window = sg.Window('Window Title', layout)
while True:
    event, values = window.read()
    if event in (sg.WIN_CLOSED, 'Exit'):
        break
    if event == '-showTooltips-':
        for i in range(1,3):
            if values['-showTooltips-']:
                window["-frame"+str(i)+'-'].Update(visible=False)
                window["-frame"+str(i)+'-'].hide_row()
                window["-frame"+str(i)+"Tooltips-"].Update(visible=True)
                window["-frame"+str(i)+"Tooltips-"].unhide_row()
            else:
                window["-frame"+str(i)+'-'].Update(visible=True)
                window["-frame"+str(i)+'-'].unhide_row()
                window["-frame"+str(i)+"Tooltips-"].Update(visible=False)
                window["-frame"+str(i)+"Tooltips-"].hide_row()
window.close()

A: Use sg.pin to keep the position, and hide_row and unhide_row are not required.

Pin's an element provided into a layout so that when it's made invisible and visible again, it will
be in the correct place.  Otherwise it will be placed at the end of its containing window/column.

The code from layout updated to
layout = [
            [sg.Checkbox('Tooltips', key="-showTooltips-", enable_events=True)],
            [sg.pin(sg.Frame('Frame1',frameContent, key='-frame1-',visible=True))],
            [sg.pin(sg.Frame('Frame2',frameContent2, key='-frame2-',visible=True))],
            [sg.pin(sg.Frame('Frame3',frameContent3, key='-frame1Tooltips-',visible=False))],
            [sg.pin(sg.Frame('Frame4',frameContent4, key='-frame2Tooltips-',visible=False))]
        ]

window = sg.Window('Window Title', layout)
while True:
    event, values = window.read()
    if event in (sg.WIN_CLOSED, 'Exit'):
        break
    if event == '-showTooltips-':
        for i in range(1,3):
            if values['-showTooltips-']:
                window["-frame"+str(i)+'-'].Update(visible=False)
                window["-frame"+str(i)+"Tooltips-"].Update(visible=True)
            else:
                window["-frame"+str(i)+'-'].Update(visible=True)
                window["-frame"+str(i)+"Tooltips-"].Update(visible=False)
window.close()


text:
Q: content (or background) remains when draggin the splitter bar to resize two panels I have a main window with 3 child: hwndTocBox (left panel), hwndSplitter and hwndCanvas (right panel).
hwndTocBox has a child hwndTreeView, which is a TreeView control. When I drag hwndSplitter to the right (i.e want to make hwndTocBox and hence hwndTreeView bigger), the content (and background?) of hwndCanvas and hwndSplitter will remain for a while. (When I drag the splitter to the left, there is no problem at all.)
When hwndSplitter is draged, it uses DeferWindowPos() to resize and move hwndTocBox, hwndSplitter and hwndCanvas. When hwndTocBox is resized, in WM_SIZE case of its windows procedure, it resizes hwndTreeView (still using DeferWindowPos(), since it resizes not only hwndTreeView but also others).
I have tried to use CLIPCHILDREN and WS_CLIPSIBLINGS in several places, but it doesn't solve the problem.
Why the contents remain there for a while and erased later?
Could you indicate me how to solve this issue, please.

A: You'll need to repaint the portions of the window that you've resized, otherwise you'll get these strange artifacts. There's a reason they look like smears, because that's almost exactly what they are. A certain portion of the content was painted and appeared on screen normally. Then you resized the window. The portion that had already been painted was not repainted because you didn't invalidate it, but the newly-exposed portion had to be repainted because there was nothing there before.
The fix is simple: add a call to the InvalidateRect() function at the bottom of your resizing code to ensure that the portion of the window you're resizing gets redrawn the next time that the window processes a WM_PAINT message.
If you want to make sure that a WM_PAINT message gets processed immediately (resulting in the immediate redrawing of your window's affected regions), follow up with a call to the UpdateWindow() function. But this really shouldn't be necessary. It's much more efficient to postpone all of the redrawing to later when everything is finalized, rather than doing it incrementally. Relatively speaking, repainting a window is an expensive operation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I be sure I don't miss the "open" event on WebSockets? This is more of an abstract question really. How can I be sure that I don't miss a WebSocket's open event? As I understand it, the browser starts establishing a connection as soon as I call the constructor, so if things go badly, an open (or error) event might be fired before my handlers for those events are connected.
var socket = new WebSocket("ws://www.example.com");
/*Because I'm an unlucky guy, the open-event fires before the next line*/
socket.addEventListener("open", function(event){...});

In this case, my open-Handler would never be called. Most likely this is never a real problem because establishing the connection takes longer than executing the next line of JavaScript. However, the same could be said for XMLHttpRequest, and there the recommended order of things is:
var ajax = new XMLHttpRequest();
ajax.addEventListener("load", function(event){...});
ajax.open();
ajax.send();

This makes sure that the event can not be lost. Why is WebSocket different in that respect? Am I overlooking something and missing the event is not really an issue?
Thank you for some clarification on this.

A: Your second example with Ajax has a faulty assumption. With Ajax, there is no actual problem putting your event handler after the send call, as long as both are included in the same synchronous set of operations. Here's a fiddle that sends the Ajax request, burns several seconds (plenty of time for the fetch to complete) and then attaches listeners. As you can see, the events fire just fine.
So, this is okay:
var ajax = new XMLHttpRequest();
ajax.open();
ajax.send();
ajax.addEventListener("load", function(event){...});

Due to the single-threaded nature of browser JavaScript, the load event does not actually fire until the current code is finished running. (NOTE: maybe this behavior is different in older browsers, but it's certainly how it works in any browser that supports WebSockets.)
This, however, is not okay:
var ajax = new XMLHttpRequest();
ajax.open();
ajax.send();
setTimeout(function() {
    ajax.addEventListener("load", function(event){...});
}, 1000);

This is because you've created a race condition between two asynchronous actions: the setTimeout resolution and the load event firing. As long as your delay between firing the Ajax request and setting the listener is in the same synchronous execution, there is no risk of "missing" an Ajax event.
It works the same way with WebSockets -- you can't miss the open event as long as you construct the WebSocket and attach your listener in the same synchronous set of instructions. Here's another fiddle that does an analogous synchronous wait for a WebSocket. As you can see, even after waiting several seconds to attach the event listener, it still fires.
I'm not sure where the practice of "attach listeners before you act" comes from. Perhaps it was important in older browsers, or perhaps it is important for some APIs other than Ajax. Whatever the reason the practice came about, you don't actually need to adhere to it in modern browsers for either Ajax or WebSockets.


text:
Q: Drag Image into Div and Alert I need to drag a picture into a div and if it touches "yes" it would alert : YES, but if it touches "no" it would alert : NO !
I can't actually do it, you can see what i have here, i don't know why, but in my project i can at least drag the JS image and in jsfiddle i can't, so i basically need an if to do the alerts!
http://jsfiddle.net/vy635/1/

    yes

    no

Thanks !


text:
Q: How to get user information from localStorage I've been struggling to grab the information from local Storage. I want to get the
username  and ._id of the current user who logs in and render it to my navbar as well as redirecting to the profile of the current user via Link.
I can grab its information after I refresh once I already logged in
this is my local storage local storage
When I log it in first, I encounter this problem. This is what shows after logging in
First Render
But once I refresh the page Refresh Page
sorry if i used too much image, my english is not good and I can't find the exact words
Navbar.js
const Navbar = () => {
  const {user} = useSelector((state) => state.user)
  const user2 = JSON.parse(user).username
  const id = JSON.parse(user)._id

return (
    <Typography marginRight={2} sx={{color: {xs: 'white', md: 'black'}}}> Hello
    {user2}  </Typography>

    <Link to={`/edit_user/${id}`} style={{textDecoration: 'none', color:
         'inherit'}}>
      <MenuItem onClick={handleCloseUserMenu}>
              {settings[0]}
            </MenuItem>
     </Link>
      )
}

userSlice.js
 import {createSlice} from '@reduxjs/toolkit'

const user = localStorage.getItem("token")

export const userSlice = createSlice({
  name: 'user',
  initialState : {
    user: user ? user : null,
    isError: false,
    isSuccess: false,
    isLoading: false,
    message: ''
  },
  reducers: {getUserStart: (state) =>{
      state.isLoading = true;
      state.isError = false;
    },
    getUserSuccess:(state, action) =>{
      state.isLoading = true;
      state.isSuccess = true;
      state.user = action.payload;
    },
    getUserFailure: (state, action) =>{
      state.isLoading = false;
      state.isError = true;
      state.message = action.payload
      state.user = null
    }
  }

})

apiCalls.js
 export const getUser = async (dispatch,id) =>{
       getUserStart()
       try {
            const getUser = await publicRequest.get('/users/find/'+id)
            dispatch(getUserSuccess(getUser.data))
        } catch (error) {
            dispatch(getUserFailure())
        }
    }export const loginUser = async (userData, dispatch) =>{
    dispatch(loginStart())
    try {
        const res = await publicRequest.post('/auth/login', userData)
        localStorage.setItem('token', JSON.stringify(res.data))
        dispatch(loginSuccess(res.data))
    } catch (error) {
        const message =
        "Wrong Username or Email "
        dispatch(loginFailure(message))
    }
}


text:
Q: ASP.net core AntiForgeryToken issue : data doesn't bind to model I have a working project for a booking system in asp.net core that uses a google Timeline chart. When you click on the chart a modal popup with a partial view pops up up to enter data. Javacript has a click event on the save button to send the data to the controller. The controller validates the data and sends the partial view  back to javascript where it is sent back to the modal popup. I have two flags on the view that if set true, javascript hides the popup. This all works until I decorate the controller with [ValidateAntiForgeryToken]
I have the code as follows

StartUp:
services.AddAntiforgery(options => {
    options.HeaderName = "RequestVerificationToken";
});

Javascript:
(function() {
        var PlaceHolderElement = $('#PlaceHolderHere');
        //create popup save
        PlaceHolderElement.on('click', '[data-save="modal"]', function(event) {
            event.preventDefault();
            var form = $(this).parents('.modal').find('form');
            var token = $("input[name='__RequestVerificationToken']").val();
            var actionUrl = form.attr('action');
            var sendData = form.serialize();
            $.ajax({
                type: 'POST',
                url: actionUrl,
                data: sendData,
            }).done(function(data1) {
                var newBody = $('.modal-body', data1);
                PlaceHolderElement.find('.modal-body').replaceWith(newBody);
                var isValid = newBody.find('[name="IsValid"]').val() === 'True';
                var isValid2 = newBody.find('[name="BookingFree"]').val() === 'True';
                if (isValid && isValid2) {
                    PlaceHolderElement.find('.modal').modal('hide');
                    location.reload();
                }
            })
})

Controller:
[HttpPost]
public IActionResult EditBooking(BookingViewModel model) {

  if (ModelState.IsValid) {
    ... other code
  }
}

when I decorate the controller with [ValidateAntiForgeryToken] and change the jarvascript to
data: {
    model: sendData,
    __RequestVerificationToken: token,
}

the Validate works but the model is empty! if I declare the model as string then I get a string.
If I send the token in headers:, the token validation fails
I need the data in the model in order for the ModelState to set IsValid

A: 1..serialize() will pass the form data together with __RequestVerificationToken value by default.
2.When you use form element with method="post" and tag helper, it will dynamically generate token input which name="__RequestVerificationToken" inside the form. But if you specific the action attribute for form like:<form action="/url" method="post"></form>, it will not generate the token input.
So if you specific the action attribute, you need manually add token input by using @Html.AntiForgeryToken() in the form:
<form action="/url" method="post">
     @Html.AntiForgeryToken()
     //....
</form>

A simple working demo you could follow:
View:
<form asp-action="EditBooking" asp-controller="Home" method="post">
    <input asp-for="Name" />
    <input type="button" onclick="PostForm()" value="Post" />
</form>

@section Scripts
{
    <script>
        function PostForm() {
            //var token = $("input[name='__RequestVerificationToken']").val();
            var actionUrl = $('form').attr('action');
            var sendData = $('form').serialize();
            console.log(sendData)
            $.ajax({
                type: 'POST',
                url: actionUrl,
                data: sendData,
            }).done(function(data1) {
            })
}
    </script>
}

And no need add the following code:
services.AddAntiforgery(options => {
    options.HeaderName = "RequestVerificationToken";
});


text:
Q: Node.js listener definition how would you definte listeners in node.js?
They are event emitter objects that listen for certain events to occur and then notify the event emitter or call a callback function?
any help is appreciated

A: Use Event Emitter
Here is a simple example:
const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();

myEmitter.on('someCoolEvent', () => { // Here is where we are listening for event to occur
  console.log('an event occurred!');
});

myEmitter.emit('someCoolEvent'); // here is how we emit the event


text:
Q: Java reflection vs Jess it seems to me that Jess is a way to change dynamically what we put inside a Java class, when I've face the java Reflection, surprisingly seems to me that have the same objective.
If this is true, when should I use one or other ?
Cheers,

A: Jess does include a traditional programming language with the ability to manipulate Java objects, But the main part of what Jess does is allow you to write declarative rules. This is a completely different programming paradigm. In a traditional imperative language you write code that tells the computer explicitly how to solve a problem. In a declarative language, on the other hand, you describe the problem, and the language itself figures out how to solve it. Because Jess itself is written in Java, it makes no sense to say that Jess is more or less powerful than Java itself: it's just a different approach to programming, and it makes solving certain classes of problems easier.


text:
Q: NUnit test results and reportunit I am currently using NUnit in Visual Studio to execute my Selenium tests. What I want is some good reporting and I found ReportUnit.
What I cannot seem to figure out is where NUnit places the test result xml files on my machine. I am no tech-wiz so I am struggling to find out how to get ReportUnit working. I found the documentation here: http://relevantcodes.com/reportunit/
But cannot quite figure out how to get my test result files in a specific folder and then open them with ReportUnit.
Any help is appreciated.
Kind regards,
Anand

A: Use the --out option of nunit3-console.exe to specify where the result file should go. e.g.
nunit3-console.exe MyTests.dll --out=C:/TestResult.xml


text:
Q: How to solve the duplicate subscription (Subscribe.OnSubscribe()) error in listener code in azure eventhubs with Ktor (Kotlin server)? The error is:
Duplicate Subscription has been detected.
java.lang.IllegalStateException: Spec. Rule 2.12 - Subscriber.onSubscribe MUST NOT be called more than once (based on object equality)
This is the error that I'm getting on the listener side in azure eventhubs with ktor server.
The error is in the PARTITION_PROCESSOR part. How do you solve this error?
package com.example.eventhub

import com.azure.messaging.eventhubs.EventHubClientBuilder
import com.azure.messaging.eventhubs.EventProcessorClientBuilder
import com.azure.messaging.eventhubs.checkpointstore.blob.BlobCheckpointStore
import com.azure.messaging.eventhubs.models.PartitionContext
import com.azure.storage.blob.BlobContainerClientBuilder
import java.util.function.Consumer
import com.azure.messaging.eventhubs.models.EventContext
import com.azure.messaging.eventhubs.models.ErrorContext
import com.azure.messaging.eventhubs.EventData

class AzureEventHubClient {

    fun listenEvent() {

        val blobContainerAsyncClient = BlobContainerClientBuilder()
            .connectionString("DefaultEndpointsProtocol=https;AccountName=[[ REDACTED ]];AccountKey=[[ REDACTED ]];EndpointSuffix=core.windows.net")
            .containerName("[[ REDACTED ]]")
            .buildAsyncClient()

        val PARTITION_PROCESSOR: Consumer<EventContext> = Consumer<EventContext> { eventContext ->
            val partitionContext: PartitionContext = eventContext.partitionContext
            val eventData: EventData = eventContext.eventData
            System.out.printf(
                "Processing event from partition %s with sequence number %d with body: %s%n",
                partitionContext.partitionId, eventData.sequenceNumber, eventData.bodyAsString
            )

            // Every 10 events received, it will update the checkpoint stored in Azure Blob Storage.
            if (eventContext.getEventData().getSequenceNumber().toInt() % 5 === 0) {
            eventContext.updateCheckpoint()
            }
        }

        val ERROR_HANDLER: Consumer<ErrorContext> = Consumer<ErrorContext> { errorContext ->
            println(
                "Error occurred in partition processor for partition ::" + errorContext.partitionContext.partitionId
            )
        }
        val clientConnectionString: String =
            "Endpoint=sb://[[ REDACTED ]].servicebus.windows.net/;SharedAccessKeyName=[[ REDACTED ]];SharedAccessKey=[[ REDACTED ]];EntityPath=[[ REDACTED ]]"

        val eventProcessorClientBuilder = EventProcessorClientBuilder()
            .connectionString(clientConnectionString, "[[ REDACTED ]]")
            .consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
            .processEvent(PARTITION_PROCESSOR)
            .processError(ERROR_HANDLER)
            .checkpointStore(BlobCheckpointStore(blobContainerAsyncClient))

        // Use the builder object to create an event processor client
        val eventProcessorClient = eventProcessorClientBuilder.buildEventProcessorClient()

        println("Starting event processor")
        eventProcessorClient.start()
        println("Press enter to stop.")
        Thread.sleep(150000)
        println("Stopping event processor")
        eventProcessorClient.stop()
        println("Event processor stopped.")

        println("Exiting process")

    }
}


text: Q: visual studio 2022 community и github у меня есть в solution есть два проекта, первый проект загрузил в репозиторий в github.com. Второй проект тоже загрузил в репозиторий в github.com, после добавления второго проекта в репозиторий,к второму проекту создано отдельный папка, и от solution'а отделилось, а я хочу чтоб был один solution, и для каждого проекта отдельный репозиторий чтоб не отделилось. по гуглил не нашел решение. Можно так сделать, как хочу я, если да то поскажите как, если нет, то может какой то решение найдется. Заранее спасибо


text:
Q: Handlebars - How to use a Path in the #if I am trying to setup a #if conditional for a nested path but cannot seem to get it to work. I have tried the following:
{{#if person.showName}}

{{#if person/showName}}

{{#if (lookup person 'showName')}}

But cannot get it to go into the if branch. The object is setup as this:
{
  person {
    firstName: 'Uncle',
    lastName: 'Bob',
    showName: true
  }
}

Is this something that is just not supported within handlebars for the basic if conditional check? I would like to avoid using a {{#with}} or flattening all of the "flags" down to the base object.

A: Turns out I had a {{#with}} commented out in the HTML but it was apparently still getting executed even though it was commented out. As I am new to using Handlebars, it is a learning experience.


text:
Q: How to boot a FreeBSD 11 image on a Raspberry PI B? I downloaded the latest FreeBSD snapshot image for the Raspberry PI B model (FreeBSD-11.0-CURRENT-arm-armv6-RPI-B-20141222-r276066.img) from the official FreeBSD ftp.
I copied the image to the SD card using the program Disk Image Writer on Ubuntu.
After plugging in the SD card to the RPI and switching it on, the FreeBSD kernel gets not loaded. The last message on the monitor is always:
kernel entry at 0x100100...
kernel args: (null)
Using an FreeBSD 10 image instead works fine. Does anybody experience the same issue?
Does anybody have an idea what I did wrong?
Thank you all!
Jo


text:
Q: Unable to nuget restore after changing target framework from .NetStandard 2.0 to .net 4.7.2 I've just updated several of our projects from .net framework 4.6.2 to .net framework 4.7.2 and I'm getting the following errors:
Package Microsoft.AspNetCore 2.1.2 is not compatible with net472 (.NETFramework,Version=v4.7.2). Package Microsoft.AspNetCore 2.1.2 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.AspNetCore.Authentication.Cookies 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2). Package Microsoft.AspNetCore.Authentication.Cookies 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.AspNetCore.Authentication.JwtBearer 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2). Package Microsoft.AspNetCore.Authentication.JwtBearer 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.AspNetCore.Cors 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2). Package Microsoft.AspNetCore.Cors 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.AspNetCore.Identity.EntityFrameworkCore 2.1.2 is not compatible with net472 (.NETFramework,Version=v4.7.2). Package Microsoft.AspNetCore.Identity.EntityFrameworkCore 2.1.2 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.AspNetCore.Mvc 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2). Package Microsoft.AspNetCore.Mvc 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.AspNetCore.StaticFiles 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2). Package Microsoft.AspNetCore.StaticFiles 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.EntityFrameworkCore.SqlServer 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2). Package Microsoft.EntityFrameworkCore.SqlServer 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.EntityFrameworkCore.Tools 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2). Package Microsoft.EntityFrameworkCore.Tools 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.Extensions.Configuration.UserSecrets 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2). Package Microsoft.Extensions.Configuration.UserSecrets 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.Extensions.Logging.Debug 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2). Package Microsoft.Extensions.Logging.Debug 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.VisualStudio.Web.BrowserLink 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2). Package Microsoft.VisualStudio.Web.BrowserLink 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2). Package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.EntityFrameworkCore.Relational 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2). Package Microsoft.EntityFrameworkCore.Relational 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.VisualStudio.Web.CodeGenerators.Mvc 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2). Package Microsoft.VisualStudio.Web.CodeGenerators.Mvc 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    One or more packages are incompatible with .NETFramework,Version=v4.7.2.
    Package Microsoft.AspNetCore 2.1.2 is not compatible with net472 (.NETFramework,Version=v4.7.2) / win7-x86. Package Microsoft.AspNetCore 2.1.2 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.AspNetCore.Authentication.Cookies 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2) / win7-x86. Package Microsoft.AspNetCore.Authentication.Cookies 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.AspNetCore.Authentication.JwtBearer 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2) / win7-x86. Package Microsoft.AspNetCore.Authentication.JwtBearer 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.AspNetCore.Cors 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2) / win7-x86. Package Microsoft.AspNetCore.Cors 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2) / win7-x86. Package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.AspNetCore.Identity.EntityFrameworkCore 2.1.2 is not compatible with net472 (.NETFramework,Version=v4.7.2) / win7-x86. Package Microsoft.AspNetCore.Identity.EntityFrameworkCore 2.1.2 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.AspNetCore.Mvc 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2) / win7-x86. Package Microsoft.AspNetCore.Mvc 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.AspNetCore.StaticFiles 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2) / win7-x86. Package Microsoft.AspNetCore.StaticFiles 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.EntityFrameworkCore.SqlServer 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2) / win7-x86. Package Microsoft.EntityFrameworkCore.SqlServer 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.EntityFrameworkCore.Tools 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2) / win7-x86. Package Microsoft.EntityFrameworkCore.Tools 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.Extensions.Configuration.UserSecrets 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2) / win7-x86. Package Microsoft.Extensions.Configuration.UserSecrets 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.Extensions.Logging.Debug 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2) / win7-x86. Package Microsoft.Extensions.Logging.Debug 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.VisualStudio.Web.BrowserLink 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2) / win7-x86. Package Microsoft.VisualStudio.Web.BrowserLink 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.EntityFrameworkCore.Relational 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2) / win7-x86. Package Microsoft.EntityFrameworkCore.Relational 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    Package Microsoft.VisualStudio.Web.CodeGenerators.Mvc 2.1.1 is not compatible with net472 (.NETFramework,Version=v4.7.2) / win7-x86. Package Microsoft.VisualStudio.Web.CodeGenerators.Mvc 2.1.1 supports: netstandard2.0 (.NETStandard,Version=v2.0)
    One or more packages are incompatible with .NETFramework,Version=v4.7.2 (win7-x86).

What really confuses me with this is that .NETFramework 4.7.2 is compatible with .NET Standard 2.0 so why are we getting this error message?  It doesn't make sense!
Any help greatly appreciated.

A: I had this issue on our CI server, turned out an older copy of nuget.exe was installed, upgrading that to the latest fixed the issue (v4.1 to 4.7)

A: Solution that worked for me in AzureDevOps known as VSTS :
1 - Add a dotnet restore step.
2 - In the advanced options of the Nuget Restore step, select the Custom version and set the "Path to Nuget.exe" as : $(Build.BinariesDirectory)\nuget.exe
3 - Before the NuGet restore Task add an Inline PowerScript shell, Refer to this github link :
https://github.com/Microsoft/vsts-tasks/issues/3756#issuecomment-288185011
Don't forget to change the version of nuget in the Shell Script to the one you want ( for me it's the 4.3.0).

A: Update your NuGet installer to version 2.*. After that NuGet.exe will auto-update to version 4.3


text:
Q: Where should I put my credential data streaming with Kafka in databricks? I have some values in Azure Key Vault (AKV)
A simple initial googling was giving me
username = dbutils.secrets.get(scope = "DATAAI-CEC", key = "dai-kafka-cec-api-key")
pwd = dbutils.secrets.get(scope = "DATAAI-CEC", key = "dai-kafka-cec-secret")

from kafka import KafkaConsumer

consumer = KafkaConsumer('TOPIC',
                     bootstrap_servers = 'SERVER:PORT',
                     enable_auto_commit = False,
                     auto_offset_reset = 'earliest',
                     consumer_timeout_ms = 2000,
                     security_protocol = 'SASL_SSL',
                     sasl_mechanism = 'PLAIN',
                     sasl_plain_username = username,
                     sasl_plain_password = pwd)

This one works one time when the cell in databricks runs, however, after a single run it is finished, and it is not listening to Kafka messages anymore, and the cluster goes to the off state after the configured time (in my case 30 minutes)
So it doesn't solve my problem
My next google search was this blog on databricks (Processing Data in Apache Kafka with Structured Streaming in Apache Spark 2.2)
from pyspark.sql.types import *
from pyspark.sql.functions import from_json
from pyspark.sql.functions import *

schema = StructType() \
  .add("EventHeader", StructType() \
    .add("UUID", StringType()) \
    .add("APPLICATION_ID", StringType())
    .add("FORMAT", StringType())) \
  .add("EmissionReportMessage", StructType() \
    .add("reportId", StringType()) \
    .add("startDate", StringType()) \
    .add("endDate", StringType()) \
    .add("unitOfMeasure", StringType()) \
    .add("reportLanguage", StringType()) \
    .add("companies", ArrayType(StructType([StructField("ccid", StringType(), True)]))))

parsed_kafka = spark \
                .readStream \
                .format("kafka") \
                .option("kafka.bootstrap.servers", "SERVER:PORT") \
                .option("subscribe", "TOPIC") \
                .option("startingOffsets", "earliest") \
                .load()\
                .select(from_json(col("value").cast("string"), schema).alias("kafka_parsed_value"))

There are some issues

*

*Where should I put my GenID or user/pass info?

*When I run the display command, it runs, but it will never stop, and it will never show the result

A:
however, after a single run it is finished, and it is not listening to Kafka messages anymore

Given that you have enable_auto_commit = False, it should continue to work on following runs. But this isn't using Spark...

Where should I put my GenID or user/pass info

You would add SASL/SSL properties into option() parameters.
Ex. For SASL_PLAIN
option("kafka.sasl.jaas.config",
  'org.apache.kafka.common.security.plain.PlainLoginModule required username="{}" password="{}";'.format(username, password))

See related question

it will never stop

Because you run a streaming query starting with readStream rather than a batched read.

it will never show the result

You'll need to use parsed_kafka.writeStream.format("console"), for example somewhere (assuming you want to start with readStream, rather than display() and read


text:
Q: How to upload paid app using IAP in swift I want to upload paid app on iTunes Connect means if you want to download the app then you have to pay first. For this do I need to implement IAP? I already integrated IAP so many times but inside the app. I want to know the process of uploading paid app on iTunes Connect. Any help would be highly appreciated. Thanks

A: There is no need to In-App Purchase for paid apps. Instead you have mention price in AppStore Connect.
Login in to App Store Connect. Open the app you want to make it paid.
Go to the Pricing and Availability, in that select the price from Price Schedule

Please let me know if you have doubt.


text:
Q: LinkerErrors on opencv3.0 included project First of all I have already checked many LinkerError questions in stackoverflow. But everything seems connected on my sight. Let me share some information:
Code:
#include<opencv\cv.h>
#include<opencv\highgui.h>

void main(){
    IplImage* img = cvLoadImage("C:\kaplan.jpg");
    cvNamedWindow("ImgDisp", CV_WINDOW_AUTOSIZE);
    cvShowImage("ImgDisp", img);
    cvWaitKey(0);
    cvReleaseImage(&img);
    cvDestroyWindow("ImgDisp");
}

System settings:

*

*Configuration : Debug

*Platform : x64

*VC++ Directories -> Executable directories =
C:\opencv\build\x64\vc12\bin;$(ExecutablePath)

*VC++ Directories -> Library directories =
C:\opencv\build\x64\vc12\staticlib;C:\opencv\build\x64\vc12\lib;$(LibraryPath)

*C/C++ -> General -> Additional Include directories =
C:\opencv\build\include\opencv2;C:\opencv\build\include;C:\opencv\build\include\opencv;%(AdditionalIncludeDirectories)

*Linker -> General -> Additional Library directories =
C:\opencv\build\x64\vc12\staticlib;C:\opencv\build\x64\vc12\lib;%(AdditionalLibraryDirectories)

*Linker -> Input -> Additional Dependencies =
opencv_calib3d300d.lib;opencv_core300d.lib;opencv_features2d300d.lib;opencv_flann300d.lib;opencv_hal300d.lib;opencv_highgui300d.lib;opencv_imgcodecs300d.lib;opencv_imgproc300d.lib;opencv_ml300d.lib;opencv_objdetect300d.lib;opencv_shape300d.lib;opencv_stitching300d.lib;opencv_superres300d.lib;opencv_ts300d.lib;opencv_video300d.lib;opencv_videoio300d.lib;opencv_videostab300d.lib;%(AdditionalDependencies)
Error obtained :

1>opencv_imgcodecs300d.lib(loadsave.obj) : error LNK2005: "public:
  __cdecl std::_Container_base12::_Container_base12(void)" (??0_Container_base12@std@@QEAA@XZ) already defined in
  msvcprtd.lib(MSVCP120D.dll)
1>opencv_core300d.lib(stat.obj) : error LNK2019: unresolved external
  symbol ippicviNormDiff_L2_8s_C3CMR referenced in function "double
  __cdecl cv::norm(class cv::_InputArray const &,class cv::_InputArray const &,int,class cv::_InputArray const &)"
  (?norm@cv@@YANAEBV_InputArray@1@0H0@Z)
1>opencv_core300d.lib(matmul.obj) : error LNK2019: unresolved external
  symbol ippicviDotProd_32s64f_C1R referenced in function "double
  __cdecl cv::dotProd_32s(int const *,int const *,int)" (?dotProd_32s@cv@@YANPEBH0H@Z)
1>c:\users\juhsis\documents\visual studio
  2013\Projects\Project1\x64\Debug\Project1.exe : fatal error LNK1120:
  528 unresolved externals

So, what did I miss?

A: I have just found the source of problem. In opencv 3.0, I realised that all library files I have previously used and located in \lib file has been moved into \staticlib. In \lib file there are only 2 libraries placed: opencv_world300d.lib;opencv_ts300d.lib . Then I erase all links to staticlib folder and all libs under that folder and replaced with \lib folder and libraries under that folder.
Here are the changes in settings I am currently using:

*

*Configuration : Debug

*Platform : x64

*C/C++ -> General -> Additional Include directories =
C:\opencv\build\include;%(AdditionalIncludeDirectories)

*Linker -> General -> Additional Library directories =
C:\opencv\build\x64\vc12\lib;%(AdditionalLibraryDirectories)

*Linker -> Input -> Additional Dependencies =
opencv_world300d.lib;opencv_ts300d.lib;%(AdditionalDependencies)


text:
Q: Exchange 2010 and Outlook SSL Error I have a new setup of windows SBS. When I connect via outlook I get a message that the SSL for "remote.mail.mydomain.com" does not match.
I setup the SSL for "mail.mydomain.com". I can't find where to change the URL that outlook should use. I know it would be an exchange setting, but I've been through all the screens and I can't find it.

A: I believe you're looking for the configuration option to set the external client URL that outlook or activesync devices use when accessing mail either through EWS or activesync.
To set this in exchange 2010 via the EMC (Exchange Management Console):

*

*Open the EMC.

*Expand the "Server Configuration" tree in the left hand pane.

*Select the "Client Access" item under "Server Configuration"

*In the Actions pane, located to the right of the window, now select "Configure External Client Access Domain" and follow the wizard:

I would also suggest creating an A record in your external and internal DNS servers pointing to your exchange server, this will allow for far easier configuration of your email clients.

A: I would try the PowerShell script located here.
I'm a little tired at the moment, but what's left of my brain is telling me that this is one of those things in Exchange 2010 that can't be changed in the GUI and requires PowerShell.


text:
Q: Data frame with different encodings in R Here is a snippet from data encoding in R memory. The CSV file was read with encoding "Latin-1" using data.table::fread.
As this piece suggests, the data is stored with different encodings, which is not desirable because I'll leave the data in a SQLite database, so whenever I send data to database and call it back, Latin-1 is not read in appropriately. Is there a way to normalize this?
It seem that common functions like iconv won't work, once the data have multiple encodings in different parts of the data.frame.
Encoding(Data$DESC)

 [5305] "unknown" "unknown" "unknown" "unknown" "unknown" "unknown"
 [5311] "unknown" "unknown" "unknown" "latin1"  "unknown" "unknown"
 [5317] "unknown" "latin1"  "latin1"  "latin1"  "latin1"  "unknown"
 [5323] "latin1"  "latin1"  "latin1"  "latin1"  "unknown" "latin1"


text:
Q: Maven release:perform not passing settings file to the deploy phase I'm having an issue where Maven is not passing the settings to the deploy phase when I use the release plugin.  I have my settings.xml file in the same folder as my pom.xml.  When I run the following command it deploys successfully to the Maven repository.
mvn deploy -s settings.xml

However when I run this command, it fails saying that it doesn't have permissions to deploy to the repository.
mvn release:perform -B -s settings.xml

Here is the error message:
[INFO] [INFO] Error deploying artifact: Failed to transfer file: http://mavenrepo/groupId/artifactId/versionId/artifactId-versionId.pom. Return code is: 401
The only thing I can think that is causing the second to fail is that the release plugin doesn't pass the settings down to the deploy phase.  How do I get this to work?
I used to have the MAVEN_OPTS environment variable set to specify my settings.xml file, but since this will run on from TeamCity, that is no longer an option.

A: I found a bug in the codehaus Jira for this same issue here. It was fixed in maven-release-plugin 2.2.2. As soon as I changed the version number in my pom.xml, it worked fine.


text:
Q: Excel: time series with markers for events I have daily data for two stocks for about 10 years, and sometimes there are some specific events (such as an announcements or a political events, not numerical data) I would like to show on my graph.
When I'm plotting the 2 time series I would like to add a cross or a line from the x-axis on the graph when the specified eventS happen.
My data on the Excel sheet are presented as follow: 1st column is the dates, 2nd colum is the value of stock 1, column 3 is the value of stock 2, and last column is the name of the event when there is one otherwise it's written #N/A.
I've tried a few tutorials online but they don't work.
Thanks for any help you can provide.
:)

A: To achieve an effect like this:

1)  Convert your existing data into a Data Table Insert>Table.
2)  Add a helper column, called "Event_Helper", with the following formula =IF([@event]="",na(),0).  This returns a 0 value whenever you have a named event in your Event column, otherwise it returns #N/A which is ignored by Excel when charting a series.
3)  Create an XY/Scatter Chart (not a line chart), using

*

*X Values = Date column

*Y Values = Stock A, Stock B, and Event_Helper columns

4)  Add data labels to your event data series and format to taste.
If you'd like to add vertical lines like this:

5)  Add an additional helper column "Error_Helper" to your table with the following formula:=IF([@Event]="",NA(),MIN(Table1[@[StockA]:[StockB]])).  This returns the minimum and lowest charted stock value when there's a named event, otherwise it returns #N/A.
6)  Add error bars to your Event_Helper data series.
7)  Delete the horizontal error bars.
8)  Format the vertical error bars with a Custom Error Amount, using:

*

*Positive Error Value = Error_Helper

*Negative Error Value = 0

9)  Format the error bars to taste.


text:
Q: Print a nodes elements in java generic binary search tree I am still trying to learn some of the nuances of working with generics in java and I'm a bit caught up on trying to print some elements of a Node type which holds the actual data of my binary search tree's binary nodes.
Here is my most basic node class which holds the BinaryNodes data
public class Node implements Comparable<Object> {

private String word;
private int frequency;

public Node(String word) {
    super();
    this.word = word;
    this.frequency = 1;
}

public String getWord() {
    return word;
}

public void setWord(String word) {
    this.word = word;
}

public int getFrequency() {
    return frequency;
}

public void setFrequency(int frequency) {
    this.frequency = frequency;
}

public void incrementFrequency() {
    this.frequency++;
}

@Override
public String toString() {
    return "Node [word=" + word + ", frequency=" + frequency + "]";
}

public int compareTo(Object x) {
    Node that = (Node) x;
    return this.getWord().compareTo(that.getWord());
}

public boolean startsWith(Object x) {
    Node that = (Node) x;
    return that.getWord().startsWith(this.getWord());
}
}

The Class which makes up the actual nodes of the binary search tree is a BinaryNode class which is set up as follows
public class BinaryNode <AnyType> {
AnyType element; //the data in the node
BinaryNode<AnyType> left; //left child
BinaryNode<AnyType> right; //right child

BinaryNode(AnyType theElement){
    this(theElement, null, null);
}

BinaryNode(AnyType theElement, BinaryNode<AnyType> lt, BinaryNode<AnyType> rt){
    element = theElement;
    left = lt;
    right = rt;
}
}

next I have my BinarySearchTree class which is set up as
public class BinarySearchTree <AnyType extends Comparable<? super AnyType>> {

//the root of the tree
BinaryNode<AnyType> root;

followed by methods for getting and printing the root, inserting and a few others..
and last I have my HashedBST class which contains an ArrayList with each index containing its own BST.
public class HashedBSTs<AnyType> {

private ArrayList <BinarySearchTree<Node>> table;

public HashedBSTs(int size){
    table = new ArrayList<BinarySearchTree<Node>>(size);
    for(int i = 0; i < size; i++){
        table.add(new BinarySearchTree());
    }
}
    public void printHashCountResults(){
    for(BinarySearchTree<Node> BST : table){
        if(BST.root != null){
            //Node n = (Node)BST.root.element;

            //int freq = BST.root.element.getFrequency();
            //String word = "";
            //int numNodes = 0;
            //System.out.println("This tree starts with Node "
            //+"[word="+word+", frequency="+freq+"] and has "+numNodes  +"nodes");

            BinaryNode<AnyType> bn =  (BinaryNode<AnyType>) BST.getRoot();
            Node n = (Node) bn.element;
            System.out.println(n.toString());
        }else{
            System.out.println("this tree has no nodes");
        }
    }
}

No matter whichever approach I try to take to access and print the information of the most basic data Nodes data I end up with
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to proj2.Node
Any help towards how I should do this properly would be greatly appreciated.
Edit:
So I tired to change around how some of my classes are set up based on the answers but I'm still running into the same road block as before.
In my HashedBSTs class I changed the class structure and constructor to
public class HashedBSTs<AnyType extends Comparable<? super AnyType>> {

private ArrayList <BinarySearchTree<AnyType>> table;

public HashedBSTs(int size){
    table = new ArrayList<BinarySearchTree<AnyType>>(size);
    for(int i = 0; i < size; i++){
        table.add(new BinarySearchTree<AnyType>());
    }
}

However I still run into the same issue trying to reach the Node classes methods within another class. Some of the suggestions were to change how my Node class is set up however I cant do this. The Node class is a class that is given to build from and I cannot modify that class.
Next I tried some new approaches such as
        if(t.element instanceof Node){
            Node n = (Node) t.element;
            int freq = n.getFrequency();
            System.out.println("Frequency: "+freq);
            System.out.println(t.toString());
            System.out.println(((Node) t.element).toString());
        }

However that conditional will not be True when I run my program, and when I remove the if statement then I still get the java.lang.ClassCastException on Node n = (Node)t.element;

A: First off, Node should implement Comparable< Node >, not Comparable< Object >.  That change alone will allow the compiler to prevent problems with comparing the wrong kinds of things, which is exactly what your runtime error is suggesting is the problem.  Catching these things early is the whole point of generics.  If your assignment forbids modifying this class, you should inform your professor or TA that this class is flawed.  The class cast exception is probably coming from inside a call to compareTo, meaning that the problem is not the attempt to print out the information, but rather the attempt to populate your tree in the first place, as inserting an element is going to cause some comparisons to take place.
Second, don't use a type variable that looks like the name of an actual class (AnyType).  I've seen questions whose cause is entirely related to bucking this convention come back at least once a week on SO.  Use a single capital letter like T if possible.
Third, I notice that you are attempting to initialize the backing list inside HashedBSTs using instances of the raw type BinarySearchTree, instead of BinarySearchTree< AnyType >, forcing you to cast things all over the place.  You should not need a single cast anywhere if you're doing it right. Node should be replaced with AnyType (or a better type variable name) everywhere inside HashedBSTs, and you will need to add the same constraint to AnyType in the definition of HashedBSTs that you have used in the definition of BinarySeaerchTree (namely, that AnyType be comparable with itself).
Finally, the one thing you have not shown us is the code you are using to populate your tree for testing. Since you have allowed your binary tree class to hold any type at all, I am guessing that you are populating a tree with Strings instead of Nodes. It should therefore come as no surprise that your instanceof test is failing.
Is it possible you have misunderstood the assignment?
The Node class is what holds the data.  The given example is a Node of String, but if the data itself is what is supposed to be generic, that's where the variable should be.
public class Node< T extends Comparable< ? super T > >
implements Comparable< Node< T > > {
    T data;
    int frequency;
    // ...
}

The reason I assume this misunderstanding is that if the Node is the thing that could be any type, then within HashedBSTs you would have no means of interrogating the contents of the trees, other than the methods of Object (like toString()).  For example, your attempt to call getFrequency() is simply not possible unless you know that the nodes in your trees are Nodes; AnyTypes don't necessarily have a getFrequency() method.


text:
Q: Create generic list from any XML file The title explains most of it. What I am doing probably is not the best solution. I saw many websites saying that you should know the structure of the XML file. But my goal is this.
I want to create a c# function that reads XML information to a list. I want to read the entire file, no matter the structure and keep it in memory.
I already built some code wich reaches every tag in the XML file and it works.
private void Form1_Load(object sender, EventArgs e)
{
    XDocument file = XDocument.Load("file.xml");

    foreach (XElement element in file.Root.Elements())
    {
        text += element.Name + Environment.NewLine;

        if (element.HasElements)
            readElement(element);
    }

    MessageBox.Show(text);
    Application.Exit();
}

private void readElement(XElement element)
{
    IEnumerable<XElement> nodes = element.Elements();

    foreach (XElement el in nodes)
    {
        text += el.Name + Environment.NewLine;

        if (element.HasElements)
            readElement(el);
    }
}

So lets say I have this XML file to read:
<?xml version="1.0" encoding="UTF-8"?>
<parent>
    <element1>
        <element2>
            <element3></element3>
        </element2>
    </element1>
    <element4>
        <element5></element5>
    </element4>
    <element6>
        <element7>
            <element8>
                <element9></element9>
            </element8>
        </element7>
    </element6>
</parent>

Like I said, i want the code to be able to work with any XML file, no matter the structure. So my function starts with the root, wich will be an empty list, don't even knowing the type. Since it has children elements, this list will create on fly a list inside it, with the children elements. After that, it will see every child and create a list inside it if it has children elements too.
So at the end, I will have lists inside lists, exactly like the structure of my file. This is where I'm stuck right now, trying to add these list attributes to the root list.
Besides this, I also want to add an attribute with the name 'Value' and type 'object' to store the data inside the tag.
This may be a little confuse to understand and possibly impossible to do, but I just decided to try, since I couldn't find a generic code to read any XML file data on the internet.
Thanks for the help in advance. :)

A: To begin with I would probably use an XmlReader instead because I think the XDocument.Load will cause problems if the file you are trying to read is a big file.
using (XmlReader reader = XmlReader.Create(@"file.xml"))
{
    while (reader.Read())
    {
       // Process each node (myReader.Value) here
    }
}

Hope that helps somewhat at least...


text:
Q: Citing court cases in APA 7 with BibLaTeX I'm having trouble citing a U.S. District Court case using the apa7 class with Biber.
According to this reference, the format should be as follows (using the information I need in my citation):

Oracle America, Inc. v. Google, Inc. 872 F. Supp. 2d. 974 (2012). https://www.leagle.com/decision/infdco20120601k39

In this case, the volume is 872, the name of the book is F. Supp. 2d. (including the periods), and the page number is 974.
I've defined my reference as follows:
@book{initial_suit,
    author = "{\relax Oracle America, Inc. v. Google, Inc.}",
    volume = {872},
    book = "{\relax F. Supp. 2d.}",
    page = {974},
    date = {2012-05-31}
}

And I've cited it in my document as follows:
\parencite{initial_suit}

I get the correct format for the in-text citation, but the bibliography at the end of my document is completely incorrect. I see the following:

How should I format my Biber citation to correctly display the contents?
Here is an MWE:
\documentclass[man]{apa7}
\usepackage[american]{babel}
\usepackage{csquotes}
\usepackage[style=apa,sortcites=true,sorting=nyt,backend=biber]{biblatex}
\DeclareLanguageMapping{american}{american-apa}
\begin{filecontents*}{mwe.bib}
@book{initial_suit,
 author = "{\relax Oracle America, Inc. v. Google, Inc.}",
 volume = {872},
 book = "{\relax F. Supp. 2d.}",
 page = {974},
 date = {2012-05-31}
}
\end{filecontents*}
\addbibresource{mwe.bib}

\title{Minimum Working Example}
\shorttitle{Lorem Ipsum}

\author{nhubbard}
\authorsaffiliations{TeX.SX}

\leftheader{TeX.SX}

\abstract{
  \textbf{TODO: Write this abstract \textit{after} writing the rest of the proposal.}
}

\keywords{example}

\begin{document}
    \maketitle
    This is a citation. \parencite{initial_suit}
    \printbibliography
\end{document}

A: biblatex-apa comes with an extensive example .bib file which includes many - if not all - examples from the APA manual. Especially for more complex and less common entry types I highly recommend you have a look at that file if you don't know how to format your .bib entries.
For court decisions have a look at the entry 11.4:3 (ll. 2488-2497 in biblatex-apa-test-references.bib) and the following entries.
Here you might end up with something like
\documentclass[man]{apa7}
\usepackage[american]{babel}
\usepackage{csquotes}
\usepackage[style=apa]{biblatex}

\title{Minimum Working Example}
\shorttitle{MWE}
\author{nhubbard}

\begin{filecontents*}{\jobname.bib}
@jurisdiction{initial_suit,
  title         = {Oracle America, Inc. v. Google, Inc.},
  citation      = {872 F. Supp. 2d. 974},
  url           = {https://www.leagle.com/decision/infdco20120601k39},
  date          = {2012},
}
\end{filecontents*}
\addbibresource{\jobname.bib}

\begin{document}
  \maketitle
  This is a citation. \parencite{initial_suit}
  \printbibliography
\end{document}


text:
Q: Why does a seccomp process always get killed? Why does a process that has gone into seccomp mode always get killed on exit?
$ cat simple.c
#include <stdio.h>
#include <stdlib.h>
#include <linux/prctl.h>

int main( int argc, char **argv )
{
    printf("Starting\n");
    prctl(PR_SET_SECCOMP, 1);
    printf("Running\n");
    exit(0);
}
$ cc -o simple simple.c
$ ./simple || echo "Returned $?"
Starting
Running
Killed
Returned 137

A: From the man page, under PR_SET_SECCOMP, the only allowed system calls are read, write, exit, and sigreturn.
When you call exit(0) in the standard library (in recent Linux), you call the exit_group system call, not exit.  This is not allowed, so you get a SIGKILL.
(You can see this if you strace the process...)


text:
Q: NullPointerException because of overwritten function and call by superclass Following setup:
public class Superclass
{
    private String params;

    public Superclass(String params)
    {
        this.params = params;
        doStuff();
    }

    public void doStuff()
    {
        // uninteresting stuff
    }
}

public class Subclass extends Superclass
{
    private Object someObject;

    public Subclass(String params, Object someObject)
    {
        super(params);
        this.someObject = someObject;
    }

    @Override
    public void doStuff()
    {
        someObject.toString(); // <- causes NullPointerException
    }
}

Superclass creates an User Interface while Subclass should create a more specialized version.
From a software engineering point of view, what would be the cleanest way to prevent the NullPointerException while "Subclass" still extends "Superclass"?

A: The parent class has no apparent reason at construction time to call doStuff.
Simply put, don't put the call there.   These classes should be constructed independently of each other.  The parent class should not have a dependency on any data from the child to complete its construction; any methods that are overridden by the child that are called in the parent's constructor will introduce this dependency.
If you do find you need to invoke an extra method in the parent, though, you could make a final method and no ill effect would happen, since the child wouldn't have access to that method.
public class Superclass {
    private String params;

    public Superclass(String params) {
        this.params = params;
        doStuffParent();
    }

    public final void doStuffParent() {
        // uninteresting stuff
    }

    public void doStuff() {
        // uninteresting stuff...again?
    }
}

A: From a software engineering perspective, you are trying to perform an action on an object that has not yet been constructed. Map this idea to your real class and its job, you'll understand that there's some problem with the super class constructor because its trying to work on an object in a bad state.
That being said, you have a few options.

*

*If it makes sense, try to pass Object someObject to the super class. May be the super class really needs it for it to work.

*Do not call doStuff() within the super class constructor. It probably even makes sense to call it explicitly outside of both constructors.

*Let your extended class's constructor call doStuff(..).


text:
Q: Strange Silverlight Problem I have a method that generates XML for a class I have created -getXML(). This is called from the following methods:
private void send_Response()
    {
        String xmlUrl = ((App)Application.Current).Resources["xmlUrl"].ToString();
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(xmlUrl,              UriKind.Absolute));
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.BeginGetRequestStream(new AsyncCallback(RequestReady), request);
    }

    void RequestReady(IAsyncResult asyncResult)
    {
        HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
        Stream stream = request.EndGetRequestStream(asyncResult);
        StreamWriter writer = new StreamWriter(stream);
        writer.WriteLine("assessmentXml=" + assessment.getXML(testComplete));
        writer.Flush();
        writer.Close();

        request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
    }

    void ResponseReady(IAsyncResult asyncResult)
    {
        HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

        Stream s = response.GetResponseStream();
        StreamReader sr = new StreamReader(s);

        String line = "";
        String Result = "";

        line = sr.ReadLine();
        while (line != null)
        {
            Result += line;
            line = sr.ReadLine();
        }

        s.Close();
    }

The getXML itself is as follows:
public String getXML(bool end)
    {
        StringWriter output = new StringWriterWithEncoding(Encoding.UTF8);
        XmlWriterSettings ws = new XmlWriterSettings();
        ws.Indent = true;
        ws.Encoding = new UTF8Encoding(true);
        ws.ConformanceLevel = ConformanceLevel.Document;

        using (XmlWriter writer = XmlWriter.Create(output, ws))
        {
            writer.WriteStartElement("root");

            if (end)
            {
                writer.WriteAttributeString("testComplete", "true");
            }
            else
            {
                writer.WriteAttributeString("testComplete", "false");
            }

            for (int i = 0; i < theSections.Count(); i++)
            {
                writer.WriteStartElement("section");
                writer.WriteAttributeString("id", theSections.ElementAt(i).Id.ToString());
                writer.WriteAttributeString("title", theSections.ElementAt(i).Name.ToString());
                writer.WriteAttributeString("completed", theSections.ElementAt(i).Completed.ToString());

                for (int j = 0; j < theSections.ElementAt(i).Elements.Count(); j++)
                {
                    writer.WriteStartElement(theSections.ElementAt(i).Elements.ElementAt(j).Name.ToString());

                    for (int a = 0; a < theSections.ElementAt(i).Elements.ElementAt(j).Attributes().Count(); a++)
                    {
                        writer.WriteAttributeString(theSections.ElementAt(i).Elements.ElementAt(j).Attributes().ElementAt(a).Name.ToString(), theSections.ElementAt(i).Elements.ElementAt(j).Attributes().ElementAt(a).Value);
                    }

                    for (int c = 0; c < theSections.ElementAt(i).Elements.ElementAt(j).Elements().Count(); c++)
                    {
                        writer.WriteStartElement(theSections.ElementAt(i).Elements.ElementAt(j).Elements().ElementAt(c).Name.ToString());
                        writer.WriteString(theSections.ElementAt(i).Elements.ElementAt(j).Elements().ElementAt(c).Value);
                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }

            writer.WriteEndDocument();
            writer.Flush();
            writer.Close();

        }
        return output.ToString();
    }

(Sorry about the excess amounts of code).
This all works fine, and I can see the xml output. But now I want to add some more code to the getXML() function, and Silverlight just won't let me do it. Even a simple MessageBox.Show("something") won't display, and the whole method now fails to generate any XML. Having said that, there are no errors or warnings generated within Visual Studio.
I've added new code in other areas of the same .cs file and it all works fine, it is just in this one method. I've tried rebuilds but also to no avail, so I'm confused as to how this could be the case. Is it a Visual Studio bug?
Thanks in advance for any help.

A: I've got it working. No ideas why. I think the Cross Thread Error was to do with messageBox being part of the UI, so I removed that and just added in some new xmlwriter stuff... and it worked. I had tried this before and it didn't work so I'll keep my eye on it but so far so good. Still puzzled, but nevermind.


text:
Q: Write the final dataset output for spark Java into s3 I am not able to find the correct way to write data to s3 from dataset spark. What should be some more configurations that I should add. Do I have to mention the AWS configurations in my code or it will pick it up from local .aws/ profile?
Please guide
import java.util.Properties;

import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;

public class sparkSqlMysql {

private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(sparkSqlMysql.class);

private static final SparkSession sparkSession = SparkSession.builder().master("local[*]").appName("Spark2JdbcDs")
        .getOrCreate();

public static void main(String[] args) {
    // JDBC connection properties

    final Properties connectionProperties = new Properties();
    connectionProperties.put("user", "root");
    connectionProperties.put("password", "password");
    connectionProperties.put("driver", "com.mysql.jdbc.Driver");
    final String dbTable = "(select * from Fielding) t";
    final String dbTable1 = "(select * from Salaries) m";
    final String dbTable2 = "(select * from Pitching) n";

    // Load MySQL query result as Dataset

    Dataset<Row> jdbcDF2 = sparkSession.read().jdbc("jdbc:mysql://localhost:3306/lahman2016", dbTable,
            connectionProperties);
    Dataset<Row> jdbcDF3 = sparkSession.read().jdbc("jdbc:mysql://localhost:3306/lahman2016", dbTable1,
            connectionProperties);

    Dataset<Row> jdbcDF4 = sparkSession.read().jdbc("jdbc:mysql://localhost:3306/lahman2016", dbTable2,
            connectionProperties);

    jdbcDF2.createOrReplaceTempView("Fielding");
    jdbcDF3.createOrReplaceTempView("Salaries");
    jdbcDF4.createOrReplaceTempView("Pitching");

    Dataset<Row> sqlDF = sparkSession.sql(
            "select Salaries.yearID, avg(Salaries.salary) as Fielding from Salaries inner join Fielding ON Salaries.yearID = Fielding.yearID  AND Salaries.playerID = Fielding.playerID group by Salaries.yearID limit 5");

    Dataset<Row> sqlDF1 = sparkSession.sql(
            "select Salaries.yearID, avg(Salaries.salary) as Pitching from Salaries inner join Pitching ON Salaries.yearID = Pitching.yearID  AND Salaries.playerID = Pitching.playerID group by Salaries.yearID limit 5");

    // sqlDF.show();

    // sqlDF1.show();

    sqlDF.createOrReplaceTempView("avg_fielding");

    sqlDF1.createOrReplaceTempView("avg_pitching");

    Dataset<Row> final_query_1_output = sparkSession.sql(
            "select avg_fielding.yearID, avg_fielding.Fielding, avg_pitching.Pitching from avg_fielding inner join  avg_pitching ON avg_pitching.yearID = avg_fielding.yearID");

    final_query_1_output.show();

The output of the query is :
 final_query_1_output.show();
+------+------------------+------------------+
|yearID|          Fielding|          Pitching|
+------+------------------+------------------+
|  1990|  507978.625320787| 485947.2487437186|
|  2003|2216200.9609838845|2133800.1867612293|
|  2007|2633213.0126475547|2617533.3393665156|
|  2015|3996199.5729421354| 3955581.121535181|
|  2006| 2565803.492487479| 2534756.866972477|
+------+------------------+------------------+

I want to write this dataset to s3 : how can I do that?
    final_query_1_output.write().mode("overwrite").save("s3n://druids3migration/data.csv");


text:
Q: how to find the avg in nested lists using for/while loop in python def average_list(M):
'''(list of list of int) -> list of float

Return a list of floats where each float is the average of
the corresponding list in the given list of lists.

>>> average_list([[4, 6], [5, 5]])
[5.0, 5.0]

'''
L = []

for item in M:
    for i in range(len(item)):
        avg = sum(item[i])/len(item[i])
        L.append(avg)
return L

error:
average_list([[4, 6], [5, 5]])
Traceback (most recent call last):
    avg = sum(item[i])/len(item[i])
builtins.TypeError: 'int' object is not iterable
I want to know how to fix it, thanks a lot!
And any other way to do in while loop?

A: What are you trying to do in your for loop? All you need is to iterate over M by value, not by index. This line for i in range(len(item)): is causing your error. Your inner for loop is not needed.
def average_list(M):
    L = []
    for item in M:
        avg = sum(item)/len(item)
        L.append(avg)
    return L

But you should Use list comprehension instead. In my opinion, it would be the most canonical way to solve your problem, not to mention the most "Pythonic":
>>> def average_list(M):
        return [sum(sublist)/len(sublist) for sublist in M]

>>> average_list([[4, 6], [5, 5]])
[5.0, 5.0]
>>>

A: Your error is that item[i] is a single element, which you cannot sum or len. You did not need that inner loop and for loops would be preferred over while loops because you have a finite collection.
If using Python3, you can use the mean function, and map that over the list of lists
from statistics import mean

def average_list(M):
    return list(map(mean, M))

Borrowed from Finding the average of a list

A: in python 3:
lst=[[4, 6], [5, 5]]
list(map(lambda x: sum(x)/len(x), lst))
Out[104]: [5.0, 5.0]

or in python 2:
from __future__ import division
lst=[[4, 6], [5, 5]]
map(lambda x: sum(x)/len(x), lst)
Out[104]: [5.0, 5.0]


text:
Q: Python-XMPP - Iterate the IQ stanza items I'm using python-xmpp to connect to gtalk. I'm receiving the responses and I can send and receive a message to a specific user/email. I am looking for a way to iterate over the IQ items so that I can get the jid and name attribute for each item.
The IQ stanza is of the form:
<iq to="example@gmail.com/test" id="3" type="result">
<query xmlns="jabber:iq:roster">
<item jid="test2@example.com" subscription="both" name="ABCD"/>
<item jid="test2@example.com" subscription="both" name="EFGH"/>
.
.
</query>
</iq>

I'd also like to update the user on receiving <presence> stanza. I'm guessing I should use a callback, like I am doing now to handle receiving of messages.

A: I realized that the node can be parsed as any xml.
This is what solved my problem:
query_node=iq_node.getQueryChildren()
for node in query_node:
    print node.getAttr("name")

iq_node is the xmpp.protocol.Iq object and every node is a xmpp.simplexml.Node object


text:
Q: How should I interpret "[Something] isn't for me"?
I'm afraid German beer isn't for me.

Does it mean that "This beer isn't suitable for me" or "This isn't given to me"? How should I understand "for" in this context?

A: Great example of why context is important. Let me add one word to the sentence you have provided:

I'm afraid this German beer isn't for me.

That could mean either of the things you mention in your question. If a waitress was putting a stein down in front of a customer who looked confused, I'd assume the sentence meant:

I didn't order this German beer.

or:

I don't know who ordered this German beer, but it wasn't me.

However, if the man had been sipping from the stein for awhile, and his friend asked, "What do you think of that German beer?" then I'd assume the sentence meant:

This German beer isn't quite to my liking.

or:

I don't think I'll be ordering another one of these any time soon.

In the former scenario, for is being used in accordance with definition 1a in Macmillan, whereas in the latter scenario, for is being used in accordance with Macmillan's definitions #7 & #19:

for (prep.)
  1a used for saying who or what is intended to receive something
  7 used for saying what you prefer
  19 used for saying which person a particular thing would be appropriate for

Sometimes, when a word has well over a dozen meanings, there is no way to tell which meaning is being applied simply by analyzing a single sentence. This is particularly true for prepositions, which can be very tricky.
Back to your original question, though:

I'm afraid German beer isn't for me.

Because that sentence isn't talking about a specific German beer, it's more evident that the person is talking about their liking for German beer in general.

A: Deriving the context from just the sentence, it would be something like:

I don't like German beer.

Saying something "isn't for me" is a polite way of stating that you don't like something. There could be many reasons for disliking it, but normally this phrase is used in the context of personal taste or preference.
Edit:
The "I'm afraid" phrase is also a way to make a statement sound more polite. It's close to "I'm sorry," but can be used when someone doesn't really need to apologize.


text:
Q: Filtering and parsing text over Solar Region Summary files I was trying to filter some .txt files that are named after a date in YYYYMMDD format and contain some data about active regions in the Sun. I made a code that, given a date in YYYYMMDD format, can list the files that are within a time range which I expect the active region I am looking for to be and parse the information based on that entry. An example of these txts can be seen below and more information about it (if you feel curious) can be seen on SWPC website.
:Product: 0509SRS.txt
:Issued: 2012 May 09 0030 UTC
# Prepared jointly by the U.S. Dept. of Commerce, NOAA,
# Space Weather Prediction Center and the U.S. Air Force.
#
Joint USAF/NOAA Solar Region Summary
SRS Number 130 Issued at 0030Z on 09 May 2012
Report compiled from data received at SWO on 08 May
I.  Regions with Sunspots.  Locations Valid at 08/2400Z
Nmbr Location  Lo  Area  Z   LL   NN Mag Type
1470 S19W68   284  0030 Cro  02   02 Beta
1471 S22W60   277  0120 Cso  05   03 Beta
1474 N14W13   229  0010 Axx  00   01 Alpha
1476 N11E35   181  0940 Fkc  17   33 Beta-Gamma-Delta
1477 S22E73   144  0060 Hsx  03   01 Alpha
IA. H-alpha Plages without Spots.  Locations Valid at 08/2400Z May
Nmbr  Location  Lo
1472  S28W80   297
1475  N05W05   222
II. Regions Due to Return 09 May to 11 May
Nmbr Lat    Lo
1460 N16    126
1459 S16    110

The code I am using to parse over these txt files is:
import glob

def seeker(noaa_number, t_start, path = None):
    '''
    This function will open an SRS file
    and look for each line if the given AR
    (specified by its NOAA number) is there.
    If so, this function should grab the
    entries and return them.
    '''

    #defaulting path if none is given
    if path is None:
        #assigning
        path = 'defaultpath'

    #listing the items within the directory
    files = sorted(glob.glob(path+'*.txt'))

    #finding the index in the list of
    #the starting time
    index = files.index(path+str(t_start)+'SRS.txt')

    #looping over each file
    for file in files[index: index+20]:

        #opening file
        f = open(file, 'r')

        #reading the lines
        text = f.readlines()

        #looping over each line in the text
        for line in text:

            #checking if the noaa number is mentioned
            #in the given line
            if noaa_number in line:

                #test print
                print('Original line: ', line)

                #slicing the text to get the column values
                nbr = line[:4]
                Location = line[5:11]
                Lo = line[14:18]
                Area = line[19:23]
                Z = line[24:28]
                LL = line[29:31]
                NN = line[34:36]
                MagType = line[37:]

                #test prints
                print('nbr: ', nbr)
                print('location: ', Location)
                print('Lo: ', Lo)
                print('Area: ', Area)
                print('Z: ', Z)
                print('LL: ', LL)
                print('NN: ', NN)
                print('MagType: ', MagType)

     return

I tested this and it is working but I fell a bit dumb for two reasons:

*

*Despite these files being made following a standard, one extra space is all it takes to crash the code considering the way I am slicing the arrays by index. Is there a better option to that?

*The information on tables IA and II are not relevant for me so, ideally, I would like to prevent my code to scan them. Since the number of lines on the first column varies, is it possible to tell the code when to stop reading a giving document?
Thanks for your time!

A: Robustness:
Instead of slicing by absolute position you could split the lines up into a list using the .split() method. This will be robust against extra spaces.
So instead of
Location = line[5:11]
Lo = line[14:18]
Area = line[19:23]
Z = line[24:28]
LL = line[29:31]
NN = line[34:36]

You could use
Location = line.split()[1]
Lo = line.split()[2]
Area = line.split()[3]
Z = line.split()[4]
LL = line.split()[5]
NN = line.split()[6]

If you wanted it to be faster you could split the list once and then just pull the relevant data from the same list rather than splitting it every time:
data = line.split()
Location = data[1]
Lo = data[2]
Area = data[3]
Z = data[4]
LL = data[5]
NN = data[6]

Stopping:
To stop it from continuing reading the file after it's passed the relevant data you could just have something that exits the loop once it no longer finds the noaa_number in the line
# In the file function but before looping through the lines.

started_reading = False ## Set this to false so
                        ## that it doesn't exit
                        ## before it gets to the
                        ## relevant data

for line in text:
    if noaa_number in line:
        started_reading = True

        ## Parsing stuff

    elif started_reading is True:
        break # exits the loop


text:
Q: Need to this table with 100 rows and assign a valor to the code PHP I need to solve this simple thing:
Got this code:
<?php
$xml=simplexml_load_file("d2ladder.xml") or die("Error: Cannot create object");
?>

    <tr class="<?php if ($xml->ladder[12]->char[0]->status == "alive") { echo "alive"; } else { echo "dead"; } ?>">
      1.
      <?php echo $xml->ladder[12]->char[0]->prefix; ?> <?php echo $xml->ladder[12]->char[0]->name; ?>
      <?php echo $xml->ladder[12]->char[0]->class; ?>
      <?php echo $xml->ladder[12]->char[0]->level; ?>
      <?php echo $xml->ladder[12]->char[0]->experience; ?>

        <tr class="<?php if ($xml->ladder[12]->char[1]->status == "alive") { echo "alive"; } else { echo "dead"; } ?>">
      2.
      <?php echo $xml->ladder[12]->char[1]->prefix; ?> <?php echo $xml->ladder[12]->char[1]->name; ?>
      <?php echo $xml->ladder[12]->char[1]->class; ?>
      <?php echo $xml->ladder[12]->char[1]->level; ?>
      <?php echo $xml->ladder[12]->char[1]->experience; ?>

Need to create rows on this table till char[99]
Maybe I need to use while? Because sometimes it wont get to 99 on the sitemap

A: Use for/while cycle:
for ($i = 0; $i < 100; $i++) {
    ?>
  <tr class="<?php if ($xml->ladder[12]->char[$i]->status == "alive") { echo "alive"; } else { echo "dead"; } ?>">
  <?php echo $i; ?>.
  <?php echo $xml->ladder[12]->char[$i]->prefix; ?> <?php echo $xml->ladder[12]->char[$i]->name; ?>
  <?php echo $xml->ladder[12]->char[$i]->class; ?>
  <?php echo $xml->ladder[12]->char[$i]->level; ?>
  <?php echo $xml->ladder[12]->char[$i]->experience; ?>

<?php }

See for cycle
Hope this helps.


text:
Q: Trazer dados como o mural do facebook estou implementando uma funcionalidade de trazer dados como o mural de post's do facebook, aparentemente não é nada muito difícil, porém, tenho uma dúvida e gostaria de saber se alguém tem uma solução ou sugestão para esse meu problema.
O código
$(document).scroll(function(){
  if ($(window).scrollTop() + $(window).height() == $(document).height()) {
    pesquisar("","");
  }
});

No código acima, eu possuo uma função que faz uma execução ajax para retornar determinados dados, porém, eu gostaria de atualizar a página com novos dados e não repetindo eles que é o que acontece comigo no momento. Eu testei a função find('div').remove() para ter uma suposta "atualização" de dados, porém, isso é horrível, o usuário perde a referência de onde o scroll está e acaba voltando pro início. Alguém teria uma sugestão melhor para adicionar a informação sem repetir o conteúdo já adicionado?

A: Tente utilizar a função AppendTo('#elemento') ou isertAfter("#elemento"), ambas vão manter o conteúdo atual e adicionar o novo conteudo ao final do elemento passado como parâmetro.
Ficaria assim:
//insere os dados dentro do container, no final.
$(dadosVindosDoAjax).appendTo("#containerDePosts");

ou:
//este insere os dados depois da ultima postagem
$(dadosVindosDoAjax).insertAfter($("#containerDePosts").find("#postagens").last());


text:
Q: how to launch bash in my newly made kernel? I want to launch bash inside my kernel.
I have tried using system() but... I found out it's only really for little things. And not for kernel developing. And im stuck here at the moment...
void kernel_entry()
{
  init_vga(GREEN, BLACK);
  print_string("$ ");
  test_input();

where it says print_string I will replace it with the code to bring up bash. But I need help with that part...

A: To elaborate on @Adam Zahran's answer:
In order to run a process from the kernel, you need to create a new process and then execve("/bin/bash").
A reference would be:
start_kernel() -> arch_call_rest_init() -> rest_init() -> kernel_init() -> try_to_run_init_process() -> run_init_process()
all of which you can find here.
Specifically bash, at least on Linux, is compiled as a dynamically-linked ELF binary (as is /sbin/init...)
So your kernel needs to be able to support the ELF binary format and dynamic loading.
Needless to say, it also needs to support all the system calls that bash makes, you can run bash under strace(1) to see what system calls are used.


text:
Q: Determine Bitrate for WebM Video Files I am trying to debug some WebM videos and need to determine their bitrate. An application like FFmpeg can get this data but I have not been able to successfully install it on my system. Tools like Quicktime Player have "inspector" functionalities but, e.g., QT Player can't open WebM files.
Appreciate any suggestions people may have.

A: mediainfo is your friend: http://mediaarea.net/en/MediaInfo/Download
free and has GUI and CLI support.
hope this helps


text:
Q: Why oldversion of Django being used? I have  created  a virtual environment with no-site-packages, activated the environment and installed django 1.4.3. But, when I do 'django-admin.py --version' it shows 1.3.  I am on Windows XP with Python 2.7. All my other projects use Django 1.3 and are not using virtual environment.
thanks


text:
Q: Metro App Certification hangs on performance test because of byte code generation I try to build a metro-style-app with Javascript and when I run the Windows App Cert Kit (WACK) Certification tool the test always fails on the performance test with the following message:

Following errors were detected when tested the byte code generation:
  This package was made available for the development or Authoringmodus. Uninstall the package and reinstall it in the normal way.

I'm using jquery and some jquery-mobile libraries inside my app. Is that the problem? The error doesn't make sense for me, because it doesn't say which package I should reinstall. I also try to uninstall the App itself (by right click onto the app) and build it again in the Release-Modus of VS2012, but the WACK tool always prompts this error :(

A: Find out that the WACK Tool allways shows this error if you don't run Store -> Create App Package and select "No" and press the next button. After that the WACK-Tool is started automatically and it passes the bytecode generation.

A: First save the all javascript files with encoding utf 8 format with signature
then create the app package
     http://msdn.microsoft.com/en-us/library/windows/apps/hh975357.aspx
then if u already install the latest windows app certification kit then u will be able to see run with windows app certification kit button after creating app package .


text:
Q: What's the most elegant way to swap out events when setting a property? Doing component-based development, I find myself doing this fairly often:
public class SomeClass
{
    SomeOtherClass foo;

    public SomeOtherClass Foo
    {
        get { return foo; }
        set {
            if (value != foo) {
                if (value != null) {
                    // subscribe to some events
                    value.SomeEvent += foo_SomeEvent;
                }

                if (foo != null) {
                    // unsubscribe from subscribed events
                    foo.SomeEvent -= foo_SomeEvent;
                }

                foo = value;
            }
        }
    }

    void foo_SomeEvent(object sender, EventArgs e)
    {
        // do stuff
    }
}

Is there any more elegant way to do this event "swapout"?
(Of course, the whole issue could be avoided if foo was immutable, but then I wouldn't get any visual designer support.)

A: I do think your current implementation is perfectly acceptable.  It is very clear and easy to follow.

If you want to shorten the code, since you're doing this a lot, you could make a method that does it:
private void SwapEventHandler<T>(T a, T b, Action<T> subscribe, Action<T> unsubscribe)
    where T : class
{
    if (a != null)
        subscribe(a);
    if (b != null)
        unsubscribe(b);
}

You could then write:
if (value != foo)
{
    SwapEventHandler(value,foo, (o) => o.SomeEvent += foo_SomeEvent, (o) => o.SomeEvent -= foo_SomeEvent );
    foo = value;
}

A: What you are doing is fine, but I would generally prefer the convention of unsubscribing old event handlers before subscribing the new ones, just to avoid any potential "overlap" where both objects could try to handle the same event if it fired from another thread in between the calls.
For a marginal improvement, you could dispense with unnecessary braces to make the code more compact and "tidier" (where "tidier" is in the eye of the beholder).

set
{
    if (value != foo)
    {
        if (foo != null)
            foo.SomeEvent -= foo_SomeEvent;
        if (value != null)
            value.SomeEvent += foo_SomeEvent;

        foo = value;
    }
}

If you make it illegal to use null references (e.g. by using a reference to a "Null Foo Object" instead of a null) then you could dispense with the ifs entirely:

set
{
    if (value != foo)
    {
        foo.SomeEvent -= foo_SomeEvent;
        value.SomeEvent += foo_SomeEvent;
        foo = value;
    }
}

In some cases where you have many properties working with similar objects/events you could possibly also implement the swap code in a (generic) helper method so that you have the implementation in one place and your properties all just call a shared helper method. This would only be of benefit if you could share one implementation for many properties though:

set
{
    Helpers.SetValueAndResubscribeFooSomeEvent(ref foo, value);
}

A: If you dont know which events has been registered on the event, and want to clear it completly, you can do the following:
public class SomeOtherClass
{
    public event EventHandler SomeEvent;

    public void ClearSomeEvent()
    {
        foreach (EventHandler e in SomeEvent.GetInvocationList())
        {
            SomeEvent -= e;
        }
    }
}

And in SomeClass.Foo property setter:
if (foo != null)
{
    // unsubscribe from subscribed events
    foo.ClearSomeEvent();
}

If you do know the subcribed delegate, youre current solution is fine.


text:
Q: Dynamically pass domain name into an a href link in Spring Jpa I am trying to create a dynamic link in an email which am sending out using Spring Jpa. I created a variable in my application.properties file so that whenever I am pushing to server I can easily change that variable from localhost to the domain name for live deployment. However, when I try to pass the domain name value, the link becomes inactive. I would appreciate if you could point me in the right direction.
Here is the application.properties snippet below:
server.port=8008

spring.jpa.database=POSTGRESQL
spring.datasource.platform=postgres

spring.datasource.url=jdbc:postgresql://41.207.248.189:xxxx/xxx
spring.datasource.username=****
spring.datasource.password=****

##GMAIL PROPERTIES
senderEmail = xxxxx
spring.mail.host=xxxx
spring.mail.port=xxx
spring.mail.username=xxxxxx
spring.mail.password=xxxxxxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.ssl.trust=xxxxxxx

domain-name=localhost:4200

spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

Here is the snippet for the a href I need to pass the domain-name into:
 "\n" +

 "Click Here"+

"\n" +

This approach above is not working but when I pass the link manually, the "click here" link works:
  "Click Here"+

I would appreciate your help. Thanks
UPDATE
Below is the html for the email body where I am setting the domain-name

            try {
                emailService.sendEmail("PAYMENT NOTIFICATION",

                        "
Dear sir/ma,
\n" +
                                "\n" +
                                "\n" +
                                "
LETTER OF NOTICE
\n" +
                                "\n" +
                                "\n" +
                                "
This is to notify you of the status of your organisation .....
\n" +
                                "
You are hereby put on notice to remit the outstanding amount on or before ....
\n" +
                                "
Kindly follow the link below to make....\n
\n" +
                                "\n" +
                                "Click Here"+
                                "\n" +
                                "\n" +
                                "
Thank you.
 \n" +
                                "\n"
                        , org.getEmail());
            } catch (
                    MessagingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                System.out.println("Email Service error");
                e.printStackTrace();
            }
        }

I hope this helps... I look forward to getting a solution. Thanks.

A: Based on the comments/discussion here's what you need to do:

*

*Read/Inject the property to a String variable using @Value
@Value("${domain-name}") String domainName;

*Use the variable to construct your href

Full code:
application.properties
domain-name=www.abc.com
DomainNameApp:
package domainname;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;

@SpringBootApplication
public class DomainNameApp {
    public static void main(String[] args) {
        SpringApplication.run(DomainNameApp.class, args);
    }
}

@RestController
class Ctrl {

    @Value("${domain-name}")
    String domainName; // or use constructor injection

    @GetMapping("a")
    void a() {
        String hashlink = "jsdklfsdklflsdf";
        String html = "
" +
                "Click Here" +
                "
";
        System.out.println(html);
    }

}

A: Based on answers by @gtiwari333...  I made some corrections to my code. I decided to detail the changes I made for future readers.
First of all, I added http:// to the parameter in my application.properties, as below:
domain-name=http://localhost:4200

next, I added @Value annotation to the top of my class as below:
@Value("${domain-name}")
    String domainName;

Then I was able to pass it into the a href link with ease as below:
"
Kindly follow the link below to make....\n
\n" +
                                "\n" +
                                "Click Here" +
                                "\n" +
                                "\n" +
                                "
Thank you.
 \n" +
                                "\n"

Thanks. I give credit to @gtiwari333 for helping me with this.


text:
Q: Bazel build error in tensorflow I am using TensorFlow Android Camera Demo. I follow step given in README file.I do following things:
Import andorid project
Install bazel using chocolaty
Edit SDK and NDK path in workspace file.

While I run bazel build command :
   bazel build -c opt //tensorflow/examples/android:tensorflow_demo
I getting error that Couldn't find java at '$(ls -d C:/Program\ Files/Java/jdk* | sort | tail -n 1)/bin/java.exe'.
My JDK is installed at C:\Program Files (x86)\Java\jdk1.8.0_66\bin . I also set environment variable
JAVA_HOME="$(ls -d C:/Program\ Files/Java/jdk* | sort | tail -n 1)" and
BAZEL_SH=c:/tools/msys64/usr/bin/bash.exe


text:
Q: database query help wanted Is it possible to limit the results a mysql select query returns with a condition?
For example I have a reviews table:

review_id, member_id, text, date

And I'd like to get the latest 10 reviews but member_id = 123 should only be taken once
Can this be achieved with a single query?

A: My interpretation of the problem:

*

*the 10 most recent reviews

*including at most 1 review with member_id = 123

I'm going to solve this by:

*

*starting with the full reviews result set

*removing all reviews that have member_id = 123 except for the most recent one

*from the modified result set, take the 10 most recent

Here's the query:
create view newest123 as ( -- this gets the newest review for member_id 123
  select *
   from reviews
   where member_id = 123
   order by date desc limit 1
)

select *
from (
  select * from newest123
  union
  select *                    -- all the reviews that aren't for member_id 123
    from reviews
    where member_id != 123) filtered
order by date desc limit 10   -- sort 'em and take the top 10


text:
Q: How to do index/ match excel equivalent in R So I have a large data set that I want to process in R. The equivalent excel function is below. I'm trying get the same result using the expss package match_row / index_row functions. Any help with this would be greatly appreciated. Basically I want the output value in df1 column D to be the value in column C in df2 where value A and value B in df1 match the value A and value B in the df2.
in excel I have this function:
=INDEX(df1!C:C, MATCH(1,INDEX((A2=df1!A:A)*(B2=df1!B:B),0,1),0))
see screenshot of my excel example below
which achieves what I want. however my dataset is to big for excel to handle and I want an executable script since the dataset will be updated periodically.
df1   (A)     (B)     (C)
#    Organism Drug    MIC
#          A  P       15
#          A  AM      11
#          B  P       9
#          B  AM      13
#          C  P       12
#          C  AM      10

df2   (A)     (B)     (C)     (d)- calculated values
#    Organism Drug    Zone    MIC
#          C  P       13      [MIC for row C, P in df1 = 12]
#          A  P       11      [MIC for row A, P in df1 = 15]
#          C  AM      10
#          A  AM      15
#          B  P       16
#          C  AM      12

Excel df1
Excel df2

A: This is a duplicate, but for your data:
merge(df1, df2, by = c("Organism", "Drug"), all = TRUE)
#   Organism Drug MIC Zone
# 1        A   AM  11   15
# 2        A    P  15   11
# 3        B   AM  13   NA
# 4        B    P   9   16
# 5        C   AM  10   10
# 6        C   AM  10   12
# 7        C    P  12   13

Data, in a reproducible format:
df1 <- structure(list(Organism = c("A", "A", "B", "B", "C", "C"), Drug = c("P", "AM", "P", "AM", "P", "AM"), MIC = c(15L, 11L, 9L, 13L, 12L, 10L)), class = "data.frame", row.names = c(NA, -6L))
df2 <- structure(list(Organism = c("C", "A", "C", "A", "B", "C"), Drug = c("P", "P", "AM", "AM", "P", "AM"), Zone = c(13L, 11L, 10L, 15L, 16L, 12L)), class = "data.frame", row.names = c(NA, -6L))


text:
Q: Spark Structed Streaming read nested json from kafka and flatten it A json type data :
{
    "id": "34cx34fs987",
    "time_series": [
        {
            "time": "2020090300: 00: 00",
            "value": 342342.12
        },
        {
            "time": "2020090300: 00: 05",
            "value": 342421.88
        },
        {
            "time": "2020090300: 00: 10",
            "value": 351232.92
        }
    ]
}

I got the json from kafka:
spark = SparkSession.builder.master('local').appName('test').getOrCreate()
df = spark.readStream.format("kafka")...

How can I manipulate df to get a DataFrame as shown below:
     id             time          value
34cx34fs987  20200903 00:00:00  342342.12
34cx34fs987  20200903 00:00:05  342421.88
34cx34fs987  20200903 00:00:10  351232.92

A: Sample code in pyspark
df2 = df.select("id", f.explode("time_series").alias("col"))
df2.select("id", "col.time", "col.value").show()

A: Using Scala:
If you define your schema as
val schema: StructType = new StructType()
    .add("id", StringType)
    .add("time_series", ArrayType(new StructType()
      .add("time", StringType)
      .add("value", DoubleType)
    ))

you can then make use of Spark SQL built-in functions from_json and explode

  import org.apache.spark.sql.functions._
  import spark.implicits._

  val df1 = df
    .selectExpr("CAST(value as STRING) as json")
    .select(from_json('json, schema).as("data"))
    .select(col("data.id").as("id"), explode(col("data.time_series")).as("time_series"))
    .select(col("id"), col("time_series.time").as("time"), col("time_series.value").as("value"))

Your output will be then
+-----------+-----------------+---------+
|id         |time             |value    |
+-----------+-----------------+---------+
|34cx34fs987|20200903 00:00:00|342342.12|
|34cx34fs987|20200903 00:00:05|342421.88|
|34cx34fs987|20200903 00:00:10|351232.92|
+-----------+-----------------+---------+