text:
Q: nodeJs soap libarary can not send request to wsdl url I Have a SOAP API like https://example.com/TokenService?wsdl,
i send a request to create Client in below function  :
let soap = require('soap');
   soap.createClient(url, function(err, client) {
       console.log('err is ',err) ;
        client.myFunction(input_params, function(err, result) {
            console.log(result);

        });
    });

Then i get an error like this:

Error: ENOENT: no such file or directory, open 'https:///example.com//TokenService?wsdl'
    errno: -2,
    code: 'ENOENT',
    syscall: 'open',
    path: 'https://example.com/TokenService?wsdl`

And my client is undefiend.

A: I think you're very nearly there. Here's an example of a call you can test:
const soap = require('soap');

const url = 'http://www.webservicex.net/globalweather.asmx';
const wsdlURL = 'http://www.webservicex.net/globalweather.asmx?WSDL';

soap.createClient(wsdlURL, {endpoint: url}, function(error, client) {
    if (error) {
        console.error(error);
    } else {
        client.GetCitiesByCountry({ CountryName: 'Russian Federation'}, function(error, result) {
            if (error) {
                console.error(error);
                process.exit(1);
            }
            console.log(result);
        });
    }
});

I think you may just need to pass two urls to the function, the service url and the WSDL url. Sometimes you don't need to do this and the WSDL will contain the links to all the operation URLs. Some calls will work if you omit the {endpoint: url } option, and some won't.
Also check the WSDL link, ensure the WSDL is valid, you can look at it in your browser, it should look like this:
http://www.webservicex.net/globalweather.asmx?WSDL
You can also download the WSDL to a file and try that:
"use strict";

const wsdlFileName = 'globalweather.wsdl';
const path = require('path');
const wsdlFile = path.join(__dirname, wsdlFileName);

const soap = require('soap');

const url = 'http://www.webservicex.net/globalweather.asmx';

soap.createClient(wsdlFile, {endpoint: url}, function(error, client) {
    if (error) {
        console.error(error);
    } else {
        client.GetCitiesByCountry({ CountryName: 'Russian Federation'}, function(error, result) {
            if (error) {
                console.error(error);
                process.exit(1);
            }
            console.log(result);
        });
    }
});

You need to put the WSDL file in the same directory as your script.
I get can this working in a C# client, the XML POST looks like this:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <reservation xmlns="http://token.ws.web.cnpg/">
            <Token_param xmlns="">
                <AMOUNT>amount</AMOUNT>
                <CRN>crn</CRN>
                <MID>mid</MID>
                <REFERALADRESS>referaladdress</REFERALADRESS>
                <SIGNATURE>signature</SIGNATURE>
                <TID>tid</TID>
            </Token_param>
        </reservation>
    </s:Body>
</s:Envelope>

And the response:
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <ns2:reservationResponse xmlns:ns2="http://token.ws.web.cnpg/">
            <return>
                <result>3</result>
                <token>Security check was not successful.</token>
            </return>
        </ns2:reservationResponse>
    </S:Body>
</S:Envelope>

I can do a POST to the address by doing the following:
var request = require('request');
var url = 'https://example.com/TokenService';
var tokenXML = `<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
        <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <reservation xmlns="http://token.ws.web.cnpg/">
                <Token_param xmlns="">
                    <AMOUNT>amount</AMOUNT>
                    <CRN>crn</CRN>
                    <MID>mid</MID>
                    <REFERALADRESS>referaladdress</REFERALADRESS>
                    <SIGNATURE>signature</SIGNATURE>
                    <TID>tid</TID>
                </Token_param>
            </reservation>
        </s:Body>
    </s:Envelope>`;

console.log('Posting..')
console.log(tokenXML);
request.post(
    {url: url,
    body : tokenXML,
    headers: {'Content-Type': 'text/xml'}
    }, function optionalCallback(err, httpResponse, body) {
  if (err) {
    return console.error('upload failed:', err);
  }
  console.log('Upload successful!  Server responded with:', body);
});

For some reason the NPM soap library does not like this webservice!
But you could fill in the values in the XML yourself, it might get you a bit further if you have the details you need to fill.
I'm getting the response:
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <ns2:reservationResponse xmlns:ns2="http://token.ws.web.cnpg/">
            <return>
                <result>3</result>
                <token>Security check was not successful.</token>
            </return>
        </ns2:reservationResponse>
    </S:Body>
</S:Envelope>

But I don't the the username password maybe. If you can fill in these details maybe you will get a successful response. You need to do an NPM install request BTW to get the request library.


text:
Q: Add event listener to multiple generated elements I'm trying to make Tic-Tac-Toe for my school in pure JS and based on CSS and HTML GUI. I know it's probably not the best approach, but I thought it may work. Unfortunately, it doesn't work at all.
I'm trying to generate whole board by JS in Board.generate(), because I want to make my board resizeable, and then add event listeners to every generated cell, but this isn't working. Onclick is called only on the last element and not on the previous ones. I think I could bypass this problem by making a function, but I want to understand why my code doesn't work.
Here's my code:

class Board {
  constructor(size) {
    this.size = size;

    this.cells = [];
    for (let x = 0; x < size; x++) {
      this.cells[x] = [];
      for (let y = 0; y < size; y++) {
        this.cells[x][y] = new Cell(x, y, null);
      }
    }
  }

  generate() {
    document.getElementById('game').innerHTML = '

';

    let boardEl = document.getElementById('board');

    for (let y = 0; y < this.size; y++) {
      boardEl.innerHTML += '

';
      let rowEl = document.getElementById('r' + y);

      for (let x = 0; x < this.size; x++)
        this.cells[x][y].addElement(rowEl);
    }
  }
}

class Cell {
  constructor(x, y, mark) {
    this.x = x;
    this.y = y;
    this.mark = mark;
    this.id = 'c' + x + y;
    this.element = null;
  }

  addElement(rowEl) {
    rowEl.innerHTML += '
 CELL
';
    this.element = document.getElementById(this.id);
    this.element.addEventListener('click', () => this.clicked(), false);
  }

  clicked() {
    console.log(this.x, this.y, ' CLICKED!');
  }
}

window.onload = function () {
  var game = new Board(3);
  game.generate();
};

I know my code is a mess right now, but I was just frustrated, and it's only a sketch, I'll work on it.
Also, sorry for my English if I made some mistakes.

A: Any time you set the innerHTML property you are overwriting any previous HTML that was set there. This includes concatenation assignment, because
element.innerHTML += 'Hello';

is the same as writing
element.innerHTML = element.innerHTML + 'Hello';

This means all handlers not attached via HTML attributes will be "detached", since the elements they were attached to no longer exist, and a new set of elements has taken their place. To keep all your previous event handlers, you have to append elements without overwriting any previous HTML. The best way to do this is to use DOM creation functions such as createElement and appendChild:
let divEl  = document.createElement("div");
divEl.innerHTML = "CELL";
divEl.className = 'board-cell'
divEl.id = this.id;
rowEl.appendChild(divEl);

The same is for row div elements:
let divRowEl  = document.createElement("div");
divRowEl.className = 'board-row'
divRowEl.id = 'r' + y;
boardEl.appendChild(divRowEl);

class Board {
  constructor(size) {
    this.size = size;

    this.cells = [];
    for (let x = 0; x < size; x++) {
      this.cells[x] = [];
      for (let y = 0; y < size; y++) {
        this.cells[x][y] = new Cell(x, y, null);
      }
    }
  }

  generate() {

    document.getElementById('game').innerHTML = '

';

    let boardEl = document.getElementById('board');

    for (let y = 0; y < this.size; y++) {
      let divRowEl  = document.createElement("div");
      divRowEl.className = 'board-row'
      divRowEl.id = 'r' + y;
      boardEl.appendChild(divRowEl);
      let rowEl = document.getElementById('r' + y);

      for (let x = 0; x < this.size; x++)
        this.cells[x][y].addElement(rowEl);
    }
  }
}

class Cell {
  constructor(x, y, mark) {
    this.x = x;
    this.y = y;
    this.mark = mark;
    this.id = 'c' + x + y;
    this.element = null;
  }

  addElement(rowEl) {
    let divEl  = document.createElement("div");
    divEl.innerHTML = "CELL" + this.id;
    divEl.className = 'board-cell'
    divEl.id = this.id;
    divEl.addEventListener('click', () => this.clicked(), false);
    rowEl.appendChild(divEl);
  }

  clicked() {
    console.log(this.x, this.y, ' CLICKED!');
  }
}

