Bluetooth not working on Asus SonicMaster laptop with RT-3290 Ralink driver running Ubuntu 16.04

Question: I cannot seem to get the bluetooth hardware to work with Ubuntu. I can get a USB dongle working, but I'm sure the laptop has internal bluetooth hardware.
Update:
I have halfway succeeded in getting the bluetooth to work by doing step 12 in the list directly below. I actually did this on Lubuntu 16.04, but will test it with Ubuntu 16.04 as well. I successully paired a bluetooth mouse, and am able to use it. However, it is laggy, but not to the point of being unusable. I am also able to send and receive files to my LG G4 via bluetooth. I am, however, not able to pair to bluetooth speakers. I tried pairing to two speakers of different brands, and it appears to connect briefly for a second and then disconnects.
Update:
I have also just gotten the bluetooth speakers to work on Lubuntu 16.04 by doing step 13 directly below. I also was able to get it working on a freshly installed Ubuntu 16.04. I posted the steps to do it as an answer below.
What I have tried:
1) Okay, so I have the Blueman Bluetooth Manager/BlueZ installed.
2) I know the bluetooth programs are functional because I can plug in a bluetooth usb dongle and eveything works how it should with the dongle. I am able to connect bluetooth devices with the dongle.
3) I also know that the laptop itself has bluetooth hardware apart from the dongle I plugged in, because I can unplug the dongle and boot into Windows 10, and bluetooth functions on the Windows 10 OS.
4) I left bluetooth enabled on Windows as well.
5) There are no hard buttons (that I can find) on my laptop to enable or disable bluetooth.
6) In UEFI, bluetooth is enabled.
7) In UEFI, Secure Boot is disabled.
8) I have tried$ rfkill unblock bluetoothfrom this post to no avail.
9) I have also tried $ sudo hciconfig hci0 reset which sadly didn't work and gives the output
"Can't get device info: No such device"
10) I have also tried $ sudo chmod +x /usr/sbin/bluetoothd and sudo service bluetooth restart from this post.
11) I have tried reinstalling software as suggested in this post:
$ sudo apt-get install bluetooth blueman bluez-hcidump bluewho python-bluez  bluez-tools

12) I was able to get bluetooth partially working on Lubuntu 16.04 by following the steps from this post by Klip. I had to modify the steps slightly to get it working though, so I will post my modified steps.

