My Huawei P30 lite doesn't discover other bluetooth devices in my android studio app

Question: I have already searched for the problem that my huawei p30 lite doesn't discover other bluetooth devices. I tried it with an onther device and it worked but I don't get it why it doesn't work on my huawei p30 lite.
Manifest.xml
<code>    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.notfallapp">
    <uses-feature android:name="android.hardware.bluetooth" />

    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/notfallapplogo"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.DayNight.NoActionBar">

        <uses-library android:name="org.apache.http.legacy" android:required="false"/>

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".menubar.MapActivity"
            android:label="@string/title_activity_map"></activity>
        <activity
            android:name=".Login.LoginActivity"
            android:screenOrientation="portrait"></activity>
        <activity
            android:name=".Login.SignUpActivity"
            android:screenOrientation="portrait"></activity>
        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".menubar.contact.ContactActivity"
            android:screenOrientation="portrait"></activity>
        <activity
            android:name=".menubar.contact.AddContactActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".menubar.AlarmsActivity"
            android:screenOrientation="portrait"></activity>
        <activity
            android:name=".menubar.SettingsActivity"
            android:screenOrientation="portrait"></activity>
        <activity
            android:name=".alarm.CallAlarmActivity"
            android:screenOrientation="portrait"
            android:persistent="true"/>
        <activity
            android:name=".alarm.AlarmCanceledActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".alarm.AlarmSuccesfulActivity"
            android:screenOrientation="portrait" />
        <activity android:name=".menubar.ChangeProfilActivity"></activity>
        <activity android:name=".connectBracelet.AddBraceletActivity"
            android:screenOrientation="portrait">
        </activity>
        <activity android:name=".menubar.ChangeProfilActivity">
        </activity>
    </application>

</manifest>
</code>
AddBraceletActivity.kt
<code>package com.example.notfallapp.connectBracelet

import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.util.Log
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.notfallapp.MainActivity
import com.example.notfallapp.R
import com.example.notfallapp.interfaces.ICreatingOnClickListener

class AddBraceletActivity : Activity(), ICreatingOnClickListener {

    private lateinit var btnSos: Button
    private lateinit var btnHome: ImageButton
    private lateinit var btnContact: ImageButton
    private lateinit var btnAlarms: ImageButton
    private lateinit var btnMap: ImageButton
    private lateinit var btnSettings: ImageButton

    private lateinit var btnRetrySearching: Button
    private lateinit var btnCancel: Button
    private lateinit var tvConnectBracelet: TextView
    private lateinit var lvDevices: ListView
    private lateinit var builder: AlertDialog.Builder
    private var bAdapter: BluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
    private lateinit var mReceiver: BroadcastReceiver
    private var context = this
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_add_bracelet)

        configureButtons()
        initComponents()

        btnCancel.setOnClickListener() {
            Log.d("ButtonCancel", "Cancel Button was clicked in AddBraceletActivity")
            sureDialog()
            val alert = builder.create()
            alert.show()
        }

        btnRetrySearching.setOnClickListener() {
            Log.d("ButtonSearch", "Search Button was clicked in AddBraceletActivity")
            searchDevices()
        }
        searchDevices()
    }
    private fun configureButtons() {
        // SOS Button
        btnSos = findViewById(R.id.btn_sos)

        // Button bar
        btnHome = findViewById(R.id.btnHome)
        btnAlarms = findViewById(R.id.btnAlarms)
        btnContact = findViewById(R.id.btnContact)
        btnMap = findViewById(R.id.btnMap)
        btnSettings = findViewById(R.id.btnSettings)

        createOnClickListener(this, btnSos, btnHome, btnAlarms, btnContact, btnMap, btnSettings)
    }

    private fun initComponents() {
        btnRetrySearching = findViewById(R.id.btn_retry_searching)
        btnCancel = findViewById(R.id.btn_cancel_searching_device)
        tvConnectBracelet = findViewById(R.id.tvConnectBracelet)
        lvDevices = findViewById(R.id.lvDevices)
        builder = AlertDialog.Builder(this)
        mReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                System.out.println("Hello 2")
                val action = intent.action
                if (BluetoothAdapter.ACTION_DISCOVERY_STARTED == action) {
                    //discovery starts, we can show progress dialog or perform other tasks
                } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) {
                    //discovery finishes, dismis progress dialog
                } else if (BluetoothDevice.ACTION_FOUND == action) {
                    //bluetooth device found
                    val device =
                        intent.getParcelableExtra<Parcelable>(BluetoothDevice.EXTRA_DEVICE) as BluetoothDevice
                    val toast = Toast.makeText(context, "Found device " + device.name, Toast.LENGTH_LONG)
                    toast.show()
                }
            }
        }
    }

    private fun searchDevices() {
        //TODO search for Bluetooth devices.
        Log.d("SearchDevices", "SearchDevices was called in AddBraceletActivity")
        if (bAdapter == null) {
            tvConnectBracelet.setError(getResources().getString(R.string.deviceNotSupportBluetooth))
            return;
        }

        if (!bAdapter.isEnabled) {
            val eintent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivity(eintent)
        }

        val discoverableIntent: Intent = Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).apply {
            putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300)
        }
        startActivity(discoverableIntent)

        if (bAdapter.isDiscovering){
            bAdapter.cancelDiscovery()
        }

        /*val pairedDevices = bAdapter.bondedDevices
        if (pairedDevices.size > 0) {
            // There are paired devices. Get the name and address of each paired device.
            for (device in pairedDevices) {
                System.out.println(device.address)
            }
        }*/

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

            Log.i("info", "No fine location permissions")

            ActivityCompat.requestPermissions(this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                1)
        }
        bAdapter.startDiscovery()

        val onFoundFilter = IntentFilter(BluetoothDevice.ACTION_FOUND)
        onFoundFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED)
        onFoundFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        registerReceiver(mReceiver, onFoundFilter)
    }

    override fun onDestroy() {
        bAdapter.cancelDiscovery()
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    private fun sureDialog() {
        builder.setTitle(getResources().getString(R.string.confirm))
        builder.setMessage(getResources().getString(R.string.sureStopSearching))

        builder.setPositiveButton(getResources().getString(R.string.Yes)) { dialog, which ->
            var intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            dialog.dismiss()
        }

        builder.setNegativeButton(getResources().getString(R.string.No)) {dialog, which ->
            dialog.dismiss()
        }
    }
}
</code>
These are my files where I have the permissions and where I scan for bluetooth devices.
Thank you very much for help!
Answer: Hello I solved my problem by reinstall my device to the base settings.


xslt select between 2 values

Question: Is it possible to select only those values that lay between 2 given values using xslt?
i.e.
<value>1</value>
<value>1.2</value>
<value>1.3</value>
<value>1.4</value>
<value>1.5</value>
<value>2</value>
<value>2.1</value>
<value>2.3</value>
<value>2.4</value>
<value>2.5</value>