window.onload = function () {
  var game = new Board(3);
  game.generate();
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get next page link in python beautifulsoup? I have this link:
http://www.brothersoft.com/windows/categories.html

I am trying to to get the link for the item inside the div.
Example:
http://www.brothersoft.com/windows/mp3_audio/midi_tools/

I have tried this code:
import urllib
from bs4 import BeautifulSoup

url = 'http://www.brothersoft.com/windows/categories.html'

pageHtml = urllib.urlopen(url).read()

soup = BeautifulSoup(pageHtml)

sAll = [div.find('a') for div in soup.findAll('div', attrs={'class':'brLeft'})]

for i in sAll:
    print "http://www.brothersoft.com"+i['href']

But I only get output:
http://www.brothersoft.com/windows/mp3_audio/

How can I get output that I needed?

A: Url http://www.brothersoft.com/windows/mp3_audio/midi_tools/ is not in tag <div class='brLeft'>, so if output is http://www.brothersoft.com/windows/mp3_audio/, that's correct.
If you want to get the url you want, change
sAll = [div.find('a') for div in soup.findAll('div', attrs={'class':'brLeft'})]

to
sAll = [div.find('a') for div in soup.findAll('div', attrs={'class':'brRight'})]

UPDATE:
an example to get info inside 'midi_tools'
import urllib
from bs4 import BeautifulSoup

url = 'http://www.brothersoft.com/windows/categories.html'
pageHtml = urllib.urlopen(url).read()
soup = BeautifulSoup(pageHtml)
sAll = [div.find('a') for div in soup.findAll('div', attrs={'class':'brRight'})]
for i in sAll:
    suburl = "http://www.brothersoft.com"+i['href']    #which is a url like 'midi_tools'

    content = urllib.urlopen(suburl).read()
    anosoup = BeautifulSoup(content)
    ablock = anosoup.find('table',{'id':'courseTab'})
    for atr in ablock.findAll('tr',{'class':'border_bot '}):
        print atr.find('dt').a.string      #name
        print "http://www.brothersoft.com" + atr.find('a',{'class':'tabDownload'})['href']   #link


text:
Q: Error when trying to create a print function I have been following the How to Print Text tutorial on the Oracle Java Documentation website. However when I have tried to implement some of the code into my code I get an error.
javac PrintableForms.java
PrintableForms.java:165: error: incompatible types: PrintableForms cannot be converted to Component
JOptionPane.showMessageDialog(this, msg, "Printing", type);

My code is
import javax.swing.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.print.PrinterException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.*;
import java.text.MessageFormat;
import javax.xml.transform.Source;

public class PrintableForms
{
    JFrame myMainWindow = new JFrame("This is my title");

    JPanel  firstPanel = new JPanel();

    JButton btnDoc1 = new JButton();
    JButton btnP1 = new JButton();

    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String []fontFamilies = ge.getAvailableFontFamilyNames();
    Font FontT5 = new Font("SansSerif", Font.BOLD, 50);
    ///////////
    JCheckBox backgroundCheck = new JCheckBox();
    JCheckBox interactiveCheck = new JCheckBox();
    JTextArea text = new JTextArea();
    JTextField headerField = new JTextField();
    JTextField footerField = new JTextField();

    public void runGUI()
    {
        myMainWindow.setBounds(10, 10, 1200, 500);
        myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        myMainWindow.setLayout(new GridLayout(1,1));

        createFirstPanel();

        myMainWindow.getContentPane().add(firstPanel);

        myMainWindow.setVisible(true);
        load(text, "Athlete.txt");
    }

    public void createFirstPanel()
    {
        firstPanel.setLayout(null);

        btnDoc1.setLocation(10,120);
        btnDoc1.setSize(900,50);
        btnDoc1.setText("Update Personal Information");
        btnDoc1.setFont(FontT5);
        firstPanel.add(btnDoc1);

        btnP1.setLocation(910,120);
        btnP1.setSize(250,50);
        btnP1.setText("Print");
        btnP1.setFont(FontT5);
        btnP1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                print(evt);
            }
        });
        firstPanel.add(btnP1);

        footerField.setText("Page {0}");
        headerField.setText("Athlete Form");
        backgroundCheck.setSelected(true);
        interactiveCheck.setSelected(true);
    }

    private void load(JTextArea comp, String fileName) {
        try {
            comp.read(
                new InputStreamReader(
                    getClass().getResourceAsStream(fileName)),
                null);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void print(java.awt.event.ActionEvent evt)
    {
        MessageFormat header = createFormat(headerField);
        MessageFormat footer = createFormat(footerField);
        boolean interactive = interactiveCheck.isSelected();
        boolean background = backgroundCheck.isSelected();

        PrintingTask task = new PrintingTask(header, footer, interactive);
        if (background)
        {
            task.execute();
        }

        else
        {
            task.run();
        }
    }

    private class PrintingTask extends SwingWorker<Object, Object>
    {
        private final MessageFormat headerFormat;
        private final MessageFormat footerFormat;
        private final boolean interactive;
        private volatile boolean complete = false;
        private volatile String message;
        JTextArea text = new JTextArea();

        public PrintingTask(MessageFormat header, MessageFormat footer, boolean interactive)
        {
            this.headerFormat = header;
            this.footerFormat = footer;
            this.interactive = interactive;
        }

        @Override
        protected Object doInBackground() {
            try {
                complete = text.print(headerFormat, footerFormat,
                        true, null, null, interactive);
                message = "Printing " + (complete ? "complete" : "canceled");
            } catch (PrinterException ex) {
                message = "Sorry, a printer error occurred";
            } catch (SecurityException ex) {
                message =
                    "Sorry, cannot access the printer due to security reasons";
            }
            return null;
        }

        @Override
        protected void done() {
            message(!complete, message);
        }
    }

    private MessageFormat createFormat(JTextField source) {
        //String text = new Scanner( new File("Athlete.txt") ).useDelimiter("\\A").next();
        String text = source.getText();
        if (text != null && text.length() > 0) {
            try {
                return new MessageFormat(text);
            } catch (IllegalArgumentException e) {
                error("Sorry, this format is invalid.");
            }
        }
        return null;
    }

    private void message(boolean error, String msg)
    {
        int type = (error ? JOptionPane.ERROR_MESSAGE :
                            JOptionPane.INFORMATION_MESSAGE);
        JOptionPane.showMessageDialog(this, msg, "Printing", type);
    }

    private void error(String msg)
    {
        message(true, msg);
    }

    public static void main(String[] args)
    {
        PrintableForms pf = new PrintableForms();
        pf.runGUI();
    }
}

I am trying to get it so when I click a button, btnP1 in this case, it opens a dialog and then allows you to print off a pre-set document. In this code that document is Athlete.txt and all it reads is This is a test
I would any help in fixing this problem, Thanks

A: you should extends Component class or create Component type object and pass as argument instead of this because
JOptionPane.showMessageDialog(this, msg, "Printing", type);
first argument is of Component Type and you are passing parameter of type PrintableForms as this .

A: You could pass on the frame object which is the main window that you created when you want to show the dialog window.
Like below.
JOptionPane.showMessageDialog(myMainWindow, msg, "Printing", type);

A: Try implementing the Printable interface.


text:
Q: Sort excel data which is in short notations example 190B, 1.2K ,1.35M , 2.24B, 1000 How can I sort such data How to sort below data in excel in descending order
19.42B
86.40M
7.65B
6.09B
6.59B
1.2M
100

A: You will need a helper column that converts the text to their equivalent number then sort both columns on that new column.
Use this formula to get the number equivalent:
=IFERROR(LEFT(A1,LEN(A1)-1)*10^(MATCH(RIGHT(A1,1),{"K","M","B","T"},0)*3),A1)

Then sort on the new column:


text:
Q: Making authorised requests from Google Cloud Build I'm trying to set up a deployment street in Google Cloud Build. To do this, I want to:

*

*Run unit test

*Deploy to Cloud Run without traffic

*Run integration tests

*Migrate traffic in Cloud Run

I've got this mostly set up, but my integration tests include a couple of calls to Cloud Run to validate that authenticated calls return 200 and unauthenticated return 401. The thing I'm having difficulties with is to make signed requests from Cloud Build. When deploying by hand and running integration tests, they work, but not from Cloud Build.
Ideally, I would like to use the Cloud Build Service Account for invoking Cloud Run like I usually do in AWS, but I can't find how to get access to that from the Cloud Runner. So instead, I retrieve a credentials file from Secret Manager. This credentials file is from a newly created Service Account with Cloud Run Invoker role:
steps:
  - name: gcr.io/cloud-builders/gcloud
    id: get-github-ssh-secret
    entrypoint: 'bash'
    args: [ '-c', 'gcloud secrets version access latest --secret=name-of-secret > /root/service-account/credentials.json' ]
    volumes:
      - name: 'service-account'
        path: /root/service-account
...
  - name: python:3.8.7
    id: integration-tests
    entrypoint: /bin/sh
    args:
      - '-c'
      - |-
        if [ $_STAGE != "prod" ]; then
          python -m pip install -r requirements.txt
          python -m pytest test/integration --disable-warnings ;
        fi
    volumes:
      - name: 'service-account'
        path: /root/service-account

For the integration tests, I've created a class called Authorizer and I have __get_authorized_header_for_cloud_build and __get_authorized_header_for_cloud_build2 as attempts:
import json
import time
import urllib
from typing import Optional

import google.auth
import requests
from google import auth
from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account
import jwt

class Authorizer(object):
    cloudbuild_credential_path = "/root/service-account/credentials.json"

    # Permissions to request for Access Token
    scopes = ["https://www.googleapis.com/auth/cloud-platform"]

    def get_authorized_header(self, receiving_service_url) -> dict:
        auth_header = self.__get_authorized_header_for_current_user() \
                      or self.__get_authorized_header_for_cloud_build(receiving_service_url)
        return auth_header

    def __get_authorized_header_for_current_user(self) -> Optional[dict]:
        credentials, _ = auth.default()
        auth_req = google.auth.transport.requests.Request()
        credentials.refresh(auth_req)
        if hasattr(credentials, "id_token"):
            authorized_header = {"Authorization": f'Bearer {credentials.id_token}'}
            auth_req.session.close()
            print("Got auth header for current user with auth.default()")
            return authorized_header

    def __get_authorized_header_for_cloud_build2(self, receiving_service_url) -> dict:
        credentials = service_account.Credentials.from_service_account_file(
            self.cloudbuild_credential_path, scopes=self.scopes)
        auth_req = google.auth.transport.requests.Request()
        credentials.refresh(auth_req)
        return {"Authorization": f'Bearer {credentials.token}'}

    def __get_authorized_header_for_cloud_build(self, receiving_service_url) -> dict:
        with open(self.cloudbuild_credential_path, 'r') as f:
            data = f.read()
        credentials_json = json.loads(data)

        signed_jwt = self.__create_signed_jwt(credentials_json, receiving_service_url)
        token = self.__exchange_jwt_for_token(signed_jwt)
        return {"Authorization": f'Bearer {token}'}

    def __create_signed_jwt(self, credentials_json, run_service_url):
        iat = time.time()
        exp = iat + 3600
        payload = {
            'iss': credentials_json['client_email'],
            'sub': credentials_json['client_email'],
            'target_audience': run_service_url,
            'aud': 'https://www.googleapis.com/oauth2/v4/token',
            'iat': iat,
            'exp': exp
        }
        additional_headers = {
            'kid': credentials_json['private_key_id']
        }
        signed_jwt = jwt.encode(
            payload,
            credentials_json['private_key'],
            headers=additional_headers,
            algorithm='RS256'
        )
        return signed_jwt

    def __exchange_jwt_for_token(self, signed_jwt):
        body = {
            'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
            'assertion': signed_jwt
        }
        token_request = requests.post(
            url='https://www.googleapis.com/oauth2/v4/token',
            headers={
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            data=urllib.parse.urlencode(body)
        )
        return token_request.json()['id_token']

So when running locally, the __get_authorized_header_for_current_user is being used and works. When running in Cloud Build, __get_authorized_header_for_cloud_build is used. But even when temporarily disabling __get_authorized_header_for_current_user and let cloudbuild_credential_path reference to a json-file on my local pc, it keep getting 401s. Even when I give the service account from the credentials-file Owner rights. Another attempt is __get_authorized_header_for_cloud_build where I try to get the token more by myself instead of a package, but still 401.
For completeness, the integration test look somewhat like this:
class NameOfViewIntegrationTestCase(unittest.TestCase):
    base_url = "https://**.a.run.app"
    name_of_call_url = base_url + "/name-of-call"

    def setUp(self) -> None:
        self._authorizer = Authorizer()

    def test_name_of_call__authorized__ok_result(self) -> None:
        # Arrange
        url = self.name_of_call_url

        # Act
        response = requests.post(url, headers=self._authorizer.get_authorized_header(url))

        # Arrange
        self.assertTrue(response.ok, msg=f'{response.status_code}: {response.text}')

Any idea what I'm doing wrong here? Let me know if you need any clarification on something. Thanks in advance!

A: Firstly, your code is too complex. If you want to leverage the Application Default Credential (ADC) according with the runtime environment, only these lines are enough
from google.oauth2.id_token import fetch_id_token
from google.auth.transport import requests
r = requests.Request()
print(fetch_id_token(r,"<AUDIENCE>"))

On Google Cloud Platform, the environment service account will be used thanks to the metadata server. On your local environment,  you need to set the environment variable GOOGLE_APPLICATION_CREDENTIALS with as value the path of the service account key file
Note: you can generate id_token only with service account credential (on GCP or on your environment), it's not possible with your user account

The problem here, it's that doesn't work on Cloud Build. I don't know why, but it's not possible to generate an id_token with the Cloud Build metadata server. So, I wrote an article on this with a possible workaround


text:
Q: Multiline textbox in OSAScript I am wanting to edit the TestFlightApp archive script so that when it prompts for release notes it will be a bigger textbox than just one line. Right now it displays the size of one line but will allow me to press CTRL+J to add multiple lines.
However my issue is trying to see what I have typed is a pain as I can only view one line at a time.
Here is what I have.
# Bring up an AppleScript dialog in Xcode to enter the Release Notes for this (beta) build:
NOTES=`osascript -e "tell application \"Xcode\"" -e "set notes_dialog to display dialog \"Please provide some release notes:\nHint: use Ctrl-J for New Line.\" default answer \"\" buttons {\"Next\"} default button \"Next\" with icon 1" -e "set notes to text returned of notes_dialog" -e "end tell" -e "return notes"`

A: It's not possible, text field of display dialog in Xcode or Automator can't be resized.
But this is possible using the display dialog of osax "StandardAdditions".
Try this.
notes=`osascript -e "tell application \"Dock\"" -e "activate" -e "display dialog \"Please provide some release notes.\" default answer \"\r\r\r\r\r\r\r\r\r\" buttons {\"Next\"} default button \"Next\" with title \"Xcode\"" -e "set notes to text returned of the result" -e "end tell" -e "set {tid, text item delimiters} to {text item delimiters, \"\n\"}" -e "set r to (paragraphs of notes) as string" -e "set text item delimiters to tid" -e "activate application \"Xcode\"" -e "return r"`

The text field show 9 lines.
To add a line: press the return key.
If you have more than 9 lines, you can scroll with (the arrow key, page key or the mouse).
The script convert carriage returns to newlines and it doesn't return the trailing blank lines.


text:
Q: Python audiolab install, unable to install (or find) libsndfile on Mac OSX Trying to install scikits.audiolab-0.11.0 on Mac, bit it requires libsndfile: http://www.mega-nerd.com/libsndfile/. I did install libsndfile supposedly, using libsndfile_python-1.0.0-py2.7-macosx10.5.mpkg, but the audiolab setup gives an error: libsndfile library not found. The error from the audiolab installer is below. It suggests that the location of the libsndfile can be specified in the site.cfg.
My inexperience with these type of installs are getting in the way of understanding this. Can anyone offer some advice on how to get this done?, or answer my questions below?

*

*If the libsndfile was installed, where would it be, so I can specify the location? Else how to install it properly?

*What is the site.cfg file? I see a site.cfg.bdist_wininst, and a site.cfg.win32 in the scikits.audiolab-0.11.0 folder that I downloaded.

*What is meant by "specified in the site.cfg file in section [sndfile]" (see error below). Does this mean that I should replace the word "sndfile" with the /path/to/libsndfile between the brackets?

By the way, I checked in my /usr/lib dir and there is no libsndfile. I take it that there is where the audiolab setup will look for the file, by default.
Thanks for reading, and any help.
Error from audiolab installer:
numpy.distutils.system_info.NotFoundError: sndfile (http://www.mega-nerd.com/libsndfile/) library not found.
Directories to search for the libraries can be specified in the
site.cfg file, in section [sndfile].

A: libsndfile_python sounds like a binding to libsndfile rather than libsndfile itself. You probably do not have libsndfile installed. It should, however, be quite easy to install if you already have the developer tools installed:

*

*First, download the latest source.

*Unpack it somewhere.

*Open Terminal and cd to the directory you unpacked.

*Configure it: ./configure

*Build it: make -j8

*Install it (requires administrative rights): sudo make -j8 install
You can then delete the directory you unpacked, but you may want to keep it for easy uninstallation.

A: To install libdsnd in a mac (Tested in a Yosemite 10.10.3):
1- Install Homebrew (paste this on a terminal):
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
2- Install libsnd:
    brew install libsndfile

3- Link libsnd:
    brew link --overwrite libsndfile

4- Install scikits.audiolab:
    sudo easy_install scikits.audiolab

There you go!

A: For windows users:
Download file :
"scikits.audiolab‑0.11.0‑cp27‑cp27m‑win32.whl"

from "https://www.lfd.uci.edu/~gohlke/pythonlibs/#scikits.audiolab"
Install it using command : pip install scikits.audiolab‑0.11.0‑cp27‑cp27m‑win32.whl
install libsndfile from http://www.mega-nerd.com/libsndfile/ using setup:
http://www.mega-nerd.com/libsndfile/files/libsndfile-1.0.28-w32-setup.exe

copy "libsndfile-1.dll" from C:\Program Files (x86)\Mega-Nerd\libsndfile\bin
to folder Lib\site-packages\scikits\audiolab folder within your Python installation folder,
ex: C:\Python2711\Lib\site-packages\scikits\audiolab
For me this solved a problem.
Credits to "https://github.com/cournape/audiolab/issues/7" - "samuelgarcia"


text:
Q: List all object methods of MyTypes::Object class created by wsdl2perl After successfully building my interface with wsdl2perl, I'm looking to retrieve data of this web service but in a generic way.
I'm a newbie with SOAP and WSDL, I plowed thru google/CPAN and of course right here on the Stack, how to get data out via the Web Service API and I prefer Perl! After considering the following options:

*

*SOAP::Lite

*SOAP::WSDL (and yes! My Web Service provide does have a clean wsdl)

*wsdl2perl!

*stubmaker

I opted for option 3, (Was that correct choice ?)
I'm looking to get ALL the data returned by the Web Service which returns an array where not all individual attributes of the original class would always be present (pending if it was in the returned XML). I could use as_hash_ref! as follows:
my $h = $objects->get_return()->[0]->as_hash_ref();
print join ", " => keys %$h, "\n";

That gives me all the keys of the very first of the array, however, I assume, I'm not guaranteed that it would return all possible keys based on what was created by wsdl2perl in the MyTypes::Object.
I basically, am looking to get all the class methods of a class whose super class is of type: SOAP::WSDL::XSD::Typelib::ComplexType !
I tried to look for some hints in the class itself:
confess "Can't locate object method \"$_\" via package \"$class\". \n"
        . "Valid methods are: "
        . join(', ', map { ("get_$_" , "set_$_") } keys %{ $ATTRIBUTES_OF{ $class } })
        . "\n"

However digging further, I realize that $ATTRIBUTES_OF is filled by the call to __PACKAGE__->_factory and I'm stuck how to get all the getters of a given MyTypes::Object class created by wsdl2perl.
Simply put, I'm looking to generically iterate over all elements of the array returned by a Web Service, and print out (to csv file) all possible attributes of the MyTypes::Object class created by wsdl2perl.


text:
Q: Can't use FormData in UI material forms to fetch form field values I am just trying to post data from my UI-material form into backend.
I am using react hooks here.
Below is code that i am trying to do using simple fetch.
  const [name, setName] = useState ('');
  const [email_id, setEmail] = useState ('');
  const [subject, setSubject] = useState ('');

  const onSubmit = (e) => {
    e.preventDefault();
    const data = new FormData(e.target);
    console.log(data);
    fetch("http://127.0.0.1:8000/api/contact/", {
      method: "POST",
      body: data,
    })
      .catch((error) => console.log("Request failed", error));
  }

This is the material UI form which i am using
<form onSubmit={onSubmit}>
            <TextField
              autoComplete="new-password"
              id="outlined-basic"
              label="Full Name"
              variant="outlined"
              value={name}
              onChange={(e) => setName(e.target.value)}
              required
            />
            <TextField
              id="outlined-basic"
              label="Email Address"
              variant="outlined"
              autoComplete="new-password"
              value={email_id}
              onChange={(e) => setEmail(e.target.value)}
              required
            />
            <TextareaAutosize
              className="textbox"
              aria-label="minimum height"
              rowsMin={3}
              placeholder="Subject"
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
            />
            <button>Submit</button>
          </form>

While using with material UI form it gives me error that says
{"name":["This field is required."],"email_id":["This field is required."],"subject":["This field is required."]}

When i use normal html form it works perfectly fine. But when i try to do the same with material-UI form it doesnt work.
It will be really helpful if anyone can help.
Thanks in advance.

A: You need to set a name attribute to the input fields so they get submitted with the form.
In material-ui you can set name prop of the TextField and any other input field, for example:
<TextField
  autoComplete="new-password"
  id="outlined-basic"
  name="name"
  label="Full Name"
  variant="outlined"
  value={name}
  onChange={(e) => setName(e.target.value)}
  required
/>


text:
Q: Two Dell representatives told me that Windows 7 Ultimate allows multiple simultaneous remote desktop connections Read my subject...
I tried to achieve that with my computer, which has Windows 7 Ultimate.
I opened one Remote Desktop Client, logged successfully with User1.
I opened another RDC, but before login, Windows tells me that another user is currently logged on and must be disconnected before.
Is Dell representatives are lying to me? Which version of Windows ca

A: Desktop Windows editions have never allowed this and Windows 7 is no different. The Dell techs are simply mis-informed. There are third-party hacks out there to enable this functionality but I cannot personally vouch for their viability. They also most certainly violate Microsoft's Terms of Service and any support contracts you might have.

A: The PC being accessed (not the PC doing the accessing) must support multiple RDP sessions.
If you are trying to RDP to a remote machine and that REMOTE machine does not support multiple RDP sessions, it will inform you that you need to boot someone off.


text:
Q: onTouchListener() in Android not called after including ImageView from BaseActivity-XML The following code shows an abstract Activity (AppActivity), other Activities have to extend from. There is already a layout defined, but inherits nothing more then including a round button (extending ImageView).
MainActivity defines an own layout, which has to include the button mentioned before. Looking at my current results, the Button sucessfully is inherited and shown, can not be null
Nevertheless, the onTouchListener() attached to this ImageView never gets called from perspective "MainActivity". Note, that i return true if MotionEvent.ACTION_DOWN and UP occurs. So this cant be the cause. Any suggestions?
Abstract Activity with CircleButton (extends ImageView) inclusive onTouchListener()
public abstract class AppActivity extends Activity {

    public CircleButton circleButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.voice_btn_layout);

        circleButton = (CircleButton) findViewById(R.id.voiceControlBtn);

        circleButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.i("TOUCH", "");
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    ButtonGotPressed();
                    return true;
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    circleButton.ButtonGotReleased();
                    return true;
                }
                return false;
            }
        });
}

