text:
Q: How React hook access closure variable When I tried the counter example in React with hooks, i want to see how async operation works in hooks, so I put code like:

function App() {

  const [count, setCount] = useState(0);

  var times = count>0?"times":"time";
  var txt = count + " " + times;

useEffect(()=>{
  setTimeout(()=>{
    console.log(txt)
  }, 5000)
},[])

  return (

Clicked {txt}

      <button onClick={()=>{setCount(1+count);}}>Click</button>

  );
}

After the page load, I clicked the button several times and I see the count increased, but after 5 sec, the console still print out "0 time", I wonder why it does not access the txt variable value in the closure scope
Thanks.

function App() {
  if(!window.stack) {
    window.stack = []
  }
  const [count, setCount] = useState({v:0});

  window.stack.push(count);
  var times = count.v>0?"times":"time";
  var txt = count.v + " " + times;

  return (

Clicked {txt}

      <button onClick={()=>{setCount({v:1+count.v});}}>Click</button>

  );
}

A: Every time the component renders or re-renders, App runs again. Each re-render creates a new count variable.
The useEffect runs only on the initial render, since its dependency array is []. On the initial render, count is 0. If you click the button, the component will have re-rendered, but the timeout in the useEffect still closes over only the initial render's count variable.
If you need something like this, you could use a ref as well, for which there is a stable reference across all renders, so the initial render's closure can reference the object that gets mutated in a later render:

const App = () => {
  const [count, setCount] = React.useState(0);
  const times = count > 0 ? "times" : "time";
  const txt = count + " " + times;
  const txtRef = React.useRef(txt);
  txtRef.current = txt;

  React.useEffect(() => {
    setTimeout(() => {
      console.log(txtRef.current);
    }, 5000)
  }, []);

  return (

Clicked {txt}

      <button onClick={()=>{setCount(1+count);}}>Click</button>

  );
}

ReactDOM.render(<App />, document.querySelector('.react'));

Another (probably worse, more complicated) option would be to call clearTimeout in useEffect's cleanup, and call setTimeout on every render, pass the timeout time remaining from render to render by checking Date.now(). (this wouldn't work well for components that get frequently re-rendered)


text:
Q: Slow SSAS cumulative sum calculated measure I have a cumulative sum of a measure structured as:
Aggregate (
    { NULL : [Date].[Year - Month - Date].CurrentMember }
    ,[Measures].[Applications] )

From the date of the first application to the current date, the days of the date range must be contiguous.
The Date dimension however contains dates ranging from 1900-01-01 to well into the future.
I've attempted to eliminate dates before the first application, and future dates by structuring the calculated measure as follows:
CREATE MEMBER CURRENTCUBE.[Measures].[Applications TD] AS
CASE
WHEN
    /* Eliminates dates before first applications, i.e. year 1900-01-01 */
    Aggregate (
        { NULL : [Date].[Year - Month - Date].CurrentMember }
        ,[Measures].[Applications] ) < 0
THEN NULL
WHEN
    /* Eliminates dates after today */
    [Date].[Year - Month - Date].CurrentMember.MemberValue >= StrToMember('[Date].[Date].&['+Format(Now(),"yyyy-MM-ddT00:00:00")+']').MemberValue
THEN NULL
ELSE
    Aggregate (
            { NULL : [Date].[Year - Month - Date].CurrentMember }
            ,[Measures].[Applications] )
END

I have been unsuccessful in any attempt to optimizing this by aggregating only where needed using a SCOPE as an alternative to the case statement, utilizing EXISTS and EXCEPT functions and many others.
When browsing the cube and dimensioning [Measures].[Applications TD] by [Date].[Year - Month - Date] user-defined hierarchy it is terribly slow.

A: IIF is generally faster than CASE, and SUM is often faster than AGGREGATE.
Although your main problem is the second part of your condition using membervalue - is it required or will the following not do the same thing? :
CREATE MEMBER CURRENTCUBE.[Measures].[Applications TD] AS
IIF(
     SUM (
        { NULL : [Date].[Year - Month - Date].CurrentMember }
        ,[Measures].[Applications]
     ) < 0
   , NULL
   ,
   SUM (
         { NULL : [Date].[Year - Month - Date].CurrentMember }
          ,[Measures].[Applications]
    )
)

I'd separate this out as a custom member:
CREATE MEMBER CURRENTCUBE.[Date].[Date].[All].[Today] AS //<< a  little of syntax for this create
    StrToMember('[Date].[Date].&['+Format(Now(),"yyyy-MM-ddT00:00:00")+']')

Then try a nested IIF:
CREATE MEMBER CURRENTCUBE.[Measures].[Applications TD] AS
IIF(
    [Date].[Year - Month - Date].CurrentMember.MemberValue >= [Date].[Date].[All].[Today].MemberValue
   , NULL
   , IIF(
       SUM (
          { NULL : [Date].[Year - Month - Date].CurrentMember }
          ,[Measures].[Applications]
       ) < 0
     , NULL
     ,
     SUM (
           { NULL : [Date].[Year - Month - Date].CurrentMember }
            ,[Measures].[Applications]
      )
  )
)

BUT
Rather than bothering with the "Today" member it will be a lot more efficient if you add an isToday column to DimDate  - then have an attribute of the cubes date dimension using the column. That way you should be able to simplify this [Date].[Year - Month - Date].CurrentMember.MemberValue >= [Date].[Date].[All].[Today].MemberValue

redpajama_set_name: RedPajamaStackExchange


text:
Q: Check if the entry in DB exists - Drupal 7 I have made a module that when cron run it gets the wid and variables and timestamp from the watchdog table and pass it in a new table blablabla. I want if a value with same variables exists in the blablabla table do not pass this value. Here follow my code:
function blablabla_cron() {

  // Begin building the query.
  $query = db_select('watchdog', 'th')
    ->extend('PagerDefault')
    ->orderBy('wid')
    ->fields('th', array('wid', 'timestamp'))
    ->limit(2000);

  // Fetch the result set.
  $result = $query -> execute();

  // Loop through each item and add to $row.
  foreach ($result as $row) {
    blablabla_table($row);
  }
}

function error_log_jira_table($row) {

  $timestamp = $row -> timestamp;
  $wid = $row -> wid;
  $variables = $row -> variables;

  $nid = db_insert('error_log_jira')
    ->fields(array(
      'timestamp' => $timestamp,
      'wid' => $wid,
      'variables' => $variables
    ))
    ->execute();
}

A: You need to query the table to see if the data exists before writing to it, if a row exists matching the criteria then do nothing. For example;
function blablabla_cron() {

  // Begin building the query.
  $query = db_select('watchdog', 'th')
    ->extend('PagerDefault')
    ->orderBy('wid')
    ->fields('th', array('wid', 'timestamp', 'variables'))
    ->limit(2000);

  // Fetch the result set.
  $result = $query -> execute();

  // Loop through each item and add to $row.
  foreach ($result as $row) {

    // Query Blablabla table for row matching timestamp and variables
    $r = db_select('blablabla', 'b')
      ->fields('b')
      ->condition('timestamp', $row->timestamp, '=')
      ->condition('variables', $row->variables, '=')
      ->execute();

    // If row doesn't exist then create it (I assume blablabla_table creates?)
    if($r->rowCount() == 0) {
      blablabla_table($row);
    }
  }
}

Pretty difficult to give an example given that you're missing the blablabla_table() function in your question, I assume it writes to the blablabla_table. In the future ask questions without placeholder names.


text:
Q: Vanilla JS multi image upload doesn't work when dropping files, does work when selecting files manually I am using a script based on this one to allow users to add multiple images to a form.
The form has multiple other inputs and the multi-image selection is part of it.
If I select files 'manually' using the 'click here' then the files are sent with the form submit. If the user drops them onto the 'dropzone' however, they do not get sent with the form. How can I make sure they do?

let dropBox = document.getElementById('dropBox');

['dragenter', 'dragover', 'dragleave', 'drop'].forEach(evt => {
  dropBox.addEventListener(evt, prevDefault, false);
});

function prevDefault(e) {
  e.preventDefault();
  e.stopPropagation();
}
['dragenter', 'dragover'].forEach(evt => {
  dropBox.addEventListener(evt, hover, false);
});
['dragleave', 'drop'].forEach(evt => {
  dropBox.addEventListener(evt, unhover, false);
});

function hover(e) {
  dropBox.classList.add('!bg-lime-100', 'border-lime-300');
}

function unhover(e) {
  dropBox.classList.remove('!bg-lime-100', 'border-lime-300');
}

dropBox.addEventListener('drop', mngDrop, false);

function mngDrop(e) {
  let dataTrans = e.dataTransfer;
  let files = dataTrans.files;
  filesManager(files);
}

function filesManager(files) {
  files = [...files];
  files.forEach(previewFile);
}

function previewFile(file) {
  if (!file.type.match(/image.*/)) {
    return alert('Only JPG, JPEG and PNG files are allowed');
  }

  let fReader = new FileReader();
  let gallery = document.getElementById('gallery');

  fReader.readAsDataURL(file);

  fReader.onloadend = function() {
    let wrap = document.createElement('div');
    let img = document.createElement('img');

    img.src = fReader.result;
    img.classList.add('rounded-lg');

    let imgCapt = document.createElement('p');

    let fSize = Math.round((file.size / 1024 / 1024) * 10) / 10 + ' MB';

    imgCapt.innerHTML = `<span class="text-md font-bold tracking-tight">${fSize}</span>`;
    gallery.appendChild(wrap).appendChild(img);
    gallery.appendChild(wrap).appendChild(imgCapt);
  }
}
<form method="post" action="..." enctype="multipart/form-data">

  <input type="text" name="name">
  <input type="text" name="example">
  <input type="text" name="etc">

Drag and drop your images here, or

    <input type="file" name="photos[]" id="imgUpload" multiple accept="image/*" onchange="filesManager(this.files)" class="hidden">
    Click here to select from your computer

</form>

I tried adding this in the previewFile function but that doesn't work:
let dropBox = document.getElementById('dropBox');
let formData = new FormData(dropBox[0]);
formData.append('photos', file);

A: <input type="file"> elements are read-only inputs. Files can't be assigned to them. For security reasons user input is necessary to attach a file on the client computer to a form. The "Browse..." or "Choose file..." button provides that user input.
In the case of a drag and drop interaction create a FormData object:
const photoFormData = new FormData();

...and append() each file to it using forEach():
files.forEach((file, idx) => {
  photoFormData.append(`photos[${idx}]`, file);
});

