text:
Q: XSP.showDialog doesn't work in onStart event? I have the following test XPage.
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core"
    xmlns:xe="http://www.ibm.com/xsp/coreex">
    <xp:panel id="pagePanel">
        <xp:text escape="true" id="didThePageCompile">
            <xp:this.value><![CDATA[#{javascript:var d = new Date();
return d.toLocaleString();}]]></xp:this.value>
        </xp:text>
        <xp:br></xp:br>
        <xp:button value="Label" id="button1">
            <xp:eventHandler event="onclick" submit="true"
                refreshMode="partial" refreshId="dialog1"
                onStart="XSP.openDialog('#{id:dialog1}')"
                onComplete="XSP.closeDialog('#{id:dialog1}')">
            <xp:this.action><![CDATA[#{javascript:var agent = database.getAgent("runLongTime");
var response = agent.run();

// var d = getComponent("dialog1");
// d.show();
}]]></xp:this.action>
</xp:eventHandler>
</xp:button>
<xe:dialog id="dialog1" title="Test Dialog">This is a test dialog</xe:dialog></xp:panel>
</xp:view>

The agent "runLongTime" just sleeps for 10 seconds. This works fine. When I click the button however the dialog box does not show up. I checked the source and it generates the correct code, and that code works when I manually put it into the console.
I don't get any errors and the agent executes fine. I've also tried changing the refreshId to "pagePanel", but still the same.

A: XSP.openDialog() and XSP.closeDialog() each trigger a partial refresh. The XPages client-side API includes logic for preventing multiple partial refresh operations from executing in parallel, which is likely preventing your dialog from displaying because by the time it attempts to run the refresh to show the dialog, it's already running your button event.
Add a JSON-RPC (called "Remote Services" in the control palette) to the page. Move your button's server event code to a method of the RPC. You can then change the button event to be purely client-side: call XSP.openDialog(), then call the RPC method and close the dialog in the onComplete of that method. This should prevent the race condition you're currently experiencing.

A: as far as I can see here, you are trying to open/close the same dialog.
Some days ago I got the same issue and wondered why this was not working.
Finally I checked the events and ended with the spectacular result that onStart and onComplete fired up almost parallel.
Maybe you could try to insert a timeout (window.timeout) before calling the XSP.closeDialog event.


text:
Q: Fedora 26 strange calendar/date and SELinux bahaviour after Kernel update Yesterday I've installed all of the latest official updates for Fedora 26 64-bit Workstation, including 4.12 Kernel update.
After the system restart, SELinux is reporting following problems:
The source process:     sm-notify, unix_chkpwd, accounts-daemon, systemd-tmpfile
Attempted this access:  dac_read_search
Also, the calendar on my LXDE panel is showing "null" values, and a "date" command in the terminal is displaying strange characters instead of Polish letters (my LC_TIME is set to Polish).
Please check the attached images:
 and
.
Do you have any suggestions about what is wrong and how to fix it?

A: OK, I've figured it out myself.
You can fix the SELinux problems by running "dnf update" again and installing remaining updates which were waiting, and restarting the system - after that I get no SELinux error reports.
To fix the Polish characters in the "date" command and on the LXDE calendar I just had to set "LANG" system variable to "en_US.utf8" and then set "LC_TIME" to "pl_PL.utf8" back again (sudo localectl set-locale LC_TIME=pl_PL.utf8).
Also, after installing the updates, TeamViewer stopped working, it just didn't run. To make it work, I've uninstalled it, then manually removed remaining TeamViewer folders from /home//.config and /home//.local/share and installed it - now it works.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Beautifulsoup get previous element using find_all_previous I would like to identify some size in specific category, for example, I would like to scrap '(2)募入決定額' under the category '6.価格競争入札について'  and '7.非競争入札について'
But somehow the structure for these are a little bit tricky as there is no hierarchy for these elements.
The website I use is :
https://www.mof.go.jp/jgbs/auction/calendar/nyusatsu/resul20211101.htm

And I tried the following code but nothing print out.
rows = soup.findAll('span')
    for cell in r:
        if "募入決定額" in cell:
        a=rows[0].find_all_previous("td")
        for i in a:
            print(a.get('text'))

Much appreciate for any help!

A: In newer code avoid old syntax findAll() instead use find_all() or select() with css selectors - For more take a minute to check docs

You could select all <td> that contains 募入決定額 and from there its nearest sibling <td> that contains a <span>.
soup.select('td:-soup-contains("募入決定額") ~ td>span')

To get its previous categorie iterate over all previous <tr>:
[x.td.text for x in e.find_all_previous('tr') if x.td.span][0]

Read more about bs4 and css selectors and under dev.mozilla
Example
import requests
from bs4 import BeautifulSoup

base_url = 'https://www.mof.go.jp/jgbs/auction/calendar/nyusatsu/resul20211101.htm'
soup = BeautifulSoup(requests.get(base_url).content)
for e in soup.select('td:-soup-contains("募入決定額") ~ td>span'):
    print(e.text)

    # or
    print([x.td.text for x in e.find_all_previous('tr') if x.td.span][0],e.text)

Output
2兆1,205億円
4億8,500万円
4,785億円

or
6. 2兆1,205億円
7. 4億8,500万円
8. 4,785億円


text:
Q: Can't use silverlight namespace Whenever I try to reference the following namespace in my XAML, the code compiles and the project starts, but the InitializeComponent method throws an error.  Here's the XAML reference:
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
and here's the use of ExtendedVisualStateManager
<ei:ExtendedVisualStateManager/>

The error is this:
The type 'ExtendedVisualStateManager' was not found because 'http://schemas.microsoft.com/expression/2010/interactions' is an unknown namespace. [Line: 19 Position: 37]

Is there a new namespace I need to use to use this control?

A: Here are some facts.

*

*The Microsoft.Expression.Interactions.dll version 4.0.5.0 contains the namespace Microsoft.Expression.Interactivity.Core.

*This Microsoft.Expression.Interactivity.Core contains the type ExtendedVisualStateManager.

*The Microsoft.Expression.Interactions.dll version 4.0.5.0 carries a XmlnsDefinition that maps the URL "http://schemas.microsoft.com/expression/2010/interactions" to the namespace Microsoft.Expression.Interactivity.Core.

Hence a project referencing version 4.0.5.0 of Microsoft.Expression.Interactions.dll can contain Xaml using xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" that can then contain ei:ExtendedVisualStateManager.
You'll note I've repeated the version number a few times.  If you do have an interactions dll referenced in a Silverlight 4 project but your code doesn't work then perhaps its the wrong version.  However in that case Dan's answer should still have worked.

A: Make sure your Silverlight application has a reference to the Microsoft.Expression.Interactions assembly.
<UserControl
    xmlns:ei="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions"
    ...other namespaces... />
    <VisualStateManager.CustomVisualStateManager>
        <ei:ExtendedVisualStateManager/>
    </VisualStateManager.CustomVisualStateManager>
</UserControl>

A: I had everything correct per the other answers and like you, the problem still existed.  It was failing at runtime on a usercontrol in my project (and that project did reference Microsoft.Expression.Interactions).
However, that usercontrol was being used on a form in another project.  Once I added the reference to Microsoft.Expression.Interactions to the outer project, the runtime error was solved.  I was not loading assemblies dynamically and so I'm not 100% certain why this was a problem.

A: I think you should look in your project's properties. Find the references (Microsoft.Expression.Interactions or/and other "Expression" assemblies you may use, and set the "Copy Local" property to TRUE and try it again.

A: None of the answers solved this puzzling problem to me.
Apparently I needed  Microsoft Expression Blend SDK for Silverlight 4.
Installing it has solved the issue.


text:
Q: Why would Rose hold The Doctor's hand even though he is a complete stranger? I have started re-watching the Doctor Who reboot. And in the first episode the Doctor and Rose hold hand like 10 times. They are complete strangers. Why on earth would she do that? My only thought at this point is this is a European or British thing. I spent a few months in Africa and they would randomly hold hands with people they just met but I did not hear this was the case in UK as well.
Alternatively are the writers trying to show The Doctor as someone people just trust?
Or perhaps just trying to suggest Rose's instant infatuation with him?
P.S. In case it wasn't obvious from my cultural ignorance I'm American and in America only people in a romantic relationship or pre-teen girls hold hands.

A: Humans are very social creatures. And when our world comes crashing down, we start to seek solace with those around us, be it a stranger it a being that only holds the guise of humanity.


text:
Q: Interrupting a video in python I'm trying to interrupt and stop a video with a switch interrupt and then play an alternative video. Here is what I tried so far.
import subprocess
import signal
import sys
import RPi.GPIO as GPIO
import time
from time import sleep

BUTTON1_GPIO = 2
BUTTON2_GPIO = 3

Led1 = 4
Led2 = 14
flag_0 = 0
button = 0

def signal_handler(sig, frame):
    GPIO.cleanup()
    sys.exit(0)

def Picture_0():
    filename = "welcome.jpeg"
    import webbrowser
    webbrowser.open(filename)

def video0():
    video = 'cvlc --play-and-exit  --no-video-deco Intro_Vid.mp4'
    subprocess.run(video, shell=True)

def video1():
    video = 'cvlc --play-and-exit  --no-video-deco 1.mp4'
    subprocess.run(video, shell=True)

def video2():
    video = 'cvlc --play-and-exit  --no-video-deco 2.mp4'
    subprocess.run(video, shell=True)