Activity extending from AppActivity
  public class MainActivity extends AppActivity implements ICadeCommand {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(eu.alfred.batterywarnerapp.R.layout.activity_main);
        }

activity_main.xml (for MainActivity)
<RelativeLayout .../>

    <include layout="@layout/voice_btn_layout" />

</RelativeLayout>

voice_btn_layout.xml (for AppActivity)
    <FrameLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="80dip"
            android:layout_height="80dip"
            android:layout_margin="15dip"
            android:layout_alignParentEnd="true"
            android:layout_alignParentBottom="true">

            <packagename.CircleButton
                ...
                android:scaleType="fitXY"/>

    </FrameLayout>

A: You are setting OnTouchListener for circleButton in R.layout.voice_btn_layout.
When you call setContentView() in MainActivity, you replace the layout R.layout.voice_btn_layout with eu.alfred.batterywarnerapp.R.layout.activity_main. Therefore the onTouch() method for circleButton in AppActivity is not called because the circleButton shown on the screen is not the same as the circleButton in AppActivity.
You can test if this is indeed the case by adding an extra line in AppActivity
public abstract class AppActivity extends Activity {

public CircleButton circleButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.voice_btn_layout);

    circleButton = (CircleButton) findViewById(R.id.voiceControlBtn);
    circleButton.setVisibility(View.GONE);     // ADD THIS LINE
    circleButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
        ...