The index (idx) of the file in the files array is used to differentiate each file in the FormData object.
When the user submits the form, use a submit addEventListener() to post the FormData object holding the files to the location the form is posted to using fetch():
document.querySelector('form').addEventListener('submit', function ({target}) {
  fetch(target.action, {
    method: 'put',
      body: photoFormData
  })
  .then(result => { console.log('Success:', result); })
  .catch(error => { console.error('Error:', error); });
});

Appending the files can happen in the filesManager() function:
function filesManager(files) {
  files = [...files];
  files.forEach((file, idx) => {
    photoFormData.append(`photos[${idx}]`, file);
  });
  files.forEach(previewFile);
}

let dropBox = document.getElementById('dropBox');
const photoFormData = new FormData();

document.querySelector('form').addEventListener('submit', function ({target}) {
        fetch(target.action, {
        method: 'put',
            body: photoFormData
  })
  .then(result => { console.log('Success:', result); })
  .catch(error => { console.error('Error:', error); });
});

['dragenter', 'dragover', 'dragleave', 'drop'].forEach(evt => {
  dropBox.addEventListener(evt, prevDefault, false);
});

function prevDefault(e) {
  e.preventDefault();
  e.stopPropagation();
}
['dragenter', 'dragover'].forEach(evt => {
  dropBox.addEventListener(evt, hover, false);
});
['dragleave', 'drop'].forEach(evt => {
  dropBox.addEventListener(evt, unhover, false);
});

function hover(e) {
  dropBox.classList.add('!bg-lime-100', 'border-lime-300');
}

function unhover(e) {
  dropBox.classList.remove('!bg-lime-100', 'border-lime-300');
}

dropBox.addEventListener('drop', mngDrop, false);

function mngDrop(e) {
  let dataTrans = e.dataTransfer;
  let files = dataTrans.files;
  filesManager(files);
}

function filesManager(files) {
  files = [...files];
  files.forEach((file, idx) => {
    photoFormData.append(`photos[${idx}]`, file);
  });
  files.forEach(previewFile);
}

function previewFile(file) {
  if (!file.type.match(/image.*/)) {
    return alert('Only JPG, JPEG and PNG files are allowed');
  }

  let fReader = new FileReader();
  let gallery = document.getElementById('gallery');

  fReader.readAsDataURL(file);

  fReader.onloadend = function() {
    let wrap = document.createElement('div');
    let img = document.createElement('img');

    img.src = fReader.result;
    img.classList.add('rounded-lg');

    let imgCapt = document.createElement('p');

    let fSize = Math.round((file.size / 1024 / 1024) * 10) / 10 + ' MB';

    imgCapt.innerHTML = `<span class="text-md font-bold tracking-tight">${fSize}</span>`;
    gallery.appendChild(wrap).appendChild(img);
    gallery.appendChild(wrap).appendChild(imgCapt);
  }
}


text:
Q: React.js Music-Player: How can I play audio when list element is clicked? Good afternoon all,
I am a new programmer and I recently started following a music-player tutorial, and am experiencing a couple of issues with it.
Project Overview:
As previously described, it is a music-player project made with create-react-app.  The objective is to click the image of the song of your choosing, and for the song to be played for you.
The songs are saved as mp3's  in a folder named music. The music folder is located in the src directory. Each song is assigned to its given song image (as you'll see on the code I provided below). Then the songs/images are wrapped in an
 list element.
The Problem:
I am having trouble with playing the audio when the image is clicked. I've integrated a lot of the advice I've recieved from different users. Though i'm grateful for the result, which is that the code compiles (no error messages), I'm still experiencing the same issue, and that is that the audio doesn't play when clicked.
So to clarify, How can I make it so that when I click the list element, It will play the assigned audio?  Please correct my code and provide an example of the solution using the code I've provided below. Due to my novice skills, I am not familiar with any complex terms.
The Code:
Turkish.js (the music-player file):
import React, { Component,audio,useRef } from 'react';

import turk1 from "../music/turk1.mp3";
import turk2 from "../music/turk2.mp3"
import turk3 from "../music/turk3.mp3"
import turk4 from "../music/turk4.mp3"

const data = [
    { imgSrc: 'turk1.png', audioSrc: turk1 },
    { imgSrc: 'turk2.png', audioSrc: turk2 },
    { imgSrc: 'turk3.png', audioSrc: turk3 },
    { imgSrc: 'turk4.png', audioSrc: turk4 },
  ];

  export default class Turkish extends Component {
    render() {
      return (

            {data.map(({ imgSrc, audioSrc }) => (
              <MediaComponent imgSrc={imgSrc} audioSrc={audioSrc} />
            ))}

      );
    }
  }

  const MediaComponent = ({ imgSrc, audioSrc }) => {
    const audioRef = useRef(null);
    const toggleAudio = () =>
      audio.ref.current.paused
        ? audioRef.current.play()
        : audioRef.current.pause();
    return (

        <audio ref={audioRef} src={audioSrc} />

    );
  };

Package.json:

{
  "name": "spotifly",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^12.1.5",
    "@testing-library/user-event": "^13.5.0",
    "bootstrap": "^5.1.3",
    "navbar": "^2.1.0",
    "react": "^18.0.0",
    "react-audio-player": "^0.17.0",
    "react-bootstrap": "^2.2.3",
    "react-bootstrap-icons": "^1.8.1",
    "react-dom": "^18.0.0",
    "react-is": "^18.0.0",
    "react-router-dom": "^6.3.0",
    "react-scripts": "5.0.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Picture of the Music folder:

When I click on the song file, it tells me this:

I really appreciate your time & effort, let me know what you think!
Best,
-Zpo

A: Remove 'audio' from import React, { Component,audio,useRef } from 'react';
const MediaComponent = ({ imgSrc, audioSrc }) => {
  const audioRef = useRef(null);
  const toggleAudio = () =>
    audioRef.current === null
      ? console.log("Audio component is not loaded yet.")
      : audioRef.current.paused
      ? audioRef.current.play()
      : audioRef.current.pause();
  return (

      <audio ref={audioRef} src={audioSrc} />

  );
};

I can suggest something too. It is up to you.
const AudioPlayer = ({ imgSrc, audioSrc }) => {
  const [status, setStatus] = useState({
    isPlaying: false,
    isLoop: false,
    isLoaded: false,
    error: false,
    ...others,
  });
  const audioRef = useRef(null);

  const toggleAudio = () =>
    status.isLoaded
      ? status.isPlaying
        ? audioRef.current.pause()
        : audioRef.current.play()
      : console.log("Audio has not loaded yet.");

  return (

      <audio
        ref={audioRef}
        src={audioSrc}
        onLoad={() => setStatus({ ...status, isLoaded: true })}
        onPlay={() => setStatus({ ...status, isPlaying: true })}
        onPause={() => setStatus({ ...status, isPlaying: false })}
        onError={() => setStatus({ ...status, error: true })}
      />

  );
};


text:
Q: ruby watir browser.send_keys times out after 60 seconds if machine unattended I'm working with send_keys where I have to hit Enter
@ie.element(:css, "#accountSwitcherSelect.dijitDownArrowButton").send_keys :enter

which makes another object that switches accounts visible
@ie.div(:id => "accountSwitcherSelect_dropdown").table(:id => "accountSwitcherSelect_menu")

Here's the kicker, it works perfectly if I'm there, and the browser is in focus in the foreground.
But, if I either
a) lock the Windows OS screen, or
b) are working on a Remote Desktop and switch out of RDP, or
c) started running the ruby script from a scheduled task on an unattended machine
it will see the first dropdown just fine
puts @ie.element(:css, "#accountSwitcherSelect.dijitDownArrowButton").visible?

but it never does   send_keys :enter   and never will see  "accountSwitcherSelect_menu" and throws

timed out after 60 seconds

error
watir 6.10.3, ruby 2.2.5, Windows OS, IE 11
--Here's the full error message, where line 125 is
@ie.element(:css, "#accountSwitcherSelect.dijitDownArrowButton").send_keys :enter

C:/ruby225/lib/ruby/gems/2.2.0/gems/rautomation-0.17.0/lib/rautomation/wait_helper.rb:20:in
  wait_until': timed out  after 60 seconds
  (RAutomation::WaitHelper::TimeoutError)
          from C:/ruby225/lib/ruby/gems/2.2.0/gems/rautomation-0.17.0/lib/rautomation/adapter/win_32/window.rb:153:in
  block in send_keys'
          from C:/ruby225/lib/ruby/gems/2.2.0/gems/rautomation-0.17.0/lib/rautomation/adapter/win_32/window.rb:152:in
  each'
          from C:/ruby225/lib/ruby/gems/2.2.0/gems/rautomation-0.17.0/lib/rautomation/adapter/win_32/window.rb:152:in
  send_keys'
          from C:/ruby225/lib/ruby/gems/2.2.0/gems/rautomation-0.17.0/lib/rautomation/window.rb:192:in
  send_keys'
          from C:/ruby225/lib/ruby/gems/2.2.0/gems/watir-classic-4.3.0/lib/watir-classic/browser.rb:452:in
  send_keys '
          from C:/ruby225/lib/ruby/gems/2.2.0/gems/watir-classic-4.3.0/lib/watir-classic/element.rb:124:in
  send_keys '
          from DeleteTriggers8.rb:125:inblock in '
          from DeleteTriggers8.rb:106:in each'
          from DeleteTriggers8.rb:106:in'

A: Thank you @Rajagopalan the browser window focus issue seemed to be a limitation of now deprecated watir-classic. Switching to latest watir-webdriver solves the problem.


text:
Q: Sliding a tableview in iOS How do I slide all the content in the table view and update the table view with new content, i am working on a project just like google drive IOS app, where when u click on a folder, the old content slides to left and the new content slides in from the right, does anybody have any idea about this?
Any help will be greatly appreciated, thanks!!!

A: tableView.beginUpdates()
    tableView.insertRowsAtIndexPaths(toAdd, withRowAnimation: animateLeft ? .Right : .Left)
    tableView.deleteRowsAtIndexPaths(toDelete, withRowAnimation: animateLeft ? .Left : .Right)
tableView.endUpdates()

If you are going to remove all of the data then the toDelete variable is an array of indexPaths 0 through currentContent.count. The toAdd variable is an array of indexPaths 0 through newContent.count. animateLeft is a boolean of which way you want to animate your content

A: I will do it in this way:
Customize a cell which contains the left content and right content, in normal, it shows the left content, when user clicks, the cell make a animation of position, which is slide from left to right.
Does it works for your goal?


text:
Q: Test selector for all tests in includes plus some extra (JUnit5+Surefire) How do I run all tests from the explicitly specified includes in pom.xml as well as some additional test class not contained in the includes.
In other words, I'm looking for one command to select:

*

