text:
Q: Mouse pointer jumps with external HDD I have a new (3 weeks old) WD My passport HDD 1 TB, and I use Windows 7. I run the HDD through a USB 2.0 port, since my computer doesn't have USB 3.0 ports. My mouse is connected via a USB port as well. It happens occasionally that when I try to access folders on the HDD, the mouse pointer lags and jumps in the direction I moved it to, specially if the folder have many files and folders, and when these folders change there shape according to there contents, also it sometimes happen when I check the size of a large folder.
When it happens it does when I move the pointer over an open window of this drive.
I doubted the antivirus software I have (AVG) so I disabled it but still happens, maybe reduced not really sure but it happens.
Taking in consideration that the drive have shown no sign of other issues. All the WD utility tests, and data life guard tests I ran came out "Passed". The smart report is OK. But when this condition happened I began to suspect the drive. Do I have a bad drive here??

A: ok, I add this here as answer, because I need some space (convert it to a comment if needed).
I need to know what happens on your system, so I want to run a xperf trace. Install the Windows Performance Toolkit, copy the following text into a .cmd file:
@echo off

xperf -on Latency+PROC_THREAD+LOADER+CSWITCH+FILENAME+FILE_IO+FILE_IO_INIT+DISK_IO+DRIVERS -f kernel.etl -stackwalk Profile+CSwitch+DiskReadInit+DiskWriteInit+DiskFlushInit+FileCreate+FileCleanup+FileClose+FileRead+FileWrite -BufferSize 1024 -MaxBuffers 1024 -MaxFile 1024 -FileMode Circular

echo Reproduce the problem now, hit any key to finish, collect Merged Etl file

pause

echo merging etl...

xperf -d xperfSlowIOHighCPUcir.etl

@echo on

Now open a cmd prompt with admin rights ad run the command. Now minimize the cmd Window and when you have the issue again, switch to to the CMD, wait 30s and press a key to stop logging. Compress the xperfSlowIOHighCPUcir.etl as 7z and upload it (SkDrive, Dropbox) and post a link to it.
With this file I can see what your system does when you have the issue.


text:
Q: Discord Py 'NoneType' object has no attribute 'voice_channel' I get this error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'voice_channel'

By using this code:
from discord.ext import commands
import discord

class Voice(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command(name='join')
    async def join(self, ctx):
        channel = ctx.message.author.voice.voice_channel
        print(str(channel))

def setup(client):
    client.add_cog(Voice(client))

Can't find why it doesn't work :/
I watched a yt video with exactly the same code, but there it worked ...

A: because the author can use this command although he is not in a voice channel and then he doesn't have a voice object.
you can use try and except or if to check if the voice object is empty.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How Do I loop through multiple stock data and after processing it, display it in one single .csv file at the end in Python? My data is from Yahoo Fin from numpy import array
import talib
import yfinance as yf
from tabulate import tabulate
import pandas as pd

stock_list=['ICICIBANK.NS','COALINDIA.NS','RELIANCE.NS']

appended_data={}

for stock in stock_list:

 data= yf.download(stock,period='1y', interval='1d')

 morning_star = talib.CDLMORNINGSTAR(data['Open'], data['High'], data['Low'], data['Close'])
 two_crows = talib.CDL2CROWS(data['Open'], data['High'], data['Low'], data['Close'])
 three_crows = talib.CDL3BLACKCROWS(data['Open'], data['High'], data['Low'], data['Close'])

 data['Stock Name']= stock
 data['Morning Star'] = morning_star
 data['Two Crows'] = two_crows
 data['Three Black Crows']= three_crows

 dict = {'Stock Name': data['Stock Name'],
    'Open' : data['Open'],
    'High' : data['High'],
    'Low': data['Low'],
    'Close':data['Close'],
    'Morning Star': data['Morning Star'],
    'Two Crows':data['Two Crows'],
    'Three Black Crows':data['Three Black Crows']
}

 appended_data.update(dict)
df= pd.DataFrame(appended_data)
df_latest= df.tail(5)
df_latest.to_csv('Candlestick Screener Data.csv')

Hello,
I'm super new to programming in general in Python and I'm having real trouble figuring out one thing.
When I run the above code that I've written I end up with data only for the last iteration from stock_list= ['ICICIBANK.NS','COALINDIA.NS','RELIANCE.NS'] in my CSV file. Whereas data from the first two loop iterations are missing.
The overall idea is to pull multiple datasets, process the collected data and finally store all that data in one single CSV file for me to look at.
I have a basic idea of what's missing but I'm not able to put it into code and make it work.
I'd really appreciate it if someone could look into it and help me out along with some explanantion (if possible).
Thank you

A: So the reason your data only contains the last item is because, in each loop iteration, it gets overwritten with the stuff from that iteration.
Calling update on your append_data dict doesn't work, because the "new" dict has the same field names as the old, so it'll just overwrite them!
Now given that eventually you want to write it all to a csv, you'll want to collect the data in a pandas DataFrame. If I remember correctly, a dataframe can be built from a list of dictionaries as the data.
So here's what you can do: Before the for loop, create an empty list like so
dict_list = []

and then inside the loop, instead of your update call, you say
dict_list.append(dict)

And then you should be able to do
df = pd.DataFrame(dict_list)


text:
Q: open a secure socket on the server side I have a server application that opens a socket and then listens to any connections being made on that socket.
public Server(){
    try {
        ServerSocket sSocket = new ServerSocket(nPort);
        System.out.println("Server started at: " + new Date());
        System.out.println("===============================================\n");

        //Loop that runs server functions
        while(true) {
            //Wait for a client to connect
            Socket socket = sSocket.accept();
            socket.setSoTimeout(30000);
            //Create a new custom thread to handle the connection
            ClientThread cT = new ClientThread(socket, nPort);
            //Start the thread!
            new Thread(cT).start();
        }
    }
    catch(IOException ex) {ex.printStackTrace();}
}

Whenever new connection attempted, a new thread is started using the ClientThread class. The ClientThread class has a run method that does all the things need to be done (read input, send respons etc.)
public class ClientThread implements Runnable{
private Socket threadSocket;
private int nPort = 0, maxCon = 2;

//This constructor will be passed the socket
public ClientThread_v3(Socket socket, int port){
    threadSocket = socket;
    nPort = port;
}

public void run(){
    System.out.println("New connection at " + new Date() + "\n");
    try {
        DataInputStream in = new DataInputStream (threadSocket.getInputStream());
        out = new DataOutputStream (threadSocket.getOutputStream());
        while (running){
            // do some stuff ....

            // go to sleep
            Thread.sleep(1000);
        }
    }
    catch (IOException ex) {ex.printStackTrace();}
    catch (InterruptedException ex) {ex.printStackTrace();}
    finally {
        try {
            threadSocket.close();
            System.out.println("Connection closed.\n");
        } catch (IOException ex) {ex.printStackTrace();}
    }
}}

My question is how do i make the socket connection secure? how do i open a secure connection?
I don't want to use any HTTP packages for that matter, want to keep it as a socket connection.
Any help would be appreciated. Thank you.


text:
Q: Convert Mat to PvBuffer (from Pleora eBUS SDK lib.) thank you in advance for reading this.
For better readability I'll list pieces of info. necessary in point form.

*

*building an app based on eBUS player sample provided by Pleora.

*Grabbing images in 16 bit gray in 50 fps.

*my app is processing image data using openCV within the OnBufferDisplay function in DisplayThread

*so far, I have successfully processed images suiting my needs and am trying to convert my Mat(processed already) data back to PvImage or PvBuffer s.t. the image can be displayed in the eBUS Player using the already existing display function(this way I can still use other features in the Player app without having to make too many modifications to the original app).

*The difficulty arises from the fact that display functions and other important functions are hidden in dlls. I can only make modifications to what's exposed.

*The processing procedure is basically:

void Display Thread::OnBufferDisplay(PvBuffer *aBuffer){
   aBuffer->Attach(imageMat.data, 614400);
   //where imageMat is init'd as
   //imageMat = cv::Mat(cv::Size(imgWidth, imgHeight), CV_16U);

   //process.. the data....

   //at this point, I Have my Mat object ready to go.

   //supposed to create or have another PvImage or PvBuffer with the processed datahere for displaying.

   //Display
   mDisplay->Display(*aBuffer);
}

*

*What I have tried so far is:

memcpy(aBuffer->GetDataPointer(), imageMat.data 614400);

//and

aBuffer->free();
//and/or
aBuffer->Detach();
//then
aBuffer->Alloc(614400); //since 640 * 480 in 16 bit gray
memcpy( Mat.data to buffer->datapointer);

Please help me clarify the following:

*

*I have discovered after using Attach(), the passed aBuffer does no longer properly display image. Does that mean this function not just copies the data from aBuffer to imageMat.data but erases the data in aBuffer and then copies it to imageMat.data?

*I went for Attach() because memcpy(imageMat.data, aBuffer->GetDataPinter(), size); didn't work. It didn't copy the data properly like the way Attach() does. Anybody know why?

*The description for Attach() provided by Pleora is "Attach this PvBuffer to an external memory buffer. To use an internal memory buffer, use Alloc.".
In summary,
How do you properly create a PvImage or a PvBuffer object that contains the data from my Mat object in order to pass to the Display() function?
Are there any detours to make this work without having to create such objects?


text:
Q: .NET 2.0/3.5 application could not connect to a web service on Ubuntu 12.04 that forces connection to TLS 1.1 I have a client application written and compiled in C# 2.0 successfully referenced and call to my web service on local development server, using Ubuntu 12.04 (Precise Pangolin) and Mono but never do update. Calling to a URL like
https://192.168.1.22/service.asmx

Then I upload this web service to the production server on Amazon EC2 with the same configuration, but updated Ubuntu 12.04. In the client application only change the URL to https://myserver.com/service.asmx.
But my client application failed to connect. The debug message was shown as:

Received an unexpected EOF or 0 bytes from the transport stream.

I could open the web service description page on web browser so that mean the web service is working fine.
I took an hour trying to fix this, but no luck. Finally I found the deference between two servers.
In browser, the SSL connection of local server is using TLS 1.0 while the SSL connection of the EC2 server is using TLS 1.1. I googled and found .NET Framework 2.0 only supports TLS 1.0 and that.
I could not find how to disable TLS 1.1 in Apache 2.
I don't know if this is a bug in OpenSSL on Ubuntu 12.04 or Mono or .NET. I am still trying to find a solution.


text:
Q: Getting error while comparing resultset object's data in JSP I tried a code in JSP in which I have 2 databases n I have to get a value from database 1 n compare with the value from the another database. All the data got works well. Even it printing on page. But not comparing with it.
This is the code which I tried.
<%@ page import="java.sql.*" %>

<%!
String userName;
int marks;
int i=3;
String obj1,obj2;
int whileCount=0;
%>

<%
    userName=request.getParameter("u_n");
    try
    {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con1=DriverManager.getConnection("jdbc:odbc:login_dsn");
    Connection con2=DriverManager.getConnection("jdbc:odbc:model_ans");

    Statement st1=con1.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    String query="select * from login where id="+userName;
    ResultSet res1=st1.executeQuery(query);

    Statement st2=con2.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet res2=st2.executeQuery("select * from model_ans");

    res1.first();
    res2.first();

    i=3;
    marks=0;

    do
    {
    obj1=res1.getString(i);
    obj2=res2.getString(2);
    whileCount++;

    out.println(obj1+"  "+obj2+"       " );

    if(obj1.equals(obj2)==false)
        marks++;

    i=i+1;
    }while(res2.next());

    out.println("total while count:"+whileCount);
    whileCount=0;

    out.println("Total marks:"+marks);

    con1.close();
    con2.close();

    }

    catch(Exception e)
    {
     out.println(e.toString());
    }
%>

The data base query is like :
1.First DB:
create table login(id number,password text,q1 text,q2 text,[upto 30],q3 text);

2.Second DB:
create table model_ans(id number,Ans text);


text:
Q: User table with users following other users in Amplify I'm new to GraphQL and Amplify, and I basically want to accomplish this from the cli:
type User @model {
  id: ID!
  follows: [User]
}

So a user can follow other users, and I want to be able to add users to follow to a user, get a list of the users a user follows, and also list all the users who follows a specific user. I would guess this quite basic setup shuold be possible quite easily from the cli as I have been able to setup other such relations (but between different types), however, this (maybe naive) schema does not give me the mutations and queries I would like when running amplify push api.
What is the best way to accomplish what I want?


text:
Q: How many file descriptors created/involved after running this program - pipe From the below program,
/*****************************************************************************
 MODULE: popen.c
 *****************************************************************************/
#include <stdio.h>

int main(void)
{
        FILE *pipein_fp, *pipeout_fp;
        char readbuf[80];

        /* Create one way pipe line with call to popen() */
        if (( pipein_fp = popen("ls", "r")) == NULL)
        {
                perror("popen");
                exit(1);
        }

        /* Create one way pipe line with call to popen() */
        if (( pipeout_fp = popen("sort", "w")) == NULL)
        {
                perror("popen");
                exit(1);
        }

        /* Processing loop */
        while(fgets(readbuf, 80, pipein_fp))
                fputs(readbuf, pipeout_fp);

        /* Close the pipes */
        pclose(pipein_fp);
        pclose(pipeout_fp);

        return(0);
}

popen.c is compiled to my_program
Here is my understanding of the file descriptors created/involved after executing my_program, popen() forks & execs the my_program process but child processes does not inherit the pipe file descriptors of my_program.
So, After exec,
1) write file descriptor is only created for ls
2) read file descriptor is only created for sort
3) read and write files descriptors are created in my_program, because ls writes to my_program & sort reads from my_program