You should notice that circleButton is still visible thus showing that the circleButton displayed on screen is not the same as the one in AppActivity.


text:
Q: Monaco Editor doesn't resize inside Splitpanes package.json (question related dependencies)
"dependencies": {
  "monaco-editor-webpack-plugin": "^1.9.1",
  "splitpanes": "^2.4.1",
  "vue-monaco": "^1.2.2"
}

vue.config.js
const MonacoEditorPlugin = require('monaco-editor-webpack-plugin')

module.exports = {
  transpileDependencies: [
    'vuetify'
  ],
  configureWebpack: {
    plugins: [
      new MonacoEditorPlugin({
        languages: ['javascript', 'typescript']
      })
    ]
  }
}

CodeEditor.vue
<template>
  <Splitpanes
    style="100vh"
    class="default-theme"
  >
    <Pane size="40">
      <!-- Very long text -->
    </Pane>
    <Pane size="60">
      <MonacoEditor
        style="width: 100%; height: 100%"
        v-model="code"
        theme="vs-dark"
        language="javascript"
        :options="options"
      />
    </Pane>
  </Splitpanes>
</template>

<script>
import { Splitpanes, Pane } from 'splitpanes'
import MonacoEditor from 'vue-monaco'
import 'splitpanes/dist/splitpanes.css'

export default {

  components: {
    Splitpanes,
    Pane,
    MonacoEditor
  },

  data () {
    return {

      code: 'const noop = () => {}',

      options: {
        automaticLayout: true
      }
    }
  }
}
</script>

Monaco Editor doesn't resize, even though I set automaticLayout to true. What am I doing wrong?
Note: With monaco-editor-vue and monaco-editor-webpack-plugin 1.8.2 everything works fine (but I can't use it because it doesn't support v-model).


text:
Q: C# Json parsing - array of objects and access array If I have a json array of objects, in python I'd be able to do
var arr = json.loads(string)

and then be able to access the first element (arr[0]).
However in C# when I parse the json string using either JsonConvert.DeserializeObject or JArray.Parse, it gets turned into an object:
{
  [
    {blah: ""},
    {blah: ""}
  ]
}

and so I can't access the first element, like how I would do it in python, because of the object surrounding the array.
I get the error:
 error CS0021: Cannot apply indexing with [] to an expression of type 'object'

Is there something I'm missing? Ideally I'd like to just be able to easily access the first element of the array of objects, without having to do any for loops, etc.

A: To achieve dynamic (run-time) typing as in Python just use dynamic:
var r = ((dynamic)JsonConvert.DeserializeObject("[1,2]"))[1]; // 2

Note that usually you would deserialize Json into strongly typed object and work with it, but that would be C# way and not Python-like you are asking about.


text:
Q: Loop displays last date value I have a calendar app. I want to loop through the current month to get all the events. The only problem is that the date displays of the last event for all the events.
It seems the date value of all the events is replaced by the date value of the last event.
   CalendarEvents events = new CalendarEvents();
   final ArrayList<Event> e = new ArrayList<Event>();

    for(int i = 0; i < _calendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++){
        if(isHoliday(i, month, year, date_value))
        {
            String date = i + "-" + month + "-" + year;

            e.addAll(events.eventDetails(month, day));
            summary_data = new Summary[e.size()];

            for (int j = 0; j < e.size(); j++)
            {

               Event event = e.get(j);
               summary_data[j] = new Summary(date, event.eventdetails);
            }
        }
    }

A: Yes, that's expected given the logic of the program.
You loop through the days. For each day, you add the events of the day to a list of events (the badly named e list). And for each day, you the loop through each events in this list (which thus contains all the events from the start of the month until the current day), and create an array of Summary instances, each summary containing the date of the current day, and the details of the event (whether it's a past event or an event of the current day).
The list of events doesn't seem useful. I would simply use a list of summaries:
final List<Summary> summaries = new ArrayList<Summary>();

// loop through the days
for (int i = 0; i < calendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
    if (isHoliday(i, month, year, date_value)) {
        String date = i + "-" + month + "-" + year;
        // loop through the events of the day
        for (Event event : events.eventDetails(month, day)) {
            // add a summary for the current day and the current event of the day
            summaries.add(new Summary(date, event.eventdetails));
        }
    }
}


text:
Q: jQuery loop though DOM elements and remove I have some HTML elements like so
<input type="hidden" name="combos[0][pics][01]">
<input type="hidden" name="combos[0][pics][02]">
<input type="hidden" name="combos[1][pics][01]">
<input type="hidden" name="combos[1][pics][02]">
<input type="hidden" name="combos[2][pics][01]">
<input type="hidden" name="combos[2][pics][02]">

How can I use jquery's $.each function to loop through these and remove each DOM element ending in [pics][02].

A: You could use ending with selector $= and the full selector could be simply like :
'input[type="hidden"][name$="[pics][02]'

And you don't need a loop :
$('input[type="hidden"][name$="[pics][02]').remove();

Calling the remove() function on the selector result will remove them all.
NOTE : As @David Thomas's comment says that could be done using pure JS like :
 document.querySelectorAll('input[type=hidden][name$="[pics][02]"').forEach((el)=>el.remove());

console.log('Length BEFORE remove : ' + $('input[type="hidden"]').length);

$('input[type="hidden"][name$="[pics][02]').remove();

console.log('Length AFTER remove : ' + $('input[type="hidden"]').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="hidden" name="combos[0][pics][01]">
<input type="hidden" name="combos[0][pics][02]">
<input type="hidden" name="combos[1][pics][01]">
<input type="hidden" name="combos[1][pics][02]">
<input type="hidden" name="combos[2][pics][01]">
<input type="hidden" name="combos[2][pics][02]">


text:
Q: wxPython: Calculator won't display value in Textctrlenter I am working on a Calculator using wxPyhton. I'm having trouble on displaying the value in a Textctrlenter.
self.nameTxt = wx.TextCtrl( self, wx.ID_ANY,"",pos=(10,20),size=(260,30))

self.clickcount1 = 1
one = self.clickcount1

getBtn = wx.Button(self, self.clickcount1,label="1",pos=(10,60),size(40,40))
btn.Bind(wx.EVT_BUTTON, lambda btnClick, temp=button_name:
self.OnButton(btnClick(1), temp) )

A: Your lamba function is incorrect.
The size(40,40) parameter in getBtn, should be size=(40,40)
The Bind should be on getBtn not btn
The variable one is not used at all
You're using self.clickcount as the button id, don't, use -1 or wx.ID_ANY and wxpython will generate a unique id for you.
I assume that you are trying to do something like this:
import wx

class TestFrame(wx.Frame):
    def __init__(self, *args):
        wx.Frame.__init__(self, *args)
        self.nameTxt = wx.TextCtrl( self, wx.ID_ANY,"",pos=(10,20),size=(260,30))
        getBtn1 = wx.Button(self, id=-1, label="1", pos=(10,60), size=(40,40))
        getBtn1.Bind(wx.EVT_BUTTON, lambda event: self.OnButton(event, button=1) )
        getBtn2 = wx.Button(self, id=-1, label="2", pos=(50,60), size=(40,40))
        getBtn2.Bind(wx.EVT_BUTTON, lambda event: self.OnButton(event, button=2) )
        getBtn3 = wx.Button(self, id=-1, label="3", pos=(90,60), size=(40,40))
        getBtn3.Bind(wx.EVT_BUTTON, lambda event: self.OnButton(event, button=3) )
        self.Show()

    def OnButton(self, event, button):
        print ("Button number ", button)
        curr_value = self.nameTxt.GetValue()
        # If a value exists add to it, otherwise display value of pressed button
        try:
            curr_value = int(curr_value) + button
            self.nameTxt.SetValue(str(curr_value))
        except:
            self.nameTxt.SetValue(str(button))

if __name__ == "__main__":
    app = wx.App()
    myframe = TestFrame(None, -1, "Calculator Test")
    app.MainLoop()

With regard to your comment about wanting "11111111":
change the function OnButton to:
def OnButton(self, event, button):
    print ("Button number ", button)
    curr_value = self.nameTxt.GetValue()
    curr_value = curr_value + str(button)
    self.nameTxt.SetValue(curr_value)


text:
Q: Why the UIButton in UITableViewCell.contentView won't work? I've did lots of tests and searches and still couldn't find why the UIButton that I added into a UITableViewCell.contentView won't work. I can guarantee I did everything right, the button still won't answer the TouchUpInside event.
code like this won't work:
[self.contentView addSubview:theButton];

But this would work:
[self addSubview:theButton];

As you may expected, self was a subclass of UITableViewCell. and recording to the doc, shouldn't we always add things to contentView?
Sorry for my poor English. I hope I described it clearly.

A: try this code in cellForRowAtIndexPath method
UIButton *scanQRCodeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
scanQRCodeButton.frame = CGRectMake(260.0f, 6.0f, 45.0f, 25.0f);
scanQRCodeButton.backgroundColor = [UIColor whiteColor];
[scanQRCodeButton setTitle:@"button" forState:UIControlStateNormal];
[cell.contentView addSubview:scanQRCodeButton];

it will work.

A: if your UITableViewCell has a customer height(not the default 44.0f)。
if so, you should set the code like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.contentView.frame = CGRectMake(0, 0, tableView.width, [self tableView:tableView heightForRowAtIndexPath:indexPath]);
        // add a UIButton that you create
    }
    return cell;
}