*all tests that would be normally executed in the standard mvn test run

*a separate test class explicitly specified in the argument ExtraTestClass

something along the lines of: mvn test -Dtest="includes,ExtraTestClass"
or
mvn test && mvn test -Dtest="ExtraTestClass"
Is that possible or would I have to adjust the names of all tests included in the standard mvn test run to fit a pattern?


text:
Q: D3.js table not refreshing when data changes I'm displaying a table in the browser using d3.json function. My table in the browser is not refreshing when data changes in the json file. It's showing previous data instead of new data in the table. If I refresh manually in the browser then it works correctly the table changes with new data.
Here is the code I use:
<!DOCTYPE html>
<meta charset="utf-8">

Download

The graph is not refreshing when data changes in the json file.
Does anyone have any ideas on where the problem lies?
I was created node.js application and restful web service to get the data from database based on user requirement and data is written into "traffic.json" file. When the user is selected particular chart on the application we are sending that html file to the browser. In HTML d3.json function is firing.
Here is the code I use:
=======================
 var express = require('express'),
 http = require('http'),
 querystring = require('querystring'),
 router = express.Router(),
 fs = require('fs'),
 MongoClient = require('mongodb').MongoClient,
 format = require('util').format,
 mongo = require('mongodb'),
 monk = require('monk'),
 json2csv = require('json2csv'),
 Reloader = require('reload-json'),
 reload = new Reloader();

var Start_Date ;
var End_Date ;
var Client_Ip;
var Clientip;
var ChooseData;
var Charts;
var Chart1;
var Choosedata1;
//Getting the data from calsoftlabs page
router.post('/myaction', function(req, res, next) {

     Start_Date =   req.body.StartDate +'T'+ req.body.StartTime ;
     End_Date   =   req.body.EndDate +'T'+ req.body.EndTime;
     Client_Ip  =   req.body.ClientIP;
     Clientip   =   req.body.ClientIPS;
     ChooseData =   req.body.ChooseData;
     Charts     =   req.body.Charts;
     Chart1     =   req.body.Chart;
     Choosedata =   req.body.Data;

//converting date and time to timestamp.
function evaldate(input){
var date = new Date(input);
return date.getTime();
}

var Start_timestamp = evaldate(Start_Date),

 End_timestamp = evaldate(End_Date);

var dbdata,
 start_time,
 end_time,
 client_ip,
 choosedata,
 options,
 data,
 req;
//sending parameters to restfull webapp service
if(Choosedata == "upload" || Choosedata == "download") {
 data = querystring.stringify({
      start_time: Start_timestamp,
      end_time: End_timestamp,
      client_ip: Clientip,

    });
} else if(ChooseData == "upload_traffic" || ChooseData == "download_traffic" || ChooseData == "both" ) {

data = querystring.stringify({
      client_ip: Client_Ip,
    });

}
console.log(data);

if(ChooseData == "upload_traffic") {

options = {
    host: 'localhost',
    port:8080,
    path:'/restful/traffic/upload_traffic',
    method:'POST',
     headers: {
        'Content-Type': 'application/json',
    }
};

} else if(ChooseData == "download_traffic") {

options = {
    host: 'localhost',
    port:8080,
    path:'/restful/traffic/download_traffic',
    method:'POST',
     headers: {
        'Content-Type': 'application/json',
    }
};

} else if(Choosedata == "upload") {

options = {
    host: 'localhost',
    port:8080,
    path:'/restful/traffic/upload',
    method:'POST',
     headers: {
        'Content-Type': 'application/json',
    }
};

}else if(Choosedata == "download"){

options = {
    host: 'localhost',
    port:8080,
    path:'/restful/traffic/download',
    method:'POST',
     headers: {
        'Content-Type': 'application/json',
    }
};

} else if(ChooseData == "both") {

options = {
    host: 'localhost',
    port:8080,
    path:'/restful/traffic/both',
    method:'POST',
     headers: {
        'Content-Type': 'application/json',
    }
};

}

//creating file, writing network data to a file.
var fileName = 'views/traffic.json';
req = http.request(options, function(response) {
 var jsonString = '';
 response.on('data', function(data) {
    jsonString += data;
});
 response.on('end',function(){
    console.log(jsonString);
    fs.writeFile(fileName, jsonString,'utf-8');
    });
});

if(Chart1 == 'Line') {

  res.sendfile('views/Line.html');

} else if(Chart1 == 'Bar') {

res.sendfile('views/Newbar.html');

} else if(Chart1 == 'Area') {

res.sendfile('views/Area.html');

} else if(Chart1 == 'Pie') {

res.sendfile('views/Pie.html');

} else if(Chart1 == 'Multiline') {

res.sendfile('views/Multiline.html');

} else if(Chart1 == 'All') {

res.sendfile('views/Newall.html');

} else if(Charts == 'Table') {

res.sendfile('views/Table.html');

} else if(Charts == 'StackedBar') {

res.sendfile('views/StackedBar.html')

}

req.write(data);
req.end();
req.on('error', function(e) {
    console.error(e);
});
});

module.exports = router;

A: Your table is not refreshing because your d3.json(jsonURL, function(data) {...}) is not listening to changes to your data-file. That function will run once and that's it.
Say you rerun your data function d3.json(jsonURL, function(data) {...}) at a certain interval your next problem will be that you will never update your table but just attach a new one:
var table = d3.select("#container").append("table")

You are not selecting your table (that might already exist) but just appending a new table to the DOM. You will need to have a look at the data binding principle in d3.


text:
Q: Getting application directory in phone gap Using the file api of phone gap build, I want to get the application directory in which all files should be stored.
What command do I need to use?

A: function gotFS(fileSystem) {
    console.log("got filesystem");
    // save the file system for later access
    console.log(fileSystem.root.fullPath);
    window.rootFS = fileSystem.root;
}

document.addEventListener('deviceready', function() {
    window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}, false);

With this code you'll have a DirectoryEntry object for the root directory of your app stored in the global variable "rootFS". You can get the path of that folder like this:
rootFS.fullPath

A: You can use cordova.file.applicationDirectory for getting your app directory.
It will resolve to
file:///android_asset/ in android and
/var/mobile/Applications//.app/  in IOS
You can get all your app files in the www directory in both android and iOS.
window.resolveLocalFileSystemURL(cordova.file.applicationDirectory+'www/index.html',success,fail);
function success(fileEntry){
console.log("got the file object")
}
function fail(error){
console.log("error");
}

for getting the app directory on the filesystem where your app files will be stored can be get by cordova.file.applicationStorageDirectory
which further contains two directories files and cache both are persistent.
you can check the link for further details..
https://github.com/apache/cordova-plugin-file/blob/master/doc/index.md


text:
Q: How can I use Zeus for rake assets:precompile I'm trying to get faster startup times for building my assets and would like to use Zeus. How can I use Zeus for bundle exec rake assets:precompile?

A: zeus start
zeus rake assets:precompile

This page has more details on how to get it working.


text:
Q: Getting time from DB as UTC+9:00- Django This is my Django test code.
TODAY=timezone.localtime()
AFTER_6MONTH = datetime.timedelta(days=180)

class TestView_Time(TestCase):

    def setUp(self):
        TimeSchedule.objects.create(start_date=TODAY,
                                     end_date=TODAY+AFTER_6MONTH,
                                     round_number=1,
                                     id=1)
    def test_time_setting(self):
        print(timezone.localtime(RoundSchedule.objects.get(id=1).start_date))
        print(RoundSchedule.objects.get(id=1).end_date)

And this is Output.
2021-07-29 14:31:38.605785+09:00
2021-08-28 05:31:38.605785+00:00

I want to make second Output line as First line. not using local time function. How can I change default setting??
LANGUAGE_CODE = 'ko-kr'
TIME_ZONE = 'Asia/Seoul'
USE_I18N = True
USE_L10N = True
USE_TZ = True

A: You need to change TIME_ZONE = 'YOUR COUNTRY TIME ZONE'
Assuming you are from Korea
TIME_ZONE = 'Asia/Seoul'


text:
Q: Zend Framework: Flash Messenger, add a message from the model Any idea on how best to add a message to flash messenger from the model?
As FlashMessenger is an action helper, this seems not to be possible, so the obvious solution is to create an internal message object in the model, and return that to the controller from where you can use addMessage(). But if you want to return something else as well, this falls down.
Another idea is an additional session namespace for these internal messages, which is then merged in with the Flash Messenger namespace messages at output time?
Anyone have any thoughts or experience on this? Cheers.

A: You can fetch the FlashMessenger from your model like this:
$messenger = Zend_Controller_Action_HelperBroker::getStaticHelper('flashMessenger');
$messenger->addMessage('test message');

A: Both routes sound valid.
One idea would be to add a $message arrayto your model, which the action helper can access to retrieve the messages. This way you could return multiple messages at once.
Another option would be to use a Subject/Observer pattern. Have your models implement the Subject interface and when you need to output messages, notify the observers, e.g. the flash messenger (for which you would have to implement the Observer interface).


text:
Q: How to generate Dart code for annotations at fields? I'm writing a code generator for Dart using the build_runner, but my builder is not being called for annotations at fields, although it does work for annotations at classes.
Is it possible to also call the generator for annotations at fields (or at any place for that matter)?
For example, the builder is called for the following file:
import 'package:my_annotation/my_annotation.dart';

part 'example.g.dart';

@MyAnnotation()
class Fruit {
  int number;
}

But not for this one:
import 'package:my_annotation/my_annotation.dart';

part 'example.g.dart';

class Fruit {
  @MyAnnotation()
  int number;
}

Here's the definition of the annotation:
class MyAnnotation {
  const MyAnnotation();
}

And this is how the generator is defined. For now, it just aborts whenever it's called, causing an error message to be printed.
library my_annotation_generator;

import 'package:analyzer/dart/element/element.dart';
import 'package:build/build.dart';
import 'package:my_annotation/my_annotation.dart';
import 'package:source_gen/source_gen.dart';

Builder generateAnnotation(BuilderOptions options) =>
    SharedPartBuilder([MyAnnotationGenerator()], 'my_annotation');