GPIO.setmode(GPIO.BCM)
GPIO.setup(BUTTON1_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(BUTTON2_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP)

def interrupt_handler(channel):
    global button
    print("interrupt handler")

    if channel == BUTTON1_GPIO:
        button = 1
    elif channel == BUTTON2_GPIO:
        button = 2

GPIO.add_event_detect(
    BUTTON1_GPIO, GPIO.FALLING,
    callback=interrupt_handler, bouncetime=500
)
GPIO.add_event_detect(
    BUTTON2_GPIO, GPIO.FALLING,
    callback=interrupt_handler, bouncetime=500
)
GPIO.setup(Led1, GPIO.OUT)
GPIO.setup(Led2, GPIO.OUT)
GPIO.output(Led1, GPIO.HIGH)    # Led off
GPIO.output(Led1, GPIO.HIGH)

while True:
    if button == 0:
        button = 100
        print("Button 0")
        GPIO.output(Led1, GPIO.HIGH)
        GPIO.output(Led2, GPIO.HIGH)
        video0()
    elif button == 1:
        print("Button 1")
        GPIO.output(Led1, GPIO.LOW)    # Led on
        video1()
        button = 0
    elif button == 2:
        print("Button 2")
        GPIO.output(Led2, GPIO.LOW)
        video2()
        button = 0

My code does capture the interrupt but the first video plays in its entirety before the videoplayer proceeds to the next video selected by the switch, rather than being stopping the first video as I require.
What am I missing?

A: First, save the subprocess into a global variable:
def video0():
    global videoProcess

    video = 'cvlc --play-and-exit  --no-video-deco Intro_Vid.mp4'
    videoProcess = subprocess.run(video, shell=True)

Then kill it before starting the second video:
while True:
    if button == 0:
        ...
    elif button == 1:
        ...
        videoProcess.kill()
        video1()
        ...
    elif button == 2:
        ...

If that doesn't kill the subprocess, it's likely because its child is still hanging.
To resolve this you can try using shell=False or find a more complicated way of terminating the subprocess in this question.


text:
Q: Inverter output frequency is 46 Hz but it should be 50 Hz, will it cause any problem? I bought a car inverter (150W.) The inverter output should be 220V 50Hz (in Turkey) but the output is 227V  46Hz.  I think the voltage is at a reasonable value but is the frequency OK?
I measured the values with the power meter. When I measured the normal home socket with the same power meter, I saw 222.5V 50Hz.

A: Obviously your inverter is a cheap inverter that only outputs an AC frequency that is only approximately 50 Hz but not exactly.
You need a more expensive ("pure sinewave") inverter to get a more accurate 50 Hz.
The fact that you the frequency isn't exactly 50 Hz is only a problem with devices that rely on the 50 Hz to be accurate because they use the 50 Hz as a reference for timing.
Some motors need AC to make them spin, if the frequency isn't exactly 50 Hz the motor could spin too slow or too fast.
Examples of such devices are clocks and maybe some older televisions.
Devices that are unaffected are devices that rectify the AC into DC like power adapters and chargers. Some devices state that they can use 50 / 60 Hz on the device itself, also these don't care much about the exact frequency.


text:
Q: rails overwrite nested attributes update I have this model Person
class Person
 generate_public_uid generator: PublicUid::Generators::HexStringSecureRandom.new(32)

 has_many :addresses, as: :resource, dependent: :destroy
 accepts_nested_attributes_for :addresses, allow_destroy: true, update_only: true,
                                        reject_if: proc { |attrs| attrs[:content].blank? }
end

in my person table, I have this public_id that is automatic generated when a person is created.
now the nested attribute in adding addresses is working fine. but the update is not the same as what nested attribute default does.
my goal is to update the addresses using public_id
class Address
    generate_public_uid generator: PublicUid::Generators::HexStringSecureRandom.new(32)

    belongs_to :resource, polymorphic: true
end

this is my address model
 { person: { name: 'Jack', addresses_attributes: { id: 1, content: 'new@gmail.com' } } }

this is the rails on how to update the record in the nested attribute
 { person: { name: 'Jack', addresses_attributes: { public_id: XXXXXXXX, content: 'new@gmail.com' } } }

I want to use the public_id to update records of addresses, but sadly this is not working any idea how to implement this?

A: Rails generally assumes that you have a single column named id that is the primary key. While it is possible to work around this, lots of tools in and around Rails assume this default – so you'll be giving yourself major headaches if you stray from this default assumption.
However, you're not forced to use integer ids. As someone else has already pointed out, you can change the type of the ID. In fact, you can supply any supported type by doing id: type, where type can e.g. be :string in your case. This should then work with most if not all of Rails' default features (including nested attributes) and also with most commonly used gems.

A: Since you say you are using your public_id as primary key I assume you don't mind dropping the current numbered id. The main advantage of not using an auto increment numbered key is that you don't publicly show record creation growth and order of records. Since you are using PostgreSQL, you could use a UUID is id which achieves the same goal as your current PublicUid::Generators::HexStringSecureRandom.new(32) (but does have a different format).
accepts_nested_attributes_for uses the primary key (which is normally id). By using UUIDs as data type for your id columns, Rails will automatically use those.
I've never used this functionality myself, so I'll be using this article as reference. This solution does not use the public_uid gem, so you can remove that from your Gemfile.
Assuming you start with a fresh application, your first migration should be:
bundle exec rails generate migration EnableExtensionPGCrypto

Which should contain:
def change
  enable_extension 'pgcrypto'
end

To enable UUIDs for all future tables create the following initializer:
# config/initializers/generators.rb
Rails.application.config.generators do |g|
  g.orm :active_record, primary_key_type: :uuid
end

With the above settings changes all created tables should use an UUID as id. Note that references to other tables should also use the UUID type, since that is the type of the primary key.
You might only want to use UUIDs for some tables. In this case you don't need the initializer and explicitly pass the primary key type on table creation.
def change
  create_table :people, id: :uuid, do |t|
    # explicitly set type uuid ^ if you don't use the initializer
    t.string :name, null: false
    t.timestamps
  end
end

If you are not starting with a fresh application things are more complex. Make sure you have a database backup when experimenting with this migration. Here is an example (untested):
def up
  # update the primary key of a table
  rename_column :people, :id, :integer_id
  add_column :people, :id, :uuid, default: "gen_random_uuid()", null: false
  execute 'ALTER TABLE people DROP CONSTRAINT people_pkey'
  execute 'ALTER TABLE people ADD PRIMARY KEY (id)'

  # update all columns referencing the old id
  rename_column :addresses, :person_id, :person_integer_id
  add_reference :addresses, :people, type: :uuid, foreign_key: true, null: true # or false depending on requirements
  execute <<~SQL.squish
    UPDATE addresses
    SET person_id = (
      SELECT people.id
      FROM people
      WHERE people.integer_id = addresses.person_integer_id
    )
  SQL

  # Now remove the old columns. You might want to do this in a separate
  # migration to validate that all data is migrating correctly.
  remove_column :addresses, :person_integer_id
  remove_column :people, :integer_id
end

The above provides an example scenario, but should most likely be extended/altered to fit your scenario.

I suggest to read the full article which explains some additional info.

A: Because you still need an :id field in your params, unless you want to change your to_param directly in model. Try something like this:
person  = Person.first
address = person.address
person.update({ name: 'Jack', adddresses_attributes: { id: address.id, public_id: XXX, _destroy: true } } )

A: This is the way I have my nested-attributes
#app/models/person.rb
class Person < ApplicationRecord
  ...
  has_many :addresses, dependent: :destroy
  accepts_nested_attributes_for :addresses, reject_if: :all_blank, allow_destroy: true
  ...
end

my controller
#app/controllers/people_controller.rb
class PeopleController < ApplicationController
   ...
   def update
     @person = Person.find_by(id: params[:id])
     if @person.update(person_params)
       redirect_to person_path, notice: 'Person was successfully added'
     else
       render :edit, notice: 'There was an error'
     end
   end
   ...
   private
   def person_params
     params.require(:person).permit(
        ... # list of person fields
        addresses_attributes: [
          :id,
          :_destroy,
          ... # list of address fields
        ]
     )
   end
   ...
end

I hope that this is able to help you.
Let me know if you need more help


text:
Q: Brightness - external monitor drivers I'm using Linux arch on Thinkpad X1C6.
I bought external monitor Samsung C27F396FHU and I have a problem with brightness.
I cannot use a physical button to adjust the brightness of the monitor - at first,  on the "quick acces" there was a text "unavailable", and in the main menu, the brightness text it was non-existant. After installing drivers:
sudo pacman -S xf86-video-intel
The "brightness" row appeared on the monitor main menu, but the text is dimmed (unclickable).
xrandr --output HDMI-1 --brightness 0.1 dims the screen artificially (rgb-like), but doesn't affect the backlight (true brightness).
sudo modprobe i2c-dev; sudo ddcutil capabilities state that MCCS version: not present.
I also tried xorg-xbacklight, but writing xbacklight -set 25 changes just the brightness of a laptop, not monitor. (I don't know what to type as the display of xbacklight -display <display>.)
TL;DR;
Brightness doesn't work on an external monitor on my ArchLinux, and I have no clue what can I do to fix it.
sudo ddcutil detect
Display 1
   I2C bus:             /dev/i2c-3
   EDID synopsis:
      Mfg id:           SAM
      Model:            C27F390
      Serial number:    H4ZM504450
      Manufacture year: 2019
      EDID version:     1.3
   VCP version:         2.0

A: As it came out, this monitor had "eye saving" mode that disabled brightness internally so manipulating it wasn't possible programmatically. I had to turn off the eye saving mode in OSD, and then everything worked like charm.
ddcutil enabled everything else:

*

*sudo ddcutil vcpinfo to get the list of feature codes regarding your monitor

*sudo ddcutil getvcp 0x10 in my case to know the value of the feature I want to change

*sudo ddcutil setvcp 0x10 42 to set the brightness feature to 42.


text:
Q: How can I fix this Overleaf rendering issue in Chrome? I use Overleaf with Chrome + Microsoft Windows 10. The rendering is very poor:

How can I fix that?
I have this issue with all Overleaf projects  in Chrome + Windows 10. I don't have this issue on Chrome + Android 12:

A: Following Gantendo's comment, I changed the PDF viewer from Overleaf to Browser, and it solved the issue:


text:
Q: Understanding the group operation $U_n$ In preparation of a test, there were a few things in class that still confused me on how my instructor got the answer:
Using the following definition for $U_n$:

There were two examples we did in class that I don't understand clearly:

And this one:
Order of [3] in $U_{20}$ = 4
 [3]^2 = [9]
 [3]^3 = [7]
 [3]^4 = [1]
 [17] = [-3] = 4

I would really like to know what the process is behind these examples to understand them for my test next week. If possible, how would I start with finding the order of [7] in $U_{40}$?
Thanks for reading, really appreciate the help!

A: Mod 40, we compute: 7*7 = 49 = 9, 7*7*7 = 343 = 23, 7*7*7*7 = 2401 = 1. Therefore the order of 7 is 4.


text:
Q: What is the most idiomatic way to load and save values from an MFC CPropertySheet? I have a class derived from CPropertySheet and I am having trouble finding the "correct" way to load values on startup and save values when the user presses OK.  I'm surprised that I can't find any useful example on the web but there it is.
Ultimately, I need to read values from an external data source and write them back but for now, I have a void LoadValues(void) method on my property sheet that just uses some literals to initialize the controls on the property pages.  This works when I call LoadValues() from OnInitDialog().  But if I do:
CMyPropertySheet* pSheet = new CMyPropertySheet("My Title");

pSheet->LoadValues();

if (pSheet->DoModal() == IDOK) {
   pSheet->SaveValues();
   delete pSheet;
}

(as Microsoft suggests) the values are not there when the property page is displayed; the controls are empty or contain default values.  All the MFC control value setting routines seem to return void so there's nothing to test for success.  I did read back a value in LoadValues() after I set it and I get the correct value.
Also, SaveValues() sees gibberish.  Perhaps the property sheet is torn down before I get out of DoModal() to the values aren't there any more?
I've been told that values should get loaded in OnInitDialog() and I guess I can get my external data source to the object in the constructor but that leaves me having no idea where to save values.  There doesn't seem to be a CPropertySheet::OnOK() method.  What am I missing?

A: Although you are working with a property sheet the same issues apply to all modal dialogs. Before you call DoModal the controls do not exist. So if your LoadValues call is attempting to access the controls it will not work. (This would normally produce an assertion in a debug build.) What you need is a two-step operation: (1) LoadValues can access data members of the sheet, so pass the values to the sheet's data members that you create for that purpose. (2) In OnInitDialog of the sheet you can initialize the controls from the data members.
SaveValues needs a similar two-step because the controls no longer exist after DoModal returns. (1) In the sheet's OnOK or equivalent move the data from controls to data members. (2) After DoModal returns you can access the data members to do the SaveValues.


text:
Q: Use xhr.overrideMimeType but get server response first? I want to get a Base64 encoded file from the server in order to use it in a dataURL so I use:
xhr.overrideMimeType("text/plain; charset=x-user-defined");

So I get the unprocessed data to perform the base64 encoding on.
But I also want to get the mimetype originally returned from the server to declare my dataURL:
var dataUrl = 'data:'+mimetype+';base64,'+b64;
when I try something like the following:
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
var mimetype = xhr.getResponseHeader('content-type');
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send(null);

the content-type returned is always null
Full source:
function getFileDataUrl(link,mimetype)
{
  var url = location.origin+link;
  var getBinary = function (url)
  {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, false);
    if(mimetype == null)
    {
        mimetype = xhr.getResponseHeader('content-type');
        console.log('mimetype='+mimetype);
    }
    xhr.overrideMimeType("text/plain; charset=x-user-defined");
    xhr.send(null);
    return xhr.responseText;
   };
   var bin = getBinary(url);
   var b64 = base64Encode(bin);
   var dataUrl = 'data:'+mimetype+';base64,'+b64;
   return dataUrl;
}
var dataUrl = getFileDataUrl(link,null);

A: You can set responseType of XMLHttpRequest to "blob" or "arraybuffer" then use FileReader, FileReader.prototype.readAsDataURL() on response. Though note, onload event of FileReader returns results asynchronously. To read file synchronously you can use Worker and FileReaderSync()
var reader = new FileReader();
reader.onload = function() {
  // do stuff with `reader.result`
  console.log(reader.result);
}
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function() {
  reader.readAsDataURL(xhr.response);
}
xhr.send(null);

At chromium synchronous XMLHttpRequest() is deprecated, see https://xhr.spec.whatwg.org/.
You can use Promise at main thread to get data URI of requested resource using either Worker or when FileReader load event is dispatched. Or use synchronous XMLHttpRequest() and FileReaderSync() at Worker thread, then listen for message event at main thread, use .then() to get Promise value.
Main thread
var worker = new Worker("worker.js");
var url = "path/to/resource";

function getFileDataUrl(url) {
  return new Promise(function(resolve, reject) {
    worker.addEventListener("message", function(e) {
      resolve(e.data)
    });
    worker.postMessage(url);
  })
}

getFileDataUrl(url)
.then(function(data) {
  console.log(data)
}, function(err) {
  console.log(err)
});

worker.js
var reader = new FileReaderSync();
var request = new XMLHttpRequest();

self.addEventListener("message", function(e) {
  var reader = new FileReaderSync();
  request.open("GET", e.data, false);
  request.responseType = "blob";
  request.send(null);
  self.postMessage(reader.readAsDataURL(request.response));
});

plnkr http://plnkr.co/edit/gayWpkTVydmKYMnPr3jD?p=preview


text:
Q: How to get logged in user's complete profile information using gem 'linkedin', :git => "git://github.com/pengwynn/linkedin.git"? I am using gem 'linkedin', :git => "git://github.com/pengwynn/linkedin.git"
when i create client and get profile i get the following values
headline:   url: last_name: first_name:summary

my question is how to get user's
picture-url,public_profile_url: location: country: school_name: degree: field_of_study: start_date: end_date:

A: use picture_url like follows
client.profile(:fields => [:headline, :first_name, :last_name, :picture_url,:educations, :positions])client.profile(:fields => [:headline, :first_name, :last_name, :picture_url,:educations, :positions])

A: For a list of all the fields you can use see the documentation at LinkedIn https://developer.linkedin.com/documents/profile-fields
#Gemfile
gem 'linkedin-oauth2', '~> 1.0.0'

# Other file
api = LinkedIn::API.new(linkedin.token)
profile = api.profile(
  fields: [
      :headline,
      :first_name,
      :last_name,
      :email_address,
      :phone_numbers,
      :im_accounts,
      :industry,
      :main_address,
      :primary_twitter_account,
      :picture_url,
      :public_profile_url,
      :positions
    ]
  )


text:
Q: generate symmetric matrix from tensor I'm learning tensor algebra.
So I have a question, Given a mod 3 tensor $\chi \in \mathbf{R}^{d_1,d_2,d_2}$, find vector $x \in \mathbf{R}^{d_1}$ so that $\chi \times_1 x$ is symmetric/antisymmetric?
So here is my attempt:
We want $(\chi \times_1 x )_{ij}=(\chi \times_1 x )_{ji}$
$(\chi \times_1 x)_{ij}= \sum_k \chi_{kij}x[k]$, here $x[k]$ means the $k^{th}
$ entry of $x$. it need to be equals to $(\chi \times_1 x)_{ij}= \sum_k \chi_{kji}x[k]$.
But like making $\chi_{kji}=\chi_{kij}$ will work but that is restriction on the tensor and not the vector...

A: Obviously the zero vector will always work. However in general non-trivial solutions do not necessarily exist: if $d_1=1$, then the matrix part needs to be symmetric/anti-symmetric already. When $d_1>1$ the problem boils down to linear dependence of the slices of the tensor.
For clearer notation, let $\mathfrak X = (X_1,\ldots, X_K)$ be the 3d tensor and $v=(v_1, \ldots, v_K)$ be the vector. Let $A^+=\frac{1}{2}(A+A^T)$ and $A^-=\frac{1}{2}(A-A^T)$ denote the symmetric/anti-symmetric part of a matrix. Then we observe that
$$\begin{aligned}
\sum_k X_k v_k \overset{!}{=} +\Big(\sum_k X_k v_k\Big)^T = +\sum_{k} X_k^T v_k \iff \sum_k X_k^-v_k = 0\\
\sum_k X_k v_k \overset{!}{=} -\Big(\sum_k X_k v_k\Big)^T = -\sum_{k} X_k^T v_k \iff \sum_k X_k^+v_k = 0
\end{aligned}$$
Hence, a non-trivial solution exists if and only if the symmetric/anti-symmetric parts of the slices $X_k$ are linearly dependent. Note that the dimension of the space of symmetric/anti-symmetric matrices is $\frac{1}{2}n(n+1)$ and $\frac{1}{2}n(n-1)$ respectively. Thus, if $d_1 > \frac{1}{2}n(n\pm 1)$ then a non-trivial solution always exists.


text:
Q: Pandas dataframe to excel: AttributeError: 'list' object has no attribute 'to_excel' I'm working with a pandas dataframe, where I take an excel file, group for the maximum date in one column by the client ID in another. I want to save that as an excel file, so that I can check my work and make sure my output is what I want.
My code is as follows:
df1 = pd.read_excel('ClientTrackExport.xlsx')
grouped = [df1.groupby('ClientID')['BeginDate'].last()]
writer = pd.ExcelWriter('examples.xlsx')
grouped.to_excel(writer, 'Sheet 1', index=False)
writer.save()

And I get this error message:
AttributeError: 'list' object has no attribute 'to_excel'

I followed the Pandas documentation to the letter, so I'm stuck. Any thoughts?

A: This comment from @roganjosh did the trick:

No, it's the [ and ] on either end of that line. That makes it a single-element list. df1.groupby('ClientID')['BeginDate'].last() will give you the dataframe

Once I took away the brackets, everything worked as intended.


text:
Q: how do I extract date string "Mar 11, 2019 • 3:26AM" from a paragraph and convert it to date time format (dd/mm/yy) in python I have a paragraph that contains details like date and comments that I need to extract and make a separate column. The paragraph is in a column from which I am extracting the date is as follows:

'Story\nFAQ\nUpdates 2\nComments 35\nby Antaio Inc\nMar 11, 2019 • 3:26AM\n2 years ago\nThank you all for an amazing start!\nHi all,\nWe just want to thank you all for an awesome start! This is our first ever Indiegogo campaign and we are very grateful for your support that helped us achieve a successful campaign.\nIn the next little while, we will be dedicating our effort on production and shipping of the awesome A-Buds and A-Buds SE. We plan to ship them to you as promised in the coming month.\nWe will send out more updates as we are approaching the key production dates.\nStay tuned!\nBest regards,\nAntaio Team\nby Antaio Inc\nJan 31, 2019 • 5:15AM\nover 2 years ago\nPre-Production Update\nDear all,\nWe want to take this opportunity to thank all of you for being our early backers. You guys rock! :)\nAs you may have noticed, the A-Buds are already in production stage, which means we have already completed all development and testing, and are now working on pre-production. Not only will you receive fully tested and certified awesome A-Buds after the campaign, we are also giving you the promise to deliver them on time! We are truly excited to have these awesome true Bluetooth 5.0 earbuds in your hands. We are sure you will love them!\nSo here is a quick sneak peek:\nMore to come. Stay tuned! :)\nFrom: Antaio Team\nRead More'

This kind of paragraph is present in each row of the dataset in a particular column called 'Project_Updates_Description'. I am trying to extract the first date in each entry
The code I'm using so far is:
for i in df['Project_Updates_Description']:
if type(i) == str:
    print(count)
    word = i.split('\n',7)
    count+=1
    if len(word) > 5:
        print(word[5])
        df['Date'] = word[5]

The issue I have right now is that when I extract the date from the paragraph I'm getting it as string I need it as dd/mm/yyyy format I tried the methods like strptime it didn't work it is appending as string and when i try to append it in new 'Date' column I keep getting the same date for all entry. Could someone tell me were I am going wrong?

A: Assuming you have a dataframe with a column entitled 'Project_Updates_Description' which contains the example text and you want to extract the first date and generate a datetime stamp from this information you can do the following:
import pandas as pd
import numpy as np
def findDate(txin):
    schptrn = '^\w+ \d{1,2}, \d{4,4}'
    lines = txin.split('\n')
    for line in lines:
        #print(line)
        data = re.findall(schptrn, line)[0]
        if data:
            #print(data)
            return pd.to_datetime(data)
    return np.nan
df['date'] = df.apply(lambda row: findDate(row['Project_Updates_Description']), axis = 1)


text:
Q: How to enable hibernate query timings for logging I am trying to add timing stats mechanism for hibernate queries. Our application.properties file already has entries like this :
logging.level.org.hibernate.SQL=DEBUG
spring.jpa.hibernate.ddl-auto=validate

So I tried to add : logging.level.org.hibernate.stat=DEBUG. But this is not providing me with any timing info. Anyone know why?
edit :
I also added this to pom.xml :
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <java.version>1.8</java.version>
  <hibernate.generate_statistics>true</hibernate.generate_statistics>
</properties>

still doesn't work.

A: You also need to set hibernate system property as well: hibernate.generate_statistics=true
One way you can set the System property is by using VM argument. In your case: -Dhibernate.generate_statistics=true


text:
Q: How To Recover CSS Rules From A Corrupted CSS File My .css file was working fine but today I noticed the website is not acting based on CSS rules so I tried to inspect the rues on browser and surprisingly I noticed the CSS file is empty!
I tried to open the style.css file in Notepad++ and this is how it looks like

I also tried to open the file in Bracket editor which I got this message

Can you please let me know if there is a way to fix this issue and retrieve the CSS rules from these NULs?

A: If your file is indeed corrupted, and you have site backups as part of your hosting plan, restore your website to a point where your file worked. (Many web hosts that offer backups will store 30 days' worth, depending on your hosting plan.)
If you don't have such a hosting plan, go to Wayback Machine and search for your URL. Pick a snapshot date when your site was working. Look in your source code and find a link to Wayback's cached version of your CSS file. Copy your CSS from there.
Alternatively, try searching for your website in Google. Unless you have noarchive tags on your site, there should be a link right in your search results to access a cached version of your site. If Google last crawled your site before your file got corrupted, you should be able to access your cached CSS file through the source code (or a link in Dev Tools).
Finally, check out this thread:
https://groups.google.com/forum/#!topic/brackets-dev/4hEn8qs9MKs
You may be able to open the file in a third code editor and save it as UTF-8.


text:
Q: How to create heap dump in golang when out of memory? Is there a way in go to cause an application to write a heapdump to a file when it is out of memory?
I am looking for a global solution to the application.

A: there is a profiler tool for this go tool pprof and also pprof package. The pprof package will allow you to get information about current memory allocations, as well as total (cumulative) memory allocations. There is also an option to create a HTTP endpoint for profiling with net/http/pprof.
For the simpler implementation (without HTTP), you just import runtime/pprof and then call pprof.WriteHeapProfile("some_file.prof") to write information into a file. The output file can be later examined with go tool pprof some_file.prof.
I am not sure how to detect when your application is out of memory. But you can probably put WriteHeapProfile into defer to launch it, when your app receives the kill signal from OS caused by the high memory usage.
Sources:

*

*Package runtime/pprof

*Profiling Go Programs

*How I investigated memory leaks in Go using pprof on a large codebase

*Heat dump in Go using pprof


text:
Q: sql query to calculate the difference between two dates of different columns and adjacent rows Below is my table.

I want to populate the break column by calculating the difference between two dates
I want to calculate time between column EndD,EndT and StartD,StartD but of different rows(2nd row).
for e.g-
EndD is '2016-06-01 18:17:48' and start date is '2016-06-01 18:46:05' and break time should be calculated between these two dates
Output should be like this:

A: Try this:
SELECT  ID, AgentID, StartD, StartT, EndD, EndT,
      DATEDIFF(minute,
         CAST(t1.EndD + ' ' + t1.EndT AS DATETIME),
         (SELECT CAST(t2.StartD + ' ' + t2.StartT AS DATETIME)
            FROM yourTable t2
            WHERE t2.ID = t1.ID + 1  AND t1.AgentID = t2.AgentID)) as [break]
FROM  yourTable t1

The Datediff function takes the minutes between an embedded query (which takes the date and time from the next line with same agent) and the date and time of your current row.  Also, be sure to use brackets around your column name "break", since it is a SQL-Server reserved word.
UPDATE:
User reported negative values from my answer.  This should be resolved by switching the two date parameters in the DATEDIFF function.  I have updated the code (above) to reflect this.

A: For tsql that would work
update a
set a.break=datediff(minute,a.endt,b.startt)
from tbl a
inner join tbl b
on a.startD=b.endD and a.ID=b.ID-1

A: SELECT
DATEDIFF(minute,'2016-06-01 20:17:48','2016-06-01 20:50:17')

Mention that you should change that in order you want and always increase the startT + 1


text:
Q: Not sure how to use QtTest I want to do unit testing for some simple exercises i have done in c++ using Qt. i figured using QtTest seemed like a reasonable place to start.
i have a class that returns an integer and i want to test that the expected result is the same as the actual.
am i right in thinking i make a new c++ source file in the project to use as the QtTest
heres what i have but from reading the Qt documentation i cant work out what i have to do?
    #include "Conversion.h"
#include <QtTest/QtTest>

class ConversionTest : public QObject
{
private slots:
    void testConvert();

};

void ConversionTest::testConvert()
{
    int unit1 = 1, unit2 = 10;
    std::string sUnit1 = "stone", sUnit2 = "pound";
    double expected = 10.8862;
    double actual;

    Conversion c;
    actual = c.convert(unit1, unit2, sUnit1, sUnit2);
    QCOMPARE(expected, actual);
}

QTEST_MAIN (ConversionTest)
#include "conversiontest.moc"

this is what i produced after reading the documentation but now what how do i run it and get the (what i think is) console output that says pass/fail?
any help would be great thanks

A: You need to create an app with it (QTEST_MAIN(..) builds the main function for you), and specify CONFIG += qtestlib in the .pro file.
When you run it, a console opens that prints out the test results.

A: I solved this myself the problem was just Qt errors no problem with the code at all, for some reason it didnt like that my project files were in a folder structure of more than one folder before my project files, used the exact same code in a new dir and it worked?? :S


text:
Q: If the derivative of the natural logarithm $\frac{d}{dx}\ln(x)=\frac{1}{x}$, why isn't the derivative $\frac{d}{dx}e^{x}=x$? It might seem a little bit weird why I would think that, and I already know that $\frac{d}{dx}e^{ax}=ae^{ax}$. But I'm thinking that the differential equation $\frac{dx}{dt}=ax$, which can be interpreted as saying that the slope at each value of $x$ is equal to $x$ itself and has the solution $x(t)=e^{at}$, so using the differential equation above shouldn't the derivative be $\frac{d}{dt}e^{at}=at$?
It would also make sense because the logarithm is sort of the inverse of an exponetial and the inverse of it's derivative which is$\frac{1}{x}$ is then $\frac{1}{x}^{-1}=x$.

A: If $y=e^x$ then $x=\ln y$ and $\frac{dx}{dy}=\frac1y$, so $\frac{dy}{dx}=\frac{1}{dx/dy}=y\ne x$.


text:
Q: Runtime creation of Delphi Firemonkey components from a string How can i create at runtime a visual component as a child of the form using eventually RTTI?
All i got is a TValue instance...
 t := (ctx.FindType(Edit1.Text) as TRttiInstanceType);
 inst:= t.GetMethod('Create').Invoke(t.MetaclassType,[Form1]);

Thank you!

A: A purely RTTI approach using TRttiMethod.Invoke() would look something like this:
var
  ctx: TRttiContext;
  t: TRttiInstanceType;
  m: TRttiMethod;
  params: TArray<TRttiParameter>;
  v: TValue;
  inst: TControl;
begin
  t := ctx.FindType(Edit1.Text) as TRttiInstanceType;
  if t = nil then Exit;
  if not t.MetaclassType.InheritsFrom(TControl) then Exit;
  for m in t.GetMethods('Create') do
  begin
    if not m.IsConstructor then Continue;
    params := m.GetParameters;
    if Length(params) <> 1 then Continue;
    if params[0].ParamType.Handle <> TypeInfo(TComponent) then Continue;
    v := m.Invoke(t.MetaclassType, [TComponent(Form1)]);
    inst := v.AsType<TControl>();
    // or: inst := TControl(v.AsObject);
    Break;
  end;
  inst.Parent := ...;
  ...
end;

A much simpler approach that does not use TRttiMethod.Invoke() would look like this:
type
  // TControlClass is defined in VCL, but not in FMX
  TControlClass = class of TControl;

var
  ctx: TRttiContext;
  t: TRttiInstanceType;
  inst: TControl;
begin
  t := ctx.FindType(Edit1.Text) as TRttiInstanceType;
  if t = nil then Exit;
  if not t.MetaclassType.InheritsFrom(TControl) then Exit;
  inst := TControlClass(t.MetaclassType).Create(Form4);
  inst.Parent := ...;
  //...
end;


text:
Q: Cocoa Touch equivalent of JavaScript's focus/blur In JavaScript there's a concept of focusing and blurring input elements. Is there something similar in Cocoa Touch? I want to fire some action when user ends editing of one textfield and goes to the next one.

A: You can make
[UITextField becomeFirstResponder];

to focus the Text Field.
when the User is finished with his input, he propably uses the "next" button provided by the keyboard, in which case you should use delegates to get from one Field to another


text:
Q: Efficient way to make a new patch from some of the current changes I'm using mercurial queues quite alot, and I'm really happy with
them, but there is one workflow which I find overly complicated.
It happens sometimes that I'm working on a patch, and then I
realize I have been working on something that should be in a
separate patch (like when I fixed a bug that I found while working
on a feature, or added another feature for that I actually want to
have in a separate patch).
So the state is for the working directory is: patches A,B,C
applied, plus changes that should be put into patch C, and changes
that should be in a new patch D.
My current workflow for that is as follows:
hg qnew D.patch files-for-patch-D..
hg qnew temp.patch # changes for patch C
hg qpop
hg qpop
# Now I'm on patch C
hg qfold temp.patch # Integrate changes into patch C
# Here I could have patch errors..
hg qpush

I know I could also do it like this
hg qrefresh files-for-patch-C..
hg qnew -m "..." new-feature.patch

The downside with this approach is that the number of files for
patch C is usually large, and it's awkward to have to
put all of them onto the command line. The number of files for
patch D is usually small in comparison.
Is there a better way to accomplish this than what I have outlined
above?

A: I think you've covered the most typical approaches to this problem — I also run into it from time to time. One alternative solution I know of is to do
$ hg qrefresh -X files-for-patch-D
$ hg qnew D.patch

That is: exclude the few files that you changed for patch D, instead of trying to include all the right files for patch C.
You can also forcibly pop patch D (with hg qpop -f) instead of stashing your changes into a temporary patch. This only works if the files touched by patch D don't intersect with the changes in the working copy, i.e., when you haven't used qrecord from the record extension to create patch D.


text:
Q: Combinatorial problems where the set of elements is equivalent only under some restricted set of permutations I'm not sure if I worded the question properly, but I'm trying to understand how to solve certain problems. I'll begin with things I think I understand.
Consider for example the problem of grouping $n$ balls into bags. If the balls are all identical, and we want to know how many ways we can separate them into an unordered set of bags (any  number of bags), it is equivalent to integer partitioning of $n$. Here, the fact that the balls are identical, could be interpreted as: groupings are equivalent modulo any permutation of the balls
Conversely, if the $n$ balls are all distinct then the answer can be expressed using bell numbers, $B_n$, for the number of possible partitions of n distinct elements. Balls are distinct, means groupings are all distinct modulo any permutation.
Where I'm going with this, is how do you think of problems like this:
If you have 1 green ball and 3 red balls {G, R, R, R}, how many distinct groupings of these balls can be made? All red balls are identical, all green balls are identical, but a green and red ball are distinct. In a sense, only some permutations are allowed to make two groupings equivalent.
The answer to the above problem is 7, but what is the combinatorial way of solving any generalization of the problem?
Thank you in advance,
Alex.
P.S. I arrived at this question trying to calculate the number of factorizations of an integer given its prime factors. The above problem I think is equivalent to counting the number of factorizations of $54 = 2 \cdot 3 \cdot 3 \cdot 3$. Putting balls into a bag is the same as multiplying the corresponding primes. Thus { {G, R} {R} {R} } corresponds to $54 = 6 \cdot 3 \cdot 3$

A: Expanding on Qiaochu's comment, what you want to do is use Burnside's lemma, which relates the number of distinct arrangements of a set modulo some group of permutations (known as orbits) to the size of the group of permutations and the number of elements in the set fixed by each permutation in the group. In symbols (using the same notation as Wikipedia) this is
$$|X/G| = \frac{1}{|G|}\sum\limits_{g\in G} |X^g|$$
which we can apply to your first example of one green and three red balls.
Let $X$ be the set of functions $f:\{1,2,3,4\}\to \{1,2,3,4\}$, and let $G=S_4\times S_3'$, where $S_3'$ is the subgroup of $S_4$ which fixes $1$, act on $X$ by $(\sigma,\sigma')\cdot f(x) = \sigma(f(\sigma'(x)))$.
Computation of $|X/G|$ (currently incomplete b/c I need sleep, to be finished): We have $|G| = 24\times 6 = 148$. In this case, I will determine the sum on the RHS somewhat differently than normal, by counting the number of elements of $G$ which fix each function (which clearly gives the same sum). If a function $f$ is invariant on $1\leq n\leq 3$ elements other than $1$ and maps onto $1\leq m\leq 4$ elements, then there are $n!(4-m)!$ elements $(\sigma,\sigma')\in G$ fixing $f$ such that the range of $f$ and the set affected by $\sigma$ are disjoint. It remains to cover the cases where $\sigma$ is a two-cycle, three-cycle, and product of disjoint two-cycles when restricted to the range of $f$.
Now, this may seem like an awful lot of work to answer a simple question, and in the case of your first example it is. But it allows for a general formula. For your motivating example with $$x = \prod\limits_{i=1}^n p_i^{e_i}, c = \sum\limits_{i=1}^n e_i$$ the set becomes $$X = \left\{f: \{1,\ldots,c\}\to \{1,\ldots,c\}\right\}$$ and the group becomes $$G = S_c\times S_{e_1}\times \cdots \times S_{e_n}$$ which acts on a function $f\in X$ by $$(\sigma_0,\sigma_1,\ldots,\sigma_n)\cdot f(x) = \sigma_0(f(\sigma_j(x)))$$ where $j$ is such that $$\sum\limits_{i=1}^j e_i < x\leq \sum\limits_{i=1}^{j+1} e_i$$ which may be torturous to work with, but at least it's a unified framework.


text:
Q: How to gracefully shutdown servelts in tomcat in docker container? What I found out so far:

*

*A "docker stop" sends a SIGTERM to process ID 1 in the container.

*The process ID 1 in the container is the java process running tomcat.*)

*Yes, tomcat itself shuts down gracefully, but not do so the servlets.

*Servlets get killed after 2 seconds, even if they are in the middle of processing a reguest(!!)

*) Side note:
Although our container entrypoint is  [ "/opt/tomcat/bin/catalina.sh", "run" ], but
in catalina.sh the java process is started via the bash buildin "exec" command,
and therefore the java process replaces the shell process and hereby becomes the new process id 1.
(I can verify this by exec into the running container and do a "ps aux" in there.)
Btw, I am using tomcat 7.0.88.
I found statements about tomcat doing gracefull shutdown by default (http://tomcat.10.x6.nabble.com/Graceful-Shutdown-td5020523.html - "any in-progress connections will complete"), but all I can see is that the SIGTERM which is sent from docker to the java process results in hardly stopping the ongoing execution of a request.
I wrote a little rest servlet to test this behaviour:
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.Status;

@Path("/")
public class SlowServerRes
{
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Path("test1")
    public Response test1(@QueryParam("sleep") final int sleepDurationSec)
    {
        long received = System.currentTimeMillis();
        System.out.println("+++++++++++++++++++++ received request at " + received);

        for (int i=1; i <= sleepDurationSec; i++) {
            System.out.println("  ++++ Sleeping for 1 sec ("+i+")");
            try { Thread.sleep(1000); }
            catch (InterruptedException e) {
                System.out.println("   Sleep was interrupted at second " + i + " ... ignoring/continue sleeping.");
            }
        }

        long finished = System.currentTimeMillis();
        String result = "received: " + received + "  finished: " + finished;
        System.out.println("+++++++++++++++++++++ " + result);
        Response response = Response.status(Status.OK).entity(result).build();
        return response;
    }
}

After intensive googling I finally came across this posting:
http://grokbase.com/t/tomcat/users/113nayv5kx/tomcat-6-graceful-shutdown
So the grace period that is given to tomcat is NOT propagated as a grace period for the servlets.
I wonder weather this makes much sense, but it looks like this is the fact.
So the only way to give servlets the possibility to properly end their ongoing requests is to change
the "unloadDelay" (https://tomcat.apache.org/tomcat-7.0-doc/config/context.html).
However, I did not find the right place in the tomcat config files to define a non-default unloadDelay. In case this matters, my main concern is about jersey servlets (org.glassfish.jersey.servlet.ServletContainer).
Or maybe there are other possibilities, which I don't see by now?
(I added kubernetes to the tags list, because this may be of major concern especially for Kubernetes, as it relocates (docker stop->SIGTERM) containers quite often, just to keep the load balanced.)

A: Now I found the answer here: https://stackoverflow.com/a/11154770/2081279
It worked for me under linux with
<Context path="/myapp" unloadDelay="10000"/>

but only with upper letter "C"ontext.

A: You could expose a REST API to stop gracefully the servers.
1) Implement and use a javax filter that maintains in its own state the HTTP requests in progress.
2) As the stop event occurs, the current tomcat instance doesn't have to serve any longer new clients requests. So make sure that new requests cannot be redirected to this instance.
3) As the stop event occurs (second thing), start a thread that waits for all requests were served.  As all responses were sent, request the tomcat instance to shutdown : the command String shutdown may be a way.