I only want to display values between 1 and 2.
Comment: Which XSLT version do you use? With 2.0 there are operators `<<` and `>>` so you could use `//value[. >> //value[. = 1] and . << //value[. = 2]]`. Note that inside of XSLT you need of course escape `<<` as `<<`.
Comment: possible duplicate of [XPath between two elements](http://stackoverflow.com/questions/8181856/xpath-between-two-elements) or [XPath Get Elements that are between 2 elements](http://stackoverflow.com/questions/1489326/xpath-get-elements-that-are-between-2-elements) or [Selecting siblings between two nodes using XPath](http://stackoverflow.com/questions/3428104/selecting-siblings-between-two-nodes-using-xpath)
Comment: Do you mean "between" as in "numerically greater than the minimum and less than the maximum" or as in "after an element with one value and before another element with a different value"?
Answer: Certainly:
select="value[. > 1 and . < 2]"

if you want to include 1 and 2:
select="value[. >= 1 and . <= 2]"

if the top and bottom limits are in variables (using $min and $max as examples here):
select="value[. > $min and . < $max]"

Answer: Unlike the other answer I prefer to go with Identity Override
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="value[. < 1 or . > 2]"/>
</xsl:stylesheet>

outputs:
<root>
  <value>1</value>
  <value>1.2</value>
  <value>1.3</value>
  <value>1.4</value>
  <value>1.5</value>
  <value>2</value>
</root>

Answer: If the values are sorted (as in the provided XML document), this would be faster -- especially in the cases when there are many valu elements following the last wanted value element:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/*">
  <xsl:variable name="vStart" select=
   "(*[.>=1][1]
   |
    *[1]
    )
     [last()]
   "/>

  <xsl:variable name="vEnd" select=
   "($vStart/following-sibling::*[. > 2][1]
                             /preceding-sibling::*[1]
   |
    *[last()]
    )
     [1]
   "/>

  <xsl:variable name="vPosRange" select=
  "count($vEnd/preceding-sibling::*) - count($vStart/preceding-sibling::*)"/>

  <xsl:copy-of select=
   "$vStart|$vStart/following-sibling::*[not(position() > $vPosRange)]"/>
 </xsl:template>
</xsl:stylesheet>

When applied on the provided XML document:
<t>
    <value>1</value>
    <value>1.2</value>
    <value>1.3</value>
    <value>1.4</value>
    <value>1.5</value>
    <value>2</value>
    <value>2.1</value>
    <value>2.3</value>
    <value>2.4</value>
    <value>2.5</value>
</t>

the wanted, correct result is produced:
<value>1</value>
<value>1.2</value>
<value>1.3</value>
<value>1.4</value>
<value>1.5</value>
<value>2</value>

Do note:
In practice this gives us a pure XPath 1.0 solution, as we can substitute $vPosRange, $vStart and $vEnd with the XPath expressions that they are defined with.

xslt select between 2 values


Minimum distance between a disk in 3d space and a point above the disk

Question: How can I calculate the minimum distance between a point on the perimeter of a disk in 3d space and a point above the disk?
For example, there is a disk in 3d space with center [0,0,0]. It has radius 3 and lies flat on the x,y plane. If there is a particle above the disk at [5,5,5], how do I calculate the minimum distance from this particle to a point on the perimeter of the disk?

Here is my attempt so far:
vec1 = vector between disk center and particle
vec1 = [(5 - 0), (5 - 0), (5 - 0)]
vec1 = [5,5,5]

unitvec1 = unit vector in direction of vec1
unitvec1 = vec1/norm(vec1)
unitvec1 = [0.5774, 0.5774, 0.5774]

vec2 = vector between disk center and point on the perimeter closest to the particle
vec2 = disk radius * unitvec1, and make z element = 0
vec2 = 3 * [0.5774, 0.5774, 0]
vec2 = [1.7321, 1.7321, 0]

vec3 = vector between particle and point on the perimeter closest to the particle
vec3 = vec1 - vec2
vec3 = [3.2679, 3.2679, 5.0000]

So the min distance is
norm(vec3) = 6.8087

But this method doesn't always work. If I try it with disk center [0,0,0], particle location [0,0,6], and disk radius 9, it gives the minimum distance to be 6. this can't be correct, because the distance between the center of the disk and the particle will be 6, so the distance to the perimeter must be larger.
What am I doing wrong, and how should I actually calculate this?
Thanks!
note: I am using pseudo code, not an actual programing language
Comment: Thank you all for answering! You have all gave great answers and have been very helpful with my understanding of this problem
Answer: I am not familiar with the programming language you are using, but here is how I would set up the problem. Let the point be at $(x,y,z)$. Then
$$d^2 = (x - R \cos(\theta))^2 + (y - R \sin(\theta))^2 + z^2 = R^2-2\,\sin \theta\,y\,R-2\,\cos \theta\,x\,R+z^2+y^2+x^2$$
If $x=y=0$ then distance does not depend on $\theta$. Or else it is at the angle satisfying:
$$ y \cos(\theta)=x \sin(\theta)$$
Make sure you use $\text{atan2}$ to get the angle in the right quadrant.
You could always rotate the $x-y$ plane so $y=0$ and $x>0$!
Added in response to OP's question:
R: radius of the disk
$\theta$: Angle of a point on the rim, measured from the $x$ axis.
d: Distance from the point $P$ to the point on the rim (at angle $\theta$)
$(x,y,z)$: coordinates of the the point $P$.
Comment: Thank you for your answer. Can you please tell me what d, R, and theta represent in your equation, and how I would find them?
Comment: My attempt at an answer is written is pseudo code, not a real programing language. the equals sign is an equality, not a "gets" as it would be in a programming language. I just formatted it this way to show my working out.
Answer: Your logic is wrong because you make the wrong thing a unit vector. The length of your vec2 is not necessarily equal to the radius of the disc, because it is equal to the radius multiplied by a vector which is some component of the unit vector unitvec1.
Instead of normalizing vec1, you should normalize vec2.
In this case, be aware that vec2 might be zero (as in your final example). Thus when normalizing you should check if this happens, and if so arbitrarily set vec2 to any point on the diameter in this case.
Comment: "The length of your vec2 is not necessarily equal to the radius of the disc, because it is equal to the radius multiplied by a vector which is some component of the unit vector unitvec1"

I see where i've gone wrong, because I have modified unitvec1 by setting the z component to 0, it is no longer a unit vector and therefore when multiplied by the radius it does not give the radius vector.

However, I'm not sure if your solution will work. To get vec 2 in the first place I will need a unit vector that points in the direction towards the min point
Comment: The direction of the vector formed by projecting onto $z=0$ is correct regardless of its normalization, so this should work.
Comment: To be slightly more precise, you should (a) project by setting $z$ component to zero, (b) check if result is zero (probably within numerical error), (c) if so, just return vertical distance; (d) if not, compute `(radius / norm) * projected vector` and use that in computing `vec3`.
Answer: Your code is almost completely correct (and avoids the use of atan2, which is nice). The one problem you have is that when the vector from the disk-center to your point happens to point perpendicular to the disk, i.e., when the test point happens to be exactly above the disk's center, it falls apart: projecting that vector to the $xy$-plane gives the zero vector, whose tip does not lie on the disk's boundary circle.
Here's replacement code (mostly yours):
vec1 = vector between disk center and particle
vec1 = [(5 - 0), (5 - 0), (5 - 0)]
vec1 = [5,5,5]

pvec1 = vec1 with its z-coordinate set to 0.
if (norm (pvec1) = 0 ):
   answer = sqrt( norm(vec1) * norm(vec1) + radius * radius )
   return

unitvec1 = unit vector in direction of pvec1
unitvec1 = pvec1/norm(pvec1)
unitvec1 = [0.7071, 0.7071, 0]

vec2 = vector between disk center and point on the perimeter closest to the particle
vec2 = disk radius * unitvec1
vec2 = 3 * [0.7071, 0.7071, 0]
vec2 = [2.1..., 2.1..., 0]

vec3 = vector between particle and point on the perimeter closest to the particle
vec3 = vec1 - vec2

So the min distance is
norm(vec3) = 6.8087

That'll handle the special case on which your current code is failing. Note that you might want to replace the test "norm (pvec1) = 0" with "norm (pvec1) < .001" to make the code a bit more numerically stable, and introduce almost no error.
Comment: Thankyou very much. Although are you certain this will work? As sharkos has pointed out, unitvec1 multiplied by the radius will not give the "vector between disk center and point on the perimeter closest to the particle" as I thought it would.
Comment: What I've called pvec is the projection of the center-to-particle vector onto the $xy$ plane. Notice that to create "unitvec1", I've normalize "pvec" instead of normalizing "vec1". (This is much the same as @Sharkos's normalization of vec2). Thus radius * unitvec1 really IS a point on the boundary circle. So I'm pretty certain that this code will work fine. BTW, notice that in the "if" clause, I've got a "return" statement -- you're supposed to compute the answer and quit at that point, not continue on through the rest of the code.
Answer: I'm going to answer my own question, I've just been told a much easier way to calculate this.
Let R = radius of disk
Let r = distance from disk center to projection of particle on x,y plane
so r = ((5^2)+(5^2))^0.5 = 4.071
Distance between concentric circles = ((R-r)^2)^0.5 = 4.071
Height of particle above disk = 5
Rmin can then be calculated using Pythagorean theorem
Rmin = ( (4.071^2) + (5^2) )^0.5 = 6.448


Trying to launch a process via screen from within ansible

Question: I'm having a slightly weird, repeatable, but unexplainable problem with screen.
I'm using ansible/vagrant to build a consistent dev environment for my company, and as a slightly showy finishing touch it starts the dev server running in a screen session so the frontend devs don't need to bother logging in and manually starting the process, but backend devs can log in and take control.
However, one of the systems - despite being built from scratch - ends up with an immediately dead screen (it doesn't log anything to screenlog). Running the command manually works fine.
(the command being)
screen -L -d -m bash -c /home/vagrant/run_screen_server.sh

I've even gone to the point of nuking everything vagrant/virtualbox related on the system, making sure it's installing a clean, nightly box. Exactly the same source box works all the other machines.
Are there any other debugging steps I can be taking or is there something I'm missing?
Comment: So, all the machines are the same? and you are saying that one of them is failing and the other ones are just fine ?
Comment: They were different(ish) machines, but they had all the same versions of the relevant packages/vms.

Unfortunately (and fortunately) the problem disappeared (after a restart, never trust someone to do the automatic debugging steps you would do).

I'm rolling the deployment out to the rest of the company this week, and hopefully it will not re-emerge.
Comment: Old question but I had the same problem and what helped me was to append `> log` to my command, so my ansible command looks like this:
`command: /usr/bin/screen -dm run.sh > log`
Answer: I'm right now trying to do the same with my setup and hit the same problem.
Further testing has shown, that sleep 1 right after calling the screen helped. It seems the ssh script that ansible calls exits before the screen call is fully detached (or something else, that would explain that the sleep 1 helps)
I've also found Can't get Fabric's detached screen session example to work with the same suggestion.


Why is the answering machine making noise with a photovoltaic system connected to the house?

Question: The answering machine is making noise and there is a photovoltaic system connected to the house. What can cause this?
Comment: Inverter hash? What's the noise sound like?
Comment: Can you provide more details? How is the PV system hooked up (DIY, grid tie, battery charging...)? Does the answering machine make noise constantly or just during a call? Are the wires close to each other? When did it start? Did anything change?
Comment: If you disable the solar system (open the breaker) does the noise go away?  What brand?  What model?  How long?  Please improve your question.
Comment: Post an audio recording!
Answer: First, you need to verify that the two things are related. A bad phone line can make a noise with no PV system. If the noise is only with the answering system, it could be a defective answering system that would make noise regardless of the PV system. Seeing two things and associating them without determining an actual link can lead to a lot of wasted time debugging things that are not bugs.
Then, you need to observe and report how they are related (noise when the sun shines = MPPT controller - noise all the time = inverter - likewise, noise should stop when you shut those items down even if the sun is shining, etc.)
The cure will probably be adding capacitors and/or inductors to filter the noise, but without isolating what makes the noise, that's a bit hard to speculate further on. For noise on 120/240V power, a surge capacitor (UL listed, of course) also has the handy function of reducing EMI (electromagnetic interference - or noise on your phone line, in this case.) But if the noise is really from a MPPT charge controller, a surge capacitor on the AC side of things won't help much.
It's also worth checking and rechecking all the grounds - both that they are there, and that they are well-connected.


Bumping versions of modules with maven

Question: I have a big multi-module maven project (tens of modules, 4 nesting levels).
Every module has it's own semantic version (can be SNAPSHOT or not).
I want to find the way to bump every module major version automatically with one command or script to avoid changes in every module.
So I have for example

parent POM (1.2.3-SNAPSHOT)
|-- api-module (3.4.5)
|-- impl-module (5.6.7-SNAPSHOT)
|-- another-parent-module (1.0.1-SNAPSHOT)
|--|--sub-module1 (1.2.3)
|--|--sub-module2 (2.3.4)

and after bumping I want to have

parent POM (2.0.0-SNAPSHOT)
|-- api-module (4.0.0)
|-- impl-module (6.0.0-SNAPSHOT)
|-- another-parent-module (2.0.0-SNAPSHOT)
|--|--sub-module1 (2.0.0)
|--|--sub-module2 (3.0.0)

I know about Maven Release Plugin and about Versions Maven Plugin but I can't figure out how to make them bump major version automatically.
Could you help me with this problem?
Comment: Fist it looks you are misusing multi module build cause usually all modules/parent should have the same version. Apart from that you can change the version by using `mvn versions:set -DnewVersion=13.5.6.`
Answer: In a multi module project, every module should have the same version. I recommend to split your module in separate Maven projects and then it is easier to use the Maven Release Plugin and Versions Maven Plugin.
Comment: > In a multi module project, every module should have the same version.

why is that? any proof link?
Comment: You can also have multiple, independent applications within a single multi-module project
Comment: In short, the idea behind is that when your application is large, then you split it in modules. So your modules should have the same version like your application to recognize which modules forms a special version of your application . You can find a good introduction to this topic in the book _[Maven By Example](http://books.sonatype.com/mvnex-book/reference/multimodule.html)_
Answer: I agree with the idea that

multi module project, every module should have the same version

but we already have some module structure in a big project where several teams are participating, and it could not be changed easily.
Since I have not found a solution I created a groovy script for this purpose: https://github.com/ddska/maven-semver-bumper

Bumping versions of modules with maven


Perl sort not working as expected on numeric values

Question: I am stumped by this and obviously missing something basic. It seems perl sort is not working on particular set of value.  Here is part of test code:
    use strict;

    my $i = 7;
    my $j = 8;
    my $k = 4;

    print "before:$i:$j:$k\n";
    my @p = ($i, $j, $k);
    ($i, $j, $k) = sort(@p);
    print "after:$i:$j:$k\n";

    print "######################################\n";

    my $i = 23;
    my $j = 24;
    my $k = 7;

    print "before:$i:$j:$k\n";
    my @p = ($i, $j, $k);
    ($i, $j, $k) = sort(@p);
    print "after:$i:$j:$k\n";

print "######################################\n";

As you can see, it works when input values are (7:8:4). Doesn't seem to work when values are (23:24:7)!
before:7:8:4
after:4:7:8
######################################
before:23:24:7
after:23:24:7
######################################

Comment: Storing the array back into the individual variables seems a bit odd, and not something you'd probably do in a real-world program. You can just print the array itself: `print "after: @p\n"`
Answer: By default, sort will sort lexically. So 23 and 24 come before 7 for the same reason that bc and bd come before g in the dictionary.
sort {$a <=> $b} @p will yield a numeric sort.
http://perldoc.perl.org/functions/sort.html for more info.
Comment: (Dictionaries use language-specific collation orders. This isn't the same as `sort`'s default. You'd use `Unicode::Collate` for that.)


Ignore the typing if enter higher number than 24 or just 0

Question: I want this function to ignore the typing, if the user has entered a higher number than 24 and if the user has entered 0. As it is right now, I can enter a higher number than 24. Why?
<code>$('body').on('keyup', 'input[name="textfield-number-month"]', function(e) {
    var data_val = $(this).val();

    if(parseInt(data_val) >= 25 || parseInt(data_val) == 0) {
        e.preventDefault();
        return false;

    } else if(parseInt(data_val) <= 24) {
        // Some code...
    }
});
</code>
jsFiddle
Comment: why don't you just put a break point there and provide some details
Comment: @Steve Break point? And what more details do you want to know?
Comment: is the function being hit? whats the value of data_val? what happen when you type in 25?
Comment: @Steve Yes. Have you seen the demo? It ignores my function and types the number I choose to type in
Answer: You are just stoping further typing, but you can do number 99... you have to set the value back for example:
<code>    if (parseInt(data_val) >= 25 || parseInt(data_val) == 0) {
        $(this).val("25");
        e.preventDefault();
        return false;

    } else if (parseInt(data_val) <= 24) {
        // Some code...
    }
</code>
you could also set it just back:
<code>        $(this).val("");
</code>
Comment: Many thanks! So I can't make the function just ignore the typing the user make? For instance, the user types 23 and it works but when the user types 26, nothing will happen.
Answer: I suggest you to remove the last char when the user enters a value outside the range
<code>$(this).val(data_val.slice(0,1));
</code>
Here is a jsFiddle
Comment: Now we're getting somewhere! Many, many thanks! I'll accept your answer as soon as I can. If you know how to completely ignore/block the typing if match above the number, it would be awesome! Like nothing will happen when you're typing some number over 24
Comment: Yeah , i tried, but I gave you this solution dor now and I'll try to block typing , once I'll do it, I'll post the update


add scrollbar to jframe grid

Question: I have got a grid with rectangles which I will fill in with values. However, depending on the input the grid may be quite large so I would like to add a scrollbar option to the image. The code below does not seem to do what I want? Any help is appreciated.
<code>   class Cube extends JComponent
   {
public void paint(Graphics g)
{

    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            g.setColor(Color.GRAY);
            g.fillRect(i*40, j*40, 40, 40);
        }
    }

    for (int i = 0; i < 50; i++)
    {
        for (int j = 0; j < 50; j++)
        {
            g.setColor(Color.BLACK);
            g.drawRect(i*40, j*40, 40, 40);
        }
    }

}
public static void main(String[] a)
{
    // CREATE SCROLLBAR
    JScrollPane scroller = new JScrollPane();
    JFrame window = new JFrame();
    window.setSize(200,200);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().add(new Cube());
    //ADD THE SCROLLBAR
    window.getContentPane().add(scroller, BorderLayout.CENTER);
    window.setVisible(true);
}
</code>
}
Answer: Some tips:

You need to add Cube to scroll pane. You may find this tutorial about scrollpane helpful.
You should use event dispatcher thread when using swing.

I rewrite your program as below.
<code>class Cube extends JComponent
{
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < 10; j++)
            {
                g.setColor(Color.GRAY);
                g.fillRect(i*40, j*40, 40, 40);
            }
        }

        for (int i = 0; i < 50; i++)
        {
            for (int j = 0; j < 50; j++)
            {
                g.setColor(Color.BLACK);
                g.drawRect(i*40, j*40, 40, 40);
            }
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(1000, 1000);
    }

    public static void main(String[] a){
        // use event dispatcher thread
        EventQueue.invokeLater(
            new Runnable() {
                public void run() {
                    Cube cube = new Cube();
                    JScrollPane scroller = new JScrollPane(cube);
                    JFrame window = new JFrame();
                    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    // set the content pane
                    window.setContentPane(scroller);
                    window.pack();
                    window.setVisible(true);
                }
        });
    }
}
</code>
Comment: JComponent has paintComponent, 1st code line should be super.paintComponent, override getPreferredSize inside class Cube, then remove cube.setPreferredSize(new Dimension(1000,1000));, and to call JFrame.pack() before window.setVisible(true);

add scrollbar to jframe grid


NestJS e2e test mock Session decorator

Question: I'm trying to write an e2e test with supertest where my controller actually makes use of the @Session() decorator. I however don't want to have the full burden of initiating a session with db connection and so on so my app in the test does not actually initialize the session.
I'd instead like to mock away the data provided by the Decorator in the first place and replace it with static data. I can't really find a solution as to how to realize this however.
Sample from controller:
@Get('/user/me')
public async getMe(@Session() session: Record<string, unknown>) {
  if (!session?.user) {
    throw new InternalServerErrorException();
  }
  return session.user;
}

What I'd ideally like the mock to look like:
jest.mock(Session, jest.fn().mockImplementation(() => {
  return { user: { name: "test user" } };
})

however this won't work.
According to the official TypeScript documentation Parameter decorators can only be used to observe that a parameter has been set on a particular method. As this is not actually what's happening when using the @Session() decorator I tried having a look at the source code of how nestjs actually implements these decorators and I'm having at some trouble understanding it correctly.
If I'm not mistaking it seems like the decorator writes some metadata another decorator (probably @Get() in this case?) can make use of and extract the necessary data based on that.
I'm a little confused as to how to test this properly so I'd be very thankful for some advice :)
===========================================================================
Update: I will now go ahead and instead of mocking the Session decorator itself mock the req.session while setting up my app in beforeAll() hook. Therefore I chose the following solution:
app.use((req, res, next) => {
    req.session = {
      user: {
        firstName: 'Max',
        lastName: 'Mustermann',
      },
    };
    next();
});

I'll still be very happy in case someone knows a better solution.
Answer: To solve the problem create a common function to which creates the nest application for e2e and provided hooks config which enables overriding of testing module and application middleware injection of express
Common Setup function

/**
 * Hook for overriding the testing module
 */
export type TestingModuleCreatePreHook = (
  moduleBuilder: TestingModuleBuilder,
) => TestingModuleBuilder;

/**
 * Hook for adding items to nest application
 */
export type TestingAppCreatePreHook = (
  app: NestExpressApplication,
) => Promise<void>;

/**
 * Sets basic e2e testing module of app
 */
export async function basicE2eSetup(
  config: {
    moduleBuilderHook?: TestingModuleCreatePreHook;
    appInitHook?: TestingAppCreatePreHook;
  } = {},
): Promise<[NestExpressApplication, TestingModule]> {
  let moduleBuilder: TestingModuleBuilder = Test.createTestingModule({
    imports: [AppModule],
  });

  if (!!config.moduleBuilderHook) {
    moduleBuilder = config.moduleBuilderHook(moduleBuilder);
  }

  const moduleFixture: TestingModule = await moduleBuilder.compile();
  const app = moduleFixture.createNestApplication<NestExpressApplication>();

  if (config.appInitHook) {
    await config.appInitHook(app);
  }

  return [await app.init(), moduleFixture];
}

Usage

describe('AppController (e2e)', () => {
  let app: INestApplication;

  beforeEach(async () => {
    [app] = await basicE2eSetup({
      moduleBuilderHook: (moduleBuilder) => {
        // your overrides go here
        // Refer: https://docs.nestjs.com/fundamentals/testing#end-to-end-testing
        // eg: moduleBuilder.overrideProvider(ProviderName).useValue(value)
        return moduleBuilder;
      },
      appInitHook: async (app) => {
        const result = await someAction();
        // or get some service from app
        // eg: const service = app.get<YourService>(YourService)
        app.use((req, res, next) => {
          // do something with request of response object
          next();
        })
      }
    });
  });

  it('/ (GET)', () => {
    return request(app.getHttpServer())
      .get('/')
      .expect((res) => {
        expect(res.text).toContain('Hi There');
      });
  });
});

NestJS e2e test mock Session decorator


Vue + Flask Gmail API

Question: I am attempting to build a webapp using Vue for the frontend and Flask for the backend that reads in the users Gmail emails.
Desired functionality:

User clicks a button to "Link Gmail Account" on the frontend
User is authenticated with gmail Oauth2 and confirms. Once confirmed, they redirect back to the page they were on
Once the user confirms, the backend queries gmail to get all of the users emails and returns the data to the frontend

I have been trying to use https://developers.google.com/gmail/api/quickstart/python as a starting point, but I cannot authenticate the user -- I keep getting a redirect uri mistmatch error with a random port (I am doing this locally so have set the redirect uri to be the localhost port where I access my project).
I think I am doing something fundamentally wrong or not using the Gmail API in the correct way, but have searched all over google and youtube to no avail.
Specific things that I think could be causing an issue:

What is the best overall strategy to implement this? Should I use the Gmail API in Python or Javascript? Right now, the use clicks the "Link Account" button which calls an API in my backend which then runs the code in the Python Quickstart guide.
What kind of google project should I set up? I currently have my credentials configured for a "web application"
What should I put as the redirect uri? I am using localhost but am unsure exactly what to put here (I have tried http://localhost, http://localhost:5000, http://localhost:5000/, http://localhost:5000/emails [this is the url I want them to return to]). No matter what I put, I keep getting a redirect uri mismatch and it says the uri it is looking for is http://localhost:[random port]/

I would appreciate any help on how to approach achieving this. Thank you!
Answer: Depending on what you are going to use Gmail API for, you must select the device or category. In your case, as it is a website it should be set to "Web Application".
Also, you should be using the following redirect URI: http://localhost/emails/. You should not include the port number and you should be using trailing slashes (adding the last / at the end). Note that the redirect URI you set up in your backend must be an exact match of the one you have set up in your Credentials Page. Also please note that it might take some minutes to update this URI.

Vue + Flask Gmail API


Problem using Virtual Terminal

Question: How can I copy-paste following command:
rm -r ~/.gconf/apps/gnome-terminal
gconftools --recursive-unset /apps/gnome-terminal

into a virtual-terminal?
Comment: Why can't you use a terminal window in your desktop environment?
Comment: I cannot use the terminal normally,because after a command and my password the output of the terminal is" sudo: apt-get: command not found". I have tried to remove and re-install the terminal using synaptic package manager,but no change in the output. Hence I want to try the abovementioned method.
Comment: So you tried to reinstall `gnome-terminal` and something went wrong , right ? There's also `xterm`. Ubuntu comes with two GUI terminal emulators by default
Comment: And you can use Shift + Insert to paste copied stuff. But copy line by line, because if you try to put two commands together, it wont work. OR you can do. `rm -r ~/.gconf/apps/gnome-terminal; gconftools --recursive-unset /apps/gnome-terminal` As one line. See the semicolon ?
Answer: If you can't use the standard terminal:

...I cannot use the terminal normally ...

start your installed packet manager Synaptic and install an other terminal xterm.
Use Alt+F2 and type xterm and Return
Now you can copy and paste:

mark the command with the left mouse button
paste the command with the middle mouse button

Alternatively write a short script and start the script in the virtual terminal:

Start gedit and add the lines below:
#!/bin/bash
rm -r ~/.gconf/apps/gnome-terminal
gconftools --recursive-unset /apps/gnome-terminal

Save the file as foo in your home folder and switch to tty.
Login and make the script executable
chmod +x ~/foo

Start the script
./foo

Answer: As far as I know, there is no way to access a desktop clipboard from a virtual terminal.
The easiest thing to do in this case is to save and run these commands as a script.

Problem using Virtual Terminal


JanusGraph Custom String Vertex Ids for existing Cassandra Keyspaces

Question: I am trying out the Custom Vertex ID feature in JanusGraph as mentioned in the below documentation
https://docs.janusgraph.org/master/advanced-topics/custom-vertex-id/
I am using Cassandra as the backend store for the JanusGraph database and used the below properties for enabling the custom vertex Id feature in Janus Graph, Currently I am using Embedded JanusGraph with Java Code.
storage.cql.keyspace=janusgraph
graph.set-vertex-id=true
graph.allow-custom-vid-types=true

When I try with an existing keyspace where existing records are already present I am getting the below exception
Exception in thread "main" java.lang.UnsupportedOperationException: Vertex does not support user supplied identifiers
    at org.apache.tinkerpop.gremlin.structure.Vertex$Exceptions.userSuppliedIdsNotSupported(Vertex.java:163)
    at org.janusgraph.graphdb.tinkerpop.JanusGraphBlueprintsTransaction.addVertex(JanusGraphBlueprintsTransaction.java:119)
    at org.janusgraph.graphdb.tinkerpop.JanusGraphBlueprintsGraph.addVertex(JanusGraphBlueprintsGraph.java:143)

But once I try the same code on a new Cassandra Key space it is working as expected and able to store the string  Custom Vertex Ids using the below Code
 Vertex firstVertex = g.addV("record")
                       .property(T.id,"customVertexId1")
                       .property("recordId", "abc")
                       .next();

So my query is this Custom Vertex Id cannot be applied to existing Keyspaces? We always require to create the new keyspaces for using the Custom String type vertexId in JanusGraph? Please Suggest
Answer: See https://docs.janusgraph.org/advanced-topics/custom-vertex-id/#alter-an-existing-graph
Basically if you want to use this on an existing graph, you should do
mgmt = graph.openManagement();
mgmt.set("graph.set-vertex-id", true);
// optional, if you want to provide string ID
mgmt.set("graph.allow-custom-vid-types", true);
mgmt.commit();


Exclude certain tokens from the parse tree

Question: I'd like to exclude certain tokens from the parse-tree in antlr4.
Say I have this definition:
assignStatement: assignable EQ expression EOS;

EQ: '=';
EOS: ';';

The resulting parse-tree contains the assignable, EQ, expression and EOS as children of assignStatement. Is there any way to get rid of EQ and EOS here, since I only need them during parse-time for matching purposes?
Answer: ANTLR 4 does not omit matched terminals from the parse tree. While your application does not require access to those tokens, our experience has been that new applications using a previously written grammar frequently require access to elements that earlier applications did not. By including all elements in the parse tree, we are accounting for this case in advance to improve the long-term maintainability of applications using ANTLR 4.


How much HP does "Ygdar Orus Li Ox" revive you with?

Question: The "Ygdar Orus Li Ox" mutation "saves you one time if you die prematurely while not cursed". Do you stay at 1hp when you get saved, or do you get a bit of extra HP so you don't die immediately after if you get hit again?
Answer:
Upon taking lethal damage which does not trigger sudden death prevention, it freezes nearby enemies, restores 25% of the player's max health, removes all accumulated Malaise and then becomes disabled for the rest of the run.

Source, Dead Cells wiki.


Initial Ubuntu guest screen resolution on VMWare

Question: Windows 7 (host) with VMWare Workstation 11.
Kubuntu 15.04 as Guest.
Problem:
After system startup, in example, on login screen - screen size/resolution is 800x600. Ba, even earlier - during startup when console is active. Making window fullscreen isn't helping, as console output limits itself to small window in the middle.
Setting VMWare window into fullscreen helps a little - screen gets bigger (size of host 1920x1080) -  guest Kubuntu applications windows are taking whole  screen area.  But, for example, desktop wallpaper acts still as if 800x600 was in effect. And inside System settings -> display Virtual screen stays at 800x600, nevertheless Resolution list is long. Unfortunately - 1920x1080 isn't there.
This what xrandr shows:
Screen 0: minimum 1 x 1, current 1920 x 1080, maximum 8192 x 8192
Virtual1 connected primary 1920x1080+0+0 (normal left inverted right x axis   y axis) 0mm x 0mm
   1920x1080      60.0*+
   2560x1600      60.0
   1920x1440      60.0
   1856x1392      60.0
   1792x1344      60.0
   1920x1200      59.9
   1600x1200      60.0
   1680x1050      60.0
   1400x1050      60.0
   1280x1024      60.0
   1440x900       59.9
   1280x960       60.0
   1360x768       60.0
   1280x800       59.8
   1152x864       75.0
   1280x768       59.9
   1024x768       60.0
   800x600        60.3
   640x480        59.9

From this it seems that proper resolution is set properly.
Now, some magic. I logout from Kubuntu. Login screen is already taking whole 1920x1080 screen area. Settings -> Display shows Virtual screen as 1920x1080, xrandr shows the same set of resolutions.
VMWare Tools were installed - at least to the point that I have bidirectional access to shared folders.
What to do to have proper screen resolution right from the beginning? Yea, I know that I can freeze whole session and resume it whenever I need it.
Answer: My configuration is host : windows 7 and vmware guest : ubuntu 14.04.
For long time I've seen if I update the vmplayer or some software in vmplayer that screws my display and then in full screen it can no longer capture host display.So today I just followed the instruction provided in this link and fixed it without installing any additional software.I hope it helps other.
At first run :
$ xrandr -q

tanay@ubuntu:~$ xrandr -q Screen 0: minimum 1 x 1, current 1904 x 1070, maximum 8192 x 8192 Virtual1 connected primary 1904x1070+0+0 (normal left inverted right x axis y axis) 0mm x 0mm    800x600
60.0 +   60.3      2560x1600      60.0      1920x1440      60.0      1856x1392      60.0      1792x1344      60.0      1920x1200      59.9  1600x1200      60.0      1680x1050      60.0      1400x1050      60.0  1280x1024      60.0      1440x900       59.9      1280x960       60.0  1360x768       60.0      1280x800       59.8      1152x864       75.0  1280x768       59.9      1024x768       60.0      640x480        59.9  1904x1070_75.00   74.9*  Virtual2 disconnected (normal left inverted right x axis y axis) Virtual3 disconnected (normal left inverted right x axis y axis) Virtual4 disconnected (normal left inverted right x axis y axis) Virtual5 disconnected (normal left inverted right x axis y axis) Virtual6 disconnected (normal left inverted right x axis y axis) Virtual7 disconnected (normal left inverted right x axis y axis) Virtual8 disconnected (normal left inverted right x axis y axis)

Then you can see which output is connected,here Virtual1 is connected.
Then guess a good resolution for your screen.For me I guessed following configuration.
Eg:cvt <horizontal length> <vertical length> <refresh rate>

$ cvt 1900 1070 75

The output is
# 1904x1070 74.87 Hz (CVT) hsync: 83.85 kHz; pclk: 216.00 MHz Modeline "1904x1070_75.00"  216.00  1904 2040 2240 2576  1070 1073    1083 1120
-hsync +vsync

Then you need to copy the text after "Modelline" and paste that in following command after "newmode" like the example below
$ xrandr --newmode "1904x1070_75.00"  216.00  1904 2040 2240 2576  1070 1073 1083 1120 -hsync +vsync

Then take the screen resolution details from the quote and use it in next command.For me the command is
$ xrandr --addmode Virtual1 1904x1070_75.00

The next command to set it in ubuntu for me is
$ xrandr --output Virtual1 --mode 1904x1070_75.00

If the last command doesn't work for you,you can go back to ubuntu display gui setting and can chose the display you have added just now.For me the option was 1904 x 1070 (16:9)
However if you are fine with this experiment and have found the desired screen resolution and to make that permanent,write the all the last 3 commands starting from xrandr --newmode command in your .xprofile file using following command and then save,exit and restart your ubuntu vm and you will get your desired resolution permanently.
$ gedit ~/.xprofile

Comment: How did you found correct resolution? Did you use some command/app to display possible resolutions? Or did you try every one (modified by 1) till you found one that work?
Comment: @T4ng10r Since I was trying to mimic the host pc display,I took that value initially,and yes then there were some trial and error involved.Also the process has some pre-determined resolutions,for example if you try
cvt 1900 1070 75 the output will be 1904x1070 and not 1900x1070.So anyway you have to give some try,in my case it was manual try.
Comment: Thank you, I'll try this approach.
Hmm, perhaps some script to speed up setting process. But how to automatically verify if result is correct...?
Comment: It works for X11, but not for Wayland. Is there anyway to get 1920*1080 on Wayland?
Answer: Here is what worked for me-

$ xrandr
out-put-

Screen 0: minimum 8 x 8, current 1024 x 768, maximum 32767 x 32767
DP1 disconnected (normal left inverted right x axis y axis)
HDMI1 disconnected (normal left inverted right x axis y axis)
VGA1 connected primary 1024x768+0+0 (normal left inverted right x axis y axis) 477mm x 268mm
   1024x768      75.08*+  60.00
   800x600       60.32    56.25
   848x480       60.00
   640x480       59.94
VIRTUAL1 disconnected (normal left inverted right x axis y axis)
  1920x1080_60.00 (0x113) 173.000MHz -HSync +VSync
        h: width  1920 start 2048 end 2248 total 2576 skew    0 clock  67.16KHz
        v: height 1080 start 1083 end 1088 total 1120           clock  59.96Hz

Note:- found the connected on, for my case VGA1 connected primary
  1024x768+0+0 all others are not connected.

$ cvt 1920 1080

$ sudo xrandr --newmode "1920x1080_60.00"  173.00  1920 2048 2248 2576  1080 1083 1088 1120 -hsync +vsync

Note:- based on connection we have to use on as-

4. sudo xrandr --addmode VGA1 "1920x1080_60.00"

It worked for me, as suggested here, another source presented here.
Comment: Is there a Wayland version?
Comment: @DamnVegetables Not sure about Wayland.


How can I log in to my computer?

Question: Help! I changed my language on keyboard and I shut down my computer. Now keyboard doesn't work in English which I need to enter my password.
Comment: What language/locale did you set your keyboard to?
Comment: The local language is Amharic
Answer: If you cannot access the Keyboard settings from the GUI, try running this command:
<code>sudo dpkg-reconfigure keyboard-configuration
</code>
You can find more info here
To boot as root, at grub select "Advanced options for Ubuntu" then boot in "Recovery mode".
At the "Recovery Menu", you can choose "Drop to a root shell propmpt":

If your keyboard is working, although not in the correct keymap, you should be able to type the command.
Comment: He changed the language, it's probably a keyboard mapping issue. If I get the answer, the keyboard does work, but not with the en-US mapping.
Also he can run the terminal as root using the failsafe settings from grub.
Comment: How should the OP type that command, if English is not available?
Comment: Boot with bootable USB drive, then chroot.
Comment: If you think there is a way, edit your answer, and elaborate. As is, it doesn't answer the question.
Comment: @mikewhatever, there.
Answer:
Being on Log On screen, press Ctrl+Alt+F1 and it will take you to Terminal Screen.
In the terminal screen, type the login name and password.
Type the command, sudo dpkg-reconfigure keyboard-configuration.
Press Ctrl+Alt+F7 to get back to GUI mode.

Now, you can login as usually it was before.
Comment: I followed the steps and at the end came a command prompt. What do i do now?
Comment: If you have executed the command given in the third step, press Ctrl+Alt+F7 to return to GUI, that is Log on Screen. From there, you could proceed login process.
Comment: It doesn't still type in English
Comment: Did you run the exact command given in the step 3? Make sure each step what I have given. These steps will definitely solve you the issue.

How can I log in to my computer?


how can this query be changed for better enhancement?

Question: How can this query be modified for better enhancement?
select * from employee
where emp_id like '0%'
  and emp_id not like '00%'
  or emp_id like '1%'
  or emp_id = '999';

I want all the details of employees with emp_id like '0xxxxxxx' ,'1xxxxxx', 999 but not like '00xxxxxx'.
Comment: Before worrying about performance, make sure of using parentheses on your conditions to get the results you want: `(emp_id like '0%' and emp_id not like '00%') or ....`
Comment: what is the problem with your query?
Comment: If you have only a few employees, then performance optimization is not needed.  If you have a whole bunch of employees, then you query will probably return lots and lots of rows, so a full table scan is not much of an issue.
Comment: Yes, it has lakhs of records.
Comment: when I write emp_id like '0%' and then emp_id not like '00%', it first gets all the rows with 0% and then compares each row with 00% which takes time. Cant this be avoided?
Comment: you have actual issues to solve or this is a preemptive optimization that you think (hope? guess?) may produce any improvement? what are your expectations?
Answer: you could make use of the regexp_like function introduced in oracle 10g.
Your statement could look like this in the end
select *
from (select '1xxxxx' d from dual union
      select '0xxxxx' d from dual union
      select '00xxxx' d from dual union
      select '999'    d from dual union
      select '9999'   d from dual union
      select '555'    d from dual union
      select '5xxxxx' d from dual)
where regexp_like(d, '(^0[^0]|^1)|^999$');

The | acts like an or and it reads like, starts with 0 followed by not 0 or starts with 1 or equals 999


Rails Building an Object that has a Parent?

Question: I have the following two models in my app Spaces which are like projects & Permissions
class Space < ActiveRecord::Base
 has_many :permissions
 has_many :users, :through => :permissions

class Permission < ActiveRecord::Base
  belongs_to :user
  belongs_to :space
  belongs_to :role
  validates_presence_of :space_id , :user_id, :role_id

So here's what I'd like to do, in the Space Controller, when the user does DEF CREATE, I want to create a space, and a permission with role_id = 1, to ensure the space/project as the creator as a member...
Here's what I have. It's getting messy and not creating the permission
Space Controller:
def create
  @space = current_user.spaces.new(params[:space].merge(:creator => current_user.id))
  @space.permissions.new(:role_id => 1, :user_id => current_user.id)
  respond_to do |format|
    if @space.save
    ..
    ..

Thanks for your help
Comment: you should be doing this with callbacks in models, not in your controller. Can you be more specific about when you want the space created. Such as when new user or when a new space is getting created etc...
Comment: @Sam. Thanks. What do you mean by callbacks in models? Can you provide an example? Thansk... I want this to happen when a user creates a new space.
Answer: Callbacks are how rails deals with business logic that applies to models or their associations after one of the CRUD actions.
for example. If you want to create a space with 1 permission and that permission has one role you can do something like this.
in your user model
def before_create
   User.permissions << Permision.create({:role_id => 1})
end

Take a look at call backs in rails API. They will take a lot of your logic out of the controller and make it easier to maintain in your model.


How to change the path of a folder to point to one in Windows

Question: Basically I'm wanting my Ubuntu music folder to direct me to my Windows music folder, so that when I click my Ubuntu music folder I see the contents of my Windows music folder. I've already got my Window partition to mount automatically so that won't be an issue. Any ideas on how to accomplish this?
Answer: If you wish to access your music files in your Windows mount by using your ~/Music folder you can use mount --bind to mount the path to your Windows files in to your ~/Music folder.
You could make that automatic by adding the following /etc/fstab line (after the line that mounts your Windows partitions) using your favorite text editor, ie:

sudo nano /etc/fstab

/path_to_windows_files/music_folder /home/your_username/Music bind defaults,bind 0 0

where:

path_to_windows_files/music_folder: is the path which contains the
mounted Windows music files
your_username: is your username or the name of the user that will
have the files mounted

Close it with Ctrl+x and select y to save the file.
Comment: Could you maybe give me an example? I'm assuming the command would look something like

mount --bind /path/windows/music /path/ubuntu/music
Comment: Was working on it, it should be clear now.
Comment: @forgeSHIELD if you edit your questions and add the actual paths you have things mounted to he can make it exactly what you need.
Comment: Ok I've got it in there, but have run into another problem. The path to my windows music folder has a space in it, so it looks like this:

/media/NTFS/My Name/Music

When I restart then, it tries to find the folder Name/Music which does not exist
Comment: Fixed it. To add a space in the file path you need the escape \040, so my sample path would look like: /media/NTFS/My\040Name/Music. Thank you for your help @BrunoPereira


Outdoor Motion Sensor Light Durability

Question: A motion sensor light is to be installed where it is exposed to the Florida outdoors.  How can one gauge (is there a metric?) if the fixture is durable (last 5+ years).
As you have probably already guessed: I am weary of replacing fixtures every year.  Any suggestions or lessons learned are always appreciated: thank you.
Comment: what kind of failures have you experienced?
Comment: Failures range from not turning on when expected and vice versa.
Answer: Yes if you buy no name china with no UL listing you will be changing the fixtures out regularly.
I would suggest LED and to assure long life you want a fixture that is DLC and UL certified UL underwriters laboratory, Design Light Consortium requires a 5 year warranty.
I purchase a large number of fixtures and lamps Every year and find good prices and the above 2 certifications in many products they sell.
Check our LEDMYPlace.com and 1000bulbs.com
I have no connection to either company other than having purchased at least 100 from each and the very few problems I have had are quickly taken care of.
But in any case the DLC certification in a lamp or fixture has provided long life in rough environments where non DLC from other parts of the world have had many failures in fact not many have lasted beyond their warranty.
Comment: I've also used 1000bulbs.com and I know others who have as well. Good company to deal with. I can also tell you my stories of buying junk LEDs and having lots of failures (indoors) - learned to not do that, but most important (because even the good stuff can have occasional lemons) is to work with a retailer (whether online like 1000bulbs.com or a local store) that stands behind the products they sell.
Comment: It's amazing how difficult it is to buy good LEDs, or to be more precise, to resist the allure of the online deal on shady sites (Amazon being the #1 culprit) or the endcap offerings of the big-box store.
Answer: Separate the lights from the sensors

You can buy stalk motion sensors a-la-carte for about $20 from reputable makers.  You wire up your lighting as if it's going to be switch-controlled, except you run 3 live wires between the lamps and the motion sensor location (which can share a junction box with one of the lamps, or be located cleverly to get a better view of the geography).  You can also put the motion sensor in a more serviceable location.

White = neutral (to all lamps and motion sensors)
Red = switched-hot (to all lamps and motion sensors)
Black = always-hot (to motion sensors only)

Now, when a motion sensor goes kaput, you swap only the motion sensor. There is no reason for valuable/expensive lamps to go into the landfill.
Also, a bespoke setup like this lends a much better aesthetic.  It doesn't look like somebody bought a gimpy "2 lights and a stalk sensor" thing from CostCo and slapped on the wall... it's architected lighting designed to fit and flatter the building, with a motion sensor possibly concealed.
You can also expand into low voltage 12/24V LED lighting, which gives a great deal more design freedom.  12/24V motion sensors are definitely a thing, and are half the price of 120V sensors since they don't need internal power supplies or 120V relays.
Comment: Is this [Acuity outdoor sensor](https://www.acuitybrands.com/products/detail/775070/sensor-switch/sbor-series/outdoor-pole-high-mount) what you are thinking?  Please clarify what is meant by stalk motion sensor or provide an example link.  Concrete examples are helpful and highly appreciated.  Thank you

Outdoor Motion Sensor Light Durability


How to get text of NumericUpDown before valuechanged event?

Question: I want to make it work this way: when I write to NumericUpDown 1k the value should be 1000, when I write 4M the value should be 4000000. How can I make it?
I tried this:
private void NumericUpDown1_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyValue == (char)Keys.K)
    {
        NumericUpDown1.Value = NumericUpDown1.Value * 1000;
    }
}

But it works with the original value that I wrote.
I want to make it work as a macroses. For example, If I want to get NUD1.Value 1000, I write 1 and then, when I press K the NUD1.Value becomes 1000.
Comment: _"But it works with old value, now which i was written"_ What does that mean? What is `FrequencyCW`? Are you getting the value from another NUP control? Side note: Don't name your control `NumericUpDown` because that's the type name and things will get confusing very quickly.
Comment: You can't use a `NumericUpDown` control to accept natural-language input. I don't believe you can use `NumericUpDown` to convert `"4K"` of input into a `.Value = 4000`. You'll have to use a separate `TextBox` for that, I imagine.
Answer: Let's assume we have a NumericUpDown named numericUpDown1. Whenever the user presses k, we want to multiply the current value of the NUP by 1,000, and if the user presses m, the current value should be multiplied by 1,000,000. We also don't want the original value to trigger the ValueChanged event. So, we need to have a bool variable to indicate that the value is being updated.
Here's a complete example:
private bool updatingValue;

private void numericUpDown1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyData != Keys.K && e.KeyData != Keys.M) return;

    int multiplier = (e.KeyData == Keys.K ? 1000 : 1000000);

    decimal newValue = 0;
    bool overflow = false;
    try
    {
        updatingValue = true;
        newValue = numericUpDown1.Value * multiplier;
    }
    catch (OverflowException)
    {
        overflow = true;
    }
    updatingValue = false;

    if (overflow || newValue > numericUpDown1.Maximum)
    {
        // The new value is greater than the NUP maximum or decimal.MaxValue.
        // So, we need to abort.
        // TODO: you might want to warn the user (or just rely on the beep sound).
        return;
    }

    numericUpDown1.Value = newValue;
    numericUpDown1.Select(numericUpDown1.Value.ToString().Length, 0);
    e.SuppressKeyPress = true;
}