class MyAnnotationGenerator extends GeneratorForAnnotation<MyAnnotation> {
  @override
  generateForAnnotatedElement(Element element, ConstantReader annotation, _) {
    throw CodeGenError('Generating code for annotation is not implemented yet.');
}

Here's the build.yaml configuration:
targets:
  $default:
    builders:
      my_annotation_generator|my_annotation:
        enabled: true

builders:
  my_annotation:
    target: ":my_annotation_generator"
    import: "package:my_annotation/my_annotation.dart"
    builder_factories: ["generateAnnotation"]
    build_extensions: { ".dart": [".my_annotation.g.part"] }
    auto_apply: dependents
    build_to: cache
    applies_builders: ["source_gen|combining_builder"]

A: At least from my experience, your file 'example.dart' would need at least one annotation above the class definition to be parsed by GeneratorForAnnotation.
example.dart:
import 'package:my_annotation/my_annotation.dart';

part 'example.g.dart';

@MyAnnotation()
class Fruit {
 @MyFieldAnnotation()
 int number;
}

To access annotations above class fields or class methods you could use a visitor to "visit" each child element and extract the source code information.
For example, to get information about the class fields you could override the method visitFieldElement and then access any annotations using the getter: element.metadata.
builder.dart:
import 'dart:async';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/visitor.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:build/src/builder/build_step.dart';
import 'package:source_gen/source_gen.dart';
import 'package:my_annotation/my_annotation.dart';

class MyAnnotationGenerator extends
GeneratorForAnnotation<MyAnnotation> {
  @override
  FutureOr<String> generateForAnnotatedElement(
      Element element,
      ConstantReader annotation,
      BuildStep buildStep,){
    return _generateSource(element);
  }

  String _generateSource(Element element) {
    var visitor = ModelVisitor();
    element.visitChildren(visitor);
    return '''
      // ${visitor.className}
      // ${visitor.fields}
      // ${visitor.metaData}
    ''';
  }
}

class ModelVisitor extends SimpleElementVisitor {
  DartType className;
  Map<String, DartType> fields = {};
  Map<String, dynamic> metaData = {};

  @override
  visitConstructorElement(ConstructorElement element) {
    className = element.type.returnType;
  }

  @override
  visitFieldElement(FieldElement element) {
    fields[element.name] = element.type;
    metaData[element.name] = element.metadata;
  }
}

Note: In this example, _generateSource returns a commented statement. Without comments you would need to return well-formed dart source code, otherwise, the builder will terminate with an error.
For more information see:
Source Generation and Writing Your Own Package (The Boring Flutter Development Show, Ep. 22) https://www.youtube.com/watch?v=mYDFOdl-aWM&t=459s

A: The built-in GeneratorForAnnotation uses the LibraryElement's annotatedWith(...) method, which only checks for top-level annotations.
To also detect annotations on fields, you'll need to write something custom.
Here's the Generator I wrote for my project:
abstract class GeneratorForAnnotatedField<AnnotationType> extends Generator {
  /// Returns the annotation of type [AnnotationType] of the given [element],
  /// or [null] if it doesn't have any.
  DartObject getAnnotation(Element element) {
    final annotations =
        TypeChecker.fromRuntime(AnnotationType).annotationsOf(element);
    if (annotations.isEmpty) {
      return null;
    }
    if (annotations.length > 1) {
      throw Exception(
          "You tried to add multiple @$AnnotationType() annotations to the "
          "same element (${element.name}), but that's not possible.");
    }
    return annotations.single;
  }

  @override
  String generate(LibraryReader library, BuildStep buildStep) {
    final values = <String>{};

    for (final element in library.allElements) {
      if (element is ClassElement && !element.isEnum) {
        for (final field in element.fields) {
          final annotation = getAnnotation(field);
          if (annotation != null) {
            values.add(generateForAnnotatedField(
              field,
              ConstantReader(annotation),
            ));
          }
        }
      }
    }

    return values.join('\n\n');
  }

  String generateForAnnotatedField(
      FieldElement field, ConstantReader annotation);
}

A: I had a very similar issue trying to target specific methods within my annotated classes. Inspired by your answers I slightly modified the class annotation model_visitor to check the method annotation before selecting elements.
class ClassAnnotationModelVisitor extends SimpleElementVisitor<dynamic> {
  String className;

  Map<String, String> methods = <String, String>{};
  Map<String, String> parameters = <String, String>{};

  @override
  dynamic visitConstructorElement(ConstructorElement element) {
    final elementReturnType = element.type.returnType.toString();
    className = elementReturnType.replaceFirst('*', '');
  }

  @override
  dynamic visitMethodElement(MethodElement element) {
    if (methodHasAnnotation(MethodAnnotation, element)) {
      final functionReturnType = element.type.returnType.toString();
      methods[element.name] = functionReturnType.replaceFirst('*', '');
      parameters[element.name] = element.parameters.map((e) => e.name).join(' ,');
    }
  }

  bool methodHasAnnotation(Type annotationType, MethodElement element) {
    final annotations = TypeChecker.fromRuntime(annotationType).annotationsOf(element);
    return !annotations.isEmpty;
  }
}

Then, I can use the basic GeneratorForAnnotation class and generate for class and methodsArray.


text:
Q: Yeti CRM will not attach files using PHPMailer I am using a form in the Yeti CRM that allows the user to view a document then gives them the option to email said document. It is using PHPMailer but I cannot get it to attach the document. All other fields are responding to edits (To, From, Subject, Body) but nothing is attaching. Error logs do not throw an error.
I have tried directly linking a file that I know exists but still no luck. Can anyone see in the code below where I am not actually attaching the document?
Here is the PHP function
public function process(\App\Request $request)
{
    $moduleName = $request->getModule();
    $recordId = $request->getInteger('record');
    $documentRecordModel = Vtiger_Record_Model::getInstanceById($recordId, $moduleName);
    $currentUser = Users_Record_Model::getCurrentUserModel();

    $mails = $request->get('to');
    $message = $request->get('message');
    $from['email'] = $currentUser->get('email1');
    $name = $currentUser->get('first_name') . " " . $currentUser->get('last_name');
    $from['name'] = $name;
    $file = $documentRecordModel->get('filename');
    $title = $documentRecordModel->get('notes_title') . substr($file, strrpos($file, "."));
    if (strpos($file, "\\\\") !== false) {
        $file = trim($file);
        $file = str_replace('\\\\', '\\', $file);
        $file = str_replace('\\', '/', $file);
        $file = str_replace(' ', '%20', $file);
        $file = ROOT_DIRECTORY . DIRECTORY_SEPARATOR .
            "public_html" . DIRECTORY_SEPARATOR .
            "external" .
            $file;
        $attachment[$file] = $title;
    } else {
        //this is a http type document, so just link straight to it.
        $message .= '
' . '' . $title . '';
    }

    if (count($mails) > 0) {
        $results[] = \App\Mailer::sendFromTemplate([
            'template' => 'ZcoSendPDFFile',
            'moduleName' => 'Documents',
            'recordId' => $recordId,
            'to' => $mails,
            'from' => $from,
            'message' => $message,
            'attachments' => $attachment,
            //'smtp_id' => 2,
        ]);
    }
     $response = new Vtiger_Response();
 $response->setResult($results);
 $response->emit();
}

}
This is the js file that builds the params
$(document).ready(function () {
var form = document.getElementById("emailDocument");
form.onsubmit = function (event) {
    event.preventDefault();
    let thisInstance = this;
    let fromEmail = $("#fromEmail").html();
    let toEmail = $("#toEmail").val();
    let message = $("#message").val();
    let recordId = getParameterByName("record");
    let attachment = $("#pdfAttach").html();
    let params = {
        'module': 'Documents',
        'action': 'ZcoEmailFile',
        'mode': 'process',
        'from': fromEmail,
        'to': toEmail,
        'message': message,
        'record': recordId,
        'attachments': attachment
    };
    $.post({
        url: "index.php",
        data: params,
        ContentType: "text/json",
        success: function() {
            alert('Email has been sent!');
        },
        beforeSend: function(xhr) {
            $("#submitEmail").attr("disabled", "disabled");
        },
        complete: function() {
            $("#submitEmail").removeAttr("disabled");
        },
        error: function(msg) {
            alert(JSON.stringify(msg));
        }
    });
};

});
And the form
<form id="emailDocument">

{$FILENAME}

From:

{$USER_MODEL->get('email1')}

To:

<input type="text" id="toEmail" value="{$CONTACT->get('email')}">

                Additional Message:
                <textarea type="text" id="message" rows="3" cols="50"></textarea>

                <input type="submit" value="Submit" id="submitEmail">

</form>

The email sends fine with all of the fields except the attachment. I haven't used PHP in six years so suffice to say I'm a little rusty. Can anyone see why the attachment is not attaching?

A: With a little help from @Synchro I have solved my issue. My PHP file was not calling the attachment correctly. The field is an array and I was trying to make it a string. Once I set $attachment equal to the values in the array built in PHPMailer it sent without issue.
Code added:
$attachment = array($path, $file, $name, $encoding, $type, false, $disposition, $name);


text:
Q: Energy and particle conservation in Maxwell-Boltzmann statistics I was working with a derivation of Maxwell-Boltzmann statistics occupation probability today and I got this problem with the constraints:
We know that the particle number is conserved when we are increasing the value of $N_i$ by a little amount, so we write that, $$\sum_{i}^{N}\delta N_i=0$$ where $N$ is the total number of particles.
Also, since if the number of particles of a particular energy $E_i$ increases, then by energy conservation, that same energy change has to be accompanied by some other particles, in different quantum states. So, for that we write:
$$\sum_{i}^{N}E_i \delta N_i=0$$
However, I am not being able to understand this last equation. For example- Suppose we have $1000$ particles with energy $2 eV$ and $2000$ particles with energy $1 eV$, the total energy of the system is $4000\ eV$. Now, assuming that $1$ and $2$ $eV$ are the only energies that can be possessed by the particles, let us decrease the number of particles in the state $1 eV$ by $100$. So now we have $900$ particles in the $1 eV$ state, and since the energy of the system has to be conserved, the number of particles increased in the state $2 eV$ is 50.
This is where I start facing problems. The last argument shows that the number of particles having energy $2 eV$ is now $2050$, which, if added to the other ones, gives $2950$ particles, whereas the total number, in the beginning, was $3000$.
What am I missing here?

A: Looking at your constraints, it seems like you're dealing with a micro-canonical ensemble description of statistical physics. The constraints you give have physical meaning. The first one
$$\sum_i^N \delta N_i = 0$$
tells you that the number of particles in your system is fixed.
The second one
$$\sum_i^N \delta N_i = 0$$
tells you that the total energy of your system is conserved.
Now be careful. N IS NOT the number of particles in your system, but the number of states that a particle can occupy. In the case you're describing, N = 2, because you have two possible energies (I' m not considering eventual degeneracies).
In you' re example you cannot satisfy the constraints, because particle conservation tells that
$$\delta N_1 + \delta N_2 = 0,$$
while energy conservation implies that
$$\delta N_1 + 2 \delta N_2 = 0.$$
They can' t be satisfied at the same time.