As shown above, Are these the only file descriptors involved/created?
Note: 'in' & 'out' are just naming conventions used here

A: Child processes from a fork() have exactly the same set of open file descriptors as the parent process.
The popen() call uses pipe() to create two file descriptors; it then executes fork(). The parent process arranges that one end of the pipe is closed and the other converted to a file stream (FILE *). The child process closes the other end of the pipe and arranges for the one end to become standard input ("w") or standard output ("r") for the process it executes (using dup() or dup2() for the task).
You use popen() twice; you end up with 2 open descriptors in the parent, and transiently there's a third.

*

*When you say, 'the parent process arranges that one end of the pipe is closed', do you mean read file descriptor (stdin)?

Depending on the mode argument to popen(), one of the two ends of the pipe in the parent is closed immediately; the other is closed by pclose().  The file descriptor is 'never' the one for standard input or standard output — you have to go through extraordinary gyrations to make it so that is one of the standard I/O channels.

*Do all process thru popen() make sure they dup() to make sure they use stdout & stdin?

Each pipe has a read end and a write end. Take popen("ls", "r"); your program reads from the ls process. It (popen()) creates a pipe and forks. In the child, the write end of the pipe is connected to stdout (dup2() or perhaps dup()), and the read end of the pipe is closed, before the command is executed. In the parent, the read end of the pipe is 'converted to' or 'attached to' a stream (fdopen(), more or less) and the write end of the pipe is closed. In the parent process, the pipe is never connected to either stdout or stdin.
In the child process, either standard input or standard output is connected to the pipe, depending on the mode argument to popen().


text:
Q: How can I tell easily that functions have been inlined? Other than opening a disassembly view, is there any decent mechanism or tool to determine quickly whether LLVM actually inlined methods in a CPP file (i.e., outside the actually class declaration) designated with the 'inline' option?

A: You can use nm to list the symbols from your program. If the method doesn't show up in the output, it was an inline method:
nm your_program | grep your_method

I tried this solution with gcc. For llvm you can see this command: llvm-nm


text:
Q: VS2010 asking to upgrade SIlverlight? I'm running the absolute latest versions of Silverlight and Visual Studio 2010 Professional and built a solution that contained a WPF project.  From there, I added a SketchFlow project (based on Blend 4 RC) and I can run each project within the solution just fine by setting whenever I switch between them as startup projects.  From there, I added a Silverlight 4 Business Application (taking all the defaults), and when simply trying to set that as the startup project and running it, VS2010 is giving me the following error after trying to open a web page:
Line: 56 (in file TestPage.aspx)
Error: Unhandled Error in Silverlight Application
Code: 8001
Category: InitializeError
Message: Upgrade required
If I choose not to debug, I get the Silverlight page saying "This page requires a more recent version of Silverlight"!  Clicking "Install Now" on the popup window brings me to Mirosoft's Silverlight page where I see:
"The version of Silverlight originally requested is not available. You can get a supported version from this page. This Web browser or operating system may not be compatible with Silverlight. Please review the system requirements and, if you wish to proceed, choose the link for your operating system."
If I choose to upgrade anyway, I'm told that I'm running the latest version of Silverlight available.
What the heck?  I'm running the final versions of VS2010 Pro, Silverlight 4, and the latest version of Expression Blend 4 (RC).  Why can't VS2010 run this default Silverlight Business App?  Any ideas?  Please??
Thanks,
Lu10ntDn
PS. This is on Windows 7 with UAC turned off, and ALL latest Windows Updates installed.

A: Open TestPage.aspx and find the following block:
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
          <param name="source" value="ClientBin/TheNameOfYourApp.xap"/>
          <param name="onError" value="onSilverlightError" />
          <param name="background" value="white" />
          <param name="minRuntimeVersion" value="4.0.50401.0" />
          <param name="uiculture" value="<%= System.Threading.Thread.CurrentThread.CurrentUICulture %>" />
          <param name="culture" value="<%= System.Threading.Thread.CurrentThread.CurrentCulture %>" />
          <param name="autoUpgrade" value="true" />

        </object>

Do the values above match with what you have in your aspx page? if not then you need to make sure you are using the latest version of Silverlight. If that is the case, then you can change the values in your file to match the ones shown above.

A: Did you install the developer verison of Silverlight?  If not, that may be why Visual Studio can't run the application.
If you did install the developer version of Silverlight, then you may take a look at the minRuntimeVersion needed by the application.  See this MSDN reference regarding the Silverlight Plug-in versioning.


text:
Q: Typescript using object spread to satisfy a generic union type Given a union type with common fields type and fedBy. I want to write a function that takes in an Animal as the type and a second argument with the params unique to that animal. I can get the signature and inference working, but doing something wrong in how to return the result.
type FeedAnimalParams =
  | {
      type: 'Dog'
      fedBy: string
      bowl: true
    }
  | {
      type: 'Cat'
      fedBy: string
      fish: string
    }
  | {
      type: 'Bird'
      fedBy: string
      seed: string
    }

I'm inferring a literal type, pulling out the type property
type Animal = FeedAnimalParams['type']
//type Animal = "Dog" | "Cat" | "Bird"

I'm pulling the unique fields required for each animal using a generic.
type UniqueAnimalParams<T extends Animal> = Omit<Extract<FeedAnimalParams, { type: T }>, 'type' | 'fedBy'>

type FeedResult<T> = {
  message: string
  result: T
}

Here's the function I'm trying to write
function feed<T extends Animal>(
  byWhom: string,
  animalType: T,
  params: UniqueAnimalParams<T>,
): FeedResult<FeedAnimalParams> {
  return {
    message: `Fed by ${byWhom}`,
    result: { //compile error here
      type: animalType,
      fedBy: byWhom,
      ...params,
    },
  }
}

//other lib
function CantChangeSignature(input:FeedAnimalParams){
  console.log(input)
}

I get the intellisense when calling the function, so inference appears to be working but the function doesn't compile.

feed('Colin', 'Bird', {
  seed: 'Sunflower',
})

feed('Joe', 'Dog', {
  bowl: true,
})

Playground link
Edit:1
Trying to avoid changing the return type signature since I need to pass it into another function I can't change.
FeedResult<FeedAnimalParams>

//also tried this as the return type

FeedResult<Extract<FeedAnimalParams, {type:T}>>

Updated playground.

A: You need to relate to the return type to the generic otherwise TS can't make the return value to be specific to the passed animalType so it thinks it's all of them all at once.
function feed<T extends Animal>(
  byWhom: string,
  animalType: T,
  params: UniqueAnimalParams<T>,
): FeedResult<UniqueAnimalParams<T> & {type: T, fedBy: string}>   {
  return {
    message: `Fed by ${byWhom}`,
    result: {
      type: animalType,
      fedBy: byWhom,
      ...params,
    },
  }
}


text:
Q: grails intellij ide 'run application' fails to load any controllers any number of problems tonight.
I have a grails 3.3.8 app in intellij.  I have built some domain classes,  and in the ide I selected the domain classes and told it to generate the controllers, which it does.
if i right click the Application project in project browser (either to run debug) the app comes up but no controllers are loaded.  so i have to cease the session.
if i open gradle view and issue the bootRun command the app starts and the controllers get loaded!
however if i right click on the boot run action and select debug, if disappears off into the ether on a background thread and the IDE never fires and i dont get control of the debug session in the IDE.
This has got terribly frustrating and i've burn't alot of time tonight going round in circles
does anyone know why the right click on Application,  in project explorer, fails to load the controllers,  whilst bootRun does load them .
If i can fix that - then the debug from the project explorer should work.   Its very odd.
i had to try and recreate the project as this evening it got lost telling me my domain classes were no domain classes and when i tried to delete and controllers/services and rebuild them it kept telling me cmdb.$xxxServices gorm data services couldn't be found and refused to build hibernate datastore
you can find the project to look at enter link description here but it needs another project (ticketAdapter to run, and a library project softwoodUtils) i've used the json end points directly on my browser for the ticketAdapter (server) project and i know thats working - its not a grails app itself)

A: Looks like you are trying to launch a Run/Debug Configuration of a standard Java  Application with the public static void main method. For Grails 3 rather use Grails Run/Debug Configuration where specify the Grails module to load and grails command to run the app with:

A: You can also use gradle actions  like bootRun to run your app.id youdouble click a gradle actions from the gradle panel it will automatically  create and run a gradle run configuration. Then you can run or debug that configuration.


text:
Q: Proxy pass fails with Spring secuity i have written set of rules to redirect
http://server.com/application/c/<UserIdValue>