the reason for this problem is the cell.contentView.size is default (320.f, 44.0f), if your button is over the rect, then the button could not accept the event, so you should set the cell.contentView.frame yourself, like i do the code。
Good Luck。


text:
Q: How to change btn text on click using jquery I have built a basic btn. i need some help with creating the jquery.
the functionality i need is the following.
once clicked on the "follow btn"  the button turns green and says following.
once you hover back over the btn it needs to turn red and say unfollow.
If then pressed the button will then turn back to grey and say follow.
can anybody help with this?
Please update the fiddle.
http://jsfiddle.net/a3LGN/
Follow

.follow-btn{
    display: block;
    text-align: center;
    font: normal 1.6em "Helvetica Neue", helvetica, sans-serif;
    -webkit-border-radius: 6px;
    -moz-border-radius: 6px;
    border-radius: 6px;
    border: none !important;
    padding: 10px 20px;
    color: #fff !important;
    cursor: pointer;
    font-size: 16px;
    background:grey
}

A: See this fiddle, is this what you want?
code:
var flag_clicked = false;

$('a.follow-btn').click(function() {
    if(flag_clicked) {
        $(this)
            .find('span')
            .text('Follow')
            .end()
            .css('backgroundColor','gray');
        flag_clicked = false;
    } else {
        $(this)
            .find('span')
            .text('following')
            .end()
            .css('backgroundColor','green');

        flag_clicked = true;
    }
}).hover(function() {
    if(flag_clicked) {
        $(this)
        .find('span')
        .text('unfollow')
        .end()
        .css('backgroundColor','red');
    }
},
    function(){
    if(flag_clicked) {
        $(this)
        .find('span')
        .text('following')
        .end()
        .css('backgroundColor','green');
    }

         });

A: Since you have tagged jquery hoping you dont mind using jquery , then you can do something like this
$('#bt1').mouseenter(function(){
if($(this).hasClass('follow-btn1'))
{
$(this).css("background-color","red");
$('span').text("unfollow");
}
});
$('#bt1').mouseleave(function(){
$(this).addClass("follow-btn1");
$(this).css("background-color","green");
$('span').text("following");
});
$('#bt1').click(function(){
$(this).addClass("follow-btn1");
$(this).css("background-color","green");
$('span').text("following");
});

working fiddle


text:
Q: Issues with Three.Points; opacity, size and rotation Yep, Another question about Three.points. I've been having issues for a while now trying to figure out how to adjust opacity, size and rotation for a while. I took a break to work on other areas of my code and I'm back to it.
My issue now is, after my previous question about it I've made a bit of progress with trying to get it to work but I've come across and issue with pushing the points out as I'm unfamiliar with this method or making particles happen.
This is a dumbed down version of my code, so hopefully it will get the point across;
var dirs = [], parts = [], container = document.createElement('div');
  document.body.appendChild( container );
  var renderer, camera, scene
var cameramode, composer
var particleSystem = [], particleCount = 15;
for (var i = 0; i < particleCount; ++ i) {
  var pgeometry = new THREE.Geometry();
  var pMaterial = new THREE.PointsMaterial({
    map: new THREE.TextureLoader().load("x.png"),
    blending: THREE.screenBlending,
    size: 60, depthTest: true,
    transparent: true, opacity: 1,
    depthTest: false, sizeAttenuation: true
  });
}

init();
animate();
update();

function init() {
 for (var p = 0; p < particleCount; p++) {
  pX = Math.floor(Math.random()*2) == 1 ? 1 : -1,
  pY = Math.floor(Math.random()*2) == 1 ? 1 : -1,
  pZ = Math.floor(Math.random()*2) == 1 ? 1 : -1;
  var particle = new THREE.Vector3(pX, pY, pZ);
 }
 particle.velocity = new THREE.Vector3(0, 0, 0);
 geometry.vertices.push(particle);
 var points = new THREE.Points(geometry, pMaterial);
 scene.add(points);
 particleSystem.push(points);
}

function animate(){
  requestAnimationFrame( animate );
  controls.update(), composer.render();
  update(), render();
};

function update() {
  requestAnimationFrame( animate );

  while (pCount--) {
    var points   = particleSystem[i];

    if (particle.x < -150) {
      particle.z = (Math.floor(Math.random()*2) == 1 ? 1 : -1)* 20;
      particle.x = (Math.floor(Math.random()*2) == 1 ? 1 : -1)* 20;
      particle.velocity.x = 0, particle.velocity.y = 0, particle.velocity.z = 0};
    if (particle.z < -150) {
      particle.z = (Math.floor(Math.random()*2) == 1 ? 1 : -1)* 20;
      particle.x = (Math.floor(Math.random()*2) == 1 ? 1 : -1)* 20;
      particle.velocity.x = 0, particle.velocity.y = 0, particle.velocity.z = 0 };
    if (particle.y < -150) {
      particle.z = (Math.floor(Math.random()*2) == 1 ? 1 : -1)* 20;
      particle.x = (Math.floor(Math.random()*2) == 1 ? 1 : -1)* 20;
      particle.velocity.x = 0, particle.velocity.y = 0, particle.velocity.z = 0 };

    if (pCount%2 == 0){
      if (particle.x < 0){
        particle.velocity.x -= (Math.floor(Math.random()*2))*0.002;
        particle.velocity.y -= (Math.floor(Math.random()*2))*0.0001;
        particle.velocity.z -= (Math.sin(Math.random()*2))*0.001 };
      if (particle.x > 0){
        particle.velocity.x += (Math.floor(Math.random()*2))*0.002;
        particle.velocity.y += (Math.floor(Math.random()*2))*0.00001;
        particle.velocity.z -= (Math.random(Math.random()*2))*0.005 };
    } else {
      if (particle.x < 0){
        particle.velocity.z += (Math.floor(Math.random()*2))*0.002;
        particle.velocity.y += (Math.floor(Math.random()*2))*0.0001;
        particle.velocity.x -= (Math.random(Math.random()*2))*0.001 };
      if (particle.x > 0){
        particle.velocity.z -= (Math.floor(Math.random()*2))*0.002;
        particle.velocity.y -= (Math.floor(Math.random()*2))*0.00001;
        particle.velocity.x += (Math.random(Math.random()*2))*0.005 }};

    if (pCount%3 == 0){
      if (particle.velocity.z > 0){
        particle.velocity.y -= (Math.floor(Math.random()*2))*0.0001;
        particle.velocity.x -= (Math.random(Math.random()*2))*0.005 };
      if (particle.velocity.z < 0){
        particle.velocity.y += (Math.floor(Math.random()*2))*0.00001;
        particle.velocity.x -= (Math.random(Math.random()*2))*0.005 / 2}};
    if (pCount%5 == 0){
      if (particle.velocity.z > 0){
        particle.velocity.y -= (Math.floor(Math.random()*2))*0.0001;
        particle.velocity.z += (Math.random(Math.random()*2))*0.005 };
      if (particle.velocity.z < 0){
        particle.velocity.y += (Math.floor(Math.random()*2))*0.00001;
        particle.velocity.z += (Math.random(Math.random()*2))*0.005 }};
    if (pCount%7 == 0){
      if (particle.velocity.z > 0){
        particle.velocity.y -= (Math.floor(Math.random()*2))*0.0001;
        particle.velocity.x -= (Math.random(Math.random()*2))*0.005};
      if (particle.velocity.z < 0){
        particle.velocity.y += (Math.floor(Math.random()*2))*0.00001;
        particle.velocity.x -= (Math.random(Math.random()*2))*0.005 / 2}};
  }

  particleSystem.geometry.verticesNeedUpdate = true;
  particleSystem.rotation.y += (Math.random()*0.001)
} //animate end

renderer.setAnimationLoop(() => {
  update();
  composer.render(scene, camera);
});

function render()
{
  uniforms.tAudioData.value.needsUpdate = true;
  composer.render();
}

I keep having issues on addressing the location, the particle, point, ect and I'm not sure how to go about adjusting anything. My current issue is addressing the location of the points through this method in comparrision to;
for (var p = 0; p < particleCount; p++) {
  pX = Math.floor(Math.random()*2) == 1 ? 1 : -1,
  pY = Math.floor(Math.random()*2) == 1 ? 1 : -1,
  pZ = Math.floor(Math.random()*2) == 1 ? 1 : -1;
  var particle = new THREE.Vector3(pX, pY, pZ);
}
geometry.vertices.push(particle);
var points = new THREE.Points(geometry, pMaterial);
scene.add(points);
particleSystem.push(points);

which doesn't have any issues, but limits the functionality to only the positioning, velocity ect. There's probably a few other issues I'm causing that i'm not really aware of but how would I go about doing this or fixing the current issues that I'm having?
(A part 2 of this post: .points opacity / size within three.js)

A: Just an example of using THREE.BufferGeometry() with attributes, instead of THREE.Geometry().

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 50);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var pointsDimension = 100;

var points = [];
var size = [];
var opacity = [];
var speed = [];
for (let i = 0; i < 1000; i++) {
  points.push(new THREE.Vector3(
    Math.random(),
    Math.random(),
    Math.random()
  ).multiplyScalar(pointsDimension));
  size.push(Math.random() * 5 + 5);
  opacity.push(Math.random() * Math.PI);
  speed.push(Math.random() * 10 + 10);
}

var geom = new THREE.BufferGeometry().setFromPoints(points);
geom.addAttribute("size", new THREE.BufferAttribute(new Float32Array(size), 1));
geom.addAttribute("opacity", new THREE.BufferAttribute(new Float32Array(opacity), 1));
geom.addAttribute("speed", new THREE.BufferAttribute(new Float32Array(speed), 1));
geom.center();

var mat = new THREE.ShaderMaterial({
  uniforms: {
    time: {
      value: 0
    },
    color: {
      value: new THREE.Color(0x00ffff)
    },
    texture: {
      value: new THREE.TextureLoader().load("https://threejs.org/examples/textures/sprites/snowflake2.png")
    }
  },
  vertexShader: `
    uniform float time;
    attribute float size;
    attribute float opacity;
    attribute float speed;
    varying float vOpacity;
    void main() {
      vOpacity = 1.0 - abs(sin(time + opacity));
      vec3 pos = position;
      pos.y = 50. - mod(50. - (position.y - (speed * time)), 100.);

      vec4 mvPosition = modelViewMatrix * vec4( pos, 1.0 );
      gl_PointSize = abs(sin(time + size)) * size * ( 300.0 / -mvPosition.z );
      gl_Position = projectionMatrix * mvPosition;
    }
  `,
  fragmentShader: `
    uniform sampler2D texture;
    uniform vec3 color;
    varying float vOpacity;
    void main() {
      gl_FragColor = vec4( color, vOpacity );
      gl_FragColor = gl_FragColor * texture2D( texture, gl_PointCoord );
    }
  `,
  blending: THREE.AdditiveBlending,
  depthTest: false,
  transparent: true
});