text:
Q: Returning text within a string in Oracle SQL I have string data in a column of a table that will contain a monetary amount in it somewhere.
E.G. the column may contain something like:
"Dave once paid £50.00 to a lottery syndicate"
"Total Investment Returns for the fund in 2017 came to £150,964.39"
How can I search for the occurrence of the '£' sign and then return the number that occurs after it?
Thanks

A: Here is one way. The search expression is a bit complicated because it must allow for thousand separators and decimal points, all optional. It assumes "Western" usage of thousands separators - it would have to be modified slightly to allow for Lakh (Indian) notation, for example. It will produce NULL when there is no pound sign, or if there is a pound sign not immediately followed by at least one digit. (So it will have to be modified slightly if you allow things like £.60 instead of £0.60.) You can also capture just the amount (without the currency symbol) if desired - that is also a slight modification to the use of REGEXP_SUBSTR (use capture groups).
The biggest change would be needed if you may have more than one amount per input row.
with
     inputs ( str ) as (
       select 'Dave once paid £50.00 to a lottery syndicate.' from dual union all
       select 'Total Returns in 2017 came to £150,964.39.'    from dual
     )
-- End of simulated inputs (for testing purposes only, not part of the solution).
-- Use your actual table and column names in the SQL query below.
select str, regexp_substr(str, '£\d{1,3}(,?\d{3})*(\.\d+)?') as amount
from   inputs
;

STR                                            AMOUNT
---------------------------------------------  -----------
Dave once paid £50.00 to a lottery syndicate.  £50.00
Total Returns in 2017 came to £150,964.39.     £150,964.39

Edit
In a Comment below, the OP asked how to obtain just the amount, without the currency symbol. The easiest way is to use capture groups directly in the REGEXP_SUBSTR() function. The version below uses all six arguments to the function: as before the first is the input string and the second is the search pattern. The third and forth are the starting position and the occurrence (both always equal to 1 for this problem). The fifth, NULL, is for some special options we don't need. The sixth argument is relevant: 1 means return the first capture group, i.e. the part of the search pattern included in the first pair of matching parentheses (counting from left to right). Notice the additional pair of parentheses in the search pattern, to isolate the amount from the pound symbol:
regexp_substr(str, '£(\d{1,3}(,?\d{3})*(\.\d+)?)', 1, 1, null, 1)

Edit #2
To extract the amount in NUMBER data type, it is not necessary to remove the pound sign; the TO_NUMBER() function can handle it. Instead, the substring that is just the pound sign followed by the amount must be wrapped within TO_NUMBER(), using the proper format model and explicit currency symbol:
to_number(regexp_substr(str, '£\d{1,3}(,?\d{3})*(\.\d+)?'),
               'L999,999,999,999,999.000000', 'nls_currency=£')

Just make sure to include enough digits on the right of the decimal point to accommodate all possible amounts. (Too many digits in the format model is never a problem.)


text:
Q: Binding to [value] doesn't update FormControl's value More Info:
I have a list of items. Each item is an instance of a MyClass. MyClass has a property text and a method someMethod() that returns this property.
I have an *ngFor that lists all items on the page and when I click one of them (click)="currentItem = item" is executed and the [value]="someMethod()" is actually [value]="currentItem.someMethod()", so the selected item's text is written into the textarea.

I'm using Reactive forms and have the following in my template:
<textarea formControlName="myTextarea" [value]="someMethod()" ...

When the page renders and someMethod() outputs a string, I can see that string displaying inside the textarea.
However, the value property of the FormControl is not updated. Why?

A: look this link https://coursetro.com/posts/code/108/Angular-5-Interpolation,-Property-Binding-&-Event-Binding-Tutorial#
You can use [(ngModel)] with Reactive forms.
<form [formGroup]="form">
<input name="fname" formControlName="first" [(ngModel)]="example.first">
<input name="lname" formControlName="last" [(ngModel)]="example.last">
</form>
export class App {
form: FormGroup;
example = { fname: '', lname: ''}
constructor(builder: FormBuilder) {
 this.form = builder.group({ first: '', last:''})
}
}

A: That's because you are calling SomeMethod() in [value].
what are you looking for exactly ?
take a look here FormGroup


text:
Q: Can't edit the tag wiki for tag:synonyms https://english.stackexchange.com/tags/edit-tag-wiki/synonyms gives a 404
I assume this is a bug with the URL routing engine, where "synonyms" has special meaning.

A: Not only a problem for the tag synonyms
Also a problem for any tags named info faq users hot ... I went ahead and changed the routes a bit for editing tag wikis.
Should be deployed later today.


text:
Q: incorrect output when trying to rotate a matrix in python I'm trying to rotate a matrix(2-d list) in python by 90 degrees clockwise. Here is my code:
def rotate(matrix):
     length = len(matrix)
     new_matrix = [[0]*length]*length
     for i in range(length):
         for j in range(length):
             new_matrix[j][length-1-i] = matrix[i][j]
             print("new_matrix[",j,"][", length-1-i,"]", "is", new_matrix[j][length-1-i])
     for i in range(length):
         for j in range(length):
             print(new_matrix[i][j])
     return new_matrix
print(rotate([[1 ,2], [3, 4]]))

The idea is very simple, after rotating, the element with i, j as row number and column number will then have j, length-1-i as row and column numbers.
The print statement is used to verify I was doing it right. I tried [[1, 2], [3, 4]] and I got a wrong answer and a quite confusing output:
new_matrix[ 0 ][ 1 ] is 1
new_matrix[ 1 ][ 1 ] is 2
new_matrix[ 0 ][ 0 ] is 3
new_matrix[ 1 ][ 0 ] is 4
4
2
4
2
[[4, 2], [4, 2]]

It seems somehow values 1 and 3 got overwritten somehow. And when I tried [[1, 2, 3], [4, 5, 6], [7, 8, 8]] and new_matrix became [[9, 6, 3], [9, 6, 3], [9, 6, 3]]. So there is definitely something wrong here.
Any idea why?

A: The problem in your code is this line,
new_matrix = [[0]*length]*length

It's not doing what you think -  its actually creating a list of length number of the same inner list.
Replace it with something like the following which will create distinct inner lists,
new_matrix = [[0]*length for _ in range(length)]


text:
Q: Get BLE MAC from random private resolvable address I'd like to connect an Android device (client) to an External BLE device (server). I've a couple of questions concerning the private random resolvable address mechanism.

*

*As far as I understood from the BLE core spec, an identity-resolving key can be used to tell, if an address was generated using this key, however it can't be used to resolve the original BLE MAC address of the peer.Is that correct?

*Is there a way to acquire the original BLE MAC address, whilst still using private random resolvable addresses on the server side? Maybe its part of the bonding information?

*Could I solve the problem if only the server uses private random resolvable addresses, but not the client? Would this break the privacy protection, the private random resolvable address mechanism offers?

In the end I'd like a BLE connection, which uses private random resolvable addresses to ensure privacy and still be able to obtain the original BLE MAC of the Client on my Server for internal purpose.
I'd very much appreciate if someone could answer my questions.
Best
david

A: When bonding, zero, one or both devices can send Resolving keys if negotiated so. For each device that sends Resolving key (IRK), the Identity Address is also always sent. This contains the original Bluetooth Device address and can be either public or static random. It's this address that only bonded devices know.
The idea of the privacy feature is to never use the original Bluetooth device address in Link Layer packets but instead a randomly generated one that is changed every x minutes (usually 15). This way, if it advertises regularly, someone can't track it since it disappears after 15 min. However if you have the corresponding IRK then you can determine if the IRK matches or not. If it matches you also know the original Bluetooth Device address since your bond data contains both the IRK and original address. But if you throw away that address then you can't recover the original address, even if you have the IRK.
If only one of two devices uses random resolvable address, then the one with resolvable address can't be tracked by a non-bonded device and the one that does not use a random resolvable address can be tracked.


text:
Q: Difference between static modifier and static block Someone explain to me the differences between the following two statements?
A static final variable initialized by a static code block:
private static final String foo;
static { foo = "foo"; }

A static final variable initialized by an assignment:
private static final String foo = "foo";

A: The JLS describes a few special behaviors of what it calls constant variables, which are final variables (whether static or not) which are initialized with constant expressions of String or primitive type.
Constant variables have a major difference with respect to binary compatibility: the values of constant variables become part of the class's API, as far as the compiler is concerned.
An example:
class X {
    public static final String XFOO = "xfoo";
}

class Y {
    public static final String YFOO;
    static { YFOO = "yfoo"; }
}

class Z {
    public static void main(String[] args) {
        System.out.println(X.XFOO);
        System.out.println(Y.YFOO);
    }
}

Here, XFOO is a "constant variable" and YFOO is not, but they are otherwise equivalent. Class Z prints out each of them. Compile those classes, then disassemble them with javap -v X Y Z, and here is the output:
Class X:
Constant pool:
   #1 = Methodref          #3.#11         //  java/lang/Object."<init>":()V
   #2 = Class              #12            //  X
   #3 = Class              #13            //  java/lang/Object
   #4 = Utf8               XFOO
   #5 = Utf8               Ljava/lang/String;
   #6 = Utf8               ConstantValue
   #7 = String             #14            //  xfoo
   #8 = Utf8               <init>
   #9 = Utf8               ()V
  #10 = Utf8               Code
  #11 = NameAndType        #8:#9          //  "<init>":()V
  #12 = Utf8               X
  #13 = Utf8               java/lang/Object
  #14 = Utf8               xfoo
{
  public static final java.lang.String XFOO;
    descriptor: Ljava/lang/String;
    flags: ACC_PUBLIC, ACC_STATIC, ACC_FINAL
    ConstantValue: String xfoo

  X();
    descriptor: ()V
    flags:
    Code:
      stack=1, locals=1, args_size=1
         0: aload_0
         1: invokespecial #1                  // Method java/lang/Object."<init>":()V
         4: return
}

Class Y:
Constant pool:
   #1 = Methodref          #5.#12         //  java/lang/Object."<init>":()V
   #2 = String             #13            //  yfoo
   #3 = Fieldref           #4.#14         //  Y.YFOO:Ljava/lang/String;
   #4 = Class              #15            //  Y
   #5 = Class              #16            //  java/lang/Object
   #6 = Utf8               YFOO
   #7 = Utf8               Ljava/lang/String;
   #8 = Utf8               <init>
   #9 = Utf8               ()V
  #10 = Utf8               Code
  #11 = Utf8               <clinit>
  #12 = NameAndType        #8:#9          //  "<init>":()V
  #13 = Utf8               yfoo
  #14 = NameAndType        #6:#7          //  YFOO:Ljava/lang/String;
  #15 = Utf8               Y
  #16 = Utf8               java/lang/Object
{
  public static final java.lang.String YFOO;
    descriptor: Ljava/lang/String;
    flags: ACC_PUBLIC, ACC_STATIC, ACC_FINAL

  Y();
    descriptor: ()V
    flags:
    Code:
      stack=1, locals=1, args_size=1
         0: aload_0
         1: invokespecial #1                  // Method java/lang/Object."<init>":()V
         4: return

  static {};
    descriptor: ()V
    flags: ACC_STATIC
    Code:
      stack=1, locals=0, args_size=0
         0: ldc           #2                  // String yfoo
         2: putstatic     #3                  // Field YFOO:Ljava/lang/String;
         5: return
}