And the ValueChanged event handler should be something like this:
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
    if (updatingValue) return;

    // Simulating some work being done with the value.
    Console.WriteLine(numericUpDown1.Value);
}

Comment: @Daniel I'm not sure I understand. Right now, if you type 1 and then press k, the value becomes 1000. Isn't that what you want?
Comment: I want to make it work as a macroses. For example If I want to get NUD1.Value 1000, I should only write 1K, (should work when I press K NUD1.Value instantaneously becomes equal 1000). Can i make it using NumericUpDown?
Comment: @Daniel Repeating the same comment is hardly an answer to my question. What _exactly_ does not work as expected with the code above?
Comment: Thank you very match, for help!!! I tried this code and this work almost properly. Can I somehow make it without valuechanged event. For example when I write 1 and press K the value should change to 1000 instantaneously. But now I have value change to 1 and then value change to 1000. The problem is that I have some logics with valuechanged event (the value is sent to device and it should send 1000 not 1 and then 1000).
Comment: @Daniel Do you see the `ValueChanged` event being used anywhere in the code above? No. If you use the code above exactly as is, you should get 1000 as soon as you press k after typing 1. Perhaps you're doing something else in the `ValueChanged` event in your actual code and it's interrupting the `KeyDown` code making it not work as expected? If so, you should probably get rid of that part.
Comment: @Daniel Addressing your comment edit: I get what you mean now. In that case, you can have a `bool` variable to indicate that the value is being updated and check it inside the `ValueChanged` event. Let me update the answer to include that.
Comment: @Daniel See the full example above.