var particles = new THREE.Points(geom, mat);
scene.add(particles);

var clock = new THREE.Clock();

renderer.setAnimationLoop(() => {
  mat.uniforms.time.value = clock.getElapsedTime();
  renderer.render(scene, camera);
})
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/100/three.min.js"></script>


text:
Q: JSlider limit thumb movement Is it possible to limit the movement of the JSlider thumb? It should not be possible for the user to move the slider thumb past a lower and upper limit value.
Edit:
I set the minimum and maximum values for the slider (e.g. from 1..100). But I have another control which limits the range of values for the slider, let's say from 30..60. Now the user should not be able to move the slider thumb below 30 and above 60, but the minimum and maximum values should still be 1 and 100.

A: Since you have another control that sets the ranges for the slider, you may want to look into a RangeSlider that can supply the upper and lower bounds on a single slider (it has 2 thumbs)
Here are some different approaches from the web:

*

*Creating a Java Swing range slider

*MultiThumbSlider


text:
Q: Flex/Flex++ syntax error - "Unrecognized rule" I'm writing a grammar using Flex++ to generate a parser and this block of code always returns an "unrecognized rule" error.
%{
#include "Parserbase.h"
%}

%option noyywrap

num         [0-9]+
float       [0-9]+"."[0-9]+
comment     [["//"[.]*\n] | ["/\*"[.]*"\*/"]]
varname     [a-zA-Z][a-zA-Z0-9_]*

%%

";"             {return ParserBase::SEMICOLON;}
"\n"            {return ParserBase::ENDLINE;}

"int"           {return ParserBase::INT;}
"="             {return ParserBase::EQUALS;}
{num}           {return ParserBase::NUM;}
{comment}       {return ParserBase::COMMENT;}
{varname}       {return ParserBase::VARNAME;}

This always returns the following :
bisonc++ Compiler.y
[Warning] Terminal symbol(s) not used in productions:
257: NUM
261: ENDLINE
g++ -c parse.cc
flex++ Compiler.l
Compiler.l:21: unrecognised rule
make: *** [lex.yy.cc] Error 1

I've tried moving around the rules, changing the alias to a simple
    [a-zA-Z]
or even just
    [a-z]
All to no avail, and it's driving me mad... Anyone got any ideas?
Thanks!

A: This definition is invalid:
comment     [["//"[.]*\n] | ["/\*"[.]*"\*/"]]