type of url's to
http://localserver.com/application/?userid=<UserIdValue>

i wrote the following rules in apache httpd.conf
<Location  /application>
  ProxyPassReverse http://server.com/application/
  RewriteEngine On

  RewriteCond %{REQUEST_URI} /c/ [NC]
  RewriteRule application/c/(.*)$ http://localserver.com/application/?userid=$1 [QSA,P]

With this i can access login page and other pages in my application, but when i try to login/logout in application , it break into 'localserver' location .
the problem is with spring security j_spring_security_check, j_spring_security_logout. i dont have any clue what to do for this.
Spring security is taking precedence over proxy pass!!!!!

A: There are two things you will have to change to get this to work:

*

*Change your ProxyPass / ProxyPassReverse lines to not end with a trailing /.

*Tell your Application Server to set the contextURL correctly (ProxyPassReverse won't change URIs on forms for you). If you are using Tomcat, you do this by editing conf/server.xml, finding the  tag that has the attribute protocol="HTTP/1.1" on it, and adding two new attributes: proxyHost="localserver.com" proxyPort="80" (you don't strictly need the proxyPort="80" if localserver.com and server.com are running on the same port).

The cause of problem 1 is that Spring Security doesn't normalise URIs, so if the proxy gives your application server a URI like http://server.com/application//j_spring_security_check, the Spring Security interceptor will match it against http://server.com/application/j_spring_security_check, note that it is different due to the extra slash, and refuse to intercept the request.


text:
Q: Plotly chart background click event Is there a way to attach a click event into the background of a Plotly.js chart?
The idea is to let the user click on the chart in order to select the coordinates of a new element. So, it's not just an standard event on the div wrapper, but a specific event that can track the relative coordinates of the selected location.
The plotly_click event specified in the documentation is only attached to the specific elements (dots, lines, etc) and I couldn't find any way to achieve what I am looking for.
We are migrating from Highcharts, which lets you define a callback for a click event on the chart as well as for a click on the points.
Is there anything like this in Plotly.js or any way to accomplish it?


text:
Q: How to detect the current account type in a Outlook Web Add-In We have an Office Web add-in that is targeting the Appointment Items in Outlook (the calendar). It failed validation because, it was not possible to use it with gmail:
Functionality
1120.3.3  Office Compatibililty
The add-in did not pass compatibility tests for Gmail.
I was thinking about if i  can we detect what the current account type is from the:
Office.context.mailbox.userProfile
However i am uncertain about what properties are available and if any can tell me if it is an Exahnge Account the user is running on
Please help?
br
Michael


text:
Q: Error inyección dependencias en servicio symfony 4. Too few arguments to function NewUser:: 0 passed in RegistrationController.php 2 expected Estoy intentando configurar la inyección de dependencias para un servicio "Newuser". Para en un futuro no depender de mysql lo que hecho es crear un servicio "mysqlService" que implementa una interfaz con el método "persist". Desde el controlador instancio el caso de uso "NewUser" que en su constructor inyectando la interfaz de "DatabaseServiceInterface" y otro servicio "UserPasswordEncoderInterface". No funciona correctamente ya que symfony se queja porque "NewUser no recibe nada como parámetro" (Cuando debería inyectarse automáticamente el servicio).
Los ficheros son los siguientes.
DataBaseServiceInterface:
    <?php

namespace App\Application\Infraestructure\DatabaseService;

Interface DatabaseServiceInterface
{
    public function persist(Object $ormObject):void;
}

MysqlService:
<?php

namespace App\Application\Infraestructure\DatabaseService;

use Doctrine\ORM\EntityManagerInterface;

class MysqlService implements DatabaseServiceInterface
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function persist(Object $ormObject):void{
        $this->entityManager->persist(ormObject);
        $this->entityManager->flush();
    }

}

Caso de uso NewUser:
<?php

namespace App\Application\AppUseCases\User\NewUser;

use App\Application\Infraestructure\DatabaseService\DatabaseServiceInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class NewUser {

    private $dabaseService;
    private $passwordEncoder;

    public function __construct(
        DatabaseServiceInterface $dabaseService,
        UserPasswordEncoderInterface $passwordEncoder
    ) {
        $this->dabaseService = $dabaseService;
        $this->passwordEncoder = $passwordEncoder;
    }

    public function execute(NewUserRequest $userRegisterRequest) {

        //Encode the plain password
        $userRegisterRequest->user->setPassword(
            $this->passwordEncoder->encodePassword(
                $userRegisterRequest->user,
                $userRegisterRequest->password
            )
        );

        $userRegisterRequest->user->setEmail($userRegisterRequest->email);
        $userRegisterRequest->user->setRoles(array_unique(['ROLE_USER']));

        //crear servicio para mysql
        $this->dabaseService->persist($userRegisterRequest->user);

    }

}

Services.yaml
# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones

    #App\Application\Infraestructure\DatabaseService\DatabaseServiceInterface:
     #   autowire: true

    App\Application\Infraestructure\DatabaseService\DatabaseServiceInterface: '@database_service'
    database_service:
        class: App\Application\Infraestructure\DatabaseService\MysqlService
        autowire: true
        public: true
    App\Application\Infraestructure\DatabaseService\MysqlService: '@mysql_service'
    mysql_service:
        class: App\Application\Infraestructure\DatabaseService\MysqlService
        arguments: ['@doctrine.orm.default_entity_manager']
        autowire: true
        public: true
    App\Application\AppUseCases\User\NewUser\NewUser: '@newuser_service'
    newuser_service:
        class: App\Application\AppUseCases\User\NewUser\NewUser
        arguments: ['@database_service','@security.user_password_encoder.generic']
        autowire: false
        public: true

RegistrationController:
<?php

namespace App\Controller;

use App\Application\AppUseCases\User\NewUser\NewUserRequest;
use App\Application\Domain\User\User;
use App\Application\Infraestructure\DatabaseService\MysqlService;
use App\Form\RegistrationFormType;
use App\Application\Infraestructure\User\UserAuthenticator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
use App\Application\AppUseCases\User\NewUser\NewUser;

class RegistrationController extends AbstractController
{
    /**
     * @Route("/register", name="app_register")
     */
    public function register(Request $request, UserPasswordEncoderInterface $passwordEncoder, GuardAuthenticatorHandler $guardHandler, UserAuthenticator $authenticator): Response
    {
        $user = new User();
        $form = $this->createForm(RegistrationFormType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $newUserRequest = new NewUserRequest($user, $form->get('email')->getData(), $form->get('plainPassword')->getData());
            $newUser = new NewUser();
            $newUser->execute($newUserRequest);

            return $guardHandler->authenticateUserAndHandleSuccess(
                $user,
                $request,
                $authenticator,
                'main' // firewall name in security.yaml
            );
        }

        return $this->render('registration/register.html.twig', [
            'registrationForm' => $form->createView(),
        ]);
    }
}

Aunque symfony no lanza ningun error porqué parece que está bien la configuración sigue sin funcionar. El error que lanza al ejecutar el caso de uso es el siguiente:
Too few arguments to function App\Application\AppUseCases\User\NewUser\NewUser::__construct(), 0 passed in /var/www/symfony/src/Controller/RegistrationController.php on line 33 and exactly 2 expected


text:
Q: Put draggable div by order in droppable div So, I'm doing a card games and I've a problem with my droppables divs. I've 26 draggable divs and 2 droppable, each card has a type and a value. The goal is to put 13 cards by droppables divs and each card has to be of the same type . What I want is to be able to put cards in droppable only from smaller to bigger . It's pretty difficult for me to do it only because I'm beginner and I'm lost with all options in droppable divs. Is there someone able to help me?

A: in first i've created div html

after i've make a javascript object card ,another one for types and a table for values
var TYPE = {
     SPADE: 1,
     HEART: 2,
     CLUB: 3,
     DIAMOND: 4
 };

var VALUES = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'];

function Card(type , val)
{
    this.type = type;
    this.val = val;
}

i created a variable for each cards div
$AceOfSpade= $('#aceofspade').data('card',new Card(TYPE.SPADE, VALUES[0]));
$AceOfDiamond= $('#aceofdiamond').data('card',new Card(TYPE.DIAMOND, VALUES[0]));
$AceOfHeart= $('#aceofheart').data('card',new Card(TYPE.HEART, VALUES[0]));
$TwoOfHeart= $('#twoofheart').data('card',new Card(TYPE.HEART, VALUES[1]));
$ThreeOfHeart= $('#treeofheart').data('card',new Card(TYPE.HEART, VALUES[2]));
$FourOfHeart= $('#fourofheart').data('card', new Card(TYPE.HEART, VALUES[3]));
$FiveOfHeart= $('#fiveofheart').data('card',new Card(TYPE.HEART, VALUES[4]));
$SixOfHeart= $('#sixofheart').data('card',new Card(TYPE.HEART, VALUES[5]));