mkdir ~/tmp
cd ~/tmp
git clone https://github.com/alinefr/rtbth.git
cd rtbth
make
sudo make install
sudo mkdir /usr/src/rtbth-3.9.3
sudo cp -r ~/tmp/rtbth/* /usr/src/rtbth-3.9.3
sudo dkms install rtbth/3.9.3
sudo nano /etc/modules
Add rtbth to the end of the file, press ctrl+o then enter to save the file, and then press ctrl+x to exit.
Reboot

13) I was able to successfully pair and output audio to my bluetooth speakers on Lubuntu 16.04 by following the steps from this post by user631559. Here they are below:

sudo apt-get install pulseaudio-module-bluetooth
pactl load-module module-bluetooth-discover

Other information:
-When I open the default bluetooth GUI in System Settings... I am able to toggle the on/off switch.
-Whether the bluetooth is toggled on or off, underneath it, in the box that displays the devices you would be connected to, it says, "Bluetooth is disabled".
-When I try to run Bluetooth Manager it gives this error message:
Connection to BlueZ failed
Bluez daemon is not running, blueman-manager cannot continue.
This probably means that there were no Bluetooth adapters detected or Bluetooth daemon was not started.

Without USB Dongle

With USB Dongle

Without USB Dongle on Windows 10

Output:
$ rfkill list gives the following output:
0: asus-wlan: Wireless LAN
    Soft blocked: no
    Hard blocked: no
1: asus-bluetooth: Bluetooth
    Soft blocked: no
    Hard blocked: no
2: phy0: Wireless LAN
    Soft blocked: no
    Hard blocked: no

$ dmesg | grep -i blue gives the following output:
[ 1147.342967] Bluetooth: Core ver 2.21
[ 1147.342987] Bluetooth: HCI device and connection manager initialized
[ 1147.342991] Bluetooth: HCI socket layer initialized
[ 1147.342993] Bluetooth: L2CAP socket layer initialized
[ 1147.342998] Bluetooth: SCO socket layer initialized

$ lspci gives the following output:
00:00.0 Host bridge: Intel Corporation Haswell-ULT DRAM Controller (rev 09)
00:02.0 VGA compatible controller: Intel Corporation Haswell-ULT Integrated Graphics Controller (rev 09)
00:03.0 Audio device: Intel Corporation Haswell-ULT HD Audio Controller (rev 09)
00:04.0 Signal processing controller: Intel Corporation Device 0a03 (rev 09)
00:14.0 USB controller: Intel Corporation 8 Series USB xHCI HC (rev 04)
00:16.0 Communication controller: Intel Corporation 8 Series HECI #0 (rev 04)
00:1b.0 Audio device: Intel Corporation 8 Series HD Audio Controller (rev 04)
00:1c.0 PCI bridge: Intel Corporation 8 Series PCI Express Root Port 1 (rev e4)
00:1c.2 PCI bridge: Intel Corporation 8 Series PCI Express Root Port 3 (rev e4)
00:1c.3 PCI bridge: Intel Corporation 8 Series PCI Express Root Port 4 (rev e4)
00:1d.0 USB controller: Intel Corporation 8 Series USB EHCI #1 (rev 04)
00:1f.0 ISA bridge: Intel Corporation 8 Series LPC Controller (rev 04)
00:1f.2 SATA controller: Intel Corporation 8 Series SATA Controller 1 [AHCI mode] (rev 04)
00:1f.3 SMBus: Intel Corporation 8 Series SMBus Controller (rev 04)
00:1f.6 Signal processing controller: Intel Corporation 8 Series Thermal (rev 04)
02:00.0 Unassigned class [ff00]: Realtek Semiconductor Co., Ltd. Device 5287 (rev 01)
02:00.1 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 12)
03:00.0 Network controller: Ralink corp. RT3290 Wireless 802.11n 1T/1R PCIe
03:00.1 Bluetooth: Ralink corp. RT3290 Bluetooth

$ lsusb gives the following output:
Bus 001 Device 003: ID 0461:4d15 Primax Electronics, Ltd Dell Optical Mouse
Bus 001 Device 002: ID 8087:8000 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

$ lsmod | grep blue gives the following output:
bluetooth             520192  0
$ uname -a; dmesg | egrep 'blue|firm' gives the following output:
Linux AsusUbuntu 4.4.0-28-generic #47-Ubuntu SMP Fri Jun 24 10:09:13 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
[    2.141769] psmouse serio4: elantech: assuming hardware version 4 (with firmware version 0x361f03)
[   28.577829] ieee80211 phy0: rt2x00lib_request_firmware: Info - Loading firmware file 'rt3290.bin'
[   28.662579] ieee80211 phy0: rt2x00lib_request_firmware: Info - Firmware detected - version: 0.37

Comment: Try to disable the Secure Boot from the BIOS setting of your laptop.  if it's enabled then any unsigned drivers can't be loaded.
Comment: Secure Boot was already disabled in UEFI. Thank you for the suggestion though!
Comment: Reported bug: https://bugs.launchpad.net/bluetooth/+bug/1189721 .  One solution is in http://askubuntu.com/questions/453605/ralink-rt-3290-bluetooth-problem-on-ubuntu-14-04 ...but it involves editing source code and compiling.
Answer: To get bluetooth to work on Ubuntu 16.04 with a Ralink-3290 driver do the following.

sudo apt-get update
sudo apt-get install git
sudo apt-get install dkms
mkdir ~/tmp
cd ~/tmp
git clone https://github.com/alinefr/rtbth.git
cd rtbth
make
sudo make install
sudo mkdir /usr/src/rtbth-3.9.3
sudo cp -r ~/tmp/rtbth/* /usr/src/rtbth-3.9.3
sudo dkms install rtbth/3.9.3
sudo nano /etc/modules
Add rtbth to the end of the file, press ctrl+o then enter to save the file, and then press ctrl+x to exit.
Reboot

It should be working now! If not try running sudo dkms install rtbth/3.9.3 another time and rebooting again.
To get it working in Lubuntu 16.04 I had to install pavucontrol to get audio working at all, and then I had to install pulseaudio-module-bluetooth to get the bluetooth speakers working.

sudo apt-get install pavucontrol
sudo apt-get install pulseaudio-module-bluetooth
pactl load-module module-bluetooth-discover


Where is the Controller edit hold time setting?

Question: Recently, I have heard a lot about the edit speed (The setting) of some Fortnite's best players.

Controller Edit Hold Time - 0.12
Best xbox one Fortnite controller settings from gronky - keengamer

I have looked where all of the sensitivity options are, and so have some of my friends, and they cannot find it. Does anyone know where it is?
Answer: It is right under the Builder Pro Build Instantly Setting

If you scroll down all the way in the first section on the settings page, right above feedback, it should be there.


Error: Unable to find module 'opennebula' (Meteor.JS)

Question: I already tried meteorhacks:npm with the same errors.
In a Meteor.JS application, with iron:router installed; I am unable to load the NPM module "opennebula" (available from https://github.com/OpenNebula/addon-nodejs) into my project (on the server side); I receive the stack trace as follows:
I20150222-03:56:59.927(-5)? Exception while invoking method 'onLoad' Error: Cannot find module '/usr/local/lib/node_modules/opennebula'
I20150222-03:56:59.928(-5)?     at Function.Module._resolveFilename (module.js:338:15)
I20150222-03:56:59.928(-5)?     at Function.Module._load (module.js:280:25)
I20150222-03:56:59.928(-5)?     at Module.require (module.js:364:17)
I20150222-03:56:59.928(-5)?     at require (module.js:380:17)
I20150222-03:56:59.928(-5)?     at Object.Npm.require (/root/app/.meteor/local/build/programs/server/boot.js:129:18)
I20150222-03:56:59.929(-5)?     at [object Object].Meteor.methods.onLoad (app/server/__main__.js:6:28)
I20150222-03:56:59.929(-5)?     at maybeAuditArgumentChecks (packages/ddp/livedata_server.js:1599:1)
I20150222-03:56:59.929(-5)?     at packages/ddp/livedata_server.js:648:1
I20150222-03:56:59.929(-5)?     at [object Object]._.extend.withValue (packages/meteor/dynamics_nodejs.js:56:1)
I20150222-03:56:59.929(-5)?     at packages/ddp/livedata_server.js:647:1

The module path specified does in fact contain a module installed from NPM:
fox2 ~ # ls /usr/local/lib/node_modules/opennebula
./  ../  lib/  node_modules/  .npmignore  package.json  README.md  test/

As such, my server/__main__.js file contains the following code:
if (Meteor.isServer){
  Meteor.methods({
    'onLoad': function(){
      var OpenNebula = Npm.require('/usr/local/lib/node_modules/opennebula'); // <== THIS LINE
      var one = new OpenNebula("user:pass", "http://127.0.0.1:2633/RPC2");

      one.version(function(err, data) {
        console.log(data);
      });

      return "Survey says...";
    }
  })
}

The client code that calls this function is as follows:
if (Meteor.isClient) {
  callback = function(a){
    console.log('callback: ' + a);
  };
  Meteor.call('onLoad', callback);
}

The packages and version of the meteor app are as follows:
fox2 app # meteor update
This project is already at Meteor 220.127.116.11, the latest release.
Your packages are at their latest compatible versions.

fox2 app # meteor list
autopublish      1.0.2  Publish the entire database to all clients
insecure         1.0.2  Allow all database writes by default
iron:router      1.0.7  Routing specifically designed for Meteor
jquery           1.11.3  Manipulate the DOM using CSS selectors
meteor-platform  1.2.1  Include a standard set of Meteor packages in your app

What am I doing wrong?

I have found out this module doesn't even work in Node.JS:
fox2 Standalone # node -v
v0.12.0

fox2 Standalone # node __main__.js
module.js:338
    throw err;
          ^
Error: Cannot find module 'opennebula'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/root/Standalone/__main__.js:1:80)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)

Answer: It turned out that the answer was:

OpenNebula made a bad NPM (Node package).

I put in a pull request (PR#3) to have this fixed.


Skype on Ubuntu 18.04 issues - doesn't start and logs me out

Question: The Skype app on Ubuntu 18.04 doesn't start when using the Community Theme snap Wayland (communitheme) theme. It automatically takes me to the lock screen

Also, clicking on Skype's file sharing icon freezes the app; after a while it shuts down spontaneously. Drag and drop a file for sharing works.
Answer: You probably aren't using the latest version of Skype. Try installing the Skype snap package with:
sudo snap install skype --classic

If that doesn't work try installing the latest version of Skype from the insider channel.
sudo snap install skype --classic --channel insider/stable

Comment: That doesn't work for me
Comment: The 2nd command with --channel insider/stable works for me now. Thank you!
Comment: First one worked for me.
Answer: This is a known issue with XWayland on Ubuntu 18.04.
It will be fixed with a future HWE update (packages linux-generic-hwe-18.04, xserver-xorg-hwe-18.04, xwayland-hwe-18.04). But it remains unclear when this will actually happen.
Answer: For me worked removing skype and installing it from official skype repository:

Add Skype Linux client repository
 echo "deb [arch=amd64] https://repo.skype.com/deb stable main" | sudo tee /etc/apt/sources.list.d/skype-stable.list

Install Skype public key
 wget https://repo.skype.com/data/SKYPE-GPG-KEY
 sudo apt-key add SKYPE-GPG-KEY

Install the apt-transport-https package, if don't have one
 sudo apt install apt-transport-https

Install skype itself
 sudo apt install skypeforlinux


Return Map Row NULL

Question: I'm trying to map a json response from mysql query, but i receive ho response: data: NULL
This is my code:
const audience = rows.map((row) => {
    db.query(CountAudiences, [row.campaign], function(err, count, fields) {
        if (err) throw err;
        console.log('Query result: ', count[0].audience);
        return {
            id: row.id,
            title: row.title,
            campaign: row.campaign,
            action: row.action,
            date: row.date,
            audiences: count[0].audience
        }
    });
});
res.json({
    count: rows.length,
    data: audience
})

Response:
{
   "count":1,
   "data":[
      null
   ]
}

Do you know how solve this?
Thanks :)
Answer: In your code as you are placing a query, so it is a Async hit. Try this
 function getResponse(){
    let rows = [{ id: 1, title: 5 }, { id: 2, title: "ggg" }]
    const audience = rows.map(async (row) => {
      return new Promise((resolve,reject)=> {
       db.query(CountAudiences, [row.campaign], function (err, count, fields) {
        if (err) throw err;
        console.log('Query result: ', count[0].audience);
        resolve( {
            id: row.id,
            title: row.title,
            campaign: row.campaign,
            action: row.action,
            date: row.date,
            audiences: count[0].audience
          })
         })
        })
     });

     return Promise.all(audience)
   }

  getResponse().then((reponseData)=>{
    res.json({
    count: rows.length,
    data: reponseData
  })

Return Map Row NULL


Create Temp folder , Copy Files , Process them and delete them when process is done

Question: I have a project where i need to create temp folder ,copy files from a c:/folder with name abc , process them ( which is done using a internal dll) and after the process is done , delete that temp folder and files in that folder.
Can anyone check the template C# template below and see if i am right track.
<code>  public void TemporaryDirectory()
{
  string tempFolder = Path.GetTempFileName();
  File.Delete(tempFolder);
  Directory.CreateDirectory(tempFolder);
string foldername = "c:\folder"
foreach(files in foldername)
{
  File.Copy(files,tempFolder);
}
 //Process Stuff

//once processing done
If(Process = done)
{
File.delete(tempFolder);
}
}
</code>
Comment: This is not code writing service. Show what you have done and where you need assistance.
Comment: @JohanP added template that i think can work. please check and see if i am on right track.
Answer: Seems like a class assignment, but I'll lead you in the right direction.
You'll be using System.IO for all of your files and directories. This example is a detailed guide for the same problem.
Comment: Thank you Chandler. This is very useful information.


Python select from SQL getting error

Question: I am writing the following query:
x1 = 5
y1 = 6
z1 = 0
SQL = ("SELECT Z FROM Points WHERE X =x1 AND Y = y1")
    for row in cursor.execute(SQL):
        z1 = row.Zcor

I am getting the following error:

Traceback (most recent call last):
        File "../ppp.py", line 38, in
          for row in cursor.execute(SQLp1z):
      pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][\xc4\xf0\xe0\xe9\xe2\xe5\xf0 ODBC Microsoft Access] \xcd\xe5\xee\xef\xf0\xe5\xe4\xe5\xeb\xe5\xed\xed\xe0\xff \xf4\xf3\xed\xea\xf6\xe8\xff 'convert' \xe2 \xe2\xfb\xf0\xe0\xe6\xe5\xed\xe8\xe8. (-3102) (SQLExecDirectW)")

What's the error in my code and what do I need to do in order to prevent this from happening ?
Comment: is your spacing off for the for loop or is that just how you copied it here?
Comment: take a look at this, it looks like you're not including variables in your query string properly.   http://stackoverflow.com/questions/902408/how-to-use-variables-in-sql-statement-in-python
Answer: Your problem is that you are not including variables in your string correctly. Use string formatting:
SQL = ("SELECT Z FROM Points WHERE X ={x1} AND Y ={y1}".format(x1=x1, y1=y1)

Or in python 3.6:
SQL = (f"SELECT Z FROM Points WHERE X ={x1} AND Y ={y1}")

Python select from SQL getting error


Unable to get POST data from Spring RestController

Question: I have having trouble with getting Spring to get the POST data. The Controller should be getting the string and then echoing. However, I am getting

response: echo: null

at the main() method
What should I do to fix it?
RestController
@RestController
@RequestMapping("/")
public class HelloWorldController {

    @RequestMapping(method = RequestMethod.GET)
    public String get() {
        return "test get method";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String post(String string) {
        return "echo: " + string;
    }
}

Test POST function
public static void main(String[] args) {
    String urlString = "http://localhost/Test/";
    try{
        Gson gson = new Gson();
        Testz test = new Testz();
        test.setZ("zzzzzzzzzzzzzzzzz");
        test.setCrap("rawrrr!!");
        String urlParameters = gson.toJson(test);
        byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);
        try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
            wr.write(postData);
        } catch (Exception e) {
            e.printStackTrace();
        }

        InputStream inputStream = conn.getInputStream();
        byte[] available = new byte[inputStream.available()];
        inputStream.read(available);

        System.out.println("response: " + new String(available));
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

class Testz {
    private String z = null;
            public void setZ(String z){this.z = z;}
            public String getZ(){return z;}
    private String crap = null;
            public void setCrap(String crap){this.crap = crap;}
            public String getCrap(){return crap;}
}

Answer: Try adding the @RequestBody annotation:
public String post(@RequestBody String string) {

It should work like a charm.


Modelling CEC and Sandia modules in PVlib

Question: I am using PVlib to model a range of PV facilities and I am using PVlib v0.9.0.
I've been thinking about the availability of modules from the Sandia and CEC databases. I am able to model both modules from both (for CEC by setting pre-setting some of the models in the ModelChain, as described for example here How to predict energy output using CECMods).
The results vary quite a lot, and I assume that isn't just because I set the aoi_model to 'no loss'.
I am torn between using the different databases, since there are of course many more models in the CEC database, but the analysis is not as accurate/in-depth. You can get around the issue by simply taking a model from Sandia with similar peak power and model that, but this of course isn't ideal either (especially with Sandia panels being quite old at this time). What does the Sandia modelling take into consideration that the CEC doesn't?
Is there a clear preference to using CEC or Sandia for the modules? Is there any way of recreating an estimate of the Sandia data for new panels without the hardware tests?
Furthermore, is there any more data for modules available except CEC and Sandia? These are getting quite old now and any tips for more recent databases would be very appreciated!
Answer:
What does the Sandia modelling take into consideration that the CEC doesn't?

The CEC PV module table contains parameters for calculating PV IV curves based on effective irradiance and cell temperature.  The Sandia module table has parameters to calculate (the general shape of) IV curves from effective irradiance and cell temperature, plus parameters for modeling the module's IAM profile (the increase in reflection loss at large angle of incidence) and parameters for modeling a spectral correction factor based on airmass.  This website from the PVPMC is a good reference for these models: https://pvpmc.sandia.gov/modeling-steps/2-dc-module-iv/point-value-models/sandia-pv-array-performance-model/
Sandia's IAM model is one of several IAM models available in pvlib.  Try setting aoi_model='physical' or aoi_model='ashrae' for example.  These models don't require module-specific parameters and so can be used easily with CEC modules.

Is there a clear preference to using CEC or Sandia for the modules?
Furthermore, is there any more data for modules available except CEC and Sandia?

My impression is that CEC is increasingly preferred due to the source being kept up to date as manufacturers release new modules.  However, it is true that the copy of that table included in pvlib is getting a bit stale.  If you need a newer module not included in pvlib's table, you can use the latest table from SAM like this (source):
SAM_URL = 'https://github.com/NREL/SAM/raw/develop/deploy/libraries/CEC%20Modules.csv'
df = pvlib.pvsystem.retrieve_sam(path=SAM_URL)

P.S. I suggest posting any remaining questions to the pvlib google group (stackoverflow is more for code questions).
Comment: That's great, thank you so much!

I will have a look at the google group, thanks for pointing that out.


How to export printable text only(or any other packet property) in wireshark

Question: Long story short - I'm capturing SQLs from vendor tool to Oracle database by using Wireshark.  It already has decoder for TNS protocol (which is great) and I can access text of SQL by
Right Click->Copy->Bytes(Printable Text Only).

The problem is that there are tons of packets and doing right-click on each of them could take ages. I was wondering if there any way to export 'Printable Text Only' right from Wireshark. Ideally I want to have a text file with  statements.
Any help will be highly appreciated.
Answer: Finally found away to do this. First, use tshark capturing tns packets:
tshark -R tcp.port==1521 -T fields -e data.data -d tcp.port==1521,tns > input.txt

Then you could use home brew Ruby script below to transform from bytes to text:
file = ARGV[0]
print_all = ARGV[1]

File.open(file, "r").each {|line|
  line.gsub(",", ":").split(':').each {|byte|
    chr = Integer('0x' + byte).chr
    print chr if ((' '..'~').include?(chr) or chr == "\n") or (print_all.downcase == 'all' if print_all)
  } if !line.chomp.empty?
}

Examples are:
encode.rb input.txt > output.txt

will export printable text only from input to output
encode.rb input.txt  all > output.txt

will export all text from input to output
Comment: If you change `File.open(file, "r")` to STDIN you can can redirect stream: `tshark -R tcp.port==1521 -T fields -e data.data -d tcp.port==1521,tns | encode.rb`
Answer: An easy way of looking at them all that has worked for me is just Right Click -> Follow TCP Stream.
A note: unprintable characters are displayed as .s. If there are a bunch of these interspersed between all the text you want to extract (as there was for me), switch it to ASCII, save it and open it in your favourite text editor (vim for me), then run a search and replace similar to /\.//g.
Answer: I don't know how to do it with TNS.  but you can do something like this using tshark, for example to look at http requests.
tshark -T fields -e http.request.uri
So if you can look at the options in the TNS decoder, you should be able to grab that field and redirect the output to a file.
Comment: Thanks. I figured out field name. However in tshark output it shows as byte stream, not as string. How could I convert it to string? I checked tshark manual but it's not obvious for me.
Comment: hmm, with http you get the text output.  You can try -T text but that is only going to print summaries. I not sure exactly....
Comment: Thanks anyway. Encoding from bytestream to string is different problem and 'tshark -T fields' is exactly what I was after in the first place/


What's the proper cable to connect this power station to a solar panel?

Question: My uncle gave me his old 1000w portable power station. I already have a Bluetti SP120 portable solar panel that has mc4 connectors. I'd like to use this to the power station. I tried googling it to no avail. I also tried google lens and it didn't yield any meaningful result.
Here's a photo of the port that the power station has that'll accept solar:

here's the spec sheet if it helps:

another picture for reference:
Comment: Looks like an old mil-spec connector - is the outside threaded to screw the connector down? If the company still exists they may have cords to connect.
Comment: Go to, say, Mouser (or your regional equivalent) and search on '2 pin mil spec plug'…
Comment: Conceivable, but I don't see the notch for polarity. Plenty of drawings on line with dimensions. What I see rates them at only 7 amps which might be a little low depending on the panel.
Comment: I also tried asking, do you think it's gx16 aviation socket?
Answer: guys i've finally found it locally.. thank you for those who helped! it cost about $2.50


How to run Windows apps in Ubuntu Server 14.04 wihout GUI

Question: I have a Windows program (an .exe) in Ubuntu Server 14.04. I can run it with VNC - tightvncserver :1 . After that I connect with the Viewer, the gui is the LXDE and there is the wine icon of the program program_name.deskop, I click it and run like charm.
How to run this program without VNC and LXDE, from the shell (cli mode)? I don't have too much experience in the linux and X11 virtual displays..
Thank you, guys!:)
Answer: Well, you can search for "program_name.desktop", it's a text file and contains the actual command being run.
But it's probably something like wine foo.exe (see wine docs)
VNC might not be necessary. Get acquainted with SSH. Then you can just get a shell to your server and run the command.


Why is selinux blocking root from enabling iptables?

Question: As root, on CentOS 7
systemctl enable iptables

prints
Failed to execute operation: Access denied

Here is a screenshot of what gets put in audit.log

I take this to mean selinux is blocking me, even though I am root. Does this audit log explain why? If not, where else should I look?
Answer: Although iptables was installed, I also needed to install iptables-services and policycoreutils-python.


Proving that if $| G : N |<\infty$ then $|H: H\cap N| <\infty$, where $N$ is normal to $G$ and $H$ is subgroup of $G$

Question: Prove that if $|G : N |<\infty$ then $|H: H\cap N| <\infty$, where $N$ is normal to $G$ and $H$ is subgroup of $G$
So far I have proven that  $H\cap N$ is a subgroup of $H, HN=\{ hn, h\in H,n\in N\} \vartriangleleft H$ in order to use that $|HN|=|H||N|/|H\cap N$|$  and I really don't know how to move on from here.
Some thoughts of mine are of using Lagrange's theorem in its general form:
If $G$ group with $K<H<G$ then $| G : K| = | G : H || H : K|$.
Comment: What do you mean by, say, $(G:N)$? Do you mean a semidirect product?
Comment: I guess they mean the quotient group, but let's wait for their reply, @Shaun.
Comment: You could also show the correspondence $$h(H\cap N) \mapsto hN$$ is a well defined injection. Once you're able to do this the finite cardinality of $H/H\cap N$ is immediate.
Comment: i am sorry for the missunderstanding but it wouldnt let me put tex symbols on the title for some reason . I meant that the inidcator of N to G is finite
Comment: i am not sure whether it is called indicator or not since i am not studying maths in english
Comment: Ok, but then you should amend the title (beyond latex issues whatsoever). It is named "the index of (say) $N$ in $G$", and it is the number of the cosets of $N$ (in $G$).
Comment: oh thanks let me change it real quick
Comment: great ! thank you for your response
Answer: $\hspace{3cm}$
Since $[G : N]$ is finite, we have $[G: N]=[G:HN]\cdot[HN  : N]$. In particular $[G:HN]$, and $[HN  : N]$ are finite.
Now, $N$ is normal in $G$, thus we have $N$ is normal in $HN$, $H\cap{N}$ is normal in $H$, and $\frac{HN}{N}\cong\frac{H}{H\cap{N}}$ from second isomorphism theorem. Then $[HN:N]=[H:H\cap N]$, and finally
$$[G: N]=[G:HN]\cdot[HN  : N]=[G:HN]\cdot[H:H\cap N]<\infty$$
In particular, $[H:H\cap N]$ is finite.
Comment: thank you very much!!


Why isn't my server scoreboard team name tag colour working?

Question: I am now work on a semi-vanilla kit PVP server. Normally, when I set a team colour to blue, it should show blue colour name tag in the TAB (Player list) and above the player. Sadly, I don't know why the name tag colour only works in TAB and the death message. It doesn't work on player name above or in the chat. Please help me fix it.
NOTE: my server is 1.11.2 bukkit version
Comment: If you want us to help you fix the issue, you'll need to show us what to fix.
Answer: You need to disable plugins that alter chat messages / names.
If you have any bukkit plugin for chat tags, colours etc, vanilla way won't work. You need to get rid of such a plugin, or disable parts that interfere with those features. Or properly setup colors via group managers and use those plugins to colorize the names.
For example essentials-chat or chatex, or any other that adds prefixes etc.
Plugins do override vanilla way of showing names.
Comment: I believe that even without plugins it will not work.
Answer: Like this answer says, the chat plugins do interfere. One way to fix this is to get a nickname and take out ~ from it and make sure it says their name.


Git diff gone mad?

Question: I'm trying to figure out what's going on with my local Git repo.

I edit a file.
Git reports everything has changed in the file (I only changed one line)
At first I think "must be a newline problem", but it's not. I do a diff in TortoiseGit, everything looks fine. I do a diff with Netbeans (git plugin), everything seems fine.
I do a reset, backup the file, modify it, git again reports everything has changed.
I do a binary compare in Total Commander, the files have no differences except for the single line I changed.
I do a hard reset again. Git tells me it was done successfully. Git status still says my file has changed. I diff the thing and there are no differences - bug git says there are.

I've tried using both git bash and gui, with same results (I'm on Windows). Any clues, what's going on here?
Comment: It happens only with this repository or all repositories? Though you think it's not a newline problem, check parameter `core.autocrlf` (`git config --get core.autocrlf`) anyway, it should be `false`.
Answer: Windows uses different line feed characters, when you edit the file in the Windows environment you use those settings, then when Git looks at it it doesn't recognize the line feed. You can try using vi to set the fileformat to unix which will convert all linefeed characters to the unix style: set ff=unix
Hope that helps
Answer: After I've committed the file in question, I've restarted the workstation and now everything seems in order (I've tried editing some other files in the same repo and diff was fine).
Have no idea what happened. I'm writing this one down as "Windows"...

Git diff gone mad?


Phonegap Bonjour/Zeroconf or Websocket IP Discovery from HTML5

Question: I am trying to implement a Phonegap (HTML5) application which connects to a Websocket server (running in an embedded device, also has Bonjour service) to exchange data within home network.
I would like to know the best possible way of detecting the server IP using Phonegap. I have explored and found that Titanium and Quickconnect support Bonjour. But I would like to stick to Phonegap for various other reasons.
Any alternative way of detecting the server IP within the local network is also okay.
Need your suggestion.
Comment: I have yet to find a PhoneGap iOS binding to Bonjour discovery protocols, but I did confirm that it is available on the platform.  There is a working sample in the Apple iOS developer library called BonjourWeb.  The challenge will be finding libraries to support Android and the other platforms.
Answer: There are two iOS Bonjour plugin implementations for Phonegap (Cordova) on Github:

https://github.com/jarnoh/cordova-dnssd
https://github.com/SayGoSolutions/Cordova-BonjourBrowserProxy

Unfortunately I haven't found a cross-platform implementation.
Comment: here is one for Android
https://github.com/pankajkainthla/phonegap-plugins-all/tree/master/Android/ZeroConf


Ubuntu 10.04 Gnome/X hang

Question: I have Ubuntu 10.04 running on a Dell laptop/Nvidia video. Everything works fantastic, except for one "nit" that is VERY annoying.. Every so often the graphical interface stops responding, such that the following happens: any gnome-terminals I happen to have open are still working normally, if I have Audacious running, the music continues to play, but all Gnome panels no longer respond, I cannot drag any open windows around, but I can right-click on the desktop and get that Gnome menu, but none of the menu selections respond. The first time this happened, I had to powercycle the laptop, as I didnt have any shell-window open.. It was then I discovered that Ubuntu now disables the ctl-alt-bksp/X restart. I've since re-enabled it, and an X restart restores the gui. This happens often at least once a day, and since I use the laptop daily, it becomes annoying to lose the apps I had running when I have to restart X. I've tried checking dmseg/syslog/messages immediately after this happens, but have not spotted any "smoking-gun" pointing to why this is happening. I first thought it might be Compiz causing it, so I disabled it, still happened. Since the laptop has Nvidia 8400M video, I use the Nvidia closed-source "blob" driver.. I'm posting here to see if 1) anybody else is seeing this, 2) where I should be looking for the cause....
Thanks
Comment: `~/.xsession-errors` is a place to look for culprits
Comment: Please format your question better, it's hard to read.
Comment: This question should instead be filed as a bug report, thanks! [Instructions here](http://askubuntu.com/questions/5121/how-do-i-report-a-bug).
Answer: When the freeze happens, can you get a terminal by hitting Alt+F2 and typing gnome-terminal? If so, try a tail ~/.xsession-errors before hitting Ctrl-Alt-Backspace or otherwise restarting the X session, as that file will show errors from the current session only IIRC. You might also try ~/xsession-errors.old for information about the previous session. See man xsession for more information.
Also, you can try running xlsclients while the machine is running ok and save that output to a file. Then when the session crashes, run xlsclients again and see if there is a difference in the two sets of output.
If an entry is missing from the second set of output for a client that still shows on your screen (or that you know you didn't otherwise actively shut down) then that suggests that the client has crashed and possible hung others which depend on it for input.
Comment: Thanks for the tips.. Will try those when it next happens.. Will post back what I find...
Comment: It happened again.. if I hit Alt+F2, I get the "run program" box, but I cannot type anything into the text field.. As for the xlsclient compare, other than several '' entries in the "after" run, both lists are the same.
Comment: I also see several of the following:              sys:1: GtkWarning: Attempting to read the recently used resources file at `/home/dave/.recently-used.xbel', but the parser failed: Error reading file '/home/dave/.recently-used.xbel': Is a directory.
sys:1: GtkWarning: Attempting to store changes into `/home/dave/.recently-used.xbel', but failed: Failed to rename file '/home/dave/.recently-used.xbel.ZRR2JV' to '/home/dave/.recently-used.xbel': g_rename() failed: Is a directory
Comment: I have the file ~.recently-used.xbel on my system as well. It is definitely a file and not a directory here, I just used less to display it. XBEL is a bookmarks file format. I recommend you ls -l that file and check its permissions. If it lists as a directory, cd into it and see what's in there. It's only a file that tracks recently opened files, so it shouldn't hurt anything to just zap it. If in doubt, use mv to rename it to 'recently-used-backup-[date]' or some such. I have no idea how could become mangled in this way, I think you probably should file a bug.
Comment: By the way, where are you seeing the error messages? Are they in a file you are looking at, a console, or what?

Ubuntu 10.04 Gnome/X hang


Windows XP will not boot after installing Ubuntu

Question: I followed the installation directions for Ubuntu to windows XP. After install was complete the computer would not reboot. Andy suggestions?
Comment: Did you install it via Wubi or you made a clean install?
Comment: More information is needed. Release of Ubuntu, how you installed (as mentioned in another comment), also describe what happened when the *computer would not reboot*, add details of your computer specs (brand/model/graphics card/wifi etc). Please edit your questions with this information. Thanks
Comment: possible duplicated: [How can I repair grub? (How to get Ubuntu back after installing Windows?)](http://askubuntu.com/q/88384/62483)
Answer: Or you can simply open a terminal and give this command:
sudo update-grub
With this command, grub will find your Windows XP Partition.
Answer: Follow this:
sudo add-apt-repository ppa:danielrichter2007/grub-customizer
sudo apt-get update
sudo apt-get install grub-customizer

and add windows to the list, it will be shown at the next restart


C# JsonSerialize with no member names

Question: I have the following classes that I like to serialize to Json. I'm currently getting something like this
 var pgdata =   {"SeriesList":[{"label":"Fund","data":[{"Year":2000,"RateOfReturn":0.02},{"Year":2009,"RateOfReturn":0.03}]},{"label":"Benchmark","data":[{"Year":2000,"RateOfReturn":0.024},{"Year":2009,"RateOfReturn":0.032}]}]} ;

I like to get something like this
var pgdata =   {"SeriesList":[{"label":"Fund","data":[[2000,0.02],[2009,0.03]]},{"label":"Benchmark","data":[[2000,0.024],[2009,0.032]]}]} ;

C# Code:
public class JsonPerformGraphData
    {
        public List<Series> SeriesList = new List<Series>();

        public Series GetSeries(string name)
        {
            foreach (Series s in SeriesList)
            {
                if (s.label == name)
                    return s;
            }

            Series series = new Series(name);
            SeriesList.Add(series);
            return series;
        }

        public void Add(PerformanceGraphItem ppgi)
        {
            Series s = GetSeries(ppgi.PerformanceGraphSeries.Name);
            s.addItem(ppgi.Year, ppgi.RateOfReturn);
        }

        public class Series
        {
            public string label;
            public List<Data> data = new List<Data>();

            public Series(String name)
            {
                label = name;
            }

            public void addItem(short year, double rateOfReturn)
            {

                data.Add(new Data(year,rateOfReturn));

            }
        }

        public class Data
        {
            public short Year;
            public double RateOfReturn;

            public Data(short year, double rateOfReturn)
            {
                Year = year;
                RateOfReturn = rateOfReturn;
            }
        }

    }

Answer: Is there a particular reason you're not using json.NET?  It has already solved the serialization problem for C# developers and there's fairly few reasons not to use it.  The only problem I had with it related to its inflexibility with using interface objects in deserialization from JSON, but unless you are doing unit testing on this class that shouldn't be an issue (and it doesn't look like you are).
For your purposes, json.NET should give you the output you're looking for, with no muss or fuss on rolling a serializer all by yourself.
edit: Also, just to be clear, json.NET does support serializing without member names the way you're wanting.  Simply add a JsonProperty Attribute to each member.

C# JsonSerialize with no member names


How does one select some $i$ to prove $\exists i$ s.t. $s_i \leq A$ where $A$ is the average of real numbers $(s_1 + s_2 + . . . + s_n) / n$

Question: How does one select some $i$ to prove $\exists i$ s.t. $s_i \leq A$ where $A$ is the average of real numbers $(s_1 + s_2 + . . . + s_n) / n$
It seems like a trivial proof, but writing a proof for such an existence conventionally does not seem obvious to me.
Perhaps I am reading it wrong, but I am sure it says something like: For any real number $A$ which is the average of a set, $S$, of real numbers, there exists a number $s \in S$ s.t. $s$ is less than or equal to $A$.
Is there a special way to choose $i$ to prove this existence? It seems I cannot trivially select a set of numbers and show there is a value that satisfies $s_i \leq A$ since it is some arbitrary set. How would you select $i$ for this proof?
Comment: No, you don't know which $i$ it must be. You go about it as a proof by contradiction.
Comment: Take $s_i$ to be the smallest element in $S$ ($S$ is finite I suppose)
Answer: If not, then $s_i> A $ for all $i$. So
$$A=\frac{s_1+s_2+\cdots+s_n}{n}>\frac{\overbrace{A+A+\cdots+A}^{n\text{ times}}}{n}=A$$
So derive a contradiction.
Comment: So how might I write this then. To yield a contradiction, assume for all $i$, $i > A$. This implies the average of such a series is actually equal to, and not greater than, $A$. And this is the contradiction? Very much as you have written? Do I need to declare $i$ be a natural or something like that?
Comment: @Leonardo Assume $s_i >A$ for all $i$, then this assumption implies $A>A$ and it implies $A\neq A$.
Comment: Yes thank you, the more I stare at the answer the more obvious it seems, its like one of those hidden paintings or something.


R manipulation of dataset from .txt

Question: I'm importing a .txt in R with
my_data<-read.delim("data",as.is=1)

I got a data frame with 3000 list.
lines look like this
Hello world !
C ID equipement
A
3 5 6 45
123 567 762
876 7889 986
B
bye world

Here what i want to do with this imported file.
1/ Select only lines between the line who begin with "A" and the line who begin with "B". Those lines position can change if I download another .txt
2/ Select ID equipement from the list who begin with "C" and add the value to all the list between A and B, with the separator " "
To get list between A and B i did this:
id1 <- (which(my_data=="A")+1)
id2<- (which(my_data=="B")-1)
d<- my_data[id1:id2,1]
ll <- strsplit(d," ")

ll is a vector of list, and for example ll[1]= "3 5 6 45"
Now i want to add ID equipment to all those lists.
Any idea how to do this?
Also, if anyone has better idea for my lines selection between A and B I would be happy to see it!
thanks
Answer: For extracting the lines between A and B you can simply use startsWith, e.g.
# Your data
# This is the structure obtained using "readLines"
my_data <- c("Hello world !", "C ID equipement", "A ", "3 5 6 45", "123 567 762 ",
             "876 7889 986", "B  ", "bye world")

strsplit(my_data[(which(startsWith(my_data, "A")) + 1L):(which(startsWith(my_data, "B")) - 1L)], " ")
# [[1]]
# [1] "3"  "5"  "6"  "45"
#
# [[2]]
# [1] "123" "567" "762"
#
# [[3]]
# [1] "876"  "7889" "986"

And to retrieve the ID you can use regex, e.g.
pat <- "^C\\s+(.*?)\\s+.*"   # Expression starts with a "C", then space, then something, then space, then something
gsub(pat, "\\1", grep(pat, my_data, value = TRUE))
# [1] "ID"

Finally, for adding the ID, a very simple approach is to use lapply, e.g.
lapply(l, function(x, ID) as.numeric(x) + ID, ID = 1L)
# [[1]]
# [1]  4  6  7 46
#
# [[2]]
# [1] 124 568 763
#
# [[3]]
# [1]  877 7890  987

where l denotes the above list and ID is set to 1 for demonstration purposes (since in the example there is no actual ID).

R manipulation of dataset from .txt


Use Solr Schemaless feature without automatically adding unknown fields to managed-schema

Question: I have different datasources that uploads different documents to Solr Sink. Now if two datasources sends a same name field with different data types (say integer & double) then indexing of second field fails because data type of first  field is already added in managed-schema.
All I need is that both fields get indexed properly as they used to work in Solr 4.x versions .
Since field names come at runtime,please suggest a solution that would work for me. I suppose it needs a change in solrconfig.xml but couldnot find the required.
Answer: How was your Solr configured to work in 4.x? You can still do it exactly the same way in Solr 6.
On the other hand, schemaless feature will define the type mapping on the first time it sees the field. It has no way to know what will come in the future. That's also why all auto-definitions are multivalued.
However, if you want to deal with specific mapping of integer being too narrow, you can change the definition of the UpdateRequestProcessor chain that is actually doing the mapping. Just merge the mapping of integer/long/number into one final tdoubles type.


Is there a maximum height or width for an HTML document?

Question: I am thinking about converting a PDF document into a long scrolling HTML doc (my reason is that there is video in the document and we want to turn the video into streaming rather than require anyone viewing the presentation to download 200+mb before being able to view anything). I am wondering if there is a maximum pixel width or height to HTML documents, or if browsers start to have difficulty with the DOM at certain lengths. If I convert the whole presentation to HTML it would be about 41,000 px. Does that seem reasonable? Are there limits to the pixel height or width of documents? Or best practices considerations I should keep in mind?
Comment: Have you seen http://worlds-highest-website.com/ or http://worm.bluesfear.com/index.php?content=submissions&action=view? Modern Browsers seem to render pretty big pages...
Comment: You should be designing with your users in mind. Quick, scan friendly content.
Answer: On IE8 and lower CSS "filter" declarations fail on anything larger than 4096 pixels. This is not a restriction on document size but can sometimes cause unexpected results.
Answer: As far as I'm aware, browsers can render documents of literally any size. I had a world map page that was 40,000 x 20,000 pixels, and it ran perfectly fine, even with some fairly busy JavaScript.
Answer: It would be new to me that there is a limitation for maximum width or height of a webpage.
I have tried very big numbers and never got to a maximum.
Answer: I dont think there is any kind of limit, it will certanly be very slow to load 41.000px so my advice it´s not to do that...
I cant imagine someone scrolling down 41.000px, thats something almost crazy to do...
Find another way, split the video in small chapters.. chapter 1.. chapter 2..etc..


PHP session lost after 2nd redirect but not first

Question: I have a PHP project, which also has a Kohana PHP project in a subfolder on the site "/reports".
I redirect to the reports project like so:
redirectreports.php
<?php
session_start();
header('Location: /reports');
exit();

When a user clicks the href link, it opens the above in a new window. On the first click of the link, everything works fine and session data is available in the reports project.
The issue happens when I close the window of reports, and then click the reports link a 2nd time. My session data cannot be found the 2nd time I am redirected to reports.
I have tried passing the session id in the query string and then passing that to Session::instance('native', $_GET['id']);
But still get the following error:
Session_Exception [ 1 ]: Error reading session data.
Comment: Have a look to https://stackoverflow.com/questions/6679007/share-session-between-two-websites ... Looks like a similar issue
Comment: Error is thrown here: https://github.com/koseven/koseven/blob/master/system/classes/Kohana/Session.php#L324 Make dirty hack and check what is in original error, eg by: `throw $e`
Answer: Thanks for the comments.
The actual issue here was that there was an object being stored in the session data by the "reports" package. Result in a __PHP_Incomplete_Class error.
That class wasn't accessible to the core project and so the shared info is stored as an array rather than an object.


Honeywell Mercury Themostat 3 Wire, replace with Digital/Programmable?

Question: Have an old Honeywell thermostat (house is 17 years old). Wondering if I can replace it with a newer Digital or Programmable one?
Here are some pictures of it.
Comment: @Ecnerwal I don't see fear of mercury leakage anywhere in this question. I see OP stating what he has a wanting digital programmable instead.  Pretty reasonable.  OP should maybe go one step further even ... to smart or internet connected
Comment: But first, why? The vague fear that the nicely contained and protected mercury is going to leak out and poison you is far-fetched unless you adjust it with a hammer. The propaganda machine is in full swing, but there's very little substance there. Short of deliberate effort those capsules stay sealed. Unless you stick to simple programmables that uses batteries, you often need a wire upgrade between the thermostat and the Furnace or Boiler (and/or Air Conditioner)
Comment: They start to become inaccurate after awhile. Also it's kinda difficult to actually see what i've set the temp to. Im not worried about the mercury, nor does it even need to be programmable (even a digital one would be fine)
Comment: yes, you can replace it would just about anything. The third wire is for the fan; it can be skipped if needed, (guaranteed compat w/ any thermostat) but most newer models support them out of the box.
Comment: What type of equipment is the thermostat controlling (make and model)?
Comment: @Tester101 It's an old Bryant Furnance + Air Handler (The Heat is gas) CK5BXA030014AAAA is the model number
Comment: Thoroughly cleaning the bi-metallic spring, while gently manually moving the spring, with canned air restored my thermostat's operation.
Answer: What your options for replacement are (easily) depends on what your wiring is.
I find it odd that you claim it's getting inaccurate, but perhaps they built them better 50 years ago than 20 - all the 50-60 year old ones I have work as good as new, but those are the "classic round" version. They actually are subtly adjustable if needed, though non-subtle attempts can screw them up. They are sidelined at the moment, but in reserve in case of need.
Anyway, for a two wire setup the easy digital/programmable solution is to get a digital/programmable that uses batteries - I have a couple of examples of these in my view between home and work, and the older one eats batteries a lot slower than the newer one.
The fancy/expensive/prone to becoming obsolete so you need a new expensive - "Smart" thermostats (or hacking portals into your house) generally require a wire upgrade to supply the power they want. I'm obviously not a fan, but many people do seem to love them. Some of those people are not living in your house...
Comment: From the picture it looks like I have  3 wires? does that make things easier for me?
Comment: If it's heat/cool, no, if it's heat only, probably. I could not tell if you had 2 or 3 wires in the wall, even though I can see three colors in the thermostat.
Comment: it controls heat and cooling.


How to grant nginx permissions to phpMyAdmin on synology diskstation

Question: I have a Synology Diskstation DS216se running DSM 6.2.3-25426. I've installed MariaDB 10, Web Station, PHP 7.2, and myPhpAdmin, but when I open it at http://diskstation/phpMyAdmin/ I get this error message
"Sorry, the page you are looking for is not found."
I'm using an nginx server in Web Station, and the error log at /var/log/nginx/error.log contains multiple entries like the following
*621 open() "/var/services/web/phpMyAdmin/js/vendor/jquery/jquery.debounce-1.0.5.js" failed (13: Permission denied)

The file, and all other files with permission denied entries in the logs, exist in the /var/services/web/phpMyAdmin/ directory - what permissions need to be granted to the directory for this to succeed?
Answer: I hit this as well. I managed to recover, but it effectively amounts to hard clearing any evidence of prior installs of Web Station, PHP 7.2, phpMyAdmin, and any other web related services. Then manually ripping out some bad directories with broken symlinks/permissions.
My hypothesis is that I tried to install adminer prior to this and - having not done any set up for Web Station et. al. - it put the filesystem in a bad state.
I am not willing to try installing adminer again to test this hypothesis.
What I did to fix this:

Backup what you need (e.g., any personal web site).
SSH into your diskstation. Please be aware of what you are doing and keep in mind the big picture. Don't go deleting random things.
Uninstall Web Station, PHP 7.2, Apache, phpMyAdmin, etc. Anything that Web Station would ultimately be inclined to read and serve up.
Verify that /var/services/web doesn't contain anything you care about, and delete it (sudo rm -rf /var/services/web).
Verify that /volume1/web doesn't contain anything you care about, and delete everything inside it (sudo rm -rf /var/services/web). You may need to chmod permissions for this - I ended up leaving the web directory itself intact, but nothing inside.
Reboot. Mount any encrypted disks, etc.
Check that /var/services/web now shows it is symlinked to /volume1/web, e.g. sudo readlink -e /var/services/web.
Also check permissions for /volume1/web, e.g. ls -al /volume1. It should be owned by root:root and have permissive (777) bits.
Install Web Station, PHP 7.2, and phpMyAdmin in that order.

After this, I could open phpMyAdmin and be served its log in screen.

Debugging notes:
For me, when I SSH in I see in the logs similar issues:
2020/12/17 10:36:35 [error] 32658#32658: *1028 "/var/services/web/phpMyAdmin/index.php" is forbidden (13: Permission denied),

ps says that the nginx workers run as the http user (uid=1023(http) gid=1023(http) groups=1023(http)).
The directory /var/services/web/ appears to be owned by root, both group and user:
# ls -al /var/services/web/
total 424
drwxr-xr-x  3 root root   4096 Dec 17 10:29 .
drwxr-xr-x  3 root root   4096 Dec 17 10:22 ..
-rw-r--r--  1 root root  27959 Apr 13  2016 adminer.css
-rw-r--r--  1 root root     82 Apr 13  2016 .htaccess
-rw-r--r--  1 root root 387223 Apr 13  2016 index.php
drwxr-xr-x 10 root root   4096 Dec 17 10:29 phpMyAdmin

It's not clear to me how Web Station's nginx is intended to work at all given the mismatch - perhaps some set of actions I took prior caused it to decide to install with bad ownership.
I decided to leave everything owned by root, but changed group permissions so that http can access:
# chown -R root:http /var/services/web/
# chmod -R 775 /var/services/web/

This got past the initial error, but revealed a new one:
"/usr/syno/synoman/phpMyAdmin/index.cgi" is not found (2: No such file or directory)

Indeed, there was no trace of phpMyAdmin anywhere in that directory. Evidence of a bad install.
I decided to uninstall anything web related: phpMyAdmin, PHP 7, Apache (happened to be installed), nginx, and Web Station. Once I did, I still had two files in /var/services/web: adminer.css  index.php.
I had tried adminer prior to this. In /var/services, there were symlinks to specific volume locations, e.g.:
# ls -al /var/services/
total 12
drwxr-xr-x   3 root root 4096 Dec 17 10:22 .
drwxr-xr-x  17 root root 4096 Dec 17 10:21 ..
lrwxrwxrwx   1 root root   18 Jan 20  2020 download -> /volume1/@download
lrwxrwxrwx+  1 root root   14 Dec 17 10:22 homes -> /volume1/homes
lrwxrwxrwx   1 root root   24 Jan 20  2020 pgsql -> /volume1/@database/pgsql
lrwxrwxrwx   1 root root   13 Dec 17 10:22 tmp -> /volume1/@tmp
lrwxrwxrwx   1 root root   13 Dec 17 10:22 web

Interestingly, web was not symlinked. I fully deleted /var/services/web.
Looking over at /volume1, I do see a /volume1/web, again fully owned by root but with extremely constrained permission:
d---------+  1 root            root              52 Dec 17 10:14 web

There are only a few things in here, which look related to a blank install of Web Station. I fully deleted everything within /volume1/web, but left it as is. With everything maximally cleaned I rebooted.
Upon boot, /var/services/web was now symlinked to /volume1/web, which now also had useful permission bits (777), and owned by root:root. Maybe this was done by some boot recover process, who knows. (I still have nothing web related installed at this point.)
I installed Web Station, then PHP 7.2, then phpMyAdmin.
Answer: I had the same issue when accessing my server via
<name>.local/phpMyAdmin/

It worked when I accessed it via
<local ip>/phpMyAdmin/


No hot water, but exhaust blower running continuously

Question: This morning I went to take a shower and there was no hot water. I went to the basement to check on the water heater, and found the exhaust blower is running continuously but no hot water is being produced.
The exhaust blower has been running for over hours now, but still no hot water. Every minute or so the water heater makes a clicking noise.
I guess I will have to have a repair guy come in and take a look at it. But it there something obvious I should be looking into first?
Also, is it OK just to leave the blower running for hours and hours, or should I unplug the heater?
Answer: I'm guessing a high temperature switch has failed and needs to be replaced. I'd turn off the fuel source and power until it can be repaired to avoid wearing out the motor.
Comment: Close enough. It turned out to be the gas feed valve had failed, so no gas was being fed to the burner. The repair guy also had to replace the igniter coil, since it had burned itself out trying to ignite every minute for hours. So your advice to turn off the power would have been good, if I had done it sooner :-\
Comment: @DaveIsaacs Thanks for the follow up. We welcome self answers here, so if you want to post your findings as an answer, I'd be happy to upvote.


Replacing trim set in horse hair plaster

Question: There are a few places in my house where I would like to replace the door trim, but the walls are horse hair plaster.  Is there anyway to do this without having the plaster totally fall apart?
Answer: Yeah it is more brittle than sheetrock but still strong stuff.  Start with scoring the paint/caulk around the casing with a utility knife, then use a pry bar as normal, except use a board or plywood between your prybar and the wall.  That way you won't have the pry bar indent into the plaster as you pull the wood off.  Work your way around the door casing, prying it a little at a time.  Once you see where the nails are you can pry directly under that point, or hit the face of it with a hammer and sometimes that makes the nails pop out enough you can pry them out through the face.


What are some ways to appropriately hang things on a wall?

Question: I just moved into a new house and am at the point where I need to start hanging stuff on the walls.  Most of the stuff I want to hang is around the size of a picture frame, large mirror, or diploma frame.
What are some useful tools and tips to help make sure I hang these items appropriately?
This is my first house, so I really don't know what I am doing and would like to avoid putting unnecessary holes in the wall or having my pictures fall down while I'm asleep.
I am not opposed to using nails, but am open to other options as well.  Also, I am willing to invest in various gadgets, etc... that will help me do this job better.
Comment: invest in a good Stud finder and level.
Answer: Basically you need to look at two things:

What you are hanging (how heavy, will it sway, is it a vertical load or does it have a horizontal component)
What are you hanging it on (wallboard, plaster, old crappy plaster, stud wall, concrete wall, brick, stone, solid wood...)

Then you pick the right fastener at the intersection of these two.
Assuming you have a newer house, and are mostly hanging pictures, the old "nail into wallboard" will work okay. Just tilt it downward so the picture wire slides toward the wall, not toward the nailhead.
You can also use things like the 3M "command" strips, which work great if you follow the instructions and don't exceed the load. Don't be stingy with them.
Hanging heavier things like mirrors or glass picture frames, use the appropriate wall anchor for the wall, and/or nail or screw into the studs. With the right wall anchors, or rails or other structure attached to the studs, you can put an enormous load on the wall (tons) without problems.
If you have an old house like mine, don't even bother trying wall anchors into ancient crumbly plaster...find the studs. Hard-won lesson. ;)
Using a stud finder can be a bit of an art, so practice on a wall you don't care about. (Mark the edges of the stud, then drive a very fine nail into the wall board and see if you were right. Then, pull the nail and spackle the hole.) Also note that they read differently depending on what kind of wall it is.
Comment: I'm a huge fan of [these wall anchors](http://www.homedepot.com/webapp/wcs/stores/servlet/ProductDisplay?storeId=10051&productId=100391938&langId=-1&catalogId=10053&ci_sku=100391938&ci_src=14110944&cm_mmc=shopping-_-googlebase-_-D25X-_-100391938&locStoreNum=804) and I've used them for just about everything from bathroom fixtures to metal wall art.
Comment: This is great info, thanks.  I assume that the guys at Home Depot will be able to help me find the right wall anchor based on the type of house I have?  It's all just wood studs with sheetrock.
Comment: @Doresoom: Those may be good for drywall, but they are awful for plaster.  The plaster will eventually crumble around them, and they will fall out.
Comment: @Tester101 I could not agree more. :/ Ask about the 1" holes in my plaster some time. Really the only thing that seems to work in old plaster is nailing/screwing to the studs.
Comment: I've had luck using toggle bolts with plaster and lath walls, but hitting a stud is still the best way to go.
Comment: 3 things! 3rd being any hidden hazards behind the wall. Pipes, wires etc. having an idea of these are can come from looking at where your service outlets are.
Answer: This page shows a variety of options, tested for their strength and listed by the size of the hole you must make in the wall. I don't want to steal the full content of that page, nor leave you with only a link, so here's a summary of the results:
<code>Fastener Type                Price     Hole Size    Pound Limit
---------------------------------------------------------------
Toggle Bolt (1/4" bolt)     $ 0.75       3/4"           300+
Threaded Toggle             $ 1.50       3/8"           200+
Molly Bolt (1/8" bolt)      $ 0.50       1/4"           170
Threaded Anchor (brass)     $ 1.20       3/8"           130
Threaded Anchor (plastic)   $ 0.45       3/8"           110
Plastic Anchor (medium)     $ 0.20       1/4"            80
Picture Hanger (large)      $ 0.50       1/8"            80
Picture Hanger (medium)     $ 0.20      3/32"            70
Picture Hanger (small)      $ 0.15      1/16"            60
Picture Hanger (WallBiter™) $ 0.80      3/16"           100
Wire Hanger                 $ 0.75      1/16"            50
</code>
Comment: "that page' is gone now  and those numbers don't look right for drywall.
Comment: @Jasen Thanks for the notification. I've updated the link to use the Wayback Machine. I cannot speak to the accuracy of the data, but from the descriptions and pictures it looks like an attempt was made at empirical testing.
Answer: People will tell you:

There are no hard and fast rules to hanging pictures.

But I think it's wise to impose some order on the items that you hang on your walls.

Here is the best compilation of rules that I've found on the subject.
And here are some highlights:

Hang things where they are easiest to see and appreciate - Lower in a dining room or family room where people are usually seated and higher in a hallway where people usually stand.

If you're hanging at eye level, position the center of the picture about 5' 6" above the floor. This is the most common eye level position.
The most common mistake people make is hanging their pictures way too high.

Get Rid of Visual Clutter - Instead of displaying every piece of art you own, ask yourself if each piece still holds the magic it once did. Think minamalist (i.e. less is more.)
Odd Numbers Are Even Better - For greater visual interest, show only odd numbers of pictures on a wall or in a given room...one, three, five, etc.
Do not saturate your public spaces with pictures of people.

Stairways are a particularly good place for pictures of people.
Further commentary on Yahoo! Answers.


Same cell for different keys in Java SE 8 Hashmap

Question: HashMap<String,Integer> map = new HashMap<>();

Assume I use "put" function twice:
map.put("hello", 4);
map.put("world", 5);

I have been taught that there is a hash function behind the scenes which computes the right cell which the value is supposed to enter according to the given key.
My question is:
There is any chance that both computations will lead to the same cell, such that command #2 will result in the same cell given in #1, thus 4 value will be lost?
And if so, how do I make #2 re-map to an other cell if already occupied?
(I don't want to use hash with chaning..)
Comment: What you describe is called a "hash collision". And yes, they can happen easily and are somewhat normal, but `HashMap` takes care of them (in other words, it won't lose any values just because multiple keys happen to produce the same hash value). If it didn't it wouldn't be very useful.
Comment: So, just to make sure - you mean that if a case of "hash collision" happens in this Java implementation, value number 5 will enter an other cell and won't override the previous data. (Open addressing?)
Comment: Actually it's implemented a bit differently (each cell actually holds a linked list and/or tree, depending on some factors) with all key/value pairs that get mapped into this cell. But the outcome is similar: no other data will be overridden.
Answer: This does exactly that
map.put("hello", 4);
map.put("hello", 5);

However, I think you mean when a hash collision occurs, such that different keys are put in the map, which results in the same hash. This would use chaining.
Because they hash the same, in theory, you could .get(object) for everything before you insert it, and add alter the key if it collided.
But in practice let the map do its job and let the underlying implementation operate how it's designed.


Angular Service Worker validation file process

Question: Context
Angular PWA.
Before explaining the error, I have to specify :

We read the Angular service worker documentation
We read this post, specially the validated answer as it looks like our situation (but that didn't really answer our questions
).
All's working well during local test (ng build + http-server to serve the app).
We don't use Angular's "environment" files. Instead, we're using an "appsettings.json" which is overidding inside our CI to use the same artifact and prevents multiple build.

Globally, inside our CI : Build (ngsw.json is generated) -> overriding appsettings.json -> deploy. Yes, appsettings is overidded after building (so, after ngsw.json generation). But, before or after such a generation : appsettings.json content is the same: the generated hash has the right/same value between each deployment. Also, such a story's working locally without any issues (build -> change appsettings.json content -> serve).
Our ngsw-config.json looks like this :
{
  "$schema": "./node_modules/@angular/service-worker/config/schema.json",
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": [
          "/favicon.ico",
          "/index.html",
          "/appsettings.json", // The added line
          "/manifest.webmanifest",
          "/*.css",
          "/*.js"
        ]
      }
    },
    {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/assets/**",
          "/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)"
        ]
      }
    }
  ]
}

Problem
After each deployment (made by our CI), we faced with this error :
Failed to install app version '30ba317c7d27a544efb0c7eb47653aa0fa664fb9'
Error: Hash mismatch (cacheBustedFetchFromNetwork): https://....../appsettings.json: expected 92e837ce30053ba552fcf37c8b34b5d1b1f5f06e, got 9756c02e19847ca03c3cf2d677c65e0a4e9665ef (after cache busting)
    at PrefetchAssetGroup.cacheBustedFetchFromNetwork (https://....../ngsw-worker.js:474:21)
    at async PrefetchAssetGroup.fetchFromNetwork (https://....../ngsw-worker.js:449:19)
    at async PrefetchAssetGroup.fetchAndCacheOnce (https://....../ngsw-worker.js:428:21)

It seems service worker found a wrong hash for appsettings.
However, when the app's checking an update, the resulting ngsw.json file is correct (we compared with the latest deployed files in our server) : we didn't find the hash that the service worker got (9756c02e19847ca03c3cf2d677c65e0a4e9665ef). Once again : no hash issue locally, even after editing appsettings.
Questions
Of course, there is something we don't understand.
Inside the Angular documentation, the "hashed content" part's saying :

If a particular file fails validation, the Angular service worker attempts to re-fetch the content using a "cache-busting" URL parameter to prevent browser or intermediate caching.

What is behind this "validation" ? Is there a "rehash" operation somewhere (which would explain this unknown hash we got) ? We didn't find any explanation about this. If its the case, that doesn't explain why such a story's working locally.
As we understood (if we're not goats...), the only "hashing" process is during "ng build"... but maybe we're wrong.
Answer: Hashing happens in two occasions:
Hashing during ng-build
An algorithm will compute the hash of each file based on the file content. This happens during the build process.
Service Worker local hashing
Service Worker will first fetch ngsw.json file to see if a new version exists. If yes, it computes the hash of each file again locally and checks if it matches the hash present in ngsw.json file.
If at least one hash does not match the hash in ngsw.json file, it will throw hash-mismatch error, and the latest version of the app will not be activated.

As you already said, you are applying post-processing, so that is probably the reason for hash-mismatch error. However, the hash-mismatch issue can occur for several reasons:

Post-processing after production build: If any post-processing is done on a file after the production build has generated the ngsw.json file, it can result in a hash mismatch when the Service Worker computes it. To avoid this issue, be sure to avoid any post-processing after the production build is generated, such as changing API keys in the index.html file.

Middle layer of caching data: If a middle layer of caching data is present between the client and the server, such as Nginx, it can cause a hash mismatch with the Service Worker.

Deploying the application with Git: When deploying the application with Git using a post-receive git hook, line endings can be replaced by default, causing the files on the server to differ from the original ones, resulting in a hash mismatch.

Serving files through CDN: CDN can apply different optimizations on the files, such as minification or compression, which can change the hash value for these files and result in a hash mismatch for the Service Worker.

I wrote about all of this in my blog, so you can check the article for more details.
Comment: For the local hashing, I think I saw it in the GitHub inside of some thread.
Comment: Thank you for your answer and your article :) !

About the local hashing, I didn't find any explanation about it inside the Angular documentation (but maybe I'm wrong) and this is exactly what I was looking for… but why it's working locally ? I'm supposed to find the same issue but and this is not the case. About the last 3 points you said, we're not in any of those cases.
Comment: Yeah, it's not in the docs. I know this because I had the same issue before and I had to dive deeper into the internal logic. I still didn't quite understand why are you overriding the `appsettings.json` file. You said it will eventually have the same content as before the build, so why do you override it?
Comment: As we use the same application build in our CI (which we use it to move from an env into another), we've just to override some values inside our appsettings (our API's url by example).
That prevents multiple ng build (one for each env).
When we start the ng build, appsettings contains default values. So, when the ngsw.json will be generated, it will always "hash" the default appsettings content. Later in our CI, we'll replace values according to the targetted env.
Comment: Oh, that is the issue because the local hash will be different for that file. You should not apply any post-processing. I would say the best option for you is to create different `env` files, one for each environment, and then to create different build scripts for each environment. So, you would have `ng-build-prod`, `ng-build-stage`...
Answer: I also faced the same error for every new build. I managed to fix the error by replacing  "installMode": "prefetch" to  "installMode": "lazy" in my ngsw.json file for app group


Can't connect to a server via SSH (with my PC only)

Question: For some days I'm experiencing issues with SSH on my machine (I guess after having installed some software that I don't remember).
It's very problematic as I use Git to work on some code projects with other people, pushing my work on a repository via SSH.
I'm 100 % sure the problem is coming from my computer (Linux Mint 16 cinnamon), because:
From the same Internet connection (same router, same IP), I can connect without any problem to the same server with another computer. Therefore, it's not a firewall problem coming from the router.
The admin of the server doesn't see any issues that could create this concern, and everybody else has access as they should.
This is the error message Git tells me:
ssh: connect to host ******* port 22: Connection refused
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I  was told that could be a problem with my iptables, and have tried to sudo iptables -X (and -F), with no luck. I have no idea how to manage this further.
To be honest with you I already posted this issue on the unix & linux stack exchange but with no luck. Here is My post on Unix & Linux stack exchange
I saw a similar post on askubuntu but I coudln't follow the advices as I'm on mint and it seems even If it's based on debian, there are differences to deal with it. Other similar post on askUbuntu
Also I've looked after a solution to restore those ip-tables, to be sure it the problem is there but I've found no way to achieve this.
Comment: Are you sure you have the correct SSH key? Or that you didn't misspell the repository?
Comment: Yes, I'm sure, because I used to use this repository without any problem till the day I installed those apps It seems. Moreover, git remote -v gives me the right repository. I aswell setted up a repo on github, I can connect & push using https but not with SSH. I added as well my key on github, and my key was as well checked by the admin of the server. So on this point everything is ok. It's probably related to the iptables, but I have no idea on the way I should fix this issue.
Answer: I've finally found a way to fix the issue I had.I found this article about iptables It helped me a lot to fix the issue.
The only thing I did is run the command
sudo iptables -F

Doing that has allowed me to push again on remote repositories and thus using ssh. But I had to save that.
For this I run this other command to make all the changements due to the previous command persistent
sudo apt-get update
sudo apt-get install iptables-persistent

I found that thanks the article linked previously. I rebooted in the meantime and everything is working correctly.


how to get amount of scroll for a scrollview

Question: How do I get the amount of pixels which a user has scrolled in a scroll view. I have a scroll view which contains lot of texts. I also have a button at bottom of the screen. What I want is to change text on the button to the amount of scrolling done in the scroll view.
this is my scroll view:
 <ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/scrollverbal"
    >

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >

    <TextView
         android:layout_width="match_parent"
    android:layout_height="wrap_content"
     android:id="@+id/verbalintro"
     android:textSize="15sp"
     />

    <View
        android:layout_width="match_parent"
        android:layout_height="10dp"
    />

    <TextView
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:id="@+id/verqstns"
         android:textSize="15sp"
    />

  </LinearLayout>

</ScrollView>

and my button is
 <Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="15"
android:background="@android:color/transparent"
android:textSize="20sp"
android:textStyle="bold"
android:drawablePadding="-5sp"
android:paddingLeft="10sp"
android:drawableLeft="@drawable/tick"
/>

I read that it can be done using getScrollY() method. but don't know how to use it programatically.
Answer: Try this, where scrollX is scrolled pix in x axis and scrollY in Y axis
scrollX = scrollView.getScrollX();
scrollY = scrollView.getScrollY();

Refer this for doc
Answer: this may help you
https://stackoverflow.com/a/5966375/472336
set click listener for your btn findview by id your scroolview and on that call this method and set it as buttons text
Comment: like this:
  final Button answer= (Button) findViewById(R.id.answernumber);

  answer.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    ScrollView scrver = (ScrollView) findViewById(R.id.scrollverbal);
    int scrollposition = scrver.getScrollY();
    answer.setText(scrollposition);
   }
  });
Comment: all i want is the text should change as the user scrolls
Comment: For this you have to set text of button  inside scroll listener of your scrollview for that this link may help you http://stackoverflow.com/a/10713501/472336


Excluded non-numeric from Crystal Report Average Convert to Percent

Question: How do I exclude the text (-Very Courteous) from the value, for example (4-Very Courteous)  to do average by tech?
Can I add average by tech to this formula?
{vwsvAllSurveyResponses.DateCompleted} = {?Date Survey Completed} and
{vwsvAllSurveyResponses.Name} = {?Select Survey}
I am unable to upload example. . .
===================
January 13, 2012
thanks. This is the final formula. Val(ToText(-Val({vwsvAllSurveyResponses.Response})))
I was able to get the averages. I am trying to convert the Average to percent? Avg of @Actual Value(number)*
I get an error that the field name does not exist: {Avg of @Actual Value} /4 * 100
Answer: If your text field is always prefixed by a number; the formula Val() will help you.
Val returns the starting numbers in a string as an integer.
See this post for more details
You should then be able to produce your averages.
Selecting which averages to display is harder.  You could suppress results where the average does not meet your parameters. So on each display line have a conditional suppress statement to only show averages in a certain range. I think you may also be able to add averages in the selection formula.  I do not have crystal here to test this though!
Comment: Hi, thank you. It was not clear to me where to enter the Val() {vwsvAllSurveyResponses.DateCompleted} = {?Date Survey Completed} and {vwsvAllSurveyResponses.Name} = {?Select Survey}
Comment: From the names of the fields you have provided; it is not obvious which one you need to use it on. You need to use it on the field that gives you the text "4 - Very Courteous".  Val("4 - Very Courteous") will give you the integer 4 as a result.


Access USB port using C

Question: I know about 4 wires in a USB !i want to work on them i.e. data+ & data-, ground, power ! i use windows7.
i want to control the signals (may it be binary of digital) through the wires using c ! i want to drive a car with the 4 arrow keys on my keyboard !
the main idea is to connect the 4 wires of a USB to the remote controller of the car and when we press any arrow key the on/off signal will be sent to the specific wire indeed ill make connection in such a way that when i press forward the remote controller gets forward command and transmittes to the car which makes it move !
basically i am ready with every other thing other than connecting the usb to c program and directing it in a specific command
i want 6 commands to work;

forward
backward
right n forward
right n backward
left n forward
left n backward

please help !1!this stuff is killing me !
Comment: How did this get upvotes? And by the way, the punctuation for finishing a sentence in English is a period (`.`).
Comment: Once upon a time we could set the voltage of a pin of the parallel port by writing a bit somewhere. Things are much more difficult now :-( Sorry, I don't know which is the best option for you, but I'm pretty sure that it is not trivial at all.
Answer: USB ports on modern computers cannot be manipulated directly in the manner that you are describing, because the processor is not accessing those wires directly. There is a dedicated host controller chip that does most of the job, usually one implementing one of the various Host Controller Interface specifications. That chip handles the low-level handshaking with the various devices and may just refuse to work with a port that does not have a proper USB device connected.
The main CPU accesses the USB port by programming the host controller, which imposes several restrictions on what can and cannot be done. In addition, all major operating systems that I am aware off have a pretty rigid interface for accessing USB ports. Even if the HCI allowed direct signal manipulation of the USB port, the OS interface does not.
Finally, wiring random non-USB-compliant hardware to the USB port is a very good way to fry the port and possibly the computer. USB is intended to be implemented by both the computer and the device.
If you want to control hardware with the USB port, then you could either use an adapter to another port interface (e.g. a parallel port) or incorporate a microcontroller that supports USB connectivity in your car controller.
Answer: you can try learning assembly.
if i remember correctly you just have to pass two argumants
1. the port number
2. the data to send
then write "out" and it sends that data to that device.
it is almost the same in low level C also.
ask if i dont make sense
Hopefully i have helped.
EDIT
Sorry I about my answer it is totally useless and incorrect as I was inexperienced at the time.
Answer: The Thing was Solved.
I used L293D IC with a lan wire an connected it through Serial port to a windows 98 PC.
It worked for me.
Thank you for your Contribution.
I also got awarded the best project in my College.

Access USB port using C


Dynamically changing height to match width with jquery

Question: I have a toggle that changes the width of the element and I want the height to match the width
I looked and found this and it works but it doesn't change after the toggle is clicked
So I'm looking for a solution that responds to the change
var cw = $('.child').width();
$('.child').css({'height':cw+'px'});

Demo:
http://jsfiddle.net/47e84/1/
Please note I'm fairly new to jquery
Comment: You'll need to show how you're toggling.
Comment: Oh, sorry. Here http://jsfiddle.net/47e84/
Comment: Just something to think about - http://jsfiddle.net/833Dj/ - just click on the red.
Answer: Your are using the stored the value on page load and resetting the same value on each click, you should get the current width. Also there is no need to use if statements, for toggling the classes, .toggleClass() method can be used.
$('.feed-options-switch').on('click', function (event) {
    $('ul.feed-content').toggleClass('list grid');
    $('.work').css('height', function () {
        return getComputedStyle(this).width;
    });
});

http://jsfiddle.net/bqu2y/
Comment: That's the functionality I'm looking for! Thanks
Answer: Can you do something like
$('.child').height(cw);

Comment: That gives me the same result as $('.child').css({'height':cw+'px'});
Comment: Not sure exactly what it is you are trying to achieve. Is this better http://jsfiddle.net/wesleyskeen/47e84/2/
Comment: I was basically trying to them to be square based on the calculate width and height. @BlackSheep answer worked, thanks for the help anyway


Need to extract millions of rows from multiple tables in mysql database

Question: I have to extract millions of rows from 21 SQL tables for a list of strings. Additionally, My query has got group-by concatenation, etc.
I need to run this in a memory-friendly manner using chunks. I am using python2.
Can anyone suggest a solution?
Say here is my query, just an example.
query = """
        SELECT
            v.id AS varid,
            v.chrom AS chrom,
            v.vcf_pos AS vcf_pos,
            v.vcf_ref AS vcf_ref,
            v.vcf_alt AS vcf_alt,
            group_concat(distinct term.term) as HPO_terms,
            group_concat(distinct term.name) as HPO_names,
            group_concat(distinct pp.patientid,"-",pp.person_status,"-",pp.affected_status) as family_label,

            if(vcc.AF_Pat between 0 AND 1, vcc.AF_Pat, NULL) AS AF_Pat,
            replace(vcc.analysistypelist,',',';') AS analysistypelist,
            vcc2.HomPatCount AS AC,
            vcc2.HetPatCount AS HAC,
            vcc2.TotalPatCount AS TAAC,
            if(vcc2.AF_Pat between 0 AND 1, vcc2.AF_Pat, NULL) AS AF_Assay,
            vcc3.HomUnaffCount AS HCC,
            vcc3.HetUnaffCount AS HCC1,
            vcc3.TotalUnaffCount AS TTCC,
            if(vcc3.AF_healthy between 0 AND 1, vcc3.AF_healthy, NULL) AS AF_Control,
            g.gene_name as gene_name,
            t.tx_name as tx_name,
            ta.*,
            va.*,
            vc.*,
            ga.*,
            group_concat(
                concat_ws(':', ifnull(g.gene_name,'.'), ifnull(t.tx_name,'.'), ifnull(ta.hgvsc,'.'), ifnull(ta.hgvsp,'.'))
                SEPARATOR '|'
            ) as `AllTranscriptAnnotations`
        FROM {} AS v
            LEFT JOIN table1 vcc ON vcc.variant_id=v.id
            LEFT JOIN table2 vcc3 ON vcc3.variant_id=v.id
            LEFT JOIN table3 va on v.id=va.variant_id and va.status='active'
            LEFT JOIN table4 vc on v.id=vc.variant_id
            LEFT JOIN table5 ta on v.id=ta.variant_id and ta.status='active'
            LEFT JOIN table6 t on t.id=ta.transcript_id and t.status='active'
            LEFT JOIN table7 g on g.id=t.gene_id and g.status='active'
            .
            .
            .
            LEFT JOIN table21 pt on pt.term_id=term.id
        GROUP BY v.id,s.id
        HAVING 1 {}
        """.format(v1,sq)

Where v1 and sq are search  strings.
Now, I need to make the above query memory efficient or optimized currently it takes more than 4 hours to finish extracting.
I am looking for something along the lines of divide and conquer chunks.
Comment: Does `v` control the rows?  That is, are all the `LEFT JOIN` delivering exactly 1 row (optionally all NULLs)?
Answer: Do not use OFFSET; it will be slower and slower as you go through the table.
I would consider chunking on v.id:
WHERE v.id >    0 AND v.id <= 1000   -- in first run
WHERE v.id > 1000 AND v.id <= 2000   -- 2nd
(etc)

More on chunking:  http://mysql.rjweb.org/doc.php/deletebig#deleting_in_chunks
That link has some tricks to deal with variants (such as big gaps in id).
Is the GROUP_CONCAT() really needed?  This implies that at least some of the LEFT JOINs are delivering more than one row.  In this case, which tables?  (This may lead to an optimization that involves getting rid of both the GROUP_CONCAT and the GROUP BY`.)


Can PC saves be imported into console version of Mass Effect 3?

Question:
Possible Duplicate:
Can I transfer saved game files from my PC to my Xbox360?

Having not yet played Mass Effect 1 or 2 I plan on purchasing them before jumping into Mass Effect 3. What platform I purchase a game for is larger dependent on where I'll be spending my time in the immediate future. For instance right now I'd probably buy Mass Effect 1 for the PC. A few months from now when I'm ready to jump into Mass Effect 2 I might purchase it for the Xbox 360.
Which brings me to my question can Mass Effect save games be imported between platforms? PC to console? Or even console to PC?
Comment: I'm going to go with no. But I have never actually tried it, so I'm not sure.
Comment: @GAThrawn Given the score my answer got (ill-deserved as it was) and the contest going on, it pains me to agree with you, but I think you're completely right.
Comment: @GAThrawn GAH! that didn't appear in the results when I searched. Maybe due to the title not including Mass Effect?
Answer: MassEffectSaves.com has a page dedicated to how you can transfer saves from PC to XBox 360 and from 360 to PC. However, it doesn't appear you can do this with the PS3.
Comment: It says right on that page that you can go 360->PC.
Comment: @MBraedley Thanks, somehow I totally read that wrong.
Answer: No, the save formats are not compatible. Here's a thread where users found no way to move PC saves to PS3 ME2 save files from PC to PS3.
The main problem here is the PS3 and Xbox pair your save data with your user account, so for legal and practical reasons only saves made on PS3/Xbox normally work on those platforms. The PC save doesn't have that, so it would require some major hacking with the save file to get it to work.


MFC: draw in a control

Question: Looking for some code/project examples on how to draw a pulse waveform with certain width/frequency in a MFC control. Which control would be the best to use for this purpose?. I am very new to this. Have already done some online search and definitely can use some expert ideas. I am lost.
Comment: A picture control might seem like the natural choice, but those get implemented as a `CStatic` which resist being updated dynamically. I'd probably go for a custom class derived from `CWnd`.
Answer: The MFC CStatic class represents a picture control. You can derive a class from CStatic and paint whatever you like in its OnPaint member function.  For examples search codeproject.com and codeguru.com for "CStatic", like this one:
http://www.codeguru.com/cpp/controls/controls/chartingandanaloguecontrols/article.php/c5219/Simple-Graph-Control.htm

MFC: draw in a control


What is the derivative of $\min(f(x),\text{constant})$, wrt $x$?

Question: $f(x)$ is a continuous function of $x$ which may be less than, equal to or greater than a fixed constant, say, $a$. If I have to differentiate "$\min(f(x),a)$", how do I do it? Its a part of a much bigger problem, so I cant go about breaking it in three separate cases.
Thanks for any help.
Comment: everywhere the derivative of $g$ defined by $g(x) = min(f(x), A)$ exists is either $f'(x)$ or $0.$
Answer: Big hint:
$$
\min \{f(x),a\} = \frac{f(x)+a}{2}-\frac{|f(x)-a|}{2}.
$$
Now you have a clean function to differentiate.


Android - size of compressed and uncompressed images the same

Question: I am trying to compress an image and output the size of the compressed and original images to Logcat (using Bitmap.getAllocationByteCount()). However, the compressed and original image sizes are always the same despite a visible change in the compressed image's quality. I am making use of the Picasso SDK to read images from a resource and eventually load a bitmap returned by the callback in the Target class into an ImageView.
Here is my code:
public class MainActivity extends ActionBarActivity {

ImageView imageView1;
private Target target;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    imageView1 = (ImageView)findViewById(R.id.image_view_1);

    target = new Target(){

        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {

            Log.v("BITMAP BEFORE",Integer.valueOf(bitmap.getAllocationByteCount()).toString());

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            bitmap.compress(Bitmap.CompressFormat.JPEG,0,outputStream);

            Bitmap decodedMap = BitmapFactory.decodeStream(new ByteArrayInputStream(outputStream.toByteArray()));

            imageView1.setImageBitmap(decodedMap);

            Log.v("BITMAP AFTER",Integer.valueOf(decodedMap.getAllocationByteCount()).toString());

        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {

            Log.v("ON BITMAP FAILED", "ON BITMAP FAILED");
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

            Log.v("ON PREPARE LOAD","ON PREPARE LOAD");
        }
    };

    loadImage();
}

private void loadImage(){

    Picasso.with(getApplicationContext()).load(R.drawable.smiley).into(target);
}
}

I tried compressing JPEGs and PNG with a 0 compression factor, however the sizes are always the same. What am I doing wrong ? An explanation or even a solution would be most appreciated. I am trying to reduce the size of the Bitmap before loading it into an ImageView. Thanks in advance.
Edit:
I tried using getByteCount() and getRowBytes() * getHeight() in place of getAllocationByteCount() and the results are always the same.
Answer:
However, the compressed and original image sizes are always the same despite a visible change in the compressed image's quality.

The size in RAM of a Bitmap has nothing do to with whether the image is compressed or the image quality. It depends solely on resolution (width, height) and bit depth. getAllocationByteCount() returns the size in RAM of the Bitmap.
Compression and image quality affect the size on disk of a bitmap image.
Comment: Can we determine the compressed storage space, without actually writing the compressed image to the storage.? [This](https://stackoverflow.com/a/6424680/6420004) answer satisfies my requirement but takes up extra RAM.
Comment: @shubhamsharma: I do not know of any way to predict how well compression will work, except to actually perform the compression.


Is it possible to get a large page and a consecutive normal page

Question: Is it possible to get a large page and a consecutive normal page.
Im writing a runtime and I want to create 2M stack with a single 4K guard page. And it needs to scale to say 10 processes each with 10 threads.
Considering using a 2 Meg page because of TLB  misses this is normally not an issue with C / C++ but with region analysis we will  have more data ( entire regions) on the stack so its not just the  last pages that are hot.
Ben
Comment: Not sure why its closed its a perfectly legit question , it may be unusual but i do have good reasons which i have now added.
Answer: Speaking for Linux, it is certainly possible, per se, to allocate a large page followed by a small region allocated normally:
mmap(base, 1 << 21, PROT_X, MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_FIXED, -1, 0);
mmap(base + (1 << 21), 1 << 12, PROT_X, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);

However, I hardly think there's any way to get the kernel to properly manage the address for you such that you can get it to allocate addresses for you automatically while finding such an address that has a guaranteed free page following it, so you'll probably have to do address allocation manually.
EDIT: Actually, I'll have to revise that statement; there's a fairly simple way to get that guarantee, at least as long as you're not running multiple threads that may do allocation simultaneously. Just allocate two large pages, deallocate the latter, and the allocate the small page in the space that is now free:
p = mmap(NULL, 2 << 21, PROT_X, MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB, -1, 0);
mremap(p, 2 << 21, 1 << 21, 0);
mmap(p + (1 << 21), 1 << 12, PROT_X, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);

Comment: I don't understand what you're asking. All these addresses are virtual, of course. The kernel won't normally let you deal with physical addresses at all.
Comment: What about using virtual addresses ?
Comment: Thanks for the update. Just request a Large page and a normal page and remap via custom virtual address to be consecutive.