[ and ( are different. [...] is a character-class; that is, a list of possible characters which will match a single character. (...) is used to group regular expressions.
Also, I don't believe you can insert arbitrary space characters in a Flex++ regex.
So I think that what you intended was:
comment     ("//".*\n|"/*".*"*/")

Here I've removed the incorrect square brackets, changed the ones which were used for grouping into parentheses, and removed the unnecessary grouping around the alternatives, since | has lower precedence than concatenation. I also removed the unnecessary backslash escapes, since quoting is sufficient to make a * into a character.
However, that will not correctly match C++ comments:
First, .* is greedy (i.e., it will match the longest possible string) so
/* A comment */ a = 3; /* Another comment */

will be incorrectly recognized as a single comment.
Second, . does not match a newline character. So multi-line /* ... */ comments won't match, because .* won't reach to the end of the comment, only to the end of the line.


text:
Q: Can a place be "drop dead gorgeous"? I have heard people use "drop dead gorgeous" for handsome or beautiful people. But can this idiom be used for beautiful places?

A: My first inclination was to agree with other answers here that "drop dead gorgeous" was only (or mostly, or typically) used in reference to human people. But my interest was piqued by one of the comments referencing the phrase's occurrence in the iWeb Corpus.* A search there reveals that "drop dead gorgeous" is not only used to refer to things other than people, but that those types of references are, in fact, fairly common.
This is a very unscientific sample, but below are the first ten results for "drop dead gorgeous" in the iWeb Corpus:

*

*I think we can all agree that she is drop dead gorgeous. Her husband, however...

*...Venturi [a car] because its engineering was superb.. it still to this day is drop dead gorgeous...

*...why not take up X Theme on the invitation to customize some drop dead gorgeous registration forms for your site?...

*Drop dead gorgeous, sassy and smart, Ruby Wax brings her new one-woman show to the stage...

*...quickly earned herself the label of drop dead gorgeous online...

*She is drop dead gorgeous and somewhat of a flirt...

*While the Corvette looks great, its not drop dead gorgeous like the Jaguar....

*It conjures up an image of a drop dead gorgeous young man with dark hair...

*A drop dead gorgeous real wedding with a serene ceremony in Killruddery's glass orangery...

*There it was buried in a HomeGoods aisle... a drop dead gorgeous acacia wood tray....

As we can see, five of the first ten results use "drop dead gorgeous" to refer to something that's not a person (i.e. cars, a wedding, registration forms, a wooden tray). I didn't do an exhaustive review, but found one (likely among many) explicitly referring to a place:

*...Accommodations on a magnificent white sandy beach facing a drop dead gorgeous south pacific lagoon of crystal clear water...

A cursory glance through the more than 1,200 results suggests the above are not anomalies. Thus, it appears that "drop dead gorgeous" is used fairly commonly to refer to inanimate objects, including places.

*Searching in this corpus requires registration, which, unfortunately, may also require attesting to affiliation with a university (although that affiliation doesn't appear to be verified during registration).

A: I've only ever heard it said about people. It seems a variation of the idiom to knock (one) dead, meaning to strongly impress. While a place or a thing can be described as impressive, 'knocking someone dead' in this metaphorical way can also be a deliberate act - "knock them dead!" is often said as words of encouragement to someone wanting to make an impression. So you can see why this idiom on which it is likely based is specific to people.
The word 'gorgeous' alone does have a wider use with places and things, but I've never heard anyone describe anything like that as 'drop dead' gorgeous and, speaking as a native British English speaker, it sounds odd to me.
The fact that written examples seemingly to the contrary have been cited in other answers does not change my stance on this. It isn't uncommon for writers to use out-of-context idioms in order to make a point stand out. When you read something that wouldn't sound right spoken there is a good chance you'll read it twice to make sure, which is exactly what the writers of advertising material want. Some of these examples sound like promotional or advertising material for cars and the like. It is also not uncommon for vehicles to be personified.


text:
Q: MongoDB add array to BsonDocument I am trying to add fields in a mongodb document using C# drivers.
I am creating a document.
BsonDocument document = new BsonDocument();

and adding
document.Add(name, value); // here name and value both are string

but I am not sure how to add an array in this scenario
like document.Add(name, values); // here values is List<string>
e.g. document.Add(skills, [C++, Java, C#]);
please help me with this

A: If you're working with a List<string>:
var skills = new List<string> {"C++", "Java", "C#"};
document.Add("skills", new BsonArray(skills));

Or, more simply:
document.Add("skills", new BsonArray { "C++", "Java", "C#" } );


text:
Q: How to define and call an array in chef? Below is the resource I am using to copy many files.
['contacts_nagios2.cfg','generic-host_nagios2.cfg','generic-service_nagios2.cfg','hostgroups_nagios2.cfg','services_nagios2.cfg','timeperiods_nagios2.cfg'].each do |file|
  cookbook_file "/etc/nagios3/conf.d/#{file}" do
    source  "#{file}"
    mode '0644'
  end
end

Can we define ['contacts_nagios2.cfg','generic-host_nagios2.cfg','generic-service_nagios2.cfg','hostgroups_nagios2.cfg','services_nagios2.cfg','timeperiods_nagios2.cfg'] as an attribute within the same recipe?

A: This will create an attribute of type Array and can be defined within the recipe file:
node.default['nagios_config_files']=['contacts_nagios2.cfg','generic-host_nagios2.cfg','generic-service_nagios2.cfg','hostgroups_nagios2.cfg','services_nagios2.cfg','timeperiods_nagios2.cfg']

and if you want to add to that you can later do:
node.default['nagios_config_files']|=['more_configs.cfg','even_more_configs.cfg']

(Note the pipe '|' before the '=' sign.)
Then you can use the attribute like before:
node['nagios_config_files'].each do |file|
  cookbook_file "/etc/nagios3/conf.d/#{file}" do
    source  "#{file}"
    mode '0644'
  end
end


text:
Q: Recommendation for intro to geometric integrators? Explicit Request
Looking for book or lecture note recommendations on numerical optimization that (ideally) have the following:

*

*Emphasis on geometric and physical intuition

*Emphasis on symplectic integrators

*Many well-thought out figures

*Relatively self-contained (some of my background below)

*Pseudo-code

Goals
I don't have what's called a "use case", but one of my goals is to able to better-understand i) how to code a symplectic integrator and ii) some intuition as to what math may be useful to advance the recent paper by M. Jordan et al.'s On Symplectic Optimization.
Background: pure mathematics (algebraic geometry) and some background in physics. Never studied Hamiltonian dynamics proper and don't know what a "geometric integrator" is beyond the lovely Wikipedia article on it. Also used some of the standard gradient descent methods such as Nesterov and Adam in practice (ML), but can't say I really know the "physics" behind these methods.
Thank you!
Addenda
I haven't checked out the books by Hairer et al or Leimkuhler -- would one (or both?) fit the bill? It would be very useful to get comments on these books.


text:
Q: Close Window with JS So I have been trying to create a div that allows you to click on it and it'll close the tab. normally, I would accomplish this by placing onClick=" javascript:window.close();" within the HTML code and done. for this website, it doesn't seem to work. I have to place the code on the back end to stick but whenever I switch to frontend view, it's gone.
here is the code that works on the backend but not the front:
Close Window

the front end looks like the
Close Window

I think it's cause the system has code somewhere that prevents custom Js from firing.
I tried placing e.preventDefault but I feel like I'm not using it correctly here is the link & code:
$(() => {

  $("a[href='#close-window']").on('click', function (e) {

    e.preventDefault();

    var openedWindow;

        function openWindow() {
          openedWindow = window.open('https://www.bouncehouserentalcompany.com/bounce-house-notes/');
        }

        function closeOpenedWindow() {
          openedWindow.close();
        }

  });

A: I looked at the site and you have a console error. Besides everything else in the comment above, you're missing closing brackets: )}. Also, you need to wrap your click event handler in some kind of DOM ready function like $(document).ready(function(){... This is especially because your HTML is below the script on the DOM tree.
There is a lot going on here though and I would definitely separate logic (like load one js file with all your stuff in it) as recommended in the comment.
Also, consider XSS attacks.


text:
Q: Differentiation under integral sign. There is a integral that has to be differentiated. In an article i studied that the derivative of the integral of a function is the integral of the derivative of that function with respect to some variable. The integral is:
$$\int_2^x [t-ty(t)]dt$$
please differentiate it with respect to $x$.

A: Let $F(x) = \int_2^x [t - ty(t)]\, dt$ and assume that $y$ is a continuous function.
$$\lim_{h \to 0} \frac{F(x+h) - F(x)}{h} = \lim_{h \to 0} \frac{1}{h}\int_x^{x+h} [t - ty(t)] = x - x y(x) $$
Since for every $\epsilon>0$ there is $\delta>0$ such that $|t - x| \leq \delta$ implies
$$\big|t - t y(t) - (x - x y(x))\big|\leq \epsilon$$
There is no differentiation under the integral sign.
Edit: If $y$ is an arbitrary function, then in general you cannot differentiate it on $x$. Take $y(s) = f(s)\frac{1}{s}$ so $ F'(x) = x + \lim_{h \to 0} \frac{1}{h}\int_x^{x+h} f(s) $ wich might not exist, take for instance$$f(s) = \begin{cases}1 &s \geq x\\ -1 &s<x\end{cases}$$


text:
Q: Using Django template inheritance with ngroute - where does `` go if I want to override blocks outside of ``? This is my base.html:
<!DOCTYPE html>

    {% load static from staticfiles %}

    <meta charset="utf-8">
    <title>{% block title %}Base{% endblock %}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <base href="/">
    {% block head %}{% endblock %}

Please enable your browser's JavaScript in order to view this website.

    {% block body %}

    {% endblock %}

This is an example of a template which inherits base.html (call it home.html):
{% extends "base.html" %}

{% load static from staticfiles %}

{% block html %} ng-app="AuthenticationApp"{% endblock %}

{% block head %}
    <link rel="stylesheet" type="text/css" href="{% static 'css/home.css' %}">

{% endblock %}

{% block body %}

            {{ block.super }}

            <form ng-submit="ctrl.change()" class="form-horizontal" name="myForm"></form>

{% endblock %}

The html block is to set the ng-app which will be used for the web page. The head block is to load the relevant JS and CSS files. The body block is where the body of the HTML page goes. However, I am using ngroute to load webpages. This is the routing and JS:
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/new', {
    templateUrl: 'static/templates/new.html'
})

self.change = function() {
    $location.url("/new");
};

So in home.html, when the form is submitted, the URL changes to /new (which serves the page new.html. This is new.html:
{% block html %} ng-app="NewApp"{% endblock %}

{% body head %}
    <link rel="stylesheet" type="text/css" href="{% static 'css/new.css' %}">
{% endblock %}

{% body block %}

NEW CONTENT

{% endblock %}

So for every template which inherits base.html and gets loaded, I want to be able to redefine / override the blocks again. Where do I put

 so that I will be able to redefine the blocks with correct code structure?
I tried putting it in home.html (the page which the app loads first) right underneath

, but then it doesn't override the blocks. I can put it in base.html above / outside the , but that would be placing a
 outside of  which isn't proper code structure. Any idea how to do this?


text:
Q: Why would set view.layer.contents instead of using an UIImage Recently I encountered this code:-
self.view.layer.contents = (id)[UIImage imageNamed:@"img_bg.png"].CGImage;

This setup a background for the whole view of a UIViewController.
Usually, I would just set an UIImageView as subview, taking the whole area of the view from the UIViewController
Why would someone use one technique rather than an other ?
I found this one a bit disturbing because the background does not show in the storyboard; where I expect it.

A: that's a great question. Deeply, you are asking the different between View and Layer, you know we can think view as layer's delegate which can handle user's interaction with app or system. when there is no any interaction but render view, we can just use layer, that will take up less memory compared with the view。

A: Try this
self.view.backgroundColor = UIColor(patternImage: UIImage(named:"img_bg.png"))

Hope this will help
Cheers

A: You can try this:-
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "img_bg.png")?.drawInRect(self.view.bounds)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)

Hope this helps,
Thanks


text:
Q: Storing Images in DB is Good or Not? What should I do? I have more than 1600 Images. Should I store them directly in the application or store them in a database. Right now I'm storing in Application and my application gets hanged so please Help

Exact Duplicate: User Images: Database or filesystem storage?
Exact Duplicate: Storing images in database: Yea or nay?
Exact Duplicate: Should I store my images in the database or folders?
Exact Duplicate: Would you store binary data in database or folders?
Exact Duplicate: Store pictures as files or or the database for a web app?
Exact Duplicate: Storing a small number of images: blob or fs?
Exact Duplicate: [store image in filesystem or database?][7]

A: As with most issues, it's not as simple as it sounds. There are cases where it would make sense to store the images in the database.

*

*You are storing images that are
changing dynamically, say invoices
and you wanted to get an invoice as
it was on 1 Jan 2007?

*The government wants you to maintain
6 years of history Images stored in
the database do not require a
different backup strategy. Images
stored on filesystem do

*It is easier to control access to the
images if they are in a database.
Idle admins can access any folder on
disk. It takes a really determined
admin to go snooping in a database to
extract the images

On the other hand there are problems associated

*

*Require additional code to extract
and stream the images

*Latency may be slower than direct
file access

*Heavier load on the web server

This answer is quoted from "Conrad"

A: As pointed out previously, it depends.
One of the most common practices is to decide on the basis of the images' size.
For very small images, such as thumbnails, icons etc, you certainly store them in the DB, and you can store them as a field of an entity (say a contact).
For medium sized images, it still makes sense to store them in the DB. However, you have to decide by yourself what is a medium sized image (my threshold is 1 MByte), and you should store the image not as a field of an entity: you should create an image entity and a relation to the interested entity (say the contact).
Finally, very large images should not be stored in the DB. You store them on disk and store on the DB their pathnames. This is necessary owing to the different latency and access time of the hard disk versus the DB. Indeed, it is the DB fast access through indexes that allows you to store medium and small sized images in the DB, but huge images should be handled differently.


text:
Q: How should a DirectShow muxer filter with multiple input pins implement IMediaSeeking pass through? I'm working on a bug with a custom audio mixer filter (I have the source) where the input audio streams seem to get out of sync after any seeking with some input sources (I don't have the source for these) when more than one input is connected.
After seeking the timestamps etc look correct but the actual data in the streams is out of sync with the timestamps.
The audio mixer has a custom IMediaSeeking implementation that passes on IMediaSeeking::SetPositions calls to each input pin. This would seem to be the correct approach. If there's more than one source filter the SetPosition calls need to be passed on to each source. It's then up to the source filter to only implement seeking on only one of its pins (as documented in MSDN).
Would it be better to inherit a pass through implementation from CPosPassThru so that it supports IMediaPosition too? Some filters seem to use IMediaPosition calls rather than IMediaSeeking.
Is there anything specific a muxer filter has to do to pass on seeking calls to multiple input pins. Any good example source code out there? The Monogram blog on writing a muxer filter doesn't seem to cover seeking.

A: For the benefit of future readers, the following seems to work OK. The sync bug was elsewhere.
The audio mixer has a custom IMediaSeeking implementation that passes on IMediaSeeking::SetPositions calls to each input pin.
If there's more than one source filter the SetPosition calls need to be passed on to each source. It's then up to the source filter to only implement seeking on only one of its pins (as documented in MSDN).
It doesn't seem to be necessary to forward IMediaPosition upstream.


text:
Q: Difference of property Delegate and Event event keyword creates two methods add_* and remove_* (its working like property).
what is the difference
public event MyDelegate event1;
public MyDelegate event2 { get; set; }

why should use event keyowrd?

A: One reason is safety. If you implement an event like delegate field:
 public MyDelegate event2 { get; set; }

you'll be able to do dangerous things:
 MyObject test = new MyObject();

 // removing all listeners
 test.event2 = null;
 // just a little typo `=` instead of `+=`
 // means now complete substitution of the listeners instead of adding one
 test.event2 = myMethod;


text:
Q: Avoid XSS in Handlebars templates We use Handlebars templates to render data from one of our APIs. The data contains HTML entities - for example:
Police officers won't be able to fine you until 10 minutes after your ticket expires

Till now we've used the Handlebars triple brace to let those through, like:

{{{title}}}

But our hosting service provider tells us this is an XSS risk, and that values need to be escaped. They tell us to use {{ }} so Handlebars escapes them. But when we do this, the HTML entities show up in the front end as entity strings.
Can anyone suggest an easy way we can secure our client-side Handlebars templates against cross-site scripting while allowing HTML entities for the most typical UTF-8 characters like the non-breaking space ( ) and left single quote (‘)? I've come across Yahoo Secure Handlebars Helpers, but that seems to be intended only for use with their Handlebars Context Pre-compiler, which I'm not familiar with and anyway seems to be a server-side utility.


text:
Q: Placing a cookie with country name using geoplugin I am trying to do some cookie tracking for users on a client's website so we can conditionally show popups. I am putting this code in the 'header' part of their theme on wordpress.
I am trying to implement http://www.geoplugin.com/quickstart to get their country.
This code works;
<script language="JavaScript" src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
<script type="text/javascript">
    var name = 'country';
    var value = 'dogs';
    document.cookie = name+"="+value;
</script>

To create a cookie called 'country' with the value 'dogs'
If I change the 'dogs' part to what I thought was calling the geoplugin as below, it breaks and the cookie doesn't place. Any ideas?
<script language="JavaScript" src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
<script type="text/javascript">
    var name = 'country';
    var value =geoplugin_countryName();
    document.cookie = name+"="+value;
</script>

A: I am guessing this is happening before the browser loads the geoplugin library.
You should put all this code in the window.onload handler (https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onload)
Or if you are using jQuery using $( document ).ready()


text:
Q: Ubuntu Screen blink in dual boot laptop(windows10+Ubuntu) Recently I'm facing this annoying issue of screen blinking on my laptop. I have a dual boot laptop mostly booting into Ubuntu.
Now, when I try to boot windows 10, screen goes blank completely, but when I boot into Ubuntu the screen blink happens regularly.
Laptop: Sony vaio
Processor: Intel core i3
Graphics: Intel ironlake mobile
Ubuntu version: 18.04.4 64bit

A: @Gyru, thanks for your suggestions man, because of you I was able to explore more to find a solution.
Although the suggestions given to me didn't completely eliminate my issue. I tried the following to get rid of screen blinking.

*

*I tried to downgrade the ubuntu kernel and changed device graphics drivers but none of the worked fine. (Worked for a while but returned after sometime).

*I tried uninstalling ubuntu from dual boot, but the problem was still there even after removing ubuntu.

*Took backup of my necessary files in windows and installed Ubuntu 20.04 from bootable usb and removed windows 10 completely. (I used android mobile to create bootable ubuntu usb).
Now, I'm happily using ubuntu 20.04 (with no data loss) and I must admit it feels pretty good to use 20.04 compared to 18.04.


text:
Q: Better way in C++ to keep a big plain struct atomic? I have a big plain struct without any methods. It includes many fields and another container(std::vector).
I need to make it atomic, so as to let one producer thread and many consumer threads can access it concurrently.
consumers don't modify the data, they just read the data. there is only one producer that adds/modifys(don't remove) the data, so it must keep the integrity/consistency of the data that can be seen by consumers whenever.
I think that there are two solutions can resolve it, but I don't know which one is better.
Method 1:
struct Single_t {
   size_t idx;
   double val;
}
using Details_t = std::vector<Single_t>;