and i make them draggable and droppable
$('.card').draggable({revert : 'invalid', snap : '.droppable' , snapMode:'inner',snapTolerance : 50});
$('.droppable').droppable({
    accept : 'div.carte',
    drop : function(){
        alert('i'm in');
        return true;
    }

But about my droppable div i really don't know how to make my condition to only
accept a one of each 13 div


text:
Q: Trouble finding tangential component for $r=(3t-t^3)i+(3t^2)j$ I have
$$r=(3t-t^3)i+(3t^2)j$$
and need to find the tangential component. I got:
$$r'=(3-3t^2)i+6tj$$
$$r'*r"= 18t^3+18t$$
$$|r'|=\sqrt{9t^2(2+t^2)}=3t\sqrt{2_t^2}$$
$$\frac{r'*r"}{|r'|}=\frac{6(t^2+1)}{\sqrt{2+2t}}$$
The answer says it should be just 6t.

A: $$|r'| = \sqrt{(3-3t^2)^2+36t^2} = \sqrt{9t^4+18t^2+9} = 3\sqrt{(t^2+1)^2} = 3(t^2+1)$$


text:
Q: HtmlAgilityPack select a specific number of nodes Consider the following C# statement that implements HAP to select some HTML nodes from a given website.
var nodes = page.DocumentNode.SelectNodes("//ul[contains(@class,'relatedProductsGrid')]//div[@class='product']//a");

On the given pages, the selectors return around 20 nodes for the page, and my question is, if I wanted to limit the amount of nodes it grabs, how would I do this?
So essentially, I want to "select 3 nodes instead of 20" but in the cleanest possible way, maybe there is a LINQ expression I could use to simply my request?
Thanks all

A: You could use the position() function in XPath to restrict the number of items, in the following way:
//ul[contains(@class,'relatedProductsGrid')]//div[@class='product']//a[position() >= 1 and position() < 4]


text:
Q: Swing Components invisible When I run my code there is only the empty frame. To see the JButton and the JTextFields I have to search and click on them before they are visible. I searched everywhere on the Internet but I found nothing. I also set the visibility to true and added the JComponents. Here is my Code:
Frame Fenster = new Frame();

And this...
package me.JavaProgramm;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

public class Frame extends JFrame {
    private JButton bChange;
    private JTextField tvonEur;
    private JTextField tzuOCur; //andere Währung (other Currency)
    private JTextField tzuEur;
    private JTextField tvonOCur;
    private JComboBox cbCur; //Wärhung wählen
    private String curName;
    private double faktorUSD;
    private double faktorGBP;

    private static String[] comboCur = {"USD", "GBP"};

    public Frame() {
        setLayout(null);
        setVisible(true);
        setSize(400, 400);
        setTitle("Währungsrechner");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setAlwaysOnTop(true);
        setResizable(false);

        Font schrift = new Font("Serif", Font.PLAIN + Font.ITALIC, 30);

        tvonEur = new JTextField("Euro");
        tvonEur.setSize(80, 25);
        tvonEur.setLocation(20, 50);
        tvonEur.requestFocusInWindow();
        tvonEur.selectAll();

        tzuEur = new JTextField("Euro");
        tzuEur.setSize(80, 25);
        tzuEur.setLocation(20, 150);
        tzuEur.requestFocusInWindow();
        tzuEur.selectAll();

        bChange = new JButton("Euro zu US-Dollar");
        bChange.setSize(120, 25);
        bChange.setLocation(110, 50);

        tzuOCur = new JTextField("US-Dollar");
        tzuOCur.setSize(80, 25);
        tzuOCur.setLocation(240, 50);
        tzuOCur.requestFocusInWindow();
        tzuOCur.selectAll();

        tvonOCur = new JTextField("US-Dollar");
        tvonOCur.setSize(80, 25);
        tvonOCur.setLocation(240, 50);
        tvonOCur.requestFocusInWindow();
        tvonOCur.selectAll();

        cbCur = new JComboBox(comboCur);
        cbCur.setSize(100, 20);
        cbCur.setLocation(100, 100);

        tvonEur.setVisible(true);
        tzuEur.setVisible(true);
        tzuOCur.setVisible(true);
        tvonOCur.setVisible(true);
        bChange.setVisible(true);
        cbCur.setVisible(true);

        add(tvonEur);
        add(bChange);
        add(tzuOCur);
        add(cbCur);

        Currency currency = new Currency();

        String strUSD = currency.convertUSD();
        try {
            NumberFormat formatUSD = NumberFormat.getInstance(Locale.GERMANY);
            Number numberUSD = formatUSD.parse(strUSD);
            faktorUSD = numberUSD.doubleValue();
            System.out.println(faktorUSD);
        } catch (ParseException e) {
            System.out.println(e);
        }

        String strGBP = currency.convertGBP();
        try {
            NumberFormat formatGBP = NumberFormat.getInstance(Locale.GERMANY);
            Number numberGBP = formatGBP.parse(strGBP);
            faktorGBP = numberGBP.doubleValue();
            System.out.println(faktorGBP);
        } catch (ParseException e) {
            System.out.println(e);
        }

        cbCur.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cbCur = (JComboBox) e.getSource();
                curName = (String) cbCur.getSelectedItem();
                if (curName == "USD") {
                    tzuOCur.setText("US-Dollar");
                } else if (curName == "GBP") {
                    tzuOCur.setText("British-Pound");
                }
            }
        });

        bChange.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (curName == "USD") {
                    try {
                        Double doubleEUR = Double.parseDouble(tvonEur.getText());
                        Double doubleUSD = doubleEUR * faktorUSD;
                        tzuOCur.setText(Double.toString(roundScale3(doubleUSD)));
                    } catch (NumberFormatException nfe) {
                        System.out.println("Gebe einen richten Wert ein!");
                    }
                } else if (curName == "GBP") {
                    try {
                        Double doubleEUR = Double.parseDouble(tvonEur.getText());
                        Double doubleGBP = doubleEUR * faktorGBP;
                        tzuOCur.setText(Double.toString(roundScale3(doubleGBP)));
                    } catch (NumberFormatException nfe) {
                        System.out.println("Gebe einen richten Wert ein!");
                    }
                }
            }
        });
    }

    public static double roundScale3(double d) {
        return Math.rint(d * 1000) / 1000.;
    }
}

A: Try moving setVisible(true) after you add the children to the parent container.
Generally with Swing it's considered good practice to put code that updates visible components in the event dispatching thread, like this:
SwingUtilities.invokeLater(new Runnable() {
  @Override
  public void run() {
    Frame.this.setVisible(true);
  }
});


text:
Q: Invalid column name 'Locked'. So we have this software that queries for content of Catalogue:
10:55:36,193 [ INFO] [rest.CatalogProvider:232] GET_CATALOG: {
  Id: '*',
  Title: '*',
  Clip: '*',
  IniDate: '*',
  EndDate: '*',
  DurMin: '*',
  DurMax: '*',
  Store: '*',
  FilterConfig: '*',
  FilterNoStore: '*',
  InfoStore: '*',
  Channel: '*',
  Group: '*',
  Type: '*',
  Validated: '*',
  SourceType: '*',
  NumResults: '*',
  StartIndex: '*',
  Order: '*'
}

This terminates in error:
10:55:36,285 [ WARN] [util.JDBCExceptionReporter:233] SQL Error: 207, SQLState: S0001
10:55:36,285 [ERROR] [util.JDBCExceptionReporter:234] Invalid column name 'Locked'.
10:55:36,286 [ERROR] [service.CatalogService:434] getCatalog Exception could not execute query

However I am quite sure we do not have a column name Locked. Where is this 'locked' coming from?
The server is SQL Server 2008.

A: The name locked is either referenced in the query being sent to SQL Server or referenced in a programmability object (e.g. trigger) being executed. I suggest you start with a trace of batch and rpc starting events to rule out the first case. The name lockedsuggests it may be used for application level concurrency so perhaps there's an ORM lay or similar injecting it.
The trace can be done using the legacy Profiler/SQL Trace or an Extended Events Trace. Below is an example XE trace that filters by application name to reduce the noise or you could run an unfiltered one on a test box.
CREATE EVENT SESSION [batch_and_rpc_completed] ON SERVER
ADD EVENT sqlserver.rpc_starting(
    ACTION(package0.event_sequence,sqlserver.session_id)
    WHERE ([sqlserver].[equal_i_sql_unicode_string]([sqlserver].[client_app_name],N'YourApplication'))),
ADD EVENT sqlserver.sql_batch_starting(
    ACTION(package0.event_sequence,sqlserver.session_id)
    WHERE ([sqlserver].[equal_i_sql_unicode_string]([sqlserver].[client_app_name],N'YourApplication')))
ADD TARGET package0.event_file(SET filename=N'batch_and_rpc_completed')
WITH (MAX_MEMORY=8192 KB,EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,MAX_DISPATCH_LATENCY=5 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=ON,STARTUP_STATE=OFF);

EDIT:
Here's another trace that captures only error_reported events. This is a SQL 2014+ version gleaned from the Brent Ozar's SQL 2012 version of this trace @sp_BlitzErik referenced in his comment.
CREATE EVENT SESSION failed_queries ON SERVER
ADD EVENT sqlserver.error_reported(
    ACTION (sqlserver.sql_text, sqlserver.tsql_stack, sqlserver.database_id, sqlserver.username)
    WHERE ([severity]> 10))
ADD TARGET package0.asynchronous_file_target(SET filename = 'failed_queries' ,max_file_size = 5,max_rollover_files = 5)
WITH (MAX_DISPATCH_LATENCY = 5 SECONDS);


text:
Q: Does a loop.run_in_executor functions need asyncio.lock() or threading.Lock()? I copied the following code for my project and it's worked quite well for me but I don't really understand how the following code runs my blocking_function:
@client.event
async def on_message(message):
      loop = asyncio.get_event_loop()
      block_response = await loop.run_in_executor(ThreadPoolExecutor(), blocking_function)

where on_message is called every time I receive a message. If I receive multiple messages, they are processed asynchronously.
blocking_function is a synchronous function that I don't want to be run when another blocking_function is running.Then within blocking_function, should I use threading.Lock() or asyncio.lock()?

A: As pointed out by dirn in the comment, in blocking_function you cannot use an asyncio.Lock because it's just not async. (The opposite also applies: you cannot lock a threading.Lock from an async function because attempting to do so would block the event loop.) If you need to guard data accessed by other instances of blocking_function, you should use a threading.Lock.

but I don't really understand how the following code runs my blocking_function

It hands off blocking_function to the thread pool you created to run it. The thread pool queues and runs the function (which happens "in the background" from your perspective), and the run_in_executor arranges the event loop to be notified when the function is done, handing off its return value as the result of the await expression.
Note that you should use None as the first argument of run_in_executor. If you use ThreadPoolExecutor(), you create a whole new thread pool for each message, and you never dispose of it. A thread pool is normally meant to be created once, and reuse a fixed number ("pool") of threads for subsequent work. None tells asyncio to use the thread pool it creates for this purpose.

A: It seems you can easily achieve your desired objective by ensuring a single thread is used.
A simple solution would be to ensure that all calls to blocking_function is run on a single thread. This can be easily achieved by creating a ThreadPoolExecutor object with 1 worker outside of the async function. Then every subsequent calls to the blocking function will be run on that single thread
thread_pool = ThreadPoolExecutor(max_workers=1)
@client.event
async def on_message(message):
      loop = asyncio.get_event_loop()
      block_response = await loop.run_in_executor(thread_pool, blocking_function)

Don't forget to shutdown the thread afterwards.


text:
Q: How to Retrieve value from a User-Defined Table Type (UDTT) Goal:
I want to reach and display the value of @data inside of [wwtest].
Problem:
The UDTT is from the database [test] and I receive an error message:

The type name 'test.dbo.tvf_id' contains more than the maximum number of prefixes. The maximum is 1.

I don't know how to retrieve the data from the database [test] in a query currently in the database [wwtest]?

create table datatable (id int,
                        name varchar(100),
                        email varchar(10),
                        phone varchar(10),
                        cellphone varchar(10),
                        none varchar(10)
                       );

insert into datatable values
  (1, 'productname', 'A', 'A', 'A', 'A'),
  (2, 'cost', '20', 'A', 'A', 'A'),
  (3, 'active', 'Y', 'A', 'A', 'A');

insert into datatable values
  (4, 'productname', 'A', 'A', 'A', 'A'),
  (5, 'cost', '20', 'A', 'A', 'A'),
  (6, 'active', 'Y', 'A', 'A', 'A');

insert into datatable values
  (7, 'productname', 'A', 'A', 'A', 'A'),
  (8, 'cost', '20', 'A', 'A', 'A'),
  (9, 'active', 'Y', 'A', 'A', 'A');

CREATE TYPE [tvf_id] AS TABLE
(
    [id] [int] NULL
    ,[OrdCol] [INT] NOT NULL
)
GO

DECLARE @data tvf_id INSERT INTO @data([id],[OrdCol])
VALUES (8,1), (2,2), (4,3), (1,4), (3,5);