text:
Q: Understanding an unknown digital encoding I'm trying to understand a certain undocumented digital protocol. It looks similar to Miller or coded mark inversion (CMI) encoding. So far I managed to decode the encoded data and get the expected results. However I can't figure out one detail that prevents me from encoding data in a way identical to the black box encoder.
The symbols of the protocol are 00, 01, 10, 11 (0 and 1 in my case are certain voltage levels after clock recovery, but I think physical layer details aren't relevant to decode). 00 and 11 symbols both decode to binary 0. 01 and 10 symbols decode to binary 1.
For example, 00 11 01 00 10 11 00 decodes to 0010100. This is the result I am expecting and I'm fairly certain it is correct. This interpretation also makes sense since I know the protocol should be inversion-invariant (swapping 0 and 1 in the symbols should decode to the same bits).
This is how the state diagram looks like (based on a fairly large sample of encoded data):

For example, if last symbol was 00 and next bit to encode is 0, then the next symbol is always 11.
The problem is that some transitions are ambiguous. In particular, if last symbol was 00 and next bit is 1, sometimes the encoder produces 01 and sometimes 10. Similarly, if last symbol was 10 and next bit is 1, sometimes another 10 is produced and sometimes it goes to 01.
Here are how some sequences of bits get encoded to different symbol sequences:
1010 -> 01 00 01 00
1010 -> 01 00 10 11
1010 -> 10 11 01 00

0110 -> 00 01 01 00
0110 -> 00 10 01 00
0110 -> 00 10 10 11
0110 -> 11 01 01 00

Some transitions are never observed: there's never a 11 to 10 and 01 to 10 (this should be present if this was Miller encoding). A consequence of this is that in the symbol stream there's sometimes three consecutive 0s (which wouldn't occur in differential Manchester), but never three consecutive 1s. This goes somewhat contrary to the symmetrical nature I would expect from the protocol.
What I'm trying to understand is how these ambiguous transitions are determined. So far I've found out:

*

*It's deterministic. Resetting the encoder and encoding the same stream of bits always results in the same stream of symbols.

*It's not linked to certain positions in the stream. The bits 01 at the same  position in a stream can sometimes be encoded either 00 01 or 00 10 sequence of symbols (depending on surrounding bits). Encoding is also not determined by odd or even bits.

*It seems locally dependent on a few previous symbols, but not in a simple way. It seems if some bits are changed it only affects encoding about 4-5 symbols around the change, but for the rest of the stream encoding choices don't change.
I found that the smallest number of preceding bits that unambiguously predicts 00 to 01/10 transition is 5 bits. For 10 to 10/01 it is 4 bits. Unfortunately my ability to feed data to the encoder is somewhat limited so I wasn't able to fill a complete look up table.
Here is an example of a partial look-up table I came up with:
If preceded by:
 0, 1, 1, 0
 0, 0, 1, 0
 0, 1, 0, 1
Then
 bit 1 after symbol 10 is encoded as 10

If preceded by:
 1, 1, 0, 1
 1, 0, 0, 0
 1, 0, 1, 1
Then
 bit 1 after symbol 10 is encoded as 01

So my question is, is there a purpose for encoding bits like this? It seems deterministic enough that it looks like an intentional feature rather than a bug or undefined behavior. On the other hand, using a lookup table seems needlessly complicated when something simple like a differential Manchester encoding would suffice.
My gut feeling is that I'm missing something obvious here. I would welcome any suggestions on what the actual algorithm behind choosing the ambiguous symbol transitions in encoding could be.

A: To answer my own question:
This coding turned out to encode 4 bits in 5 symbols, similar to what @MrSnrub suggested. Following is the full encoding table (using H and L for for high- and low- voltage levels, to avoid confusion between decoded bits and symbols as suggested by @Justin. A pair of voltage levels forms one symbol).
The symbols (+) and (-) show symbols when polarity has been inverted - both decode to the same bits.
decode   symbols (+)       symbols (-)
======   ==============    ==============
0000     LH LL HH LL HH    HL HH LL HH LL
1000     LH LH LL HH LL    HL HL HH LL HH
0100     LH LL HL HH LL    HL HH LH LL HH
1100     LH LH LH LL HH    HL HL HL HH LL
0010     LH LL HH LH LL    HL HH LL HL HH
1010     LH LH LL HL HH    HL HL HH LH LL
0110     LH LL HL HL HH    HL HH LH LH LL
1110     LH LH LH LH LL    HL HL HL HL HH
0001     LH LL HH LL HL    HL HH LL HH LH
1001     LH LH LL HH LH    HL HL HH LL HL
0101     LH LL HL HH LH    HL HH LH LL HL
1101     LH LH LH LL HL    HL HL HL HH LH
0011     LH LL HH LH LH    HL HH LL HL HL
1011     LH LH LL HL HL    HL HL HH LH LH
0111     LH LL HL HL HL    HL HH LH LH LH
1111     LH LH LH LH LH    HL HL HL HL HL

This table can in fact be derived using a simple state diagram (shown here for positive polarity), similar to that I showed in my question. The crucial piece of information that I was missing was the fact that the state diagram gets reset to state LH every 4 encoded bits and an extra symbol inserted into the stream.

These encoder resets on 4 bit boundaries were the cause of ambiguous transitions to LH that were puzzling me. I found this out by using a representation of the symbols similar to what @Justin suggested. When displaying encoded symbols in that more compact way it became immediately obvious that the code is based around 5 symbol blocks.
So basically I was mislead by my early assumption that bit encoding wasn't dependent on bit position (the lookup table I mentioned in my question was constructed without considering any alignment). My poor understanding of the upper layer protocols also led me to dismiss the extraneous 1 bits in the decoded stream which in hindsight obviously appeared in every 5th position when using the naive decoding algorithm I mention in the second paragraph of my question.
I can only speculate why this specific code was chosen over something more common like differential Manchester. One benefit seems to be that it's very easy to detect errors in transmission. Since 10 voltage levels encode only 4 bits there are plenty of invalid combinations that the decoder can detect as line errors. At first glance the encoder resets seem to aid synchronization to 4-bit boundaries, but in fact they aren't that useful. In this code LH LH LH LH LH LH LH ... (long sequence of 1s) is a valid sequence and in such a sequence it's impossible to detect the 4-bit boundaries.


text:
Q: Django - Multiple File upload data not inserted in model database I have implemented a feature to upload multiple files for each RetailerMaster(as foreign key).
Once I migrate this model to microsoft sql server, FileUpload model is created without primary key which django should be creating automatically. Also if i upload multiple file, then only one record is created in database and it keeps on updating for each file.
models.py
class RetailerMaster(models.Model):
    id = models.PositiveIntegerField(unique=True)
    name = models.CharField(max_length=1000)
    address = models.CharField(max_length=4000)
    city = models.CharField(max_length=100)
    state = models.CharField(max_length=100)
    pincode = models.CharField(max_length=100)
    contact_name = models.CharField(max_length=500)
    email = models.EmailField()
    phone = models.CharField(max_length=15)
    erp = models.CharField(max_length=1000)
    remark = models.CharField(max_length=4000)

    def __str__(self):
        return self.id

class FileUpload(models.Model):
    retailer = models.ForeignKey(RetailerMaster, on_delete=models.CASCADE),
    file = models.FileField(upload_to='files')
    file_upload_datetime = models.DateTimeField()
    file_name = models.CharField(max_length=1000)

views.py
retailer = RetailerMaster.objects.get(retailer_id=retailer_id)
register_complete = retailer

files = request.FILES.getlist('file')
file_upload_datetime = file_upload_form.cleaned_data['file_upload_datetime']
for f in files:
    print(f.name)
    file_instance = FileUpload(register_complete.id,f,file_upload_datetime,f.name)
    file_instance.save()

migrations file
migrations.CreateModel(
    name='FileUpload',
    fields=[
        ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
        ('file', models.FileField(upload_to='files')),
        ('file_upload_datetime', models.DateTimeField()),
        ('file_name', models.CharField(max_length=1000)),
    ],
)

Why migration file is not having foreign key?
template file
<div id="registrationForm">
  <form
    action="{% url 'retail_forms:file-upload' %}"
    method="post"
    enctype="multipart/form-data"
  >
    {% csrf_token %} {{ retailer_registration_form|crispy }} {{ file_upload_form|crispy }}
    <input type="submit" value="Register" class="btn btn-primary" />
  </form>
</div>

eg:
If two files are uploaded 001.xlsx and 002.xlsx then below happens in database. As actual result, one record is inserted rather than two and same is updated with last file uploaded from multiple files.

Can anyone help why record is not inserted but just updated.

A: Problem is fixed by removing trailing comma for foreign key in FileUpload Model.
django - Foreign key not getting created from model


text:
Q: How to display text at the top a cell I see that text can be aligned to the left or to the right.
There are situations where one column has a lot of text and then all other columns have their values in the vertical middle of the column.
df.style.set_properties(**{'text-align': 'right'})
I tried
df.style.set_properties(**{'text-align': 'top'})
And it didn't work
It seems that this is borrowed from css so I also tried
df.style.set_properties(**{'vertical-align': 'top'})

A: The CSS pairing you want is: "vertical-align": "text-top"
Example:
import pandas as pd

pd.set_option('display.max_colwidth', None)

d = {'A': [1, "This is a medium long value"], 'B': [1, "This is a medium long value"], 'C': [1, "This is a medium long value"], 'D': [1, "This is a medium long value"],
     'E': [1, "This is a medium long value"], 'F': [1, "This is a medium long value"], 'G': [1, "This is a medium long value"], 'H': [1, "This is a medium long value"],
     'X': [1, "This is a really really really long value that goes on and on and on and on and on and on and on and on."]}
df = pd.DataFrame(data=d)

df.style.set_properties(**{"vertical-align": "text-top"})

Without "vertical-align": "text-top":

With "vertical-align": "text-top"


text:
Q: How to solve CSS include error after Apache RewriteRule? I use winXP and AppServ. I have a "showitem.php" on my website root. An example usage:
    www.mydomain.com/showitem.php?id=123
I want to use links like following:
www.mydomain.com/item/123
In .htaccess I write this line:
RewriteRule ^item/([^/]+)$ showitem.php?id=$1
Server directs to showitem.php and id is received successfully. However, main problem is with the css and js files. If I make "css/style.css" to "/css/style.css", page is shown on the internet and but not on localhost, because root is "localhost" but files are under "localhost/mydomain". I have also tried "!-f" condition for .css files but it doesn't help and it can't as far as I understand. To solve the problem, I should direct wrong css file interpretation to the correct place, so I want to redirect client request "item/css/style.css" to its original location "css/style.css". I add the following rules for localhost but is there any other way?
RewriteRule ^item/css/([^/]+)$ /mydomain/css/$1
RewriteRule ^item/img/([^/]+)$ /mydomain/img/$1

A: Set a base tag in your html head.
<base href="http://www.mydomain.com/" />
And then set your stylesheet linking paths relative to the base, e.g.
<link href="css/style.css" />

A: you could write these to the file .htaccess
ErrorDocument 404 /error_404.php

/error_404.php is your error file you want to put something in there.


text:
Q: Proxy server connection reset My proxy server is a simple Java socket server which listens on port 8081. However, requests are handled a bit different than a regular proxy server.
For example, if I want to open http://www.google.com, I'd type http://localhost:8081/http://www.google.com. My server:8081 would open a socket on http://www.google.com:80, send the same HTTP headers it received from the browser and then it would return the response from Google to the browser.
But, if for example the browser is expecting a video/mp4 stream, there is a problem. Say the requested page is http://localhost:8081/http://www.cnn.com/today.mp4. My server:8081 would then connect to http://www.cnn.com/today.mp4 with appropriate headers and start receiving the stream. The stream would be read and the chunks (not actually chunked http encoding, chunks of 32768 bytes) would be forwarded to the browser. My server creates a seperate thread for each socket, and the byte read() (from server) and write (to browser) loop is in a try-catch block, so if something fails, the socket is simply closed.
Everything works fine, but the problem happens here: when the browser requests to forward the video, i.e. to the 5th minute of the video (using the bytes-range header), my server stops working. write() fails and the socket is closed. The next socket accepted cannot be written to (or it can), but the browser request fails (when viewed in Chrome Developer Tools).
Sorry for the wall of text, I hope you might help me. If necessary, I could post some code but it's a basic multithreaded socket server with a thread per socket.
Just to clarify, by forwarding the video I mean on fast-forward and/or rewind. Browser uses the bytes-range headers to do this.

A: Turns out the problem was in the flash video player requesting the video from server with wrong headers. After tuning it's properties (talking about jwplayer), it works fine.


text:
Q: How to mock time() function while testing in Laravel? I'm doing a maths contest project using Laravel. All of the controller methods in the project uses a lot of time() functions.
Questions are returned to the user depending on whether the current time is in between the contest live time.
While writing the feature test and unit tests, how do I mimic the time() functions in the controller so as to set my desired time while running tests for the project?

A: There is two options that you can do to interact with time:
Option 1: Use Laravel inbuilt function

Note: Laravel Version >= 8

Latest version of Laravel has good method to interact with time:
$this->travel(5)->milliseconds();
$this->travel(5)->seconds();
$this->travel(5)->minutes();
$this->travel(5)->hours();
$this->travel(5)->days();
$this->travel(5)->weeks();
$this->travel(5)->years();

// Travel into the past...
$this->travel(-5)->hours();

// Travel to an explicit time...
$this->travelTo(now()->subHours(6));

// Return back to the present time...
$this->travelBack();

Ref: https://laravel.com/docs/mocking#interacting-with-time
Option 2: Carbon method
Carbon::setTestNow();

Or set any dates
$knownDate = Carbon::create(2001, 5, 21, 12);
Carbon::setTestNow($knownDate); // Or any dates
echo Carbon::now();  // will show 2001-05-21 12:00:00

Ref: https://laraveldaily.com/carbon-trick-set-now-time-to-whatever-you-want/

A: I think Carbon should be used instead of time():
Carbon::now()->timestamp // Or just now()->timestamp in 5.5+

You can easily mock Carbon instances.
If you don't use time() a lot, you could also create your own helper:
function timestamp()
{
    if (app()->runningUnitTests()) {
        return ....
    } else {
        return time();
    }
}

And use it instead of time():
timestamp()


text:
Q: Rails. a href=#page deactivates javascript I'm having trouble to find the correct way to do this. In my landing page I got a inner link like this:
Destacados

When I click on it, the page go to the #destacados id, but all the javascript stop working, so the carrusel just dies. I'm not sure if this can help, but when I click the link, the address bar change to /myapp/#destacados ... may be it has trouble routing that...  any idea??
Thanks

A: Can you show how you are binding the click event to your  ?
Just tested with JQuery (could be without)
Go To Destacados Section

The focus goes to the anchor and clicked is printed


text:
Q: How do I use BindDynamic in my code? Type name not allowed I am trying to follow a UE4 tutorial on how to use timelines in C++. However, when I try to use BindDynamic, the option to do so does not show up. An error "type name is not allowed" keeps showing up. Here Are the important parts of my code:
CPP
// Called when the game starts or when spawned
void AMyCharacter::BeginPlay()
{
    Super::BeginPlay();

    UpdateFunctionFloat.BindDynamic(this, &AMyCharacter, UpdateTimelineComp);

    if (ExampleTimelineCurve)
    {
        CrouchTimelineComp->AddInterpFloat(ExampleTimelineCurve, UpdateFunctionFloat);
    }

    TimelineFinishedFunction();
    CapsuleHalfHight = GetCapsuleComponent()->GetScaledCapsuleHalfHeight();
    standingCapsuleHalfHight = GetCapsuleComponent()->GetScaledCapsuleHalfHeight() * 2;
    cameraZOffset = FirstPersonCamera->GetRelativeLocation().Z;

    GunMesh->AttachToComponent(HandMesh,
        FAttachmentTransformRules::SnapToTargetNotIncludingScale,
        TEXT("GripPoint"));

}

void AMyCharacter::UpdateTimelineComp(float Output)
{
    float newCapsuleHight = Output;
    GetCapsuleComponent()->SetCapsuleHalfHeight(Output);
}

.h

protected:

    UPROPERTY(EditAnywhere, BlueprintReadWrite)

        class UTimelineComponent* CrouchTimelineComp;

    FOnTimelineEvent TimelineFinishedEvent;

    FOnTimelineFloat UpdateFunctionFloat;

    UFUNCTION()
        void UpdateTimelineComp(float Output);

    UFUNCTION()

        void TimelineFinishedFunction();

A: Try like this:
UpdateFunctionFloat.BindDynamic(this, &AMyCharacter, UpdateTimelineComp);

->
UpdateFunctionFloat.AddDynamic(this, &AMyCharacter::UpdateTimelineComp);


text:
Q: How to get both a number and character from the user? There are two variables a and b, and I want to get data from the user. The data can be a number from 1 to 1000 or #,  and they should be apart by a space.
So how to get this kind of input from the user?

A: In general, this is too broad a scenario to provide exact answer. However, I'll be happy to provide you the idea.

*

*Read user input using fgets().

*Tokenize the input using delimiter (space, here) by strtok().

*Use appropriate converter functions (example: strtol()) to check and convert the inputs.

Now choose a language, write the code and come back if you have any specific issue / question to be addressed / answered.


text:
Q: Expectation of product of bivariate normal distribution Let (X,Y) be a bivariate distribution with $E[X] = E[Y] =0$, and let $f$ be a function with $|f(x)| + |f'(x)| \leq Ae^{\alpha|x|}, x \in \mathbb{R}$. Use conditional expectations and properties of normal distributions to show $E[Xf(Y)] = Cov(x,Y)E[f'(Y)]$.
Honestly, I havent gotten very far as this is totally mysterious to me. I've tried to use conditional expectations to do something:
$$E[Xf(Y)] = E[E[Xf(Y)|X] = E[XE[f(Y)|X]]$$
or $$E[Xf(Y)] = E[E[Xf(Y)|Y] = E[f(Y)E[X|Y]] = E[f(Y) (\mu_x+ \frac{\rho\sigma_x}{\sigma_y}(Y-\mu_y)]$$
Using the formula for $\rho$, I can get this to:
$$(\mu_x - \frac{Cov(X,Y)}{\sigma_Y^2}\mu_y)E[f(Y)] + \frac{cov(X,Y)}{\sigma_y^2}E[f(Y)Y]$$
But I don't think this is the right approach, I'm just blindly throwing formulas at it. How can I get $f'$ to come into it? If anyone could give me some pointers it would be fantastic! Thanks

A: This generalises to $X$ and $Y$ with non-zero mean. Suppose $X \sim N(\mu_X, \sigma^2_X)$, $Y \sim N(\mu_Y, \sigma_Y^2)$ and $\text{cov}(X, Y) = \rho$. First prove the following:
$$ \mathbb E[f(X)(X - \mu_X)] = \sigma_X^2 \mathbb E[f'(X)] $$
Then prove that
$$ \mathbb E[Y \mid X] = \mu_y + \frac{\rho}{\sigma_X^2}[X - \mu_X] $$
Then we have that
\begin{align*}
\text{cov}(f(X), Y)
&= \mathbb E[(f(X) - \mathbb E[f(X)])(Y - \mu_Y)] \\
&= \mathbb E(\mathbb E[(f(X) - \mathbb E[f(X)])(Y - \mu_Y) \mid X]) \\
\end{align*}
Now from this point use the first two formulas to show $\text{cov}(f(X), Y) = \mathbb E[f'(X)] \text{cov}(X, Y)$. This is Stein's lemma if you wish to research more.


text:
Q: One led is blinking too frequently using the hardware timer (stm32f103vdh6) i recently started my internship using embedded C and i'm having some trouble with one of the tasks: Two leds should be blinking at 1Hz, one using the hardware timer, and the other one using the RTX RTOS os_dly_wait() function. The led using the RTX RTOS task is working fine, meanwhile the other led is blinking at a higher frequency (i estimate around every ~0.9 seconds). The microcontroller is operating at 72 MHz, so i'm using the prescaler value of 7200 and using a period of 10000. I'm using the TIM2 timer. I will also include a Clock tree of the microcontroller. What could be causing this?

#include <RTL.h>
#include "stm32f10x.h"
#include "stm32f10x_gpio.h"
#include <rtl.h>

#define     GPS_LED_PIN  GPIO_Pin_9
#define     NAV_LED_PIN  GPIO_Pin_2

__task void task1 (void);
__task void task3 (void);

void InitLED(void) {
    GPIO_InitTypeDef  GPIO_InitStructure;

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE | RCC_APB2Periph_GPIOB
                            | RCC_APB2Periph_GPIOD, ENABLE);
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
    GPIO_Init(GPIOD, &GPIO_InitStructure);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
    GPIO_Init(GPIOE, &GPIO_InitStructure);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
    GPIO_Init(GPIOB, &GPIO_InitStructure);
    GPIO_SetBits(GPIOE, GPIO_Pin_2);
}

void TurnOnLeds (void) {
    GPIO_SetBits(GPIOD, NAV_LED_PIN);
    GPIO_ResetBits(GPIOB, GPS_LED_PIN);
}
void InitializeTimer()
{
        TIM_TimeBaseInitTypeDef timerInitStructure;
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
    timerInitStructure.TIM_Prescaler = 7200;
    timerInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
    timerInitStructure.TIM_Period = 10000;
    timerInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    timerInitStructure.TIM_RepetitionCounter = 0;
    TIM_TimeBaseInit(TIM2, &timerInitStructure);
    TIM_Cmd(TIM2, ENABLE);
        TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
}
__task void task1 (void) {
    os_tsk_create(task3, 1);
    for (;;) {
        os_dly_wait(5);
        GPIO_SetBits(GPIOB, GPS_LED_PIN);
        os_dly_wait(95);
        GPIO_ResetBits(GPIOB, GPS_LED_PIN);
  }
}
__task void task3 (void) {
    for(;;)
    {
        int timerValue = TIM_GetCounter(TIM2);
       if (timerValue == 0)
             GPIO_SetBits(GPIOD, NAV_LED_PIN);
       else if (timerValue == 1000)
          GPIO_ResetBits(GPIOD, NAV_LED_PIN);
    }
}
/*-----------------------------MAIN---------------------------------------------*/
int main(void) {

    InitLED();
    TurnOnLeds();
    InitializeTimer();
    os_sys_init (task1);
}

A: if (timerValue == 0)
      GPIO_SetBits(GPIOD, NAV_LED_PIN);
else if (timerValue == 1000)
      GPIO_ResetBits(GPIOD, NAV_LED_PIN);

This is NOT how you use hardware timer to switch outputs.
To begin with, you assume that your task3 will check timer value when it is exactly equal to either 0 or 1000. You cannot guarantee this happening all the time in RTOS. It is possible that one check is done at, say 999, while the next one at 3, resulting in missed trigger time. Which is what you are seeing as a lower blinking frequency.
If you really want to use hardware timer, then you should configure it for PWM generation. Set OCC register to the desired LED ON duration, and the output pin will be active while counter is below this value and inactive for the rest of the cycle. (I am using "active" and "inactive" instead of high and low here, because polarity is configurable).
This way your hardware output does not depend on the RTOS task being called just in time for a switch.
However if you still wish to do this in a task, at least change exact equality to "greater than" (or "less then"). You will have much more consistent results. Something like this:
if (timerValue < 10)
    GPIO_SetBits(GPIOD, NAV_LED_PIN);
else
    GPIO_ResetBits(GPIOD, NAV_LED_PIN);

A: Just because it says it says 72MHz on the datasheet does not mean it will always run at 72MHz, it is the maximum it can run at. You don't show any initialization code so we can't tell if it has been correctly set to run at 72MHz. Inside the chip it uses much lower internal or external frequency source, which may be inaccurate.
But since you are using some kind of real-time OS, and using the delay function it provides, the delays are not exact. It just waits until the current millisecond count has been increased by the amount you requested. As the thing is completely asynchronous, assuming that you have 1ms system timer tick, there can be anything between 0 to 1ms before the next tick happens, so requesting 5ms will be in the range of 4-5 ms, so statistically speaking delay is always 0.5ms less.
I don't see why the led driven by TIMER2 counter even works. It will be awfully hard with a RTOS to hit to a point when counter is exactly 0 or exactly 1000. One count being 72MHz divided by the 7200 prescaler, so it's 0.1ms !


text:
Q: One of SESSION variables gets changed I am developing a web application with per-role user interface and functionality. In users table I have a role column, an enum, which stores each user's role. In the login script if a matching record for the user/pass is found I set a SESSION['role'] variable to the value of the record's role field. Along with the role, I also store several other bits of data, such as the display_name in other SESSION variables. Then, SESSION['role'] is used throughout the application to send the correct user interface to the browser and enforce access rules.
This all works fine on my localhost, but on the remote server, SESSION['role'] works just the first time - i.e. the correct user interface is sent to the browser. After that point, SESSION['role'] somehow changes to a different (existing) role, and as a result access rules do not allow the functions to be available. What is even more bizarre is that only SESSION['role'] changes and SESSION['displayname'] or SESSION['username'] remain intact.
I am not setting SESSION variables anywhere other than login.php. Any ideas where I should look for potential causes is greatly appreciated.

A: Check that your database structure is the same. Most notably that the ENUM has the same roles / identifiers. If you specify a value that's not valid, SQL will fail in "STRICT MODE", but otherwise it will fall back to one of the values.
(Tip: always develop in "STRICT MODE" unless there's some reason not to. Then you don't get strung when distributing to live).
If you have a separate table with the roles (such as a LEFT JOIN) check that too.

A: I found the problem. On the prod server register_globals was on (which is a tasteless choice for PHP 5.3.6 by the way).
However, I did not suspect that being the cause, because I was not aware of how it affected the super globals. I though having register_globals on was equivalent to adding this block of code at the beginning of all your scripts:
foreach($_SESSION as $kn => $val) eval("$kn = $val;");
same for other super globals ...

In other words, I thought having $_SESSION['role'] defined and equal to 'Manager' had the same effect as this line:
$role = $_SESSION['role'];
or
$role = 'Manager';

But this is only half of the story as the second line below
$role = $_SESSION['role'];
$role = 'Something else';

does not affect the SESSION['role'] and it's value would still be whatever it was. But if register_globals is on, changing $role would change $_SESSION['role'].


text:
Q: Download a file with no extension from a server I'm try to download a mp3 file from following URL. I found lot of articles and examples regarding file download. Those examples are based on URLs that end with a file extension, e.g.:- yourdomain.com/filename.mp3 but I want to download a file from following url which typically does not end with file extension.
youtubeinmp3.com/download/get/?i=1gsE32jF0aVaY0smDVf%2BmwnIZPrMDnGmchHBu0Hovd3Hl4NYqjNdym4RqjDSAis7p1n5O%2BeXmdwFxK9ugErLWQ%3D%3D
**Please note that I use the above url as-is without using Stackoverflow url formatting method to easily understand the question.
** I have tried the @Arsal Imam's solution as follows still not working
   btnShowProgress.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // starting new Async Task
            File cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"Folder Name");
            if(!cacheDir.exists())
                cacheDir.mkdirs();

            File f=new File(cacheDir,"ddedddddd.mp3");
            saveDir=f.getPath();

            new DownloadFileFromURL().execute(fileURL);
        }
    });

and the async task code is as follows
class DownloadFileFromURL extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(progress_bar_type);
    }

    @Override
    protected String doInBackground(String... f_url) {
        try{

            URL url = new URL(fileURL);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            int responseCode = httpConn.getResponseCode();

            // always check HTTP response code first
            if (responseCode == HttpURLConnection.HTTP_OK) {
                String fileName = "";
                String disposition = httpConn.getHeaderField("Content-Disposition");
                String contentType = httpConn.getContentType();
                int contentLength = httpConn.getContentLength();

                if (disposition != null) {
                    // extracts file name from header field
                    int index = disposition.indexOf("filename=");
                    if (index > 0) {
                        fileName = disposition.substring(index + 10,
                                disposition.length() - 1);
                    }
                } else {
                    // extracts file name from URL
                    fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
                            fileURL.length());
                }

                System.out.println("Content-Type = " + contentType);
                System.out.println("Content-Disposition = " + disposition);
                System.out.println("Content-Length = " + contentLength);
                System.out.println("fileName = " + fileName);

                // opens input stream from the HTTP connection
                InputStream inputStream = httpConn.getInputStream();
                String saveFilePath = saveDir + File.separator + fileName;

                // opens an output stream to save into file
                FileOutputStream outputStream = new FileOutputStream(saveDir);

                int bytesRead = -1;
                byte[] buffer = new byte[BUFFER_SIZE];
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.close();
                inputStream.close();

                System.out.println("File downloaded");
            } else {
                System.out.println("No file to download. Server replied HTTP code: " + responseCode);
            }
            httpConn.disconnect();

        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    protected void onProgressUpdate(String... progress) {
        pDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String file_url) {
        dismissDialog(progress_bar_type);

    }
}