Class Z:
Constant pool:
   #1 = Methodref          #8.#14         //  java/lang/Object."<init>":()V
   #2 = Fieldref           #15.#16        //  java/lang/System.out:Ljava/io/PrintStream;
   #3 = Class              #17            //  X
   #4 = String             #18            //  xfoo
   #5 = Methodref          #19.#20        //  java/io/PrintStream.println:(Ljava/lang/String;)V
   #6 = Fieldref           #21.#22        //  Y.YFOO:Ljava/lang/String;
   #7 = Class              #23            //  Z
   #8 = Class              #24            //  java/lang/Object
   #9 = Utf8               <init>
  #10 = Utf8               ()V
  #11 = Utf8               Code
  #12 = Utf8               main
  #13 = Utf8               ([Ljava/lang/String;)V
  #14 = NameAndType        #9:#10         //  "<init>":()V
  #15 = Class              #25            //  java/lang/System
  #16 = NameAndType        #26:#27        //  out:Ljava/io/PrintStream;
  #17 = Utf8               X
  #18 = Utf8               xfoo
  #19 = Class              #28            //  java/io/PrintStream
  #20 = NameAndType        #29:#30        //  println:(Ljava/lang/String;)V
  #21 = Class              #31            //  Y
  #22 = NameAndType        #32:#33        //  YFOO:Ljava/lang/String;
  #23 = Utf8               Z
  #24 = Utf8               java/lang/Object
  #25 = Utf8               java/lang/System
  #26 = Utf8               out
  #27 = Utf8               Ljava/io/PrintStream;
  #28 = Utf8               java/io/PrintStream
  #29 = Utf8               println
  #30 = Utf8               (Ljava/lang/String;)V
  #31 = Utf8               Y
  #32 = Utf8               YFOO
  #33 = Utf8               Ljava/lang/String;
{
  Z();
    descriptor: ()V
    flags:
    Code:
      stack=1, locals=1, args_size=1
         0: aload_0
         1: invokespecial #1                  // Method java/lang/Object."<init>":()V
         4: return

  public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=2, locals=1, args_size=1
         0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
         3: ldc           #4                  // String xfoo
         5: invokevirtual #5                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
         8: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
        11: getstatic     #6                  // Field Y.YFOO:Ljava/lang/String;
        14: invokevirtual #5                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
        17: return
}

Things to notice in the disassembly, which tell you the differences between X and Y run deeper than syntactic sugar:

*

*XFOO has a ConstantValue attribute, signifying that its value is a compile-time constant. Whereas YFOO does not, and uses a static block with a putstatic instruction to initialize the value at runtime.

*The String constant "xfoo" has become part of class Z's constant pool, but "yfoo" has not.

*Z.main uses the ldc (load constant) instruction to load "xfoo" onto the stack directly from its own constant pool, but it uses a getstatic instruction to load the value of Y.YFOO.
Other differences you will find:

*

*If you change the value of XFOO and recompile X.java but not Z.java, you have a problem: class Z is still using the old value. If you change the value of YFOO and recompile Y.java, class Z uses the new value whether you recompile Z.java or not.

*If you delete the X.class file entirely, class Z still runs correctly. Z has no runtime dependency on X. Whereas if you delete the Y.class file, class Z fails to initialize with a ClassNotFoundException: Y.

*If you generate documentation for the classes with javadoc, the "Constant Field Values" page will document the value of XFOO, but not the value of YFOO.
The JLS describes the above effects constant variables have on compiled class files in §13.1.3:

A reference to a field that is a constant variable (§4.12.4) must be resolved at compile time to the value V denoted by the constant variable's initializer.
If such a field is static, then no reference to the field should be present in the code in a binary file, including the class or interface which declared the field. Such a field must always appear to have been initialized (§12.4.2); the default initial value for the field (if different than V) must never be observed.
If such a field is non-static, then no reference to the field should be present in the code in a binary file, except in the class containing the field. (It will be a class rather than an interface, since an interface has only static fields.) The class should have code to set the field's value to V during instance creation (§12.5).

And in §13.4.9:

If a field is a constant variable (§4.12.4), and moreover is static, then deleting the keyword final or changing its value will not break compatibility with pre-existing binaries by causing them not to run, but they will not see any new value for a usage of the field unless they are recompiled.
[...]
The best way to avoid problems with "inconstant constants" in widely-distributed code is to use static constant variables only for values which truly are unlikely ever to change. Other than for true mathematical constants, we recommend that source code make very sparing use of static constant variables.

The upshot is that if your public library exposes any constant variables, you must never change their values if your new library version is otherwise supposed to be compatible with code compiled against old versions of the library. It won't necessarily cause an error, but the existing code will probably malfunction since it will have outdated ideas about the values of constants. (If your new library version needs for classes which use it to be recompiled anyway, then changing constants doesn't cause this problem.)
Thus, initializing a constant with a block gives you more freedom to change its value, because it prevents the compiler embedding the value into other classes.

A:  private static final String foo;
 static { foo ="foo";}

The value of foo is initialized when the class is loaded and static initializers are run.
private static final String foo = "foo";

Here, the value of foo will be a compile-time constant. So, in reality "foo" will be available as part of th byte-code itself.

A: The only difference is the initialization time.
Java first initializes the members and then the static blocks.

A: An additional aspect: Consider the case when you have multiple static fields, and yes this is a corner case...
As stated in Jon Skeet's answer, the JLS defines the exact order of initialization.
However, if for some reason you have to initialize multiple static attributes in a specific order, you may want to make the initialization sequence clearly visible in the code.
When using direct field initialization: Some code formatters (and developers) may decide at some point to sort fields differently, this will directly impact how the fields get initialized and introduce unwanted effects.
By the way, if you want to follow common java coding conventions, you should use capital letters when defining 'constants' (final static fields).
--- edited reflecting Jon Skeet's comments ---

A: In this example, there's one subtle difference - in your first example, foo isn't determined to be a compile-time constant, so it can't be used as a case in switch blocks (and wouldn't be inlined into other code); in your second example it, is. So for example:
switch (args[0]) {
    case foo:
        System.out.println("Yes");
        break;
}

That's valid when foo is deemed to be a constant expression, but not when it's "just" a static final variable.
However, static initializer blocks are usually used when you have more complicated initialization code - such as populating a collection.
The timing for initialization is described in JLS 12.4.2; any static final fields which are considered as compile-time constants are initialized first (step 6) and initializers are run later (step 9); all initializers (whether they're field initializers or static initializers) are run in textual order.

A: In IInd case- value of foo is early bind ie compiler identifies and assign value foo to variable FOO, which cant be changed,and this will be available apart with byte-code itself.
private static final String FOO = "foo";

and In Ist case-value of foo initialize just after class loading as a very first assignment before instance variable assigned,also here you can catch exceptions or static field can be assign by calling static methods in static block.
private static final String FOO;
static { FOO ="foo";}

So whenever there is a condition arrive when compiler must have to identify the value of variable foo, condition II will work,for ex-like value of case: in switch cases.

A: Static block give you more than simple statement. In this particular case is the same thing.
Static section will be executed at class load time, before any instances constructed. You can call methods here and assign their results to static fields. And you can catch exceptions in static blocks.


text:
Q: How to print array objects to a table? I am a complete newbie in programming so be easy on me.
I want to print an array object into a table in HTML using getElementByID.

And I want to print it in a table

      Ram
      Storage

I use a macbook and google chrome.

A: One simple approach is to use the array's build-in "forEach" method:
var ram = ["8GB", "3GB"],
    storage = ["500GB" , "120GB"];

ram.forEach(function(element, index, array){
    document.getElementById("mac.r").innerHTML += element;
});

storage.forEach(function(element, index, array){
    document.getElementById("mac.s").innerHTML += element;
});

See it here: http://jsfiddle.net/S3CY4/
Be aware though its mostly supported in modern browsers and it may not be the most performant approach.

A: If you must keep your script inline place it at the bottom of your page. See below, you can view the fiddle here
Once the element exists that you need to populate, you then loop the the data you need and fill the related element with your data.

                  Ram
                  Storage


text:
Q: No Log file is generated -- python using logging module code
I am using logging module to create log file.It checks the platform and provide method to create logfile as per the platform
import  os,platform,logging

if platform.platform('windows'):
    logging_file=os.path.join(os.getenv('HOMEDRIVE'),os.getenv('HOMEPATH'),'test.log')
else:
    logging_file = os.path.join(os.getenv('HOME'),'test.log')

print"logging to",logging_file

logging.basicConfig(level=logging.DEBUG,format='%(asctime)s : %(levelname)s :%(message)s',filename=logging_file, filemode='w')

logging.DEBUG("start of the program")
logging.info("doing something")
logging.warning("u are gonna die")

A: The code you provided is not indented properly and you should use logging.debug instead of logging.DEBUG since the later is an Integer constant used to represent log level. Here is the updated code
import  os,platform,logging

if platform.platform('windows'):
    logging_file=os.path.join(os.getenv('HOMEDRIVE'),os.getenv('HOMEPATH'),'test.log')
else:
    logging_file = os.path.join(os.getenv('HOME'),'test.log')

print"logging to",logging_file

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s : %(levelname)s :%(message)s',
                    filename=logging_file,
                    filemode='w')

logging.debug("start of the asdfasdfprogram")
logging.info("doing something")
logging.warning("u are gonna die")

A: Maybe you are using a unix system , the below statement is wrong -
platform.platform('windows')

The platform.platform function always returns the underlying platform as a string, later on you are directly testing the string in if condition, which will always return true, hence it always assumes you are in windows system.
You need a condition like -
if 'windows' in platform.platform().lower():

Also, as k4vin said - if this isn't a type you should be using logging.debug instead of logging.DEBUG , the first is a function, where as the second is the integer used to indicate the logging level DEBUG .
logging.debug("start of the program")

A: The logging handlers should be cleaned before creating the basicconfig
Code
import  os,platform,logging