Activities dual monitor issue with Ubuntu 18.04

Question: I found the Activities overview very useful in Ubuntu 18.04. Unfortunately, when I plugged the second display, I found out that it is impossible to switch between activities located at different displays using Super + Tab (or Super + Arrow Keys). Is there a way to fix that?
Comment: It is not a solution but an alternative that I found more or less appropriate: [Coverflow Alt-Tab extention](https://extensions.gnome.org/extension/97/coverflow-alt-tab/).
Answer: After playing around with Coverflow Alt-Tab extention for a while I think it is exactly a solution to my question!
You may find the usage instructions here.


Grails - No suitable driver found for jdbc:oracle:thin:

Question: My Grails web-app uses an ad-hoc library called ws-client-1.0.2.jar, this library depends on Oracle (com.oracle.ojdbc14:10.2.0.3.0).
Because Grails repository doesn't contain that Oracle driver, I removed it from DataSource.groovy and I've manually grabbed its jar putting it under lib/ folder. Then, my lib/ contains:

I ran grails compile --refresh-dependencies and it works fine.
Then, I started my app with grails run-app and everytime I get this error:
Class: java.sql.SQLException
Message: No suitable driver found for jdbc:oracle:thin:@svildb.dev:1538:QUAT

The same happens when I run the unit tests grails run test-app
Why the ojdbc driver is not loaded despite it is under lib/ folder?
Comment: I wonder if the 14 in "ojdbc14" refers to the JDK its written to.  I'd expect to see ojdbc6 or ojdbc7, matching the JDK you deploy to.  If you deploy on Tomcat 7.x or higher, it's looking for JDBC JARs in the server /lib, not your WEB-INF/lib.
Comment: You'd still have to know to tell Gradle what the right version needs to be.  It feels like one more thing to be ignorant of.  Better to get this working on your own first, in my view.
Comment: you have removed it from the build and not the datasource, right?  could you please also provide the driver, dialect and the connectionstring from your datasource config?
Comment: @duffymo my JDK is: java version "1.7.0_55".
Comment: I'm very glad.  Well done!
Comment: @nicolimo86 You may want to consider a build tool like [gradle](https://gradle.org/) to handle library dependencies.
Comment: @duffymo you are right again. Because now the error is java.lang.UnsupportedClassVersionError: oracle/jdbc/OracleDriver : Unsupported major.minor version 51.0. But I tought it was a different problem and I didn't write it here.
Answer: Thanks to @Duffymo's comment I got some progress:

I downloaded the ojdbc7.jar from here
I put it under the lib/ folder.
Comment: I prefer to wait a bit more, because that is not a complete solution to the problem.
Comment: @ChrisLoonam ok I edited it. I also added this partial solution to the post where I put the final solution. Should I delete this post?
Answer: I found the solution thanks to this post:
Thanks to @Duffymo's comment I downloaded the right Oracle's ojdbc driver:

I downloaded the ojdbc7.jar from here
I put it under the lib/ folder.

After that, in the library ws-client-1.0.2.jar which rely on Oracle ojdbc I changed the way I instantiate the Sql object:
BEFORE
import groovy.sql.Sql
...
db={ Sql.newInstance(
      'jdbc:oracle:thin:@vbsvildb.dev:1538:QUAT',
      'user',
      'password',
      'oracle.jdbc.OracleDriver'
    )
}

AFTER
import groovy.sql.Sql
import org.apache.commons.dbcp.BasicDataSource
...
/* Setting connection details */
BasicDataSource bdsQUAT = new BasicDataSource()
bdsQUAT.setUrl("jdbc:oracle:thin:@svildb.dev:1538:QUAT")
bdsQUAT.setUsername("user")
bdsQUAT.setPassword("password")
bdsQUAT.setDriverClassName("oracle.jdbc.OracleDriver")
/* Getting connection to DB */
db=Sql.newInstance(bdsQUAT.getConnection())

I built the library again and I got a new ws-client-1.0.2.jar, then I copied it to my grails project under lib/ folder.
Now if I run grails test-app everything work!


How to write Matchers that match Matchers matching stuff

Question: Ok, so I want to test my shiny new hamcrest Matchers.
Are there any Matchers that match custom Matchers matching or not matching stuff?
This would greatly help with writing tests for custom Matchers.
Comment: If you used the word "matcher" a bit more, it might be clearer.
Answer: Seems to me that you shouldn't need a Matcher for your Matcher. You should write a unit test and USES YOUR Matcher.
 @Test
 public void testPass(){
    assertThat(input, myMatcher);
 }

 @Test
 public void testFail(){
    assertThat(input, not(myMatcher));
 }

Rinse repeat for all cases you need to test.
Answer: You can use the org.mockito.Matchers class to stub your input. There are many methods exposed by this class to use your stubbing.

Matchers.anyString()
Matchers.anyInt()
etc..

Suppose you have one function in the class A as
class A{

public void loadFile(){
 file = new FileInputStream("/test/webapps/test.properties");
...
....
}

and you want to write a test case , you have to write as follow by using Matchers class for stubbing-
class Atest{
@Test
    public void testLoadFile()
       {
           final FileInputStream fileInputStreamMock = PowerMockito.mock(FileInputStream.class);
          PowerMockito.whenNew(FileInputStream.class).withArguments(Matchers.anyString())
                              .thenReturn(fileInputStreamMock);
}


DoubleAnimation complains of origin == NaN only when resource is in Window

Question: I have a large WPF application. I'm looking to make the UI multithreaded. As part of that process, I'm moving some application-level control and style resources to the Window level. (I know from experience that I can't use DynamicResource and resolve at the application level unless I'm on the application thread.) Anyway, I moved a bunch of control resources. The application works find with one nasty problem: all of my animations on FrameworkElement Height and Width broke. They all fail because the control is of width or height NaN. These animations all work when the control templates are registered at the application level. All of my controls where I animate height or width have appropriate default height or width values that are not NaN. Why would the resource location affect this?
Comment: Unfortunately, "large WPF application" isn't enough information for me to reproduce your issue. I've got a very large WPF application in VS right on my desktop here, and it's not displaying the same behavior as yours. Maybe since this is a specific issue with specific XAML in a specific context, you could share some more specifics.
Comment: I would love to post some code with this question, but I can't seem to reproduce the problem in any academic situation.
Comment: In my attempts to isolate this, I've posted a related question here: http://stackoverflow.com/questions/39987144/window-level-staticresource-fails-two-levels-deep
Comment: Thanks, I'll take a look
Answer: Use ActualWidth and ActualHeight. Nan means that these propeties are not set yet.
https://stackoverflow.com/a/607849/3955716
Answer: This is late, but in case someone else get into this.
the DoubleAnimation is a helper class that allows for a double to go from a value to another in a smooth fashion.
As you don't specify a Width explicitly for your grid, the default value is NaN.
Thus the DoubleAnimation is trying to go from NaN to Whatever the target value. This cannot be done for obvious reasons.
If you set the Width of the grid, it should work properly.
A workaround would be to set the grid width after it loads in the constructor :
<code>public Grid()
{
    InitializeComponent();
    this.Loaded += (s, _) => this.Width = this.ActualWidth;
}
</code>
Hope this help.


I cannot track referrer_install of google play

Question: I am trying to report the install event to flurry.
I have implemented ReferralReceiver to be called when the app is being installed.
I have all the parameters in a map.
I am calling Flurry using my flurry code:
<code>FlurryAgent.onStartSession(context, FlurryCode);
FlurryAgent.logEvent("Referral", referralParams);
FlurryAgent.onEndSession(context);
</code>
The data is being stored to the SharedPreferences but it is not being sent to flurry.
Has anyone encountered this problem.
<code>@Override
public void onReceive(Context context, Intent intent)
{
     LogManager.Info("ReferralReceiver intent.action=" + intent.getAction());
     LogManager.Info("ReferralReceiver intent.DataString=" + intent.getDataString());
     LogManager.Info("ReferralReceiver intent.intent=" + intent.toString());

    // Workaround for Android security issue: http://code.google.com/p/android/issues/detail?id=16006
    try
    {
        final Bundle extras = intent.getExtras();
        if (extras != null) {
            extras.containsKey(null);
        }
    }
    catch (final Exception e) {
        return;
    }

    Map<String, String> referralParams = new HashMap<String, String>();

    // Return if this is not the right intent.
    if (! intent.getAction().equals("com.android.vending.INSTALL_REFERRER")) { //$NON-NLS-1$
        return;
    }

    String referrer = intent.getStringExtra("referrer"); //$NON-NLS-1$
    if( referrer == null || referrer.length() == 0) {
        return;
    }

    try
    {
        referrer = URLDecoder.decode(referrer, "UTF-8");
    }
    catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    LogManager.Info("ReferralReceiver intent.referrer=" + intent.getStringExtra("referrer"));

    SharedPreferences storage = context.getSharedPreferences(ReferralReceiver.PREFS_FILE_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = storage.edit();
    editor.putString("referrer", referrer);
    editor.commit();

    try {
        if (intent.hasExtra("referrer")) {
            String referrers[] = referrer.split("&");
            for (String referrerValue : referrers)
            {
                String keyValue[] = referrerValue.split("=");
                if (keyValue.length==2)
                {
                    referralParams.put(keyValue[0], keyValue[1]);
                }
            }
        }
    }
    catch (Exception e)
    {
        LogManager.Error(e);
        return;
    }

    ReferralReceiver.storeReferralParams(context, referralParams);

    String FlurryCode = SaverrUtils.GetFlurryCode();
    FlurryAgent.onStartSession(context, FlurryCode);
    FlurryAgent.logEvent("Referral", referralParams);
    FlurryAgent.onEndSession(context);
    LogManager.Info("New_Install");
}

public final static String PREFS_FILE_NAME = "ReferralParamsFile";

 /*
 * Stores the referral parameters in the app's sharedPreferences.
 * Rewrite this function and retrieveReferralParams() if a
 * different storage mechanism is preferred.
 */
public static void storeReferralParams(Context context, Map<String, String> params)
{
    SharedPreferences storage = context.getSharedPreferences(ReferralReceiver.PREFS_FILE_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = storage.edit();

    for(String key : SaverrUtils.EXPECTED_REFERRER_PARAMETERS)
    {
        String value = params.get(key);
        if(value != null)
        {
            editor.putString(key, value);
        }
    }

    editor.commit();
}

// Referral Parameters
public final static String[] EXPECTED_REFERRER_PARAMETERS = {
    "utm_source",
    "utm_medium",
    "utm_term",
    "utm_content",
    "utm_campaign",
    "referrer"
};
</code>
Answer: I think flurry has a minimum amount of seconds between start/end session for it to actually count. You can save all the data to shared preference or file, then when the user starts your activity check if it's been given to flurry. If it's new do FlurryAgent.logEvent(...).


graph from weighted edge list from a database

Question: I have list of weighted edges stored in database.
How can I easily create a Graph from it (without writing it in a file and reading it)
Here the reproductible
import sqlite3
con = sqlite3.connect(":memory:")

with con:
    cur = con.cursor()
    cur.execute("CREATE TABLE DATEN(Source TEXT, Target TEXT, Weight REAL)")
    cur.execute("INSERT INTO DATEN VALUES('X33', 'X20', 0.014)")
    cur.execute("INSERT INTO DATEN VALUES('X32', 'X20', 0.024)")
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X20', 0.167)")
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X32', 0.015)")
    cur.execute("INSERT INTO DATEN VALUES('X32', 'X33', 0.003)")
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X33', 0.035)")

cur.execute('SELECT * FROM DATEN')
data = cur.fetchall()

my attempt to create a graph fails:
import networkx as nx
G = nx.Graph()
for x in data:
     x1 = {'source': data[0][0], 'target': data[0][1], 'weight':  data[0][2]}
     print x1

     G.add_edge(x1)  # THIS IS NOT WORKING

Is there an easier way to do this?
Answer: The cursor is an iterator that yields rows after a SELECT statement is executed. For example, instead of fetching all the results into a list with
rows = cur.fetchall()

You can iterate over the rows with
for row in cur:

However, since the NetworkX add_weighted_edges_from method accepts an iterator, you can pass cur directly:
G.add_weighted_edges_from(cur)

This is a nice example of polymorphism. The designers of NetworkX did not have to do anything special or even anticipate that sqlite3 cursors might be passed as an argument, they only had to write the code with the assumption that the first argument was an iterator.

import networkx as nx
import sqlite3
import matplotlib.pyplot as plt

with sqlite3.connect(":memory:") as con:
    cur = con.cursor()
    cur.execute("CREATE TABLE DATEN(Source TEXT, Target TEXT, Weight REAL)")
    cur.execute("INSERT INTO DATEN VALUES('X33', 'X20', 0.014)")
    cur.execute("INSERT INTO DATEN VALUES('X32', 'X20', 0.024)")
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X20', 0.167)")
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X32', 0.015)")
    cur.execute("INSERT INTO DATEN VALUES('X32', 'X33', 0.003)")
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X33', 0.035)")

    G = nx.Graph()
    cur.execute('SELECT Source, Target, Weight FROM DATEN')
    G.add_weighted_edges_from(cur)

nx.draw(G)
plt.show()

Comment: Thanks ! I did not realized that edges_from can take cursor as argument.
Answer: Graph.add_edge() doesn't take a dict as argument, it takes at least two nodes and optional keyword arguments. Try this:
import networkx as nx
G = nx.Graph()
for x in data:
     G.add_edge(x[0], x[1], weight=x[2])

Comment: Thanks to you and all those who replied
Answer: First, could you give us the error message ?
Then, you don't seem to use add_edge properly (see : http://networkx.github.io/documentation/latest/reference/generated/networkx.Graph.add_edge.html#networkx.Graph.add_edge )
you should try to add your edges like this:
import networkx as nx
G = nx.Graph()
for x in data:
    G.add_edge(x[0], x[1], weight=x[2])

Answer: This works
f=open('G_train.txt','r')
data=f.read()
EDGES=ast.literal_eval(data)

g = nx.DiGraph((x, y, {'weights': v}) for (x, y), v in Counter(EDGES).items())

print("Edges", g.edges(data=True), sep='\n')


Installing Windows 7 using Virtual Box without having a CD

Question: I would like to create a windows 7 virtual machine on my computer, but I don't have my install disk.  I currently have it installed on my computer in a dual boot with ubuntu 11.04 and was wondering if there is a way to create a virtual machine using the already installed version, without needing to procure a CD with windows 7 on it.
I am reasonably tech savy but would not consider myself an expert by any means.  If this is possible, would it be very difficult, and would there be any way to make it easier?
Comment: What you can do is something like this: http://ubuntuforums.org/showthread.php?t=769883 but most here know nothing about windows 7 (and most things you need to do is inside windows) so this is likely to get closed. Btw this will also transform your current windows 7 install to Vbox only ;)
Answer: I'd've made it a comment but I'm not allowed.
I'm using Windows7 through VirtualBox and I don't think things you'd like to do possible.
Another thing - as far as I understand - you can download windows7 from anywhere - it's perfectly legal - the important thing is whither you have a serial number. If you deal with laptop - it must be sticked at the bottom. Then after you'll install the Win7 with your number at VirtualBox - you'd have to make a call to your local microsoft office.
Comment: You are not allowed to have both a dual boot and a VM on a single license. It might be possible that you even need a separate license for VMs although I'm not completely sure of that.
Comment: I'm not entirely sure about that. You can't run two VMs with it at any one time, but dualbooting and using it as a VM on the same machine will probably be legal since it's the same machine and you're only running one instance at a time. No guarantees though.
Comment: I didn't ment to have dual boot and a VM in the same time. I thought You'd get rid of dual boot, and leavy just VM. That's what I did with my laptop.
Answer: Yes, it's possible, but it's not easy. You can check this guide in the VirtualBox Forum:
http://forums.virtualbox.org/viewtopic.php?t=33356
Note that this is quite offtopic and not Ubuntu related (it's a windows thing), you will be able to obtain more and better help in the Virtualbox forum or in some Windows site.


Ubuntu Software report google-chrome-stable_current_amd64.deb is unsafe in Ubuntu 22.04

Question: My Chrome says it can't be updated and I need to reinstall it.
Problem Environment: Chrome Version 101.0.4951.64 (Official Build) (64-bit) on my Ubuntu 22.04.1 LTS - jammy

Then I downloaded the 'google-chrome-stable_current_amd64.deb' file from the 'Reinstall Chrome' button directly from the browser window itself where it tells me that I can NOT update the browser.
When I wanted to install via 'Ubuntu Software' it appeared:

I find it's hard to believe that a '.deb' file generated from Google is reported as 'insecure'
Can I ignore the message and install it anyway?
Should I download the .deb file from another source?
what would be the correct procedure?
Thanks in advance for any help you can give me...
Gustavo. (Argentina)
P.D.: Sorry for my English, it is not my natural language
Answer: Problem solved.
I decided:

uninstall the browser with the command:

sudo apt install google-chrome-stable

using firefox I downloaded again the file 'google-chrome-stable_current_amd64.deb' from the URL:
https://www.google.com/intl/en_us/chrome/

I installed this time ignoring the warning message and then the browser worked well in the most stable version.

Hope this helps someone in the same situation.
Gustavo


How can I mimic Greasemonkey/Firefox's unsafeWindow functionality in Chrome?

Question: I'm just fiddling around with user scripts in chrome right now, so please bear with my potential ignorance/idiocy.
In the page I'm writing a script for, there is a


Failed to convert from type java.lang.String to type java.util.Date on one JBoss but fine on the other

Question: We have current Spring application tested on Websphere 7&8, and Jboss EAP6
Interesting finding is, this application works totally fine on one Jboss server, but will throw exception on the other one Jboss server, both are eap 6
<code>org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'masterOrderForm' on field 'orderDate': rejected value [Mon May 27 12:27:20 ART 2013]; codes [typeMismatch.masterOrderForm.orderDate,typeMismatch.orderDate,typeMismatch.java.util.Date,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [masterOrderForm.orderDate,orderDate]; arguments []; default message [orderDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'orderDate';
nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.util.Date for value 'Mon May 27 12:27:20 ART 2013'; nested exception is java.lang.IllegalArgumentException: Invalid format: "Mon May 27 12:27:20 ART 2013"]
org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'masterOrderForm' on field 'orderDate': rejected value [Mon May 27 12:27:20 ART 2013]; codes [typeMismatch.masterOrderForm.orderDate,typeMismatch.orderDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [masterOrderForm.orderDate,orderDate]; arguments []; default message [orderDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'orderDate';
nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.util.Date for value 'Mon May 27 12:27:20 ART 2013'; nested exception is java.lang.IllegalArgumentException: Invalid format: "Mon May 27 12:27:20 ART 2013"]
</code>
From the UI both Jboss server date field has format as "dd\mm\yyyy", but it just throw exception on one server but works like charm on the other
Is it something we can over come from server side configuration?
Answer: I Googled the error and found this link.
If it's all ok on code, maybe the JVMs are running with diferent locale configuration.
Comment: @Dreamer it's about the war file build and the running JVM. I will try to locate the code where the same issue occurred, so I can give you more detail.
Comment: @Dreamer I can't find the code. But I remember what we done to solve. Change the line where you get "orderDate" to get has String and then convert to Date.
Comment: Much appreciate the reply, so it is the java compiler which build the war file? or the compiler tied to JBoss?
Comment: Could you please give more specific information from your experience which java version works and which don't?
Comment: Thank you very much, could you please a little specific about it, save as String the convert to Date? So change JVM doesn't work?
Comment: @dreamer I edited the answer because the first one was really wrong.
Comment: Thank you, actually we get some details about the issue, it may because the system we are running, one server in Windows in the US the other is Linux in Argentina, so timezone may be differently interpreted, but the solution is still unkown, add init binder still not working...


Ext4 partition converted to swap. How to recover?

Question: While installing Ubuntu 11.10, I converted by Fedora's ext4 partition to swap by mistake.
Please assist to recover the files and partition.
Comment: if it's converted to swap, then it's cleared. And all info is gone
Comment: It's only gone if the swap has been used by a running OS.
Comment: It has been formatted. So long information. Sorry mate.
Answer: When formatting a partition as swap only the first few couples of bytes get overwritten, so the data should be recoverable to some extent.
I'd try testdisk and in its options mark the partition as ext4 and try to list files.
If that doesn't work, I'd try to recover by using the backup superblock (still in testdisk).
If still no luck, then try photorec to recover the files at least.
For more info see
https://help.ubuntu.com/community/DataRecovery


How to set List element property with stream?

Question: I have a simple demand for java8 stream, here's the situation:
For now, the way to solve this is sorting the list and then set the rank property by index,
so is there any better way to solve this by using java8 stream? Please help, thanks a lot!
public class Student {
    private String name;
    private int score;
    private int rank;

    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("jack", 98);
        Student s2 = new Student("jason", 86);
        Student s3 = new Student("john", 80);

        List<Student> studentList = Arrays.asList(s1, s2, s3);
        // how to set rank property by score in each student with stream?

    }
}

Comment: While it is possible to solve this with streams, as the answer by Bohemian shows, "better" is a matter of opinion here. Both sorting and counting are inherently stateful operations, but streams work best when elements can be processed independently.
Answer: The stream element index is not available, which makes sense because streams are built to process elements without context of other elements.
However, you can do it:
List<Student> studentList = Arrays.asList(s1, s2, s3);
AtomicInteger index = new AtomicInteger();
studentList.stream()
  .sorted(Comparator.comparing(s -> -s.score)) // sort highest first
  .forEachOrdered(s -> s.rank = index.getAndIncrement());

This ranks from zero to n-1. To rank from 1 to n change getAndIncrement to incrementAndGet.


ifconfig weirdly returns exit code 1

Question: I am executing the following command to find the MAC Address of eth0
<code>ifconfig eth0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'
</code>
I have a java wrapper which just calls the script containing only the above command.
If I run the java code it works fine with the above command executing successfully and outputting the MAC address.
The problem is when it is run under tomcat the Process executing the script sometime exits with exitcode 1 and output contains blank value.
Weird as it may sound but restarting the tomcat service and then trying to execute the script works fine giving the proper MAC Address. But later again it starts giving the same problem.
What is the possible solution for this ? Let me know if you want more information.
Comment: Why not just `cat /sys/class/net/eth0/address` ?
Comment: Also why don't you [get MAC Address in Java](http://docs.oracle.com/javase/6/docs/api/java/net/NetworkInterface.html#getHardwareAddress()) ?
Comment: is the path /sys/class/net/eth0/address same for all the Linux Flavours ?
Comment: Also have not used java as we need to control the interface which it is connected to. Here I have used eth0 but that could change depending on requirement. And just changing the script will be simple enough and not require tomcat restart.
Comment: /sys/class is part of linux kernel since v2.5.
Comment: If you want solution of exact problem, I suggest you to move question to stackoverflow, as I understand problem in Java code or tomcat
Answer: Found the actual problem.
When the process was running under tomcat the '/sbin' path was not present in the $PATH the tomcat was using.
You can refer here.

ifconfig weirdly returns exit code 1