A: You need to create the type inside the database where you will declare it - data types can not be reached across databases or servers. This is no different from creating a local variable using an alias type - it has to exist in the context of the current database (or your code has to execute in the context of the database where the type exists, e.g.
EXEC dbname.sys.sp_executesql N'DECLARE @t dbo.type;
  INSERT @t(cols) SELECT whatever...;
  -- do other stuff but it has to be in this dynamic SQL block';


text:
Q: Dynamical interpretation of reflecting boundary conditions in the Fokker-Planck equation Background:
For a particle driven by the dynamical equation
$$ \dot{x}(t) = a(x,t) + b(x)\xi(t),$$
where $\xi(t)$ is a Gaussian white noise, the probability distribution of position $x$ is governed by the Fokker-Planck equation
$$ \frac{\partial}{\partial t}P(x,t) = -\frac{\partial}{\partial x}J(x,t)$$
where $$J(x,t) = a(x,t)P(x,t) - \frac{1}{2}\frac{\partial}{\partial x}\Big[b(x,t)^2P(x,t)\Big]$$
is the probability current. One can solve the Fokker-Planck equation for different boundary conditions. One possibility is "reflecting" boundary conditions when the probability current vanishes at some reflection point $x=a$, which can be written
$$J(a,t)=0. $$
Question:
I am wondering how to understand what the individual particles are actually doing in a Fokker-Planck equation with reflecting boundary conditions. How are individual particle trajectories modified by reflecting boundary conditions in the Fokker-Planck equation? Is it as if they are undergoing elastic collisions with the barrier? Could one interpret reflecting boundary conditions as a potential term in the original equation of motion?

A: It means that the current in $x=a$ is 0, but the density can be whatever.
You can indeed imagine it as particles bouncing off a wall: in a small line element $[a-dx, a]$ you have $N$ particles, but $N/2$ are going towards left and $N/2$ towards the right, so the net current is $0$. The ones going "on the right" will then bounce off the wall and from then on going towards left, while the same number of particles will come from the left from the area element before ($[a-2dx, a-dx]$) to compensate. Again, the net current is 0. And so on. Of course this is true on average not for every particle.
Consider for example $N$ molecules moving in a closed box. Of course they can not escape the box, so the current $J(\text{box side}, t)=0$. But their concentration is constant everywhere ($N/\text{volume of the box}$).
In terms of potential, it would mean that the energy on the sides of the box is infinite and particles can not escape it.

A: Consider the special case where $a\equiv 0$ and $b\equiv 1\,.$ Then $x(t)$ is a standard Brownian motion. With reflection condition at zero this process has the transition density
$$
p(t,x,y)=\frac{1}{\sqrt{2\pi t}}\left\{\exp\left(-\frac{(x-y)^2}{2t}\right)+\exp\left(-\frac{(x+y)^2}{2t}\right)\right\}\,
$$
which solves the heat equation
$$
\frac{\partial p}{\partial t}=\frac{1}{2}\frac{\partial^2 p}{\partial x^2}\,.
$$
According to exercise 2.8.4 of [1], this is the transition density of the modulus of Brownian motion $|x(t)|\,.$
In other words: the trajectory of the reflected particle is $|x(t)|\,.$
The picture in [2] is also very enlightning.
[1] I. Karatzas, S. Shreve, Brownian Motion and Stochastic Calculus.  Springer Graduate Texts in Mathematics. 1991.
[2] Wikipedia Reflection principle (Wiener process).


text:
Q: $L^2$-convergence of a sequence of step functions of differences Suppose $f\in L^2=L^2([0,1])$ (that is, $f$ is square-integrable). Let $f_n$ be an approximation of $f$ by steps of differences of $\int f$. Formally,
$$f_n = \sum_{i=1}^n\mathbf{1}_{((i-1)/n,i/n]}\left(n\int_{(i-1)/n}^{i/n}f(t)dt\right)$$
Explanation: I have divided $[0,1]$ into $n$ equal parts, and let $f_n$ be constant on each part, with height equal to $\int f$'s difference on the edges of that part, divided by its length. In fact, it looks like there's nothing special about dividing into $n$ equal parts - as long as the maximal part's length tends to 0 with $n$, it should probably be all right.
My question is this: does it follow that $f_n$ converges to $f$ in $L^2$?

A: I assume that you are working only on $[0,1]$, i.e. $L^2 = L^2([0,1])$.
Let us consider the linear operators $T_n : L^2([0,1]) \rightarrow L^2([0,1]), f \mapsto f_n$.
First calculate
\begin{eqnarray*}
\Vert T_n f \Vert _2^2 = \left\Vert f_{n}\right\Vert _{2}^{2} & = & \sum_{i=1}^{n}\int_{\left(i-1\right)/n}^{i/n}\left|n\cdot\int_{\left(i-1\right)/n}^{i/n}f\left(t\right)\, dt\right|^{2}\, dx\\
 & \overset{\text{Hölder}}{\leq} & \sum_{i=1}^{n}\int_{\left(i-1\right)/n}^{i/n}\left[n\cdot\sqrt{\int_{\left(i-1\right)/n}^{i/n}1^{1}\, dt}\cdot\sqrt{\int_{\left(i-1\right)/n}^{i/n}\left|f\left(t\right)\right|^{2}\, dt}\right]^{2}\, dx\\
 & = & \sum_{i=1}^{n}\int_{\left(i-1\right)/n}^{i/n}n\cdot\int_{\left(i-1\right)/n}^{i/n}\left|f\left(t\right)\right|^{2}\, dt\, dx\\
 & = & \int_{0}^{1}\left|f\left(t\right)\right|^{2}\, dt=\left\Vert f\right\Vert _{2}^{2}.
\end{eqnarray*}
Then note that for $f \in C([0,1])$ we have $f_n \rightarrow f$ uniformly and hence in particular in $L^2$.
Because $C([0,1])$ is dense in $L^2([0,1])$, you can verify your claim using the above estimate on the operator norms of $T_n$ (how?).


text:
Q: City and State Picker for a specific Country All of you must have seen those Select Country, State and City Dropdown menus/ picker.
I can't find a way to implement that in Flutter.

Manually Adding data of all cities, states etc. is not possible.

Any Suggestion on how to do this in Flutter?

A: I know I'm late to give answer, you can use https://pub.dev/packages?q=csc_picker
It has search facility and easy integration

A: You could use this package:
https://pub.dev/packages/flutter_country_picker
Or you can extract the list of countries from the package and create your own dropdown using https://api.flutter.dev/flutter/material/DropdownButton-class.html


text:
Q: Why did the inflation era not produce decompactification of the extra dimensions of string theory? My question is undoubtedly naive, due to lack of background, but any answers, or simply comments with short explanations of my incorrect assumptions,  would be appreciated.
I must point out this question: Why does space expansion not cause matter expansion , in case of duplication concerns. I do  understand the points involved in the answers of this "normal expansion" question, but my question involves the inflationary period only, not the current observed expansion, as I feel it can be easily argued that the proposed possible inflation of the very early universe was a  completely different phenomenon.
My question is: If the normal 3  spatial dimensions that define the current volume of the universe were given a "kick start" in their initial expansion by the inflation process, why were the other proposed 6 dimensions of Calabi-Yau spaces not also affected?
I cannot stress enough my lack of knowledge of this area of physics, but despite that my curiosity leads me to speculation on two possible answers and I wonder do they have any validity:

*

*The extra dimensions only involve particles, and particles did not form until after the inflationary period ended, but this would imply that particles are involved in creating spatial dimensions, so this is probably totally incorrect.

*The extra dimensions did expand, but were so small initially that even inflation failed to expand them to beyond their present proposed minute proportions.
The final, most likely "answer" is simply that I don't yet have enough understanding of the topic to make any sensible suggestions, but any answer (or comments including a related relevant link) that involves even a small increase in my knowledge of this topic would be appreciated.

A: As far as I know, this is an open question. The technical name is the problem of "moduli stabilization" in string theory, because there some fields (called moduli) the values of which determine the size of the dimensions. The problem is that string models are consistent for a big range of these values, so indeed, it could have been that all directions are small, or all big or any crazy combination. There have been many attempts to stabilize the moduli in different string constructions, ie to find a way to predict the size of all dimensions in nature without putting them in by hand, but I think it is fair to say that none of the approaches are fully satisfactory.
One possible answer to this question, (which appears quite often when we simply don't know!), is the anthropic principle. So there might be other universes where more or fewer dimensions were decompactified (either at inflation or at different stage of the evolution) but did not lead to worlds in which life could develop. This is definitely a logical possibility, but maybe someday we will come up with a better explanation that gives further intuition on how nature works.


text:
Q: postMessage two different integers IE,Chrome,Safari and Firefox - Javascript So I have a mystery to solve. Site A receives a postMessage from Site B. The postMessage is supposed to contain Site B's height. When Site A receives this number in firefox, it is correct at 433, but when I receive this exact same message in IE, Chrome, and Safari I get extreme results.
IE, Safairi, Chrome - 1584
Firefox - 433
Does anyone have any thoughts as to why I am getting different numbers? It is consistent on reload but every time a new post message is sent I get a different number. The results are different in each browser.
IE- Pattern

*

*1584

*158399

*397

*39699

*1533901

*397

*39699

*1533901

Chrome/Safari - Pattern

*

*1584

*1583

*1581

*continues to decrement upon each request

Any thoughts are welcome. Have a great day!
var onmessage = function(e) {
    console.log(e.data); // testing - 1584(wrong) or 433(right) on first message
    height = e.data + 15;
    // Resizes the iframe to accomodate the content
    document.getElementById('api_box').parentNode.style.height = height + 'px';

 };

// Using the postMessage method we can send data from the iframe to this frame and adjust its height
if (typeof window.addEventListener != 'undefined') {
  window.addEventListener('message', onmessage, false);
} else if (typeof window.attachEvent != 'undefined') {
  window.attachEvent('onmessage', onmessage);
}

Code on Site B which sends the postMessage.
    parent.window.postMessage(document.body.offsetHeight, '*');


text:
Q: Slow internet connection requires forced reset of network adapter? Computer is connected directly to modem via ethernet. Upon boot, an online speed test is consistently 10 Mb/s. This is significantly less than my service is supposed to be (50+). As soon as I disable and enable the ethernet adapter I can run another speed test at 60+ Mb/s. The connection appears to be stable at this point.
Additional information: Ethernet adapter is Realtek PCIe GBE Family Controller. Drivers are up to date. Tried rolling back drivers. Tried an old modems. Tried flushing DNS, resetting winsock, resetting IP. Tried changing the adapters speed from auto negotiation to 100 full.
I've got nothing. For the time being I've just got a batch file (using devmanview.exe) that resets the adapter on delay after boot but I'd like a more elegant solution. I've had hilarious conversations with my ISP support where I realize this is no longer on their script so they're no help.
Thanks for any help.

A: I stumbled upon a fix. Turns out the power output to wifi in my router settings was set to 100%. On a whim, I turned this down to 75%. This didn't seem to effect the wifi performance elsewhere in the house but it made my ethernet adapter resolve the connection speed correctly and perform more reliably.
The router is a Motorola Surfboard modem/router combo.


text:
Q: Can't Update package in Ubuntu I use these command to install PHP 5.6 on Ubuntu Server 18.04
sudo apt-get install python-software-properties
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
sudo apt-get install -y php5.6

and apt-get update not working after install PHP5.6
Error:
Err:8 packages.sury.org/php bionic Release 404 Not Found [IP: 2001:1488:ac15:ff90::150 443] Reading package lists... Done

E: The repository 'packages.sury.org/php bionic Release' does not have a Release file.

N: Updating from such a repository can't be done securely, and is therefore disabled by default.

N: See apt-secure(8) manpage for repository creation and user configuration details.

Please help me!

A: Open "Software & Updates" and look for the "Other Software" tab. Uncheck the "packages.sury.org/php" url and try to "apt update" again.


text:
Q: kncokout, flat ui and bootstrap binding issue We are using flat ui in my project and we have some ui issues.

*

*File upload control issue.

*Radio buttons/check boxes/drop downs css issue.

File upload:
Normal html (design time) when we select file it's showing the change and remove button with file name. Whereas in durandal application it's not showing change/remove and file name in control, always showing select button only.
HTML content.

    Upload Condo Logo

                Select file

                      Change

                <input type="file" id="fitest" name="...">

                      Remove

Check box/radio button/dropdown
Check box:

Normal html page displaying proper style and color.
In Project, controls are not displaying and binding also not working. If we remove css its working fine.
Durandal page html
<input type="checkbox" class="case" name="case" value="1"
       data-bind="checked: $parent.selectedCondos, attr: { value : id }" />

Please help me to fix the issue.


text:
Q: Процессор в сокете шатаеться + скрипит при попытке закрыть сокет Сегодня купил новенький ryzen 5 5500 и материнскую плату B450, вставил процессор в сокет (стрелочка на процессоре совпала с стрелочкой на материнской плате), на сам процессор я не давил, он сам провалился в сокет, но когда нажимаю по краям процессора он шатаеться (в еще не закрытом состоянии) а при попытке закрыть сокет идет очень громкий звук скрипа, он чем то похож на походку по снегу, а так же сама "палочка" туго опускаеться, дожимать не стал ибо боялся сломать, как быть? идти в мастерскую не хочу, ибо стыдно что я процессор не в состоянии впихнуть в сокет даже.
фото того как я вставил процессор:


text:
Q: Placing a jquery animation on image elements when mouseover I am trying to sort out my images to wobble on mouseover. I have the below that I was testing that on click moves the whole div to the left. However, all i want is on the mouseover of each image, they wobble.
Any help and advice would be sweet!
        HTML

Smile Board

CSS
    body {
      font-family: 'Baloo Bhaina', cursive;

    }

    @media (min-width: 1200px)
    .container {
      width: 1170px;
    }

    h1 {
      text-align: center;
    }

    .page-header {
      background-color: #8AFFC1;
      padding-top: 20px;
      width: 1130px;
    }

    .top-header {
      width: 1130px;
      background-color: #8AFFC1;
      padding-top: 20px;
      width: 1290px;
    }

    .sub {
      /*background-color: #EFEC86;*/
      padding-top: 20px;
    }

    img {
      width: 100%;
      height: auto;
      display: block;
      overflow: auto;
    }

    .thumbnail {
      width: 250px;
      height: 270px;
      overflow: auto;
      /*max-width:calc(150% - 10px);*/

    }

    .row {
      margin-right: 50px;
      margin-left: -15px;
    }

JS
$(document).ready(function(){
  $("img").click(function(){
    $("div").animate({right: '250px'});
  });
});

A: Have you thought about using pure CSS and keyframes? If so then see this link that will explain...Using javascript is fine for something like this too, but in my opinion, for something this small, CSS would be fine.
https://css-tricks.com/snippets/css/shake-css-keyframe-animation/

A: See below code snippet.

$(document).ready(function(){
  $("img").on('mouseover', function(){
    $("div").animate({height: "300px"});
  });
});
body {
      font-family: 'Baloo Bhaina', cursive;

    }

    @media (min-width: 1200px)
    .container {
      width: 1170px;
    }

    h1 {
      text-align: center;
    }

    .page-header {
      background-color: #8AFFC1;
      padding-top: 20px;
      width: 1130px;
    }

    .top-header {
      width: 1130px;
      background-color: #8AFFC1;
      padding-top: 20px;
      width: 1290px;
    }

    .sub {
      /*background-color: #EFEC86;*/
      padding-top: 20px;
    }

    img {
      width: 100%;
      height: auto;
      display: block;
      overflow: auto;
    }

    .thumbnail {
      width: 250px;
      height: 270px;
      overflow: auto;
      /*max-width:calc(150% - 10px);*/

    }

    .row {
      margin-right: 50px;
      margin-left: -15px;
    }

Smile Board


text:
Q: How to break datasets in r into new data sets using empty rows I am trying to "automize" the process of separating this data into datasets based on its trials. The original data is a list of values taken at several sites, and I want to break them into individual sets without having to use notation like c(1:312) because the number of rows in each trial vary. Each trail starts with a header, like d9, and ends with a blank row before the next header. How can I separate the data into new dataframes using the headers/empty rows?
This is for analyzing water data; Depth, Temperature, DO, and Salinity. The end goal is to create a graph of each trial showing the differences is Temperature across the trials.
Data Set (starting at row 1299)
1299 NA
1300 d4
1301 0.00
1302 0.18
1303 0.20
1304 0.31
1305 0.49
1306 0.76
1307 1.12
1308 1.51
1309 1.82
1310 1.92
1311 2.08
1312 2.35
1313 2.41
1314 2.48
1315 2.68
1316 2.97
1317 3.22
1318 3.33
1319 3.40
1320 3.55
1321 3.81
1322 4.05
1323 4.30
1324 4.41
1325 4.46
1326 4.56
1327 4.61
1328 4.62
1329 4.55
1330 4.54
1331 4.56
1332 4.49
1333 4.38
1334 4.38
1335 4.55
1336 4.71
1337 4.91
1338 5.14
1339 5.22
1340 5.26
1341 NA
1342 d11
1343 0.00
1344 0.22
1345 0.22
1346 0.27

D9 <- Data[3:314,]
D12 <- Data[317:517,]
D3 <- Data[520:703,]
D15 <- Data[706:795,]
D14 <- Data[798:853,]
D2 <- Data[856:939,]
D13 <- Data[942:975,]
D1 <- Data[978:1029,]
D6 <- Data[1032:1113,]
D5 <- Data[1116:1171,]
D7 <- Data[1174:1230,]
D8 <- Data[1233:1298,]
D4 <- Data[1301:1340,]
D11 <- Data[1343:1392,]
D10 <- Data[1395:1493,]

A: We can create a list using split along with grepl and cumsum
lst <- lapply(split.data.frame(x = df, cumsum(grepl('d\\d+',df$V2))),
                function(x) {
                   names(x)[2] <- as.character(x[1,'V2'])
                   x <- x[-1,]
})

data
df <- structure(list(V1 = 1299:1346, V2 = c(NA, "d4", "0.00", "0.18",
"0.20", "0.31", "0.49", "0.76", "1.12", "1.51", "1.82", "1.92",
"2.08", "2.35", "2.41", "2.48", "2.68", "2.97", "3.22", "3.33",
"3.40", "3.55", "3.81", "4.05", "4.30", "4.41", "4.46", "4.56",
"4.61", "4.62", "4.55", "4.54", "4.56", "4.49", "4.38", "4.38",
"4.55", "4.71", "4.91", "5.14", "5.22", "5.26", NA, "d11", "0.00",
"0.22", "0.22", "0.27")), class = "data.frame", row.names = c(NA, -48L))

Note: It's advised to keep your data frames in a list instead of assigning them into Global env., see here


text:
Q: Call a function inside promise I'm trying to find a way to call the method pageLoader.fetch twice in this promise. I already tried to separate it in a new promise but I get undefined when I try to get the variable links[0]. How to do this?
pageLoader
  .fetch(url)
  .then(function(data) {
    links = html.orderdList(data);
  })
  .then(function() {
    return pageLoader.fetch(links[0]);
    //links[0] is undefined in the next line!?
  })
  .then(
    pageLoader
      .fetch(links[0])
      .then(function(innerLinks) {
        calLinks = html.unorderList(innerLinks);
      })
      .then(function() {
        return pageLoader.fetch("http:///example.com");
      })
      .catch(function(error) {
        console.log(error);
      })
  );

A: You're almost there. You have some redundant, then()s, which I've removed. It's not clear why you are calling pageLoader.fetch(links[0]) twice. Does it return different results?
You also look like you are setting some global variable (links & calLinks for example), but it's not clear how you will access them asynchronously.
This should work a little better, but given the above, it may still have issues:
pageLoader.fetch(url)
.then(function(data) {
  links = html.orderdList(data); // <-- are these global or should you have a var?;
  return pageLoader.fetch(links[0]);
})
.then(function(link) { // <-- did you want to do something with the return from above?
  return pageLoader.fetch(links[0])
})
.then(function(innerLinks) {
    calLinks = html.unorderList(innerLinks); // <-- are these global?;
    return pageLoader.fetch("http:///example.com");
})
.catch(function(error) {
    console.log(error);
})

A: The line .then(pageLoader.fetch(links[0])...) is not doing what you probably want it to be doing. Calling it like that is the equivalent of doing this:
var myCallback = pageLoader.fetch(links[0]).then().then().catch();

pageLoader
  .fetch(url)
  .then(function(data) {
    links = html.orderdList(data);
  })
  .then(function() {
    return pageLoader.fetch(links[0]);
  })
  .then(myCallback)

Your second fetch is actually being immediately executed before everything else and the result of that is being passed as the callback. You probably want to not call that code until the first fetch has happened, so you'll want to wrap it in a function (like with your other .then() statements).
I might also suggest that you could greatly simplify your code:
pageLoader
  .fetch(url)
  .then(function(data) {
    // this is called when the first fetch() returns
    links = html.orderdList(data);
    return pageLoader.fetch(links[0]);
    // returning a promise means that following .then()
    // statements will act on the returned promise rather than the original
  })
  .then(function(innerLinks) {
    // this is called when the second fetch() returns
    calLinks = html.unorderList(innerLinks);
    return pageLoader.fetch("http:///example.com");
  })
  .catch(function() {
    // this is called if the original promise or any of
    // the promises returned in the .then() callbacks throw errors
  });

I found this article to be very helpful in explaining the best ways to use Promises, and some of the mistakes that can happen: https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html


text:
Q: How to set up a network connection with 2 ISP,s 2 Routers and 1 switch I want to use 2 ISP providers at the same time, to avoid downtime. Here's a diagram of what I want to do:

What settings should I use for the routers and can I force PCs to use ISP#1 when online and ISP#2 when 1 is down?

A: How you do it will depend on the routers you have. What you are trying to do is configure the routers in failover also known as high availability mode.
You can also you two ISPs with a single router and use WAN failover. You also are able to use a dedicated device to do link balancing and connection failover.
First, you need to determine what routers you are using and then I suggest looking for the terms above to find the configuration you need to build. If you have a specific question about how to do something please let me know.


text:
Q: Discount factor for self play in reinforcement learning Imagine we have a two player game with some sort of sparse reward (few actions are rewarded over the course of a game).  My understanding is that ordinarily, the reward administered to actions would decrease by discount factor $\gamma$ each timestep as $t_\text{from reward}$ increases.
If we were attempting to learn a policy for a two player turn-based game (such as tic-tac-toe), a generally accepted strategy seems to be inverting the environment every other move such that the agent is always playing from the same perspective.  However, if we naively administered reward for the agent's actions by our previous policy, we would end up rewarding self-destructive behavior of the agent every other timestep.  Thus, it would make sense to me to give alternatingly negative reward.
Is it common practice to achieve this behavior by assigning a negative discount factor $\gamma$?  Although this would make sense to me, I haven't seen examples where $\gamma < 0$ in published literature.  Alternatively, is there a better way to set up the environment for these sorts of games such that we can still administer rewards as we would for single player games? Thank you.

A: In a simple two-player zero-sum game (i.e. my win is your loss and vice-versa), then there is no need to alter the model, just the action selection. If you have Player A and Player B, arbitrarily decide that your reward function is positive for Player A. Then any estimate of total return (all rewards summed, aka "utility") for Player B is just the negative of the estimate for Player A. So you can share one state value model between the players.
The only thing you need to "invert" between players is when making action choice. Player A should choose the action that maximises the reward. Player B should choose the action that minimises it, and can use the same estimates from the same model to do so. This is called minimax, and is used in game playing algorithms even without RL - for instance it might be used based on some expert-provided heuristic, and is a commonly used concept in game theory. You can think of RL in this context as attempting to learn the best heuristic estimates for each game state, based on learning from experience.
A negative discount factor would not achieve similar results - I'm not entirely sure what it would do, but it could well make the learning process fail. Most two player games are episodic with reward only considered at end of the episode (a win, draw or loss), in which case discounting is not much use anyway.

A: A two-player zero-sum game can indeed be modeled using negative discount factors. A positive/negative discount factor means the next player to act is the same/opposite player. This works because a negative discount factor turns maximization into minimization and viceversa.
DeepMind's MCTS library mctx uses this trick.


text:
Q: Tensor Einstein summation notation I have two tensors $A^i$ and $B_j$ with components $(2,3,4)$ and $(1,2,3)$ respectively.
What is the difference between $A^i B_i$ and $A^i B_j$?
Is it just:
$A^i B_i = 2+6+12 = 20$
$A^i B_j =$
$
        \left(\begin{matrix}
        2 \\
        3 \\
        4 \\
        \end{matrix}\right)
$
$
        \left(\begin{matrix}
        1 &2 & 3\\
        \end{matrix}\right)
$
$
        \left(\begin{matrix}
        2 & 4 & 6 \\
        3 & 6 & 9 \\
        4 & 8 & 12 \\
        \end{matrix}\right)
$?
Thanks

A: When you take $A^i B_j$, without any repeated indices, then, indeed, you're forming a $(1,1)$-tensor $C^i_{\;j} = A^i B_j$ with matrix
$$
 \begin{pmatrix} 2\\3\\4\end{pmatrix}\begin{pmatrix}1&2&3\end{pmatrix} = \begin{pmatrix}2&4&6\\3&6&9\\4&8&12\end{pmatrix}.
$$
When you repeat an index, so that it appears both as a superscript and as a subscript, then you sum over that index; in particular, if $T^i_{\;j}$ is a $(1,1)$-tensor, then $T^i_{\;i}$ is precisely the trace of the corresponding matrix. Hence, in this case
$$
 A^i B_i = C^i_{\;i} = 2 + 6 + 12 = 20.
$$
On the other hand, given the repeated index, $A^i B_i = B_i A^i$ can also be interpreted as the linear functional (or covector) $B_j$ acting on the vector $A^i$ to yield a scalar:
$$
 B_i A^i = \begin{pmatrix}1&2&3\end{pmatrix}\begin{pmatrix} 2\\3\\4\end{pmatrix} = 1 \cdot 2 + 2 \cdot 3 + 3 \cdot 4 = 20.
$$
The nice thing about this notation, however, is that this interpretation is entirely consistent with the first interpretation---the whole system of subscripts (corresponding to covectors) and superscripts (corresponding to vectors) guarantees this. Again, the essential point is that you sum over an index that appears both as a subscript and as a superscript; this is a process called contraction over that index.


text:
Q: Pull MKAnnotation Subtitle from JSON Array I am trying to add a subtitle to my MKAnnotation by pulling it from a JSON array. I am able to get the title, and coordinates with my view controller like below, but I can't figure out what to do to get the subtitle to be pulled from the JSON key "cityName". Any help would be great! Thank you!
MapViewController.m
location.latitude = [dictionary[@"placeLatitude"] doubleValue];
location.longitude = [dictionary[@"placeLongitude"] doubleValue];

newAnnotation = [[MapViewAnnotation alloc] initWithTitle:dictionary[@"placeName"]
                                               andCoordinate:location];

MapViewAnnotation.h
@interface MapViewAnnotation : NSObject <MKAnnotation> {
NSString *title;
CLLocationCoordinate2D coordinate;
}

@property (nonatomic, copy) NSString *title;
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *subtitle;
- (id)initWithTitle:(NSString *)ttl andCoordinate:(CLLocationCoordinate2D)c2d;
@end

MapViewAnnotation.m
#import "MapViewAnnotation.h"
@implementation MapViewAnnotation
@synthesize title, coordinate, subtitle;

- (id)initWithTitle:(NSString *)ttl andCoordinate:(CLLocationCoordinate2D)c2d {
title = ttl;
coordinate = c2d;
subtitle = [SUBTITLE PULLED FROM JSON]
return self;
}
@end

A: What's the problem here ? Just do exactly what you're doing with the title property.

A: Since there might be situations where you don't initialize every single property your annotation has I'd advise against putting them all into the init method.
Just do this and you won't need to change MapViewAnnotation.m or h
location.latitude = [dictionary[@"placeLatitude"] doubleValue];
location.longitude = [dictionary[@"placeLongitude"] doubleValue];

newAnnotation = [[MapViewAnnotation alloc] initWithTitle:dictionary[@"placeName"]
                                           andCoordinate:location];
newAnnotation.subtitle = dictionary[@"cityName"];


text:
Q: Best Way to Access Hardware per COM Serial Port over USB Adapter We are starting a total new Branch at our firm. I am usually developing database interfaces or internal server/client applications/tools for our company, but I never had to do something with hardware.
Szenario
My Boss want to sell a device, which has a touch-screen to set up the many, many features. However, the configuration of the device can be very time consuming. He wants to give a software free for a good customer and for a litte charge to "small" customers. The customer should only be able to use the software, if he registers at our system, so that he can't copy the software without a notice by us.
Requirements
The device has a build in USB cable. If you plug it in your computer it opens a new COM serial port. The software has the following requirements:

*

*Configurating different presents for the device

*Reading and writing the presets to the device

*Software will refuse to start, if the user has no registration at our server

*The user can store his presets at our server and share it with other customers

*One preset, copied over and over to multiple devices

My boss has seen similar system (he said something about logitech harmony remote controls) and it is now on me, to create the architecture.
Server Side:
The server is not that kind of problem. We have enough different machines to suite any kind of favour (IIS, LAMPP, Apache/Tomcat etc.) I could take MSSQL or MySQL DBase to store the data, thats not the problem.
Client Side:
This is the tricky part for me. I never did something with hardware. My boss suggested I should use Silverlight. I claimed that I want to do it with a native application. But what is the best combination?

*

*Total Client-Side (C++, C# or Java are the languages I could write)

*Mixed Structure #1 Silverlight + Native "Driver" Application

*Mixed Structure #2 Java-Applet + Native "Driver" Application

*Browser Only - Silverlight or Java-Applet?

*Any other suggest

The device is for a special customer group who's getting personal trained with any purchase so security risks like unsafe code or dangerous browser plugins are no negative selling argument.
I did some research about COM Serial Port connection with Silverlight and P/Invoke but I don't want to start without a discussion what would be the best way.

A: Definitely stay away from Java applets and Silverlight. Both are tricky for users, error-prone, and their future is uncertain at best.
The only tricky part is the client.
For client, I'd take a well-supported cross-platform language. Unfortunately, you can't be sure that a runtime for such a language is readily available on a client machine. So bring it with you.
I'd take Ruby, Javascript (node.js), or Python. Either has a relatively compact runtime, and either allows to create an self-contained standalone app from your program. Accessing COM port should not be hard from any of them. Accessing your server, even easier.
Your client app will likely require a GUI. I'd go for a web UI: start a local web server, stop caring about cross-platform GUI toolkits and the like.
I'd build a version of a client for each major OS type (Windows, OSX, Linux) without much (if any) code modifications, and would distribute it with the device.
The server part is not tricky; use whatever technology you like. For the client-server protocol I'd use REST over HTTP(S); it has the fewest problems with any kinds of network setup, firewalls, etc. It also has excellent tools for troubleshooting.
Another tricky part is server-side authorization. It'd be best if your device had an unique ID, because your program would be much easier to crack than a hardware device.
I don't see why this is needed, though. It's the device that brings you profit. You can't sell more of your support software unless you sell more devices, and the support software is useless without a device. I'd just give the software away. Your software is not unlike a driver. See, graphics cards manufacturers allow to download their huge and sophisticated drivers for free, and feel fine. So will you.

A: If the device doesn't have a network interface of its own, then there are three machines to consider for the use-cases where the device needs to access your server. The three machines are your server, the device and the computer from the customer that the device is connected to.
The customer's computer must be considered, because it must act as a go-between in the data transfer between the sever and the device.
For the server side, it does not really matter what kind of technology you use, as long as there is a defined protocol for communicating with the device and your technology stack can handle that protocol.
For the device, you should use a technology that can run entirely on the device itself, as that allows some use-cases to be executed stand-alone.
For the customer's computer, you can use either a native or a browser-based solution, but for both you should consider which OS-es, respectively browsers are likely to be used by the customers and if you can support them all. For a native solution it might mean you would have to support several versions at the same time. Also, a browser-based solution might be considered more user-friendly.

A: I have done plenty of serial comms work over the years, and writing a native application is the way to go.  It allows you to properly install the application and ensure it has sufficient OS privileges to access the COM port, rather than praying that the user's web browser is configured to even prompt the user to allow access.
You do need to consider some error conditions, such as the device being removed whilst you are in the serial comms code, but this is a viable route.

Question for you though, Why sell the devices un-configured and expect the customer to configure them, which means that they will generate lots of support questions when the process goes less than smoothly.
Why not preconfigure before you ship the device? There are bound to be things that you can do internally to simplify the configuration process when you are able to control the installation environment.


text:
Q: Using DisplayTag library, I want to have the currently selected row have a unique custom class using the TableDecorator I have been trying to figure out how to highlight the selected row in a table. In my jsp I have jsp scriplet that can get access to the id of the row the displaytag library is creating.  I want to compare it to the the id of the current row selected by the user ${currentNoteId}.  Right now if the row id = 849 (hardcoded) the class "currentClass" is added to just that row of the table.  I need to change the 849 for the {$currentNoteId} and I don't know how to do it.  I am using java, Spring MVC.  The jsp:
...
<%
request.setAttribute("dyndecorator", new org.displaytag.decorator.TableDecorator()
{
   public String addRowClass()
   {
      edu.ilstu.ais.advisorApps.business.Note row =
      (edu.ilstu.ais.advisorApps.business.Note)getCurrentRowObject();
            String rowId = row.getId();
            if ( rowId.equals("849") ) {
                return "currentClass";
            }
            return null;
        }
    });
%>

<c:set var="currentNoteId" value="${studentNotes.currentNote.id}"/>
...
<display:table id="noteTable" name="${ studentNotes.studentList }" pagesize="20"
  requestURI="notesView.form.html" decorator="dyndecorator">
    <display:column title="Select" class="yui-button-match" href="/notesView.form.html"
      paramId="note.id" paramProperty="id">
      <input type="button" class="yui-button-match2" name="select" value="Select"/>
    </display:column>
    <display:column property="userName" title="Created By" sortable="true"/>
    <display:column property="createDate" title="Created On" sortable="true"
       format="{0,date,MM/dd/yy hh:mm:ss a}"/>
    <display:column property="detail" title="Detail" sortable="true"/>
</display:table>
...

This could also get done using javascript and that might be best, but the documentation suggested this so I thought I would try it.  I cannot find an example anywhere using the addRowClass() unless the comparison is to a field already in the row (a dollar amount is used in the documentation example) or hardcoded in like the "849" id.
Thanks for any help you can provide.

A: I went ahead and did it in javascript instead.  When I used the currentNoteId in the scriptlet like this:
String rowId = row.getId();
String noteId = (String) pageContext.getAttribute("currentNoteId");
if ( rowId.equals( noteId ) ) {
    return "currentClass";
}
return null;

I received the error:  got error  Cannot refer to a non-final variable pageContext inside an inner class defined in a different method.
So instead I wrote:
function highlightCurrentTableRow(tableId, currentRowId ) {
    var table = document.getElementById(tableId);
    var rows = table.getElementsByTagName("tr");
    console.log( "rowId", "'" + currentRowId + "'" );
    for (i = 1; i < rows.length; i++) {
        rowId = rows[i].getElementsByTagName("td")[0].innerHTML;
        console.log( "  rowId", "'" + rowId + "'" );
        if ( rowId == currentRowId ) {
            console.log( "got here" );
            var rowClass = rows[i].getAttribute("class");
            rows[i].setAttribute("class", rowClass + " currentClass"   );
        };
    }
}

Actually this may not work in IE because of "class" is a key word so I used Yahoo YUI addClass(element, class) instead so I replaced
var rowClass = rows[i].getAttribute("class");
rows[i].setAttribute("class", rowClass + " currentClass"   );

with
YAHOO.util.Dom.addClass(rows[i],'currentClass');


text:
Q: Entity Framework many to many relationship and reach third table I am using fluent api to configure many to many relationship between Tags and Courses  in such way :
    HasMany(c => c.Tags)
            .WithMany(t => t.Courses)
            .Map(m =>
            {
                m.ToTable("CourseTags");
                m.MapLeftKey("CourseId");
                m.MapRightKey("TagId");
            });

Course has ICollection<Tag> Tags { get; set;} And Tag has ICollection<Course> Courses { get; set;}
However, what if i need to reach CourseTags table inside the code, something like this:
EFDbContext _db = new EFDbContext();
_db.CourseTags;

Should i create the third table mannualy :
Public class CourseTags{
CourseId...;
TagId
}

Or what is the best way to configure many to many relationship in entity framework? Would i ever need to reach the third table in code?


text:
Q: Python - kill hung process started using subprocess.Popen I've started a subprocess using:
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output = proc.communicate()[0]

Sometimes the command cmd hangs so my Python script also hangs at this point.
I'd like to let this run for a time (10 seconds?) and if I don't get a response, then simply kill the process and continue on with my script.
How can I do this?

A: If you're using python 3, Popen.communicate has a timeout kwarg:
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output = proc.communicate(timeout=10)[0]

A: From subprocess documentation proc.terminate() is what you 're looking for


text:
Q: read json data from text file according to my conditions here is my jason text file containing more than two json object having different policyNumber i want to read data on the base of policyNumber or may be another value and it show only those json object having same parameters that i request or say same policy number i sent to them.
I am working on API so i have no idea about this and i am also fresher in it field
no idea about how to return values.
plese guide and thanks in advance
my jason text file contain
{
  "jsonData": {
    "PolicyValue": {
      "PolicyNumber": "003",
      "EffectiveDate": "2022-09-14",
      "MCV_NetBaseCashValue": 9700,
      "Dividend": 0,
      "DividendsInterest": 0,
      "CouponBalance": 0,
      "CouponBalancesInterest": 0,
      "BaseCashValue": 700,
      "CashSurrenderValue": 00,
      "APLAmount": 0,
      "APLAmountsInterest": 0,
      "OPLAmount": 0,
      "OPLAmountsInterest": 0,
      "MiscellaneousSuspense": 0,
      "PremiumSuspense": 0,
      "OutstandingDisbursement": 0,
      "SurrenderCharge": 0
    }
  },
  "reponseCode": "00",
  "reponseMessage": ""
}

{
  "jsonData": {
    "PolicyValue": {
      "PolicyNumber": "123",
      "EffectiveDate": "2022-08-17",
      "MCV_NetBaseCashValue": -100,
      "Dividend": 0,
      "DividendsInterest": 0,
      "CouponBalance": 0,
      "CouponBalancesInterest": 0,
      "BaseCashValue": 100,
      "CashSurrenderValue": -100,
      "APLAmount": 0,
      "APLAmountsInterest": 0,
      "OPLAmount": 0,
      "OPLAmountsInterest": 0,
      "MiscellaneousSuspense": 0,
      "PremiumSuspense": 0,
      "OutstandingDisbursement": 0,
      "SurrenderCharge": 200
    }
  },
  "reponseCode": "00",
  "reponseMessage": ""
}

this is my first file
and my second file is
{
 "jsonData": {
 "PolicyNumber": "354",
  "PolicyCommencementDate": "2020-07-31",
  "InsuranceDetails": [ {

 "PolicyNumber": "54",
   "ClientID": "04",
    "InsuredFirstName": "LEÄ",
   "InsuredLastName": "HAÈNG",
    "InsuredDOB": "1978-01-01"
  },

  {
   "PolicyNumber": "54",
    "ClientID": "09",
    "InsuredFirstName": " YEÂN",
  "InsuredLastName": "NG",
    "InsuredDOB": "2006-11-08"
  } ]

  },
 "reponseCode": "00",  "reponseMessage": ""

 }
{
  "jsonData": {
    "PolicyNumber": "737",
    "PolicyCommencementDate": "2019-07-25",
    "InsuranceDetails": [
      {
        "PolicyNumber": "37",
        "ClientID": "15",
        "InsuredFirstName": "N HAÛI",
        "InsuredLastName": "ANH",
        "InsuredDOB": "1989-10-04"
      },
      {
        "PolicyNumber": "37",
        "ClientID": "25",
        "InsuredFirstName": "NH",
        "InsuredLastName": "AÁN",
        "InsuredDOB": "1988-01-04"
      },
      {
        "PolicyNumber": "37",
        "ClientID": "26",
        "InsuredFirstName": "RUÙC",
        "InsuredLastName": "DNG",
        "InsuredDOB": "2021-05-17"
      }
    ]
  },
  "reponseCode": "00",
  "reponseMessage": ""
}

i want to apply on the base of get request please solve this issue as soon as possible
i teried this code in my value controller
  public class ValuesController : ApiController
    {
        string[] fileConten = Directory.GetFiles(HostingEnvironment.MapPath(@"~/Documents/V1/policy/seachpolicy"));

     public string Get()
        {

            string writeResult = string.Empty;
            string strr = File.ReadAllText(fileConten[2]);
            JObject jsonObj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(strr);

            var jobj = JObject.Parse(jsonObj.ToString());

            foreach (var item in jobj.Properties())
            {
                item.Value = item.Value["PolicyNumber"].ToString();
                //item.Value = item.Value.SelectToken["PolicyValue"][0]["PolicyNumber"].ToString();
                //item.Value = item.Value["PolicyNumber"][0]["InsuranceDetails"]["InsuredFirstName"].ToString();
                int nm = Convert.ToInt32(item.Value);
                if (nm == 008019354)
                {
                    writeResult = jobj.ToString();
                    break;
                }
                break;
                //item.Value = item.Value.ToString().Replace("0", "1");
            }

            return writeResult;

            string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
            return output;

    this code not work properly

        }


text:
Q: scrollHeight not working with position:absolute I am trying to retrieve the body's scrollHeight in order to reset the size of a div with id="background1".  If in my external css I set that id to position:absolute the scrollHeight always returns 0.  If I set it to position:relative scrollHeight gives me the correct value.  There are of course many more selectors in the css one other of which is set to position:absolute - leaving it as such doesn't change the above behavior.  The code :
<script type="text/javascript">

  function getElement(elem)  {

     var art;

     if ( document.all ) {                  // this is the way old msie versions work
       art = document.all[elem];
     }
     else if ( document.layers ) {          // this is the way nn4 works
       art = document.layers[elem];
     }
     else if ( document.getElementById ) {  // this is the way the standards work
       art = document.getElementById( elem );
     }

     return art;
}

function toggleArticleDisplay(elem)  {

  var artArray = document.getElementsByTagName("article");

  for(var i = 0; i < artArray.length; i++)  {
     artArray[i].style.display = "none";
   }

   var art = getElement(elem);
   art.style.display = "block";

   var bg1 = document.getElementById("background1");
   bg1.style.height = "550px";

   var b = document.getElementById("potoococha");

   alert(b.scrollHeight);

   bg1.style.height = (b.scrollHeight >= window.innerHeight) ?
           (b.scrollHeight+20) + "px" : window.innerHeight + "px";
 }

</script>

</head>

<body id="potoococha" onLoad="toggleArticleDisplay('homeText')">

<div id="background1" style="height:615px;"/>

And now the css :
div#background1  {  position         : absolute;
                    left             : 45px;
                    top              : 0px;
                    z-index          : 1;
                    width            : 50px;
                    background-color : rgba(182,181,91,1.0); }

Merely changing that position to relative makes the javascript function return the correct scrollHeight but I need this as absolute for other reasons.  Does scrollHeight not work if some element is absolutely positioned?  As I said there is another later absolutely positioned element which doesn't have any effect on scrollHeight's return value.  Only this element which is the first child of the body element seems to be a problem.  Any ideas?

A: This is kinda a dirty hack, but you could try to do this:
bg1.style.position = "relative";

var savedHeight = b.scrollHeight;

bg1.style.position = "absolute";

Not sure if that'll work, but maybe give it a try.

A: I've solved the issue controlling the variable
document.scrollingElement.scrollHeight

instead of
document.body.scrollHeight