if 'windows' in platform.platform().lower():
    logging_file=os.path.join(os.getenv('HOMEDRIVE'),os.getenv('HOMEPATH'),'test.log')
else:
    logging_file = os.path.join(os.getenv('HOME'),'test.log')

print"logging to",logging_file
logging.getLogger('').handlers = []
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s : %(levelname)s :%(message)s',filename=logging_file, filemode='w')

logging.DEBUG("start of the program")
logging.info("doing something")
logging.warning("u are gonna die")

you could view this link for more information


text:
Q: change android emulator skin on adt bundle Hello everybody i'm trying to change the android emulator skin in the latest adt bundle for linux (android developers tools given by android developer site here http://developer.android.com/sdk/index.html). i have download skins from this link http://heikobehrens.net/2011/03/15/android-skins/ but they don't appear on the devices dropdown field even when i put them in the skin directory(/adt-bundle-linux-x86_64-20131030/sdk/platforms/android-8/skins). there is no browsable skin field that can help me to use my new skins.

So if someone have a solution for me it will be helpfull.


text:
Q: Renaming a drectory in android studio i am just trying to rename a android text directory name and i have really having a tough time and nothing seems to solve my problem . have a look below to see the screenshot of my directory.
SCREENSHOT
now you will see a  folder with the following name
com.example.gautam.droidone

what i would really like to do is rename the file to the following:
com.example.gautam.droidone.tests

i was going through this tutorial and also the android official tutorial and they require that your test directory have a suffix of tests.
now waht i did to change the name is pretty standard.
right click on the folder > select refactor > rename > in the popup that appears enter the name, i entered droidone.tests.
my folder gets renamed to the following instead:
com.example.gautam.tests

what i want is really:
com.example.gautam.droidone.tests

so how do i rename my file , can somebody address this simple issue that i am facing ?
Thank you in advance.

A: com.example.gautam.droidone is not a directory name - it's a package name, which is represented by a set of folders in the file system: com/example/gautam/droidone. Android Studio for your convenience flattens these folders into a package name.
To add tests folder to this path you can, for example, call New package while being in droidone folder, and then move your classes to this new package.


text:
Q: repeat horizontally splitted sprite to the left
I have this spritesheet and I have to repeat each column horizontally to the left for different backgrounds. How can I achieve this? I played arround with background-position, background-repeat and background-size but I can´t achieve the desired behaviour. Anyone knows how to do this?

A: I better you can create sprite vertical instead of horizontal .
Like this :

A: Why don't you save each color seperately and dynamically build your background according to what you need?
So just repeat the color you want repeated and then append the others on the sides if you want them.
Also: Please be more specific as to the effect you want to achieve.


text:
Q: Adding a different program to startup How would I add a completely different program on the computer to start up?
Would it be something like this?
My.Computer.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True).SetValue(Application.ProductName, "C:\APPLICATIONSPATH.fileextension")

P.S: Sorry for being a noob.

A: There are several ways to add a startup program.
Firstly what OS are you using?
By the looks of it a version of Windows?
And what programming language are you wanting to use? C Sharp?
Assuming you have privileges to write to the registry then what you have written looks mostly correct. Have you tried testing it?
There is also a RunOnce subkey to allow the program to only run on the next occasion of startup. I have actually done what you are trying to do before, however I am on a computer with limited privileges at the moment so I can't check that what you have written is perfectly correct. Although the idea should be fine :)
You may also like to write a shortcut to the Windows Start menu "Startup" folder.
You could write a short piece of code to create a shortcut file to the application you wish to run and then attempt to write the shortcut file to the correct startup directory?
If not a shortcut file, write a script file which is much easier. Perhaps something like:
@echo off
echo Running a startup program!
pause
::load program
start /b "" "C:\APPLICATIONSPATH.fileextension"

and programmatically write this to a file with a .vbs extension.
This way if a user who is not computer savvy wants to remove the startup item manually they can easily see it.
(I think this may be a way which will work without the requirement for administrative rights. Could be a useful alternative to writing to the registry?)
If you use Windows 8, this startup folder no longer exists under the start menu.
Instead it can be found here:
    C:\Users\YOURUSER\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
or with the Windows Run prompt: Win+R
and by running shell:startup

Have a look here for Windows 8

A: I'd developed this module which facilitates the way to add or remove an external application to Windows startup trhough registry methodology.
It covers the startup scope (Run/RunOnce), the user scope (Current User/All Users), the registry scope (x86/x64) and also is capable to add a bypass for "Secure mode" windows logon.
An example usage:
WinStartupUtil.Add(UserScope.CurrentUser, StartupScope.Run, RegistryScope.System32,
                   title:="Application Title",
                   filePath:="C:\Application.exe",
                   arguments:="/Arg1",
                   secureModeByPass:=True)

WinStartupUtil.Remove(UserScope.CurrentUser, StartupScope.Run, RegistryScope.System32,
                      title:="Application Title",
                      throwOnMissingValue:=True)

The source-code:
' ***********************************************************************
' Author   : Elektro
' Modified : 12-October-2015
' ***********************************************************************
' <copyright file="WinStartupUtil.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Option Statements "

Option Explicit On
Option Strict On
Option Infer Off

#End Region

#Region " Imports "

Imports System
Imports Microsoft.Win32

#End Region

#Region " WinStartup Util "

''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Adds or removes an application from Windows Startup.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public Module WinStartupUtil

#Region " Constants "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' The 'Run' registry subkey path.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Public Const RunSubKeyPath As String = "Software\Microsoft\Windows\CurrentVersion\Run"

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' The 'Run' registry subkey path for x86 appications on x64 operating system.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Public Const RunSubKeyPathSysWow64 As String = "Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run"

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' The 'RunOnce' registry subkey path.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Public Const RunOnceSubKeyPath As String = "Software\Microsoft\Windows\CurrentVersion\RunOnce"

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' The 'RunOnce' registry subkey path for x86 appications on x64 operating system.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Public Const RunOnceSubKeyPathSysWow64 As String = "Software\Wow6432Node\Microsoft\Windows\CurrentVersion\RunOnce"

#End Region

#Region " Enumerations "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Specifies an user scope.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Public Enum UserScope As Integer

        ''' <summary>
        ''' 'HKEY_CURRENT_USER' root key.
        ''' </summary>
        CurrentUser = &H1

        ''' <summary>
        ''' 'HKEY_LOCAL_MACHINE' root key.
        ''' </summary>
        AllUsers = &H2

    End Enum

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Specifies a Startup scope.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Public Enum StartupScope As Integer

        ''' <summary>
        ''' 'Run' registry subkey.
        ''' </summary>
        Run = &H1

        ''' <summary>
        ''' 'RunOnce' registry subkey.
        ''' </summary>
        RunOnce = &H2

    End Enum

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Specifies a registry scope.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Public Enum RegistryScope As Integer

        ''' <summary>
        ''' 'System32' registry subkey.
        ''' </summary>
        System32 = &H1

        ''' <summary>
        ''' 'SysWow64' registry subkey.
        ''' </summary>
        SysWow64 = &H2

    End Enum

#End Region

#Region " Public Methods "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Adds an application to Windows Startup.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="userScope">
    ''' The user scope.
    ''' </param>
    '''
    ''' <param name="startupScope">
    ''' The startup scope.
    ''' </param>
    '''
    ''' <param name="registryScope">
    ''' The registry key scope.
    ''' </param>
    '''
    ''' <param name="title">
    ''' The registry entry title.
    ''' </param>
    '''
    ''' <param name="filePath">
    ''' The application file path.
    ''' </param>
    '''
    ''' <param name="secureModeByPass">
    ''' If set to <see langword="True"/>, the file is ran even when the user logs into 'Secure Mode' on Windows.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <exception cref="System.ArgumentNullException">
    ''' title or filePath
    ''' </exception>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerHidden>
    <DebuggerStepThrough>
    Public Sub Add(ByVal userScope As UserScope,
                   ByVal startupScope As StartupScope,
                   ByVal registryScope As RegistryScope,
                   ByVal title As String,
                   ByVal filePath As String,
                   Optional ByVal arguments As String = "",
                   Optional secureModeByPass As Boolean = False)

        If String.IsNullOrEmpty(title) Then
            Throw New ArgumentNullException(paramName:="title")

        ElseIf String.IsNullOrEmpty(filePath) Then
            Throw New ArgumentNullException(paramName:="filePath")

        Else
            If secureModeByPass Then
                title = title.TrimStart("*"c).Insert(0, "*")
            End If

            Dim regKey As RegistryKey = Nothing
            Try
                regKey = WinStartupUtil.GetRootKey(userScope).OpenSubKey(GetSubKeyPath(startupScope, registryScope), writable:=True)
                regKey.SetValue(title, String.Format("""{0}"" {1}", filePath, arguments), RegistryValueKind.String)

            Catch ex As Exception
                Throw

            Finally
                If regKey IsNot Nothing Then
                    regKey.Close()
                End If

            End Try

        End If

    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Removes an application from Windows Startup.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="userScope">
    ''' The user scope.
    ''' </param>
    '''
    ''' <param name="startupScope">
    ''' The startup scope.
    ''' </param>
    '''
    ''' <param name="registryScope">
    ''' The registry scope.
    ''' </param>
    '''
    ''' <param name="title">
    ''' The registry entry to find.
    ''' </param>
    '''
    ''' <param name="throwOnMissingValue">
    ''' if set to <see langword="true"/>, throws an exception on missing value.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <exception cref="System.ArgumentNullException">
    ''' title
    ''' </exception>
    '''
    ''' <exception cref="System.ArgumentException">
    ''' Registry value not found.;title
    ''' </exception>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerHidden>
    <DebuggerStepThrough>
    Friend Sub Remove(ByVal userScope As UserScope,
                      ByVal startupScope As StartupScope,
                      ByVal registryScope As RegistryScope,
                      ByVal title As String,
                      Optional ByVal throwOnMissingValue As Boolean = False)

        If String.IsNullOrEmpty(title) Then
            Throw New ArgumentNullException(paramName:="title")

        Else
            Dim valueName As String = String.Empty
            Dim regKey As RegistryKey = Nothing

            Try
                regKey = WinStartupUtil.GetRootKey(userScope).OpenSubKey(GetSubKeyPath(startupScope, registryScope), writable:=True)

                If (regKey.GetValue(title, defaultValue:=Nothing) IsNot Nothing) Then
                    valueName = title

                ElseIf (regKey.GetValue(title.TrimStart("*"c).Insert(0, "*"), defaultValue:=Nothing) IsNot Nothing) Then
                    valueName = title.TrimStart("*"c).Insert(0, "*")

                ElseIf throwOnMissingValue Then
                    Throw New ArgumentException(paramName:="title", message:="Registry value not found.")

                End If

                regKey.DeleteValue(valueName, throwOnMissingValue)

            Catch ex As Exception
                Throw

            Finally
                If regKey IsNot Nothing Then
                    regKey.Close()
                End If

            End Try

        End If

    End Sub