A: Although Volley library is not recommended for large download or streaming operations, however, I'd like to share my following working sample code.
Let's assume we download only MP3 files so I hard-code the extension. And of course, we should check more carefully to avoid exceptions (NullPointer...) such as checking whether headers contain "Content-Disposition" key or not...
Hope this helps!
Volley Custom class:
public class BaseVolleyRequest extends Request<NetworkResponse> {

    private final Response.Listener<NetworkResponse> mListener;
    private final Response.ErrorListener mErrorListener;

    public BaseVolleyRequest(String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
        super(0, url, errorListener);
        this.mListener = listener;
        this.mErrorListener = errorListener;
    }

    @Override
    protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
        try {
            return Response.success(
                    response,
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        } catch (Exception e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(NetworkResponse response) {
        mListener.onResponse(response);
    }

    @Override
    protected VolleyError parseNetworkError(VolleyError volleyError) {
        return super.parseNetworkError(volleyError);
    }

    @Override
    public void deliverError(VolleyError error) {
        mErrorListener.onErrorResponse(error);
    }
}

Then in your Activity:
public class BinaryVolleyActivity extends AppCompatActivity {

    private final Context mContext = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_binary_volley);
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);
        String url = "http://www.youtubeinmp3.com/download/get/?i=3sI2yV5mJ0kQ8CnddqmANZqK8a%2BgVQJ%2Fmg3xwhHTUsJKuusOCZUzebuWW%2BJSFs0oz8VTs6ES3gjohKQMogixlQ%3D%3D";
        BaseVolleyRequest volleyRequest = new BaseVolleyRequest(url, new Response.Listener<NetworkResponse>() {
            @Override
            public void onResponse(NetworkResponse response) {
                Map<String, String> headers = response.headers;
                String contentDisposition = headers.get("Content-Disposition");
                // String contentType = headers.get("Content-Type");
                String[] temp = contentDisposition.split("filename=");
                String fileName = temp[1].replace("\"", "") + ".mp3";
                InputStream inputStream = new ByteArrayInputStream(response.data);
                createLocalFile(inputStream, fileName);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("Volley", error.toString());
            }
        });

        volleyRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 10, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        requestQueue.add(volleyRequest);
    }

    private String createLocalFile(InputStream inputStream, String fileName) {
        try {
            String folderName = "MP3VOLLEY";
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, folderName);
            folder.mkdir();
            File file = new File(folder, fileName);
            file.createNewFile();
            FileOutputStream f = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                f.write(buffer, 0, length);
            }
            //f.flush();
            f.close();
            return file.getPath();
        } catch (IOException e) {
            return e.getMessage();
        }
    }
}

Here the result screenshot:

NOTE:
As I commented below, because the direct download Url changes regularly, you should check the new url with some tools such as Postman for Chrome, if it responses binary instead of a web page (expired url), then the Url is valid and my code works for that Url.
Refer to the two following screenshots:
Expired url:

Un-expired url:

UPDATE BASIC LOGIC FOR GETTING DIRECT DOWNLOAD LINK FROM THAT SITE'S DOCUMENTATION:
According to Create Your Own YouTube To MP3 Downloader For Free
You can take a look at

JSON Example
You can also receive the data in JSON by setting the "format"
  parameter to "JSON".
  http://YouTubeInMP3.com/fetch/?format=JSON&video=http://www.youtube.com/watch?v=i62Zjga8JOM

Firstly, you create a JsonObjectRequest getting response from the above file link. Then, inside onResponse of this JsonObjectRequest you will get the direct download link, like this directUrl = response.getString("link"); and use BaseVolleyRequest volleyRequest
I have just told the logic for getting direct url, IMO, you should implement it yourself. Goodluck!