struct BigStruct_1 {
   std::string      id;
   size_t           count;
   Details_t        details;
   std::atomic_bool data_ok { false };
};
std::map<std::string, BigStruct_1> all_structs1;

Method 2:
// Single_t and Details_t are same as the ones in Method1.
struct BigStruct_2 {
   std::string id;
   size_t      count;
   Details_t   details;
};
std::map<std::string, std::atomic<BigStruct_2> > all_structs2;

I prefer Methods2 up to now because I don't need to check whether data_ok in everywhere of consumer's codes. Infact consumer holds a pointer to a single BigStructs_2, I want the data can be accessed anytime(the data will not be removed).
Fortunately there is only one producer in my system, so the producer can simply overwrite the data in one step: std::atomic<BigStruct_2>::store( tmp_pod );, So I don't need to check whether or not the data is ready/OK(It should be always OK) when a consumer is reading the data, and I also don't need to use std::atomic::compare_exchange_xxx in this case, so it isn't necessary to offer a comparing algorithm between two BigStruct_2 objs. Am I right?
If I use Method1, when I need to modify the data I have to code as following:
auto& one_struct = all_structs1["some_id"];
one_struct.data_ok.store( false, memory_order_release );
// change the data....
one_struct.data_ok.store( true, memory_order_release );

and check if data_ok everywhere in consumer's codes... it's ugly and dangerous(easy to forget to check).
Any recomments/hints will be appreciated!

A: Another solution for updating shared objects that are predominately read is seqlock:

Seqlocks are an important synchronization mechanism and represent a significant improvement over conventional reader-writer locks in some contexts. They avoid the need to update a synchronization variable during a reader critical section, and hence improve performance by avoiding cache coherence misses on the lock object itself.

A: I suggest you make your BigStructs effectively immutable, and store them like this:
std::map<std::string, std::shared_ptr<BigStruct_2> > all_structs2;

In order to make an update, the writer-thread would allocate a new BigStruct_2 (using std::make_shared or whatever), set it equal to the object it wants to modify, then modify the new BigStruct_2, then insert the new shared_ptr<BigStruct_2> into the map.
Then whenever a reader-thread wants to read a BigStruct_2 it can do so safely by holding a local std::shared_ptr<BigStruct_2> that it retrieved from the std::map.  Since your writer-thread is careful to never modify a BigStruct_2 that it has already inserted it into the map, there is no chance that a reader-thread will be wrong-footed by a BigStruct_2's contents changing while it is in the process of reading it.
Note that none of the above makes accesses to the std::map itself thread-safe, so you'd still need to synchronize all of those with a mutex.  Those actions should be quite fast, though, so I doubt that will be a problem.

A: std::atomic<BigStruct_2> will effectively be using lock: is_always_lock_free and is_lock_free are very likely to be false on aly implementation.
Also, you cannot use non-trivially-copyable type in std::atomic anyway (i.e. no std::string in your struct).
Generally, the ability of std::atomic to work with types of any size is for portability (in case if HW does not support atomics of particular size, but some does). It is not meant to be used in never-lock-free case.
The approach with data_ok is effectively lock-based either. You'll need to retry when data_ok is false.
You'd better just use std::mutex to guard data, or, if reads are prevalent, use std::shared_mutex to allow concurrent reads.

A: If you're looking to absolutely minimise the lock time, I would suggest a third approach - you have a map of items which are structs holding an atomic pointer to the current values, as opposed to a map of shared pointers.
The advantage of doing this is that you don't have to lock the map to update values; you only need to lock the map for additions and removals.
Locking the map is effectively a domain lock which would block all threads, when most of the time you only really need to block any thread reading the map entry under interest.
You effectively perform "copy-on-write" with the data to modify it.  So you have
struct Single_t {
   size_t idx;
   double val;
}
using Details_t = std::vector<Single_t>;

struct BigStruct_Container {
   std::string      id;       //maybe put this in the digest if immutable?
   size_t           count;
   Details_t        details;
};

struct BigStruct_Digest {
   std::atomic<BigStruct_Container*> current_value;
};
std::map<std::string, BigStruct_Digest> all_digests;

With this, to perform an update you take a copy of the data and generate a new container.  Then you simply update the container pointer (digest) that's in the map.  Since you're not changing the value in the map, the map remains constant so there is no need to lock the map when updating.

A word of warning with using shared-ptrs; you need to use a mutex to protect the reference counting mechanism within since it is not thread-safe.  If you're using domain locks that should be OK, but it's not an optimal solution.

Note that given the map doesn't contain much data, you could even perform copy-on-write with the map, and have an atomic-ptr to the map itself.....

This is along the lines of "lock individual members, not the collection" in the book "Seven Concurrency Models in Seven Weeks" - https://www.amazon.co.uk/Seven-Concurrency-Models-Weeks-Programmers/dp/1937785653


text:
Q: Firebase: Setvalue working with map object but not with POJO I have no Idea, why Setvalue() works with map object(static data) and throws permission denied as exception when using plain java object with dynamic data(POJO).
Works:
Saving data using Map object
Map newUserData = new HashMap();
            newUserData.put("Name", getUserName());
            newUserData.put("Surname",getUserName()+"_testSurname");
            newUserData.put("Gender","Gender_data");
            newUserData.put("PhotoURL","");

adding metadata failed com.google.firebase.database.DatabaseException: Firebase Database error: Permission denied:
Saving data using POJO
public class MetaInfo {

private String Name, Surname,Gender,PhotoURL;

public MetaInfo() {}

public MetaInfo(String name, String surname, String gender, String photoURL) {
    Name = name;
    Surname = surname;
    Gender = gender;
    PhotoURL= photoURL;
}

public String getPhotoURL() {
    return PhotoURL;
}
...
...
..

Adding data using MetaInfo object:
MetaInfo mData= new MetaInfo(name.getText().toString(),
                surname.getText().toString(),
                gender.getText().toString(),
                "");

Calling setvalue() with map object works however, permission deined with when  MetaInfo object with valid data is used.
DatabaseReference.child(getUid()).child("metadata").setValue(mData).addOn CompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    Log.i(TAG,"metadata added ");
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.i(TAG,"adding metadata failed "+e.toString());
                }
            });
                @Override

FB-rules
 rules": {
  "test":{
    "$UID":{
      // METADATA
      "metadata":{
        ".read":true,
        ".write":"auth.uid === $UID",
        ".validate":"newData.hasChildren(['Name','Surname'])",
        "Name":{
        ".validate":"newData.val()!== null"
        },
        "Surname":{

        ".validate":"newData.val()!== null"
        },
        "$other":{
        ".validate": true
        }
      }

A: In my opinion the problem is with your google-services.json file.
Make sure your application name and client id are same as in Firebase console.
If you are not sure, please re-download google-services.json file from your project's console and add it your project.
An also don't forget to set the rules to:
{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Please keep this rules only for testing purposes. Don't keep this rules always like this.
Hope it helps.

A: You skipped a few crucial pieces of your MetaInfo class. But I'll assume you have these getters:
public String getName() { return Name; }
public String getSurname() { return Surname; }

These getters map to (follow age-old JavaBean conventions) properties named name and surname. But your rules validate that any new data has Name and Surname. It might be hard to spot at first, but the casing is different.
The solution is to annotate the properties with how you want them stored:
@PropertyName("Name")
public String getName() { return Name; }
@PropertyName("Surname")
public String getSurname() { return Surname; }

If you have corresponding setters for the properties, you'll also need to annotate those.
The easiest way to troubleshoot these problems by the way is to initially write to a location in your database where everything is allowed. That way you can see what the Firebase SDK writes your POJO as, which makes it a lot easier to spot what validation rules it violates.
Also see:

*

*Firebase serialization names


text:
Q: AWS server connection refused I have a simple API set on my AWS instance. While I am able to call the api functions from US geographic location, my friend gets a connection refused from from India on the same URL.
I am unable to find out a reason for this. I tried adding the IP (both mine and his) to AWS security group. While AWS responds to all my requests, even if i use a different IP in the same geographical region, none of the IP requests from India work. This is the case even if i have the security settings to All Traffic/Anywhere in AWS.
Any direction in debugging this will prove helpful.


text:
Q: A PHP script to let users download a file from my website without revealing the actual file link in my website? The question says it all.. How do I let the users download a file from my website and not let them see what link that file comes from? I understand that there might be a need for something like a download.php which will serve as the gateway but past that phase, I dunno what to script next... If it bothers you to write the whole code, a few function names that I should need to use would be really handy!

A: You can't make someone download a file from a URL without letting them know the URL.  It's not possible under the HTTP specification.  Anything downloaded has a URL.
You can, however, have a download URL that only works once, or requires some specific information to be passed via the POST method.  You check for a token in the GET or POST variables and invalidate that token once it's used once.

A: Find a way to identify the file to download (for instance, a GET variable that matches the ID of a row in a database, or something along these lines). Make damn sure it's a valid one, because you don't want your users to be able to download anything off your site. Then, use header with Content-Disposition to tell the browser the file should be downloaded, and readfile to output it.
For instance:
<?php

$id = intval($_GET['id']);
$query = mysql_query('SELECT file_path FROM files WHERE id = ' . $id);
if (($row = mysql_fetch_row($query)) !== false)
{
    header('Content-Disposition: attachment; filename=' . basename($row[0]));
    readfile($row[0]);
}
exit;

?>

A: You can use the header() function which is documented here
I would suggest scrolling down and looking at the 1st example. It seems to be doing exactly what you want.

A: readfile should do what you want.  Put the actual file outside the web server root, and require some credentials before passing back the file.