#End Region

#Region " Private Methods "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets a <see cref="RegistryKey"/> instance of the specified root key.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="userScope">
    ''' The user scope.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' A <see cref="RegistryKey"/> instance of the specified root key.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <exception cref="System.ArgumentException">
    ''' Invalid enumeration value.;userScope
    ''' </exception>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerHidden>
    <DebuggerStepThrough>
    Private Function GetRootKey(ByVal userScope As UserScope) As RegistryKey

        Select Case userScope

            Case WinStartupUtil.UserScope.CurrentUser
                Return Registry.CurrentUser

            Case WinStartupUtil.UserScope.AllUsers
                Return Registry.LocalMachine

            Case Else
                Throw New ArgumentException("Invalid enumeration value.", "userScope")

        End Select ' userScope

    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the proper registry subkey path from the parameters criteria.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="startupScope">
    ''' The startup scope.
    ''' </param>
    '''
    ''' <param name="registryScope">
    ''' The registry key scope.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' The registry subkey path.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <exception cref="System.ArgumentException">
    ''' Invalid enumeration value.;startupScope or
    ''' Invalid enumeration value.;registryScope
    ''' </exception>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerHidden>
    <DebuggerStepThrough>
    Private Function GetSubKeyPath(ByVal startupScope As StartupScope,
                                   ByVal registryScope As RegistryScope) As String

        Select Case registryScope

            Case WinStartupUtil.RegistryScope.System32

                Select Case startupScope

                    Case WinStartupUtil.StartupScope.Run
                        Return WinStartupUtil.RunSubKeyPath

                    Case WinStartupUtil.StartupScope.RunOnce
                        Return WinStartupUtil.RunOnceSubKeyPath

                    Case Else
                        Throw New ArgumentException("Invalid enumeration value.", "startupScope")

                End Select ' startupScope

            Case WinStartupUtil.RegistryScope.SysWow64

                Select Case startupScope

                    Case WinStartupUtil.StartupScope.Run
                        Return WinStartupUtil.RunSubKeyPathSysWow64

                    Case WinStartupUtil.StartupScope.RunOnce
                        Return WinStartupUtil.RunOnceSubKeyPathSysWow64

                    Case Else
                        Throw New ArgumentException("Invalid enumeration value.", "startupScope")

                End Select ' startupScope

            Case Else
                Throw New ArgumentException("Invalid enumeration value.", "registryScope")

        End Select ' registryScope

    End Function

#End Region

End Module

#End Region


text:
Q: Tomcat 6 uses old, non-existing web.xml I have a weird issue with Tomcat 6 and OpenGrok webapp, Tomcat seems to use some old, nowadays non-existing web.xml. I'm trying to add some roles for access control to the web.xml, but Tomcat never takes the new web.xml into use.
I've tried deleting the exploded webapp directory and the .war file, restarted Apache and Tomcat, and even tried reloading the webapp via the manager (not successfully, curl command does not seem to do anything, maybe it has something to do with the SSL we are using) - all but manager reload trigger the webapp reload, but still for some unknown reason the old web.xml and the roles in it are used. Webapp also works okay with the old roles.
Anybody have any clue how to force Tomcat to use the new web.xml? Server is RHEL 6.3, Tomcat 6.0.24, Apache 2.2.15.


text:
Q: prove that if $f-g$=$o(g)$ as x approaches a then $f-g$=$o(f)$ as $x$ approaches $a$ How to prove that if $f-g = O(g)$ as x approaches a then $f-g=O(f)$ as x approaches a (f, g - functions, o - Landau symbol)

A: Suppose that $f-g=\omicron_a (g)$. This is equivalent to $\lim_a \frac{f-g}{g}=0$. Then $\lim_a \frac{f}{g}=1$. By taking the inverse, $\lim_a \frac{g}{f}=1$. We conclude that $\lim_a \frac{f-g}{f}=0$, which exactly says that $f-g=\omicron_a (f)$.


text:
Q: Selecting numbers within the slash (/) using ArcMap Field Calculator? I have date data that I'm separating into three separate fields (all fields are string type, including the input field) by day, month, and year. Unfortunately, the date field is raw data and isn't consistent; there are eight variations for how the data in this field is organized (d/m/yy; d/m/yyyy; d/mm/yy; d/mm/yyyy; dd/m/yy; dd/m/yyyy; dd/mm/yy; dd/mm/yyyy). I figured out how to separate the day and the year into separate columns, but I'm having difficulty separating the month. I've tried the VB Script Mid() function by initially separating the different formats and performing the function, but that was extremely time-consuming, and I have close to 100,000 data points that I need to go through. Is there a python code that I can use, or a combination of different VB scripts, that can select the numbers between the slashes (/) for all of these? Or am I doomed?

A:
In field calculator, you'll have to run 3 separate Calculate Field operations:
In pseudo code:
day_field = !str_field!.split("/")[0]
month_field = !str_field!.split("/")[1]
year_field = !str_field!.split("/")[2]

With cursors, this is a little simpler (and it should be faster) as it can be reduced to only iterating over str_field once:
fields = [str_field, day_field, month_field, year_field]
with arcpy.da.UpdateCursor(FC, fields) as rows:
     for row in rows:
         #only use the first 3 in case there is a 4th slash for some reason
         row[1:] = row[0].split("/")[0:3]
         rows.updateRow(row)

Here's what it looks like in Field Calculator:


text:
Q: Check elements present in array using Javascript I have a situation where i want to check if elements in one array are present in another array. If elements are present, then push those in new array. In this case, i have array of strings.
For e.g.
var check = ["6003", "6005", "6010"]; //static values. I need to check these elements if they are present in InputValues

var InputValues = ["5005", 2005", "6010"]; //dynamic input values

var result = ["6010"]; //dyanimic final array based off elements in InputValues

Similary,
var InputValues = ["5005", 6005", "6010"];

var result = ["6005", "6010"];

Can someone please let me know how to achieve this dynamic result.

A: var result = InputValues.filter((val) => check.includes(val));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Browser_compatibility
edit: Used the wrong method! .includes() works if you do not care about IE (though it is in Edge), otherwise this is the "modern" on to use :-)

A: You can use Array.indexOf with Array.filter
var result = InputValues.filter(elem => check.indexOf(elem) >= 0);

Basically what it does is, it will filter the elements of InputValues against check case-sensitive wise.


text:
Q: Trigger PTT on Baofeng UV-5R with Arduino A current project of mine is to have the Arduino Uno play an audio file off an SD card module. The audio file would come out of the Arduino and into a Baofeng UV-5R handheld transceiver. The first thing that needs to happen is Arduino would trigger Push-To-Talk(PTT) on the radio and then input the audio. I will post the pinout diagram of the 3.5mm jack. My question is can I send in a normal audio file or should I convert the file to a mono low bit rate and/or Hz file.
This is my first post here, so if a drawing or anything is need please let me know.
Thanks for the help.

A: PTT is triggered when the PTT at the top of your diagram (MIC-) is connected to ground (SPK -). When shorted, only a few mA of current flows, so your can use a small transistor as a switch. For example, a '7002 would work. Connect the drain to the PTT (MIC-), gate to an arduino digital output, and the source to ground (SPK-).
By setting the arduino digital output high, PTT will be triggered.
Arduinos are generally bad at audio stuff, but you can find some PCM audio libraries or audio shields that can  help. The radio expects an audio signal, which as you noticed, arduino can't output without some hacking. So try to get the arduino to just play the file out to headphones. If you can get that to work, then you can use that output as the input to the radio.

A: Yes, this has been done with 8kHz mono WAV files.
Otherwise, you need an MP3 shield, but I doubt that is necessary considering the size of SD memory.
https://circuitdigest.com/microcontroller-projects/arduino-audio-music-player
http://soundfile.sapp.org/doc/WaveFormat/

A: You cannot "send an audio file" as a stream of digital data.
You can transmit the audio from the file as an analog signal.
To do that, you will have to playback the audio file and convert it to an analog signal.
The bitrate doesn't much matter.  What matters (somewhat) is the audio bandwidth of the file.  In its simplest form "bandwidth" is the highest frequency present in the audio during playback.
Two-way radios like your Baofeng have a very "narrow" audio bandwidth.  They only pass frequencies between 300 and 3000 hertz.  That's about like a standard land line telephone.  Music sounds really crummy through it.  No bass, no treble.  Just mid-range.
You will need to play back the audio.  That's probably not something you'll do with your Arduino - it's too slow and doesn't have enough memory (or flash storage) to hold a useful amount of audio. It also doesn't have a real analog output.  What the Arduino software calls "analog out" is in truth a pulse train (see PWM.)  If you trasmit that, it'll sound like somebody chopping up a speaker with a chainsaw.
You'll want a small record/playback module that you can trigger with your Arduino to playback your audio, and a relay module to activate the PTT.
You'll need to reduce the signal from the playback module with a couple of resistors.  The microphone input of your Baofeng expects some few tens of millivolts, and typical audio signals from a playback module can be a couple of volts.  Just using the audio straight to the microphone input will result in terribly distorted (extremely crappy sounding) audio.

I've intentionally not posted any details.  Your project is a long way from a point where there are details to be had.

A: I've been trying to do something similar to this with the exception that I am using audio generated by third party ham radio programs running on my test computer, such as MixW for SSTV. I've got an external USB sound card that will serve as the audio interface to the radio.
I initially attempted to capture the audio output by connecting the SPK+ to analog 0 of an arduino, and sound card ground to arduino ground. This looked like it might work until I connected and turned on the radio. More isolation is needed and I might re-visit that later.
The option I am looking at now is utilizing the serial interfacing in various ham radio programs and trying to come up with a way to take those same serial commands over serial to the arduino and performing the same PTT function. I managed to get this working using specific pre-built configurations in MixW. I was able to capture tx and rx strings and key the radio at the appropriate time. Right now the code just lights an LED or turns it off at the appropriate time, I have not built up the PTT circuit yet, but will probably just use a transistor or opto-isolator as that seems to be the simplest way ahead.
Unfortunately, switching to a different program and setting up the radio serial interface the same way, I seem to get very different serial outputs and in most cases, clicking TX causes the Arduino to reset. I'm hoping to try and find out more about what is happening here so I can more effectively capture the serial input from these various programs.
Just thought I would share my own experience in case anybody