A: Use below code it works fine for encrypted URLs
public class HttpDownloadUtility {
    private static final int BUFFER_SIZE = 4096;

    /**
     * Downloads a file from a URL
     * @param fileURL HTTP URL of the file to be downloaded
     * @param saveDir path of the directory to save the file
     * @throws IOException
     */
    public static void downloadFile(String fileURL, String saveDir)
            throws IOException {
        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();

        // always check HTTP response code first
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            String disposition = httpConn.getHeaderField("Content-Disposition");
            String contentType = httpConn.getContentType();
            int contentLength = httpConn.getContentLength();

            if (disposition != null) {
                // extracts file name from header field
                int index = disposition.indexOf("filename=");
                if (index > 0) {
                    fileName = disposition.substring(index + 10,
                            disposition.length() - 1);
                }
            } else {
                // extracts file name from URL
                fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
                        fileURL.length());
            }

            System.out.println("Content-Type = " + contentType);
            System.out.println("Content-Disposition = " + disposition);
            System.out.println("Content-Length = " + contentLength);
            System.out.println("fileName = " + fileName);

            // opens input stream from the HTTP connection
            InputStream inputStream = httpConn.getInputStream();
            String saveFilePath = saveDir + File.separator + fileName;

            // opens an output stream to save into file
            FileOutputStream outputStream = new FileOutputStream(saveFilePath);

            int bytesRead = -1;
            byte[] buffer = new byte[BUFFER_SIZE];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.close();
            inputStream.close();

            System.out.println("File downloaded");
        } else {
            System.out.println("No file to download. Server replied HTTP code: " + responseCode);
        }
        httpConn.disconnect();
    }
}

A: The url returns a 302 redirect to the actual .mp3. The browser does the redirect in the background for you, but in your app you need to do it yourself. Here is an example on how to do that with HttpUrlConnection http://www.mkyong.com/java/java-httpurlconnection-follow-redirect-example/

A: If you know the type of file in advance then you can download your file from url which don't have extension.
DownloadService .java
public class DownloadService extends IntentService {
    public static final int UPDATE_PROGRESS = 8344;
    private Context context;
    private PowerManager.WakeLock mWakeLock;
    ProgressDialog mProgressDialog;
    String filename;
    File mypath;
    String urlToDownload;
    BroadcastReceiver broadcaster;
    Intent intent1;
    static final public String BROADCAST_ACTION = "com.example.app.activity.test.broadcast";
    public DownloadService() {
        super("DownloadService");
    }
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        intent1 = new Intent(BROADCAST_ACTION);
    }
    @Override
    protected void onHandleIntent(Intent intent) {

        ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
        try {
            intent1 = new Intent(BROADCAST_ACTION);
            urlToDownload = intent.getStringExtra("url");
            filename= intent.getStringExtra("filename");

            BufferedWriter out;
            try {
                File path=new File("/sdcard/","folder name");
                path.mkdir();
                mypath=new File(path,filename);
                Log.e("mypath",""+mypath);
                if (!mypath.exists()) {
                    out= new BufferedWriter(new FileWriter(mypath));
                    //ut = new OutputStreamWriter(context.openFileOutput( mypath.getAbsolutePath() ,Context.MODE_PRIVATE));
                    out.write("test");
                    out.close();

                }

            }catch(Exception e){
                e.printStackTrace();
            }
            URL url = new URL(urlToDownload);
            URLConnection connection = url.openConnection();
            connection.connect();
            // this will be useful so that you can show a typical 0-100% progress bar
            int fileLength = connection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(connection.getInputStream());
            OutputStream output = new FileOutputStream(mypath);

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                Bundle resultData = new Bundle();
                resultData.putInt("progress" ,(int) (total * 100 / fileLength));

                //Log.e("mypath",""+mypath);
                resultData.putString("mypath", ""+mypath);
                receiver.send(UPDATE_PROGRESS, resultData);

                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Bundle resultData = new Bundle();
        resultData.putInt("progress" ,100);
        resultData.putString("mypath", ""+mypath);
        receiver.send(UPDATE_PROGRESS, resultData);
        intent1.putExtra("progressbar", 100);
        sendBroadcast(intent1);
    }
}

DownloadReceiver.java
public class DownloadReceiver extends ResultReceiver{

    private Context context;
    private PowerManager.WakeLock mWakeLock;
    ProgressDialog mProgressDialog;
    String filename;

    String mypath;
    public DownloadReceiver(Handler handler ,String filename ,Context context) {
        super(handler);

    this.context = context;
        this.filename = filename;

        mProgressDialog = new ProgressDialog(context);
    }

    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        super.onReceiveResult(resultCode, resultData);
        if (resultCode == DownloadService.UPDATE_PROGRESS) {
            int progress = resultData.getInt("progress");
            mypath = resultData.getString("mypath");
            mProgressDialog.setProgress(progress);
            //Log.e("progress","progress");
            mProgressDialog.setMessage("App name");
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(true);
            if (progress == 100) {
                mProgressDialog.dismiss();

            Log.e("download","download");

            }
        }
    }
}

Now start service in your mainactivity by below code :
Intent miIntent = new Intent(mContext, DownloadService.class);
                            miIntent.putExtra("url", url);
                            miIntent.putExtra("filename", id+".mp3");

                            miIntent.putExtra("receiver", new DownloadReceiver(new Handler() , id,mContext));
                            startService(miIntent);