text:
Q: finding similar neighbourhoods in cell arrays matlab I have an array of cells,
example in the image below

I have been trying to use regionprops or any other tool to calculate the amount of neighbours with identical first index
for example below there are 5 cells circled in blue which are neighbours and have 1st index = 1 therefore there neighbourhood should = 5 for all of them and similar with the black cells

does anyone know of anyway to calculate this?
thank you.

A: You probably want to extract just the first index from each array, create a matrix (similar to a labels matrix) and then use regionprops on that.
%// Extracts the first value of each cell
firstValue = cellfun(@(x)x(1), cellArray);

%// Computes region properties using this matrix as a label matrix
result = regionprops(firstValue, property_to_compute);

The result can then be applied back to the full cell array as necessary.
Alternately, you could loop through the various first index values and compute the connected components using bwconncomp.
uniqueVals = unique(firstValue);
for k = 1:numel(uniqueVals)
    CC(k) = bwconncomp(firstValue == uniqueVals(k));
end


text:
Q: Azure Functions not being displayed I have two functions on Azure Functions but only one is displayed on Azure Portal.
Both functions works when acessed by URL.
I'm using docker, NodeJS, VSCode. Anyone knows why its happening?
Below is Visual Studio screenshot.

Below is Azure portal screenshot.

A: Thanks for the contribution of UnbearableLightness and PankajRawat.
So the solution is create a new function instance on azure and then publish your function code to azure. And then it should work.(I met two other people who faced the same problem and they solved it in the same way.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: MS Analysis Cube - one-to-many joins I am building an OLAP cube in MS SQL Server BI Studio. I have two main tables that contain my measures and dimensions.
One table contains
Date | Keywords | Measure1

where date-keyword is the composite key.
One table contains looks like
Date | Keyword | Product | Measure2 | Measure3

where date-keyword-product is the composite key.
My problem is that there can be a one-to-many relationship between date-keyword's in the first table and date-keyword's in the second table (as the second table has data broken down by product).
I want to be able to make queries that look something like this when filtered for a given Keyword:
                                Measure1    Measure2    Measure3
============================================================
Tuesday, January 01 2013        23          19          18
============================================================
    Bike                        23
    Car                         23          16          13
    Motorcycle                  23
    Caravan                     23          2           4
    Van                         23          1           1

I've created dimensions for the Date and ProductType but I'm having problems creating the dimension for the Keywords. I can create a Keyword dimension that affects the measures from the second table but not the first.
Can anyone point me to any good tutorials for doing this sort of thing?

A: Turns out the first table had one row with all null values (a weird side effect of uploading an excel file straight into MS SQL Server db). Because the value that the cube was trying to apply the dimension to was null in this one row, the whole cube build and deploy failed with no useful error messages! Grr


text:
Q: Qt debugger input not working I am trying to learn to debug using Qt Creator on OS X. Some of the exercises I am trying to complete require user input. When run normally the terminal window appears and dialogue works fine. However when run in debugger mode the terminal Windows down not appear and no input can be taken.
I have tried setting a break point and setting the values using the "watches" window (I don't know what it is actually called but that is what Code:: Blocks called it). I have also tried to skip the cin lines using the step over button but that does not work either. I found this answer which seemed similar but it was for Ubuntu and I am on Mac and I have no idea how implement their fix.
Here is an example of my problem:
#include <iostream>
using namespace std;
int main ()
{
     double base_val;
     cout << "Enter a base value: ";
     cin >> base_val;
     //the code cannot go further than this
     cout << base_val;
}

This was done in a plain C++ application with the qmake build system.
The Run in terminal option is checked (Projects / Build & Run /Run)

A: I managed it to get it running on the
qt creator
and also with code::blocks
but on arch linux - should work in windows and mac osx similar.
I installed gdb first but that is a Linux thing - windows and mac should have all on board ready installed with both editors.
(yay -S gdb:)
3 extra/gdb 8.3.1-1 (3.8 MiB 9.7 MiB) (Installed)
    The GNU Debugger

On Code::Blocks activate Debug->Debugging Windows->[x] Watches
On the qt creator it is shown after hitting F5 or Debug->Start Debugging->Start Debugging of Startup Project F5 on the right hand side named name | value
Both programs creates the same messages, took me a while - I hope that safes you guys time or helps you out if you never found it to


text:
Q: jQuery game - make flying helicopter more smooth I'm messing around making a simple game.
I have a helicopter which the user flies up and down.
I've got the basic code for this to happen working fine (touchstart + hold the helicopter goes up, release it goes down). However, it is very 'reactive'; if you want the helicopter to go in a straight line you need to quickly tap the screen, however the helicopter moves quite alot no matter how fast you can tap.
I need a way for the movement to ease at the start of going up and the start of coming down, so the helicopter can go in a fairly straight line if needs be.
My code is as follows:
var speed  = 1;

function copter_touchstart(){
    clearInterval(fall);
    fly = setInterval( start_fly, 2);
}

function copter_touchend(){
    clearInterval(fly);
    fall = setInterval( start_fall, 2);
}

function start_fly(){
    var matrix = $helicopter.css('-webkit-transform').replace(/[^0-9\-.,]/g, '').split(',');
    var y = matrix[5];
    var new_top = parseInt(y) - speed;

    $helicopter.css('-webkit-transform', 'translate3d(0, '+ new_top +'px, 0)')
}

function start_fall(){
    var matrix = $helicopter.css('-webkit-transform').replace(/[^0-9\-.,]/g, '').split(',');
    var y = matrix[5];
    var new_top = parseInt(y) + speed;

    $helicopter.css('-webkit-transform', 'translate3d(0, '+ new_top +'px, 0)')
}

$body.on('touchstart', copter_touchstart).on('touchend', copter_touchend);

JS FIDDLE: HERE
(touch changed for mouse events)
tap screen repeatedly to 'hover' the block, its too reactive, but I dont want to reduce the speed when flying normally

A: There are different types of movement for transitions, the default being linear. Have a look here:
CSS3 transitions
.object {
    position: absolute;
    transition: all 2s ease-in-out;
    -webkit-transition: all 2s ease-in-out; /** Chrome & Safari **/
    -moz-transition: all 2s ease-in-out; /** Firefox **/
    -o-transition: all 2s ease-in-out; /** Opera **/
}


text:
Q: How do you move a NSImageView? I have this situation:
I have a NSView which contains a custom NSImageView.
I'm trying to move the NSImageView from the view controller, but no success so far.
This is the header of the view controller:
#import <Cocoa/Cocoa.h>

#include "MyAppDragAndDropImageView.h"

@interface MyAppViewController : NSViewController <MyAppDragAndDropImageViewDelegate>

@property (nonatomic,assign) IBOutlet MyAppDragAndDropImageView *dragAndDropImageView;

@property (nonatomic,assign) IBOutlet NSTextField *workingFileLabel;
@property (nonatomic,assign) IBOutlet NSTextField *workingFileSizeLabel;

@property (nonatomic,assign) IBOutlet NSButton *clearButton;

-(IBAction)onClearButtonClicked:(id)sender;

All IBOutlets have been connected from the Interface Builder.
I'm using this code inside the view controller to move the custom NSImageView...
-(void)awakeFromNib
{
    //dragAndDropImageView frame
    NSRect ddivFrame = [dragAndDropImageView frame];
    ddivFrame.origin.x = SOME_NUMBER;
    ddivFrame.origin.y = SOME_NUMBER;

    [dragAndDropImageView setFrame:ddivFrame];
    [dragAndDropImageView setNeedsDisplay:YES];

}

...But nothing happens!
Using NSLog I've found that the frame "x" and "y" have been updated, but it is displayed in the old position! Any clues?
Thanks

A: I have found a solution:
-(void)awakeFromNib
{
    //dragAndDropImageView frame
    NSRect ddivFrame = [dragAndDropImageView frame];
    ddivFrame.origin.x = SOME_NUMBER;
    ddivFrame.origin.y = SOME_NUMBER;

    [[dragAndDropImageView animator] setFrame:ddivFrame];

}

This works flawlessy!

A:
dragAndDropImageView and clearButton are centered inside the view. In awakeFromNib I set them offscreen, and then I use a NSAnimation to slide them in.

Why not set them as hidden/alphaValue to 0 in the nib, and then have your NSViewAnimation both show them (fade them in) and move them into position?


text:
Q: sonarqube 5.1 temp/tmp directory fills up -- how can I tell what can be deleted? I have found many posts that indicate that these files will be cleaned up after one week (my temp/tmp has files over one month old). Some say restarting sonarqube will clean these out (does not work for me to restart the application due to continuous integration). Some posts claim that this is fixed in the next sonar and sonarqube release.
How do I know (definitively) when it is safe to delete the content from temp/tmp directory without impacting the analyses? Currently there is 31 GB of data and I badly need to reclaim that space!
any pointers are welcome!

A: Indeed, this question looks actually like a duplicate of SonarQube Temp Disk Space and this issue is a known one. And it's been fixed in SonarQube 5.1.2.
See https://jira.sonarsource.com/browse/SONAR-6700 for details.
If you can't upgrade, then you can just remove old temporary files by yourself in the meantime. Something like :
find $SONARQUBE_TMP_DIR -type f -mtime +7 -exec rm -f "{}" \;

should do the trick (the +7 is to say MORE (+) than 7 days old for last modification, mtime is modification time, adapt if you want more or less).
Warning: do NOT put less that +7. I did it some weeks ago and it crashed our instance. My guess here is that since SonarQube is supposed to automatically clean up things older than 7 days, it might still be using files old less than 7 days... Hence, leave them alone ;-).

A: Best solution I found is to restart sonarqube. It took some time to remove the tmp files, but restarting it definitely did the trick.


text:
Q: Warning: substr() expects parameter 2 to be long Why am I  getting this error while using substr:

Warning: substr() expects parameter 2 to be long`

$url = "http://coast.x-matic.net/forums/categories/pso-news";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$webdata = (string) curl_exec($ch);
curl_close($ch);

echo substr($webdata, "<a * class=\"title\">*</a>");

A: Ref:  http://php.net/manual/en/function.substr.php
Syntax of substr : string substr ( string $string , int $start [, int $length ] )
echo substr($webdata, 0, 5); should be some thing like this.


text:
Q: Apex Log manager needed, or way how to filter big amount of logs I'm looking for some tool, or extension for managing/ searching Apex logs.
My main problem is I can produce very easily, a lot of logs by myself and ofc I'm not alone.
Basically, when I reload one site, I'm working on, I can create up to 70 logs and if someone is working in the same time, is very problematic to find anything.
I would like something that allowed me to filter logs by user, time and phrase. It would be really nice if I would be able to delete those logs as well.
I'm working on VS Code and unfortunately I couldn't find any extension like that, but as far I know there is a tool like that in intellij.
I found Maven extension for chrome, it doesn't have those filters. It works, but I have a problem, that every time I have to select my last 40 logs by myself or search phrase through 2000 logs.
I saw also that I can use CLI's command sfdx force:apex:log:get but by this way I can only retrieve up to 25 logs. (and also I have problems with user filtering I feel it is not good describe)
And the last way is to use a query and select logs and later use a loop with HTTP Request inside.
But I don't feel its the best solution.
Please guys help me. I'm struggling with that for a while.


text:
Q: Android resource: array of strings with key/id? I need to create a Spinner(or exposed dropdown menu) where the user can select a duration, in this case an amount of days. Something like
one day
two days
three days

Later on I want to translate this app, so I can't use the displayed text in my code, e.g. something like
if(item.equals("one day"))

will fail for other languages than english.
So I want to have a "display value" (what's shown to the user, like "one day") and a technical id/key, something like "1DAY". How can that be done with Android resource files?
I finally want something like this:
<!-- give a technical key 1DAY/2DAYS/3DAYS etc to the items -->
<!-- this is just a mockup - how could something like this be really done? -->
<string-array name="duration">
    <item key="1DAY">@string/one_day</item>
    <item key="2DAYS">@string/two_days</item>
    <item key="3DAYS">@string/three_days</item>
    <!-- and so on -->
</string-array>

<!-- these strings could be translated -->
<string name="one_day">one day</string>
<string name="two_days">two days</string>
<string name="three_days">three days</string>

A: if(item.equals(getResources().getString(R.string.one_day)))
This will retrieve the correct string value from the correct language.
See this post for reference.

A: Another option is to use the attribute tag.  Tag save a key on your view, for example, you can create an enum like this:
enum class Days {
  ONE,
  TWO,
  THREE
}

And map your tag:
fun map(days: Days): Int =
    when(days) {
      ONE -> R.string.one
      TWO -> R.string.two
      else -> R.string.x
    }

So, the data to pass the view is:
val exampleDays = Days.ONE
val textId = map(exampleDays)

your_view.text = getString(textId)
your_view.tag = exampleDays

To recover the value, only fetch the tag:
val tag = your_view.tag as Days // cast in Kotlin
if (tag == Days.ONE)

With this approach avoid duplicate strings and is a good way to work with clean architecture.


text:
Q: Django form submit url not working I'm new to Django and cannot figure out why my form is not working. It seems that after form submit even though the url is being changed to /82nsj/update it is still going to the index method in the view.
Views
from business.models import Business, Token
from django.shortcuts import render
from business.forms import BusinessForm

def index(request, token):
    try:
        business = Business.objects.get(token__token=token)
    except Token.DoesNotExist:
        business = None
    except Business.DoesNotExist:
        business = None

    form = BusinessForm(instance=business)
    return render(request, 'business/index.html', {'form': form})

def update(request, token):
    try:
        business = Business.objects.get(token__token=token)
    except Token.DoesNotExist:
        business = None
    except Business.DoesNotExist:
        business = None

    form = BusinessForm(request.POST, instance=business)
    if form.is_valid():
        form.save()
        return render(request, 'business/index.html', {'form': form})

Urls
url(r'^$', 'business.views.index', name='home'),
url(r'^business/(?P<token>\w+)/', 'business.views.index', name='business'),
url(r'^business/(?P<token>\w+)/update/', 'business.views.update', name='business_update'),

Forms
self.helper = FormHelper(self)
self.helper.form_class = 'form-horizontal'
self.helper.form_action = 'update/'
self.helper.form_method = 'post'
self.helper.layout = Layout(
    HTML("
Please confirm your business contact information is updated and correct.
"),
    Div(
        'my',
                'fields',
        FormActions(
            Submit('save_changes', 'Save changes', css_class="btn-primary"),
        ),
        css_class='row-fluid'
    )
)

I know this isn't working because I have breakpoints setup in my index and in my update and after I press the submit button only the index breakpoint is being reached.
What am I doing wrong that is preventing the update method from running on form submit?

A: It's probably an issue with your url(... regex.
Django will go to the first URL that matches so if you have this
url(r'^business/(?P<token>\w+)/', 'business.views.index', name='business'),
url(r'^business/(?P<token>\w+)/update/', 'business.views.update', name='business_update'),

going to /business/<token>/anything_goes_here will always go to business.views.index.
To stop this, include a $ for end of expression.
url(r'^business/(?P<token>\w+)/$', 'business.views.index', name='business'),

Now your /business/<token>/update/ wont match the first URL and will then match business.views.update.


text:
Q: Determining the number of complex roots (including multiplicities) of a polynomial Could someone please explain/show me how to determine the number of complex roots including multiplicities of a polynomial such as
$P(z):= 5i z^{37} - (6 +2i)z^{4} + 4z^2 - i$
Would i need to factorise it so it is in the form
$P(z) = a_n(z - w_1)(z- w_2)...(z-w_n)$?
I know that every polynomial of degree $n \geq 1$ has preciely $n$ roots in $\mathbb C$..
Otherwise is there a quick and easy way of doing such a thing? Or is there a theorem i could use?
Any help much appreciated. Thank you.

A: As you said, the fundamental theorem of algebra says that every polynomial of degree $n$ with complex coefficients has $n$ complex roots (counting multiplicity). So your polynomial has 37 roots in $\Bbb C$ (again, counting multiplicity.)


text:
Q: When does Linux send a root mail and how to force it for testing purposes? Let's say I want to test root mail functionality after I set up nullmailer, how do I force my Debian Linux system to send a root mail?
And furthermore on which events does Linux send root mails at all?

A: I understand that you want the system to write an email to root, do it like this:
echo "Test" | mail -s "Test " root

Q: And furthermore on which events does Linux send root mails at all?

That depends entirely on your configuration.

A: To answer upon which events. This is very common from root's cron jobs that produce output. In recent times a lot of admins are receiving the MySQL warning about command line credential use.....
These can be sent to root, but root's mail can be redirected to an alias.
Further, any script run by root might send mail explicitly, although utility accounts are advised for this sort of thing.  Logwatch, Fail2Ban, Denyhosts and any number of serious exceptions might warrant an email, an asynchronous and somewhat passive notification.


text:
Q: make exe file automatically run as administrator Is there any way to make an .exe file runs automatically as administrator?
Suppose that I logged in with a Guest user in my Windows; now when I want to run some programs such as resmon.exe it requires to run it as Administrator and the below windows pop up :

I want to know, if I have password of the Administrator, is there any way to make this process automatically done when I double click on resmon.exe ?

Update :
I do a right-click on the program and select properties and change the settings in security tab as below :

But when I want to check Run this program as Administrator in compatibility tab, it is not active! why?

Note : I test other files that those are not in Windows directory,and all the options in compatibility tab are active. I move the resmon.exe file from Windows directory to another drive (D:) and options activated!!! why?

A: In the properties of the exe you can set a compatibility option for this. There is also a PE within the SysInternals Suite called ShellRunAs.exe that may prove useful.
update:
For system executable files that will not let you edit compatibility options you might be able to work around this by creating a shortcut of that exe and then within the properties of that shortcut you can select "Advanced" and set "run as admin".
If that does not work for your use case then the solution would likely require custom registry edit, which might not be appropriate to mention here.


text:
Q: How to scan for bluetooth devices with kotlin I am writing an android app in kotlin and I want to scan for nearby bluetooth devices and NOT the ones previously paired and I am NOT using BLE.
So far I have tried to use the bluetooth adapter's function startDiscovery() that will supposingly start descovering devices but nothing happens. According to the developer.android.com it should scan for 12 seconds. In my code it stops immediately after startin. The code below is what I have so far. I will put the recycleView adapter as well so that everyone can easily test the app.
RecycleView Adapter
package com.example.andruino_bt

import android.bluetooth.BluetoothDevice
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.activity_main_recycle_view.view.*

class RecyclerAdapter(private val devices: ArrayList<BluetoothDevice>) : RecyclerView.Adapter<RecyclerAdapter.DeviceHolder>(){

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DeviceHolder {
        val inflatedView = parent.inflate(R.layout.activity_main_recycle_view, false)
        return DeviceHolder(inflatedView)
    }

    override fun getItemCount(): Int {
        Log.i("", devices.size.toString())
        return devices.size
    }

    override fun onBindViewHolder(holder: DeviceHolder, position: Int) {
        val itemDevice = devices[position]
        holder.bindDevice(itemDevice)
    }

    class DeviceHolder(v: View) : RecyclerView.ViewHolder(v), View.OnClickListener {

        private var view: View = v
        private var device : BluetoothDevice? = null

        init {
            v.setOnClickListener(this)
        }

        override fun onClick(v: View) {
            Log.i("RecyclerView", "CLICK!")
        }

        fun bindDevice(device: BluetoothDevice) {
            this.device = device
            val name = "Name: ${device.name}"
            view.device_name.text = name
            val address = "Address: ${device.address}"
            view.device_add.text = address
            Log.i("RecyclerView", device.name.toString())
        }

        companion object {
            private val PHOTO_KEY = "PHOTO"
        }
    }
}

Inflate function (in separate file)
package com.example.andruino_bt

import android.support.annotation.LayoutRes
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View {
    return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot)
}

Main Activity
package com.example.andruino_bt

import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import android.support.v4.widget.SwipeRefreshLayout

class MainActivity : AppCompatActivity(){
    private lateinit var linearLayoutManager: LinearLayoutManager
    private lateinit var m_pairedDevices: Set<BluetoothDevice>
    private lateinit var adapter: RecyclerAdapter

    private var m_bluetoothAdapter: BluetoothAdapter? = null
    private val REQUEST_ENABLE_BLUETOOTH = 1
    private val devices_list : ArrayList<BluetoothDevice> = ArrayList()
    private val swipeContainer: SwipeRefreshLayout? = null

    companion object {
        val EXTRA_ADDRESS: String = "Device_address"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        supportActionBar?.hide()

        m_bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if(m_bluetoothAdapter == null) {
            Toast.makeText(this, "this device doesn't support bluetooth", Toast.LENGTH_SHORT).show()
            return
        }
        if(!m_bluetoothAdapter!!.isEnabled) {
            val enableBluetoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableBluetoothIntent, REQUEST_ENABLE_BLUETOOTH)

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

        }else{
            discoverDevices()
        }

        findViewById<SwipeRefreshLayout>(R.id.swipeContainer).setOnRefreshListener{

            devices_list.clear()
            discoverDevices()
        }

    }

    private val mReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (BluetoothDevice.ACTION_FOUND == action) {
                // A Bluetooth device was found
                // Getting device information from the intent
                val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                devices_list.add(device)
            }
        }
    }

    private fun discoverDevices(){
        if (m_bluetoothAdapter!!.isDiscovering) {
            // Bluetooth is already in mode discovery mode, we cancel to restart it again
            m_bluetoothAdapter!!.cancelDiscovery()
        }
        val bool = m_bluetoothAdapter?.startDiscovery()
        Log.i("", bool.toString())
        val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
        registerReceiver(mReceiver, filter)

        linearLayoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager = linearLayoutManager

        adapter = RecyclerAdapter(devices_list)
        recyclerView.adapter = adapter
        findViewById<SwipeRefreshLayout>(R.id.swipeContainer).isRefreshing = false
        unregisterReceiver(mReceiver)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
            if (resultCode == Activity.RESULT_OK) {
                if (m_bluetoothAdapter!!.isEnabled) {
                    Toast.makeText(this, "Bluetooth enabled", Toast.LENGTH_SHORT).show()
                    discoverDevices()
                } else {
                    Toast.makeText(this, "Bluetooth disabled", Toast.LENGTH_SHORT).show()
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Toast.makeText(this, "Bluetooth enabling has been canceled", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

As a layout I use a RecycleView in a swipeContainer for refreshing. Also in the manifest I have the below permissions:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

The biggest part of the code was found here (recycleView) and here (bluetooth). Note that the initial bluetooth code in the link is set to find previusly paired devices. That part worked greate form me but it wasn't what I wanted.
Sorry for the long post and if you need any more info tell me in a comment so I add that too. Thanks in advance.

A: You unregister the receiver when you start the discovery.
Move this: unregisterReceiver(Received) to onStop
and registerReceiver to onStart

A: Try to use startDiscovery() method before getDefaultAdapter(), or even the enable() method.
For more information, check this: BluetoothAdapter


text:
Q: mschart y-axis min / max setting issue (possible glitch?) C# I have a problem with setting the maximum and minimum values for the y-axis of my mschart.
When setting the max or min to a value, say 10.025, the value the chart sets as max is 10.024999618530273.
mainChart.ChartAreas[selectedChartArea].AxisY.Maximum = GetRoundYAxisMax(newYMax, newYRange);
mainChart.ChartAreas[selectedChartArea].AxisY.Minimum = GetRoundYAxisMin(newYMin, newYRange);

The GetRoundYAxisMax method just returns a "round" value. Code below.
private float GetRoundYAxisMax(double calculatedMax, double yAxisRange)
        {
            double rangeFactor = 0;

            if (yAxisRange > 10)
                rangeFactor = 1;
            else if (yAxisRange > 1)
                rangeFactor = 4;
            else if (yAxisRange > 0.1)
                rangeFactor = 40;
            else if (yAxisRange > 0.01)
                rangeFactor = 400;
            else if (yAxisRange > 0.001)
                rangeFactor = 4000;
            else if (yAxisRange > 0.0001)
                rangeFactor = 40000;
            else
                rangeFactor = 400000;

            float returnValue = (float)(Math.Round(calculatedMax * rangeFactor, MidpointRounding.ToEven) / rangeFactor);
            return returnValue;
        }

The rounding code evaluates properly and returns a correctly rounded value, but when setting this value to the max or min value on the y-axis it sets a value very close to it, but not rounded.
Any ideas why this is happening?

A: You can set the axis label style to round the un-rounded values:
mainChart.ChartAreas[selectedChartArea].AxisY.LabelStyle.Format = "#.###";

A: Just answering why 10.024999618530273 rather than 10.025.
Nothing on a computer is infinite in precision.  You have ( IIRC ) 80 bits to represent your number.  Part is exponent part is mantissa.  What is happening is that 10.025 is not a number that has perfect representation in that number of bits.  You dont get the whole number line, you get integral marks along it.  ( take a random 80 bit double.  That is a point on the number line.  Now, add the smallest increment to that 80 bit double that is possible.  Another  point on the line.  Now, in the "real" ( pun intended ) world, there are an infinite number of real points.  Any point on the line you try to represent on a real world number line will be represented as one of the two points that bound that point in the 80 bit world ).


text:
Q: horizontal centering within \valign cells I'm trying to use \valign to make an array of items. (See my self-answer to another question.) I'm doing this because I want to specify the items per column instead of per row, and because I want control over the spacing. I'm using LaTeX but these are plain-tex macros.
I'm happy with the following, except that the items are not vertically centred within their column, so this question is about how to achieve that.
\documentclass{article}
\usepackage{amsmath}

% this can't be an environment because the code for \end can't have parameters.
\newcommand{\colarray}[3]{
\vcenter{\hbox{\valign{&\vfil\vbox{\parindent=0pt\tabskip=#2\hsize=#1##}\vfil\cr%
#3%
}}\vskip-#2}%
}

\newcommand*\col[1]{#1\cr}

\begin{document}

\begin{equation}
    x = \colarray{4mm}{2mm}{
        \col{1 & 2 & 3}
        \col{4 & 5 & \Big(6\Big)}
    }
\end{equation}

\end{document}

This produces

From my current rather hazy understanding, centering the items should involve putting each one in an \hbox and using \vfil. However, if I try that the results are not as expected:
\documentclass{article}
\usepackage{amsmath}

% this can't be an environment because the code for \end can't have parameters.
\newcommand{\colarray}[3]{
\vcenter{\hbox{\valign{&\vfil\vbox{\parindent=0pt\tabskip=#2\hsize=#1\hbox to #1{\hfil##\hfil}}\vfil\cr%
#3%
}}\vskip-#2}%
}

\newcommand*\col[1]{#1\cr}

\begin{document}

\begin{equation}
    x = \colarray{4mm}{2mm}{
        \col{1 & 2 & 3}
        \col{4 & 5 & \Big(6\Big)}
    }
\end{equation}

\end{document}

Here's the result:

As you can see the '3' is horizontally aligned differently from the '1' and '2', and the '(6)' is not horizontally centred with respect to the '4' and '5'.
I am not able to work out why this is, so my questions are (1) why is this happening, and (2) how can I fix it?

A: You need to remove the spaces before each & in your usage of \colarray, as they are significant when they get substituted in the inner \hbox. Alternatively, replace ## with $##$ in the definition of \colarray. Also, I don't think 4mm is big enough for the parenthesized "6"; to align the columns, you will need to increase it.
By the way, you do not need to set \parindent and \hsize in your second attempted solution.

A:
This is similar to RobertR's suggestions, but as a full example.
\documentclass{article}
\usepackage{amsmath}

% this can't be an environment because the code for \end can't have parameters.
% ?? It would be more natural as an environment with \\ like array
\newcommand{\colarray}[3]{%
\vcenter{\hbox{\valign{&\vfil\tabskip=#2\hbox to #1{\strut\hfil$##$\hfil}\vfil\cr%
#3%
}}\vskip-#2}}

\newcommand*\col[1]{#1\cr}

\begin{document}

\begin{equation}
    x = \colarray{5mm}{2mm}{
        \col{1 & 2 & 3}
        \col{4 & 5 & \Bigl(6\Bigr)}
    }
\end{equation}

\end{document}


text:
Q: How can this class with another class collection inside it be better written/designed and what is wrong with this current implementation? class A
{
    public int MyProperty { get; set; }
    public List<B> B { get; set; }
}

 class B
{
    public int MyProperty { get; set; }
    public string MyProperty1 { get; set; }

    public static List<B> CreateB(int [] parameter, string str, int number)
    {
        var bList = new List<B>();

        foreach (var item in parameter)
        {
            var b = new B();
            b.MyProperty = number;
            b.SetProperty1(str);

            bList.Add(b);
        }
        return bList;
    }

    private void SetProperty1(string s)
    {
        //logic here applied to 's'
        this.MyProperty1 = s;
    }
}

class Program
{
    static void Main(string[] args)
    {
        int id = 123;
        int [] array = new int[] { 1, 2, 3 };

        var A = DataBase.GetListOfA(id);
        UpdateB(A, array);
    }

    public static void UpdateB(List<A> data, int[] numbers)
    {
        var array = new int[] {5,10,15};
        var str = "hi";
        var number = 1;

        foreach (var item in data)
        {
            if(item.B == null || item.B.Count == 0)
            {
                item.B = new List<B>();
                item.B = B.CreateB(array, str, number);
            }
            else
            {
                //B.UpdateB(/*parameters here*/);
            }
        }
    }
}

Class B is directly related to A but cannot be inside A because the amount of class B's per A is dynamic and varies.
I'm not sure how to ask for help regarding this but should class B not be creating a list of itself using a static method?
Should B be separated from A if possible or could I simply create B inside a method that fills the property inside A.
For instance a Create A method that takes some parameters to set every property in A thereby also creating B in said method?

A:
create B inside a method that fills the property inside A.
For instance a Create A method that takes some parameters to set every property in A thereby also creating B in said method

That is what I would do.  This is the approach more closely aligned with the Single Responsibility Principle.  B doesn't need to know that it is one item in an array, it just needs to represent a B object.  A knows that it contains a list of Bs so it should manage that list.

A: I am short on time, so I'll provide a suggestion regarding this one part of your question: "I'm not sure how to ask for help regarding this but should class B not be creating a list of itself using a static method?"
I would make CreateB return only a single B.  If you have a bunch of parameters that you need to make into B's (for example, an array of ints), then I would use LINQ like this:
List<B> theBees = parameter.Select(param => B.CreateB(param, str, number)).ToList();

Vladmir Khorikov talks about constructors in his excellent Pluralsight course on functional programming in C#.  Check out the Create method Vladmir defines on this Email class.  I think it's a super clean way to handle object creation and validation.


text:
Q: Facebook div empty html:

js:
$(document).ready(function(){
    window.fbAsyncInit = function() {
        FB.init();

        FB.getLoginStatus(function(response){
            runFbInitCriticalCode();
            console.log(response);
        });
    };

    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/ru_RU/all.js#xfbml=1";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
});

After the code executes, the div is filled with iframes and other facebook tags, but it's empty. I don't see anything in the page, so what can be the problem?

A: Replace facebook-jssdk with fb-root in js file second last line in given code.
(document, 'script', 'fb-root'));

A: Try this code:

In my case facebookAppId is a JavaScript variable with your Facebook application id. You need to create one here. Only after this you can take advantage on their JS API.
More info here.


text:
Q: I want to Print multiple lines of Text using a JTextPane to a window I've search this question in different wording for the past day or two now and I just can not solve it :/,
I have Window that pops up on the screen that looks like a Command Prompt there is a two buttons Run and Stop. Anyways I have on the screen once you press start it starts "Scanning files" It says "Scanning 1-1900 something" counts up to 1900 and then says Scan completed, after that I want text to go Under the existing Text
and write multiple lines of text to mess with my friend for example.
{
Scan Completed
"wait time inbetween each line of text"
Hack initialized
"wait time inbetween each line of text"
Hack installing...
"wait time inbetween each line of text"
Hack installed
ECT
}

Hopefully someone can Help me, every one I looked at did not work with my code :/
I'm new to code as well so...
thanks in advance anyways here my code its not to long :P.
   public static void main(String[] args) throws IOException {

        JFrame frame = new JFrame("Happy Monday v0.05");
        Container contentPane = frame.getContentPane();

        JTextPane jta = new JTextPane();

        JButton button = new JButton("Run");
        JButton buttonstop = new JButton("Stop");

        contentPane.add(button);
        contentPane.add(buttonstop);

        button.setBounds(-1,283,465,40);
        buttonstop.setBounds(465,283,469,40);

        frame.add(jta).setBackground(Color.black);
        console(jta);

        //Window
        frame.setSize(950, 650 / 16 * 9);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

            button.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                new SwingWorker<Void, Object>(){
                    @Override
                    protected Void doInBackground() throws Exception {
                        outputTest("Scanning...");
                        return null;

                    }}.execute();
            }});

    }

    //Testing OUTPUTS:/
    public static void outputTest(String msg){
        for(int i=0;i<1969;i++){
            System.out.println(i+" "+msg);
            try {
                Thread.sleep(01);
                System.out.println("Scan Complete");

            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void console(final JTextPane area) throws IOException {
        area.setContentType("text/html");
        final PipedInputStream outPipe = new PipedInputStream();
        System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
        new SwingWorker<Void, String>() {
            @Override
            protected Void doInBackground() throws Exception {
                Scanner s = new Scanner(outPipe);
                while (s.hasNextLine()){
                    String line = s.nextLine();
                    publish(line + "\n");
                }
                return null;
            }
            @Override
            protected void process(List<String> chunks) {
                for (String line : chunks){
                    area.setText(""+line+"");
                    }
                 }
        }.execute();
    }

}

A: The setText method does not appends the line.It overrides the text.So previous text won't be visible.
You have to append text, but have to find an mechanism for that as append method do not exist. In your console method, you can add these:
Document doc = area.getDocument();
Thread.sleep(2000);
doc.insertString(doc.getLength(),"hack installing....\n", null);
Thread.sleep(2000);
doc.insertString(doc.getLength(),"Hack installed...\n", null);

Note:
Calling Thread.sleep() is not recommended directly as you are using multi-threaded environment.It's just for your example haven't scanned your code.

A: public class NotEditableOutputArea extends JTextPane {

        public NotEditableOutputArea() {
            setEditable(false);
            DefaultCaret caret = (DefaultCaret) getCaret();
            caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
            Font defaultFont = new Font("monospaced", Font.PLAIN, 12);
            setFont(defaultFont);
        }

        public void appendColorText(String text, Color c) {
            StyledDocument doc = getStyledDocument();
            Style style = addStyle("Style", null);
            StyleConstants.setForeground(style, c);
            try {
                doc.insertString(doc.getLength(), text, style);
            } catch (BadLocationException e) {
            }

        }

        public void setColorText(String text, Color c) {
            setText(null);
            appendColorText(text, c);
        }
    }


text:
Q: How do I use a Controller Action to refresh the model without navigation? I have a MVC 5 website that displays log file entries in a grid and provides a search capability. I have both the search criteria and the grid.mvc grid on the Index page. When the user enters the search criteria and clicks the submit button I want the ProcessLogEntries method (below) to update the Model and refresh the Index.cshtml page - not navigate to a non-existent ProcessLogEntries page!
Basically, I want this application to behave like an Single Page Application...
How do I set up the HomeController.ProcessLogEntries() method to accomplish this?
public class HomeController : Controller
{
    public LogsResearchViewModel ViewModel  { get; set; }

    public HomeController()
    {
        ViewModel = new LogsResearchViewModel();
    }

    public ActionResult Index()
    {
        ViewBag.Message = "";
        return View(ViewModel);
    }

    [HttpPost]
    public ActionResult ProcessLogEntries(string txtSearchFor, string txtDateStart, string txtDateStop, string txtSource)
    {
        ViewBag.Message = "";

        string searchFor = txtSearchFor.ToString();
        DateTime start = DateTime.Parse(txtDateStart.ToString());
        DateTime stop = DateTime.Parse(txtDateStop.ToString());
        string source = txtSource.ToString();

        ViewModel.GetProcessLogEntries(searchFor, start, stop);
        ViewModel.GetErrorLogEntries(source, searchFor, start, stop);

        return View(ViewModel);
    }
}

A: If you want to update a page without reloading you'll need AJAX. Here's an outline to get started.
Partial View
Create a main view that will act as a "frame". An empty div will act as your placeholder for your grid.

Main View

Now create a partial view to hold your grid
_GridPartial
@model LogsResearchViewModel

@Html.Grid(Model)
<button id="btnTrigger">Process</button>

If you want you can embed this so the first time Main view loads you will have a populated grid.

Main View

@{Html.RenderAction("LoadGrid")}

With the supporting action
public ActionResult LoadGrid()
{
    var model = new LogsResearchViewModel() { ... };
    return PartialView("_GridPartial", model);
}

Now setup the AJAX to insert into the placeholder.

And the action returns a partial view
[HttpPost]
public ActionResult ProcessLogEntries(
    string txtSearchFor, string txtDateStart,
    string txtDateStop, string txtSource)
{
    var model = new LogsResearchViewModel();
    // ...
    return PartialView("_GridPartial", model);
}

After triggering the post the partial result replaces the grid div content.
JSON
If your grid supports JSON just return the model
 [HttpPost]
 public ActionResult ProcessLogEntries(...)
 {
     var model = new LogsResearchViewModel();
     // ...
     return Json(model);
 }

Then handle in javascript
...
.done(function(jsonResult) {
    console.log(jsonResult);  // should match LogsResearchViewModel
    loadGrid(jsonResult);     // pass off to grid's javascript
});

A: You will need to return your model. You can keep your view and extract via javascript the model from the view, or you can have a JsonResult and return only the serialized string.
From javascript side, trigger this from a button or the event of your wish.
var params = ["data","data", "data"];

$.ajax({
  type: "POST",
  url: /ProcessLogEntries,
  data: params,
  success: function(data, statusRespoonse, xhr){
   //extract your model from data or return your model via jsonresult by changing the Controller's return type.

    yourModel = data;
   },
  dataType: "json"
});


text:
Q: Making array populations in functions instantaneous I set an array
let A1 = []
then create a function to populate the array
function popA1() {
  let x = new Array(v1, v2, v3, vn);
  return A1 = x;
}

function basicTableGenerator(myArray) {
    let result = "

Table
";
    for(let i=0; i<myArray.length; i++) {
        result += "
" + myArray[i] + "
";
    }
    result +=
";
    return result;
}

and that function is called by a button click
button.addEventListener("click", () => {
  if (A1.length == 0) {
    popA1();
  }
  generateTableFromA1(A1);
}

It works well and all, except for the tiny fact that generateTableFromA1() won't work until the second time I click that button, how do I get it to work the first time?

A: function popA1() {
  let x = new Array(v1, v2, v3, vn);
  A1 = x;
}

try to remove return


text:
Q: Control stays with previous app after four-finger swipe? On my mac (Sierra, OS 10.12.6), I have it set so that I can swipe between different desktop screens with four fingers on the trackpad. But when I do this, the "control" stays with the app that was in use on the previous screen.
I.e., if I am using the Messages app, but then four-finger swipe to change to the screen where Google Chrome is open, and then I start typing, the text is entered into a conversation in Messages (only noticeable after scrolling back to the previous screen), not into Chrome.
Is there a setting that can change this behavior? It is always counterintuitive to have the app that's visible on my current desktop not actually be the one I'm controlling.
EDIT
I just found that this issue occurs consistently when switching between screens with Messages and Chrome, but doesn't seem to happen for all apps. E.g., when I switch between screens with Notes and Chrome, the control switches to the new app as desired.

A: This is unexpected behaviour. There is no setting for this. Does this also happen when you switch to a different virtual desktop with the keyboard shortcut ctrl + left/right arrow key?
I would usually tell people to trash the plist that holds any related settings but it seems that com.apple.desktop.plist doesn't exist anymore in Sierra.
Installing sierra over the current install could mend your issue. Best to have the latest installer for sierra in that case and not an older version than you already have installed. This will, by the way, not delete you stuff. It will install the OS over whatever is already there. You can only loose stuff if you go erase the disk first before installing.
Talking about re-installing, can you not install a later version of OSX? Maybe High sierra?


text:
Q: Unable to connect to server wen running c# test (Nunit) I want to run the test in c# but it gives me the following error:
System.Net.WebException :Unable to connect to the remote server ..>System.Net.Sockets.SocketException: No connection could be made becausethe target machine actively refuces it 127.0.0.1:4444 .
How can i solve?

A: Connecting to Web Resources is not part of Unit Testing.
In Unit Tests, such calls are replaced by other items which provide the same interface and are configured in a way useful for the test - that's often called "mocking".
You may write the mock classes on your own, or yo can use frameworks, e.g. Moq, RhinoMocks, etc.


text:
Q: Any way to compile Python 3.4 program to exe? Except py2exe, pyinstaller or cx-freeze I have coded selenium Python script and now I want to compile it to exe file so it can run on computer without Python installed
I've tried to install cx-freeze and pyinstaller but failed to do so and wasn't able to find the patch for the errors I am getting while installing these modules
I have installed py2exe but its not able to convert selenium Python to exe
Whenever I execute I keep getting error msg
I want to use chromedriver, here's the error I am getting

FileNotFoundError: [Errno 2] No such file or directory: 'selenium\\webdriver\\re
mote\\getAttribute.js'

A: You have to manually copy the selenium folder in the root of your project, (this is what the message says) because it include contents that can't be compiled (such as getAttribute.js)


text:
Q: Index duplicate error in pandas when there are no duplicates I have a dataframe with a datetime index and then I try to convert it to json using to_json() I get an error saying:
ValueError: DataFrame index must be unique for orient='columns'

However my index column should have unique values. I tried df.duplicates() and got this:
time
2018-01-28    False
2018-02-04    False
2018-02-11    False
2018-02-18    False
2018-02-25    False
              ...
2019-12-29    False
2020-01-05    False
2020-01-12    False
2020-01-19     True
2020-01-26    False
Length: 112, dtype: bool

You can clearly see that the second to last column is marked as a duplicate when it's not. I also tried drop_duplicates(keep='last') but I still got the same error.
Why is this happening?

A: the problem is that your index has duplicates, Series.drop_duplicates eliminates series with duplicate values (values, not in index).
Your error:

DataFrame index must be unique

Use groupby.first:
s.groupby(s.index).first()

for each unique index we select the first value


text:
Q: Why does Firebase observeEventType return a snapshot everytime in viewWillAppear? I have a query that is observed on viewWillAppear on View Controller A
let query = FIRDatabase.database().reference().child("tags").
    queryOrdered(byChild: "users/uid").queryEqual(toValue: userId)

In the same view controller, in viewDidDisappear I remove this observer.
So let's say I push into another view controller from View Controller A.
When I come back to View Controller A, the observer returns a snapshot, even though my data on the backend hasn't changed.
I only want a snapshot returning if there's been some actual change to my database. How do I solve this problem? Thanks.

A: One answer is to simply let the observer do it's job and update your data in the background.
So if the user is on controllerA the observer updates a datasource (an array) so then the UI is updated from that array.
When the user switches to controllerB, the observer can still update the array, but don't update the UI in controllerA since there's no need to.
When the user switches back to A you'll have current data available so just reload the tableView (assuming iOS here) from the array.
This solution reduces the 'polling' nature and let's Firebase do the heavy lifting to notify your app when it needs to. You're just reloading the tableViews from an array when that controller becomes active.
Edit
The idea here is to add the observer once - perhaps when the view loads the first time only (viewDidLoad) or maybe in your app delegate. Once you add the observer it will update your dataSource arrays when data changes so when you move from view to view the only action needed will be to reload the tableView from the updated array.
There are times when you may want to remove an observer but it doesn't sound like you need to do that from your question. So - attach the observers once and let them update the dataSource arrays as the data changes. Reload your tableViews when switching views.

A: *

*You have put the query in viewWillAppear, which means every time you come to viewController A, this query will be executed irrespective of you have removed the observer or not.

*Try putting the same query in viewDidLoad which means, the query will be called once and don't remove the observer anywhere. Now the query would be called only when data gets changed in firebase.


text:
Q: Blackberry text and button focus issue Hi so i have a screen which contains a labelfield with a lot of text in, then at the bottom of the screen there is a button.
As the button has focus when the screen is shown, only the bottom section of the label is visible and its not possible to scroll as only the button can gain focus.
How does i fix this?

A: You can change LabelField to RichTextField. Another option would be to add NullField before adding LabelField.

A: By adding an empty field on the top of the screen with a lesser layout and override the drawFocus() method and leave it blank, Thus, the empty field would be focussed first and since it is over ridden it doesnot show any effect. And one could see the text, which is written on the beginning of the screen.
Hope it solves your problem.
Happy Coding
Cheers.

A: Instead of label field, add rich text field and give focus for it like this
RichTextField rt  = new RichTextField("text",  RichTextField.FOCUSABLE );


text:
Q: How to justify that this set if infinite I have a doubt about how to justify why this set is infinite.
The question (about the set I'm talking about) is this:
"
a and b are real numbers.
a < b
So a < (a+b)/2 < b
which means the set a < x < b (x being a real number too) is not empty.
But it's also infinite. Explain why."
So I took the definition of an infinite set, which is "having an injective function with domain N and codomain ]a,b["
But now I'm thinking... If x is a real number, why can't our injective function have domain R... Is it impossible to happen? Or is it best to choose N as the domain because it's more guaranteed?
It's just a detail, but it made me think about it...
Thanks!

A: If your injective function has domain $\Bbb R$ you have proved even more.  You have proved that the codomain is uncountably infinite (which it is here), but you were not asked for that.  You have found one number in $(a,b)$, which can be the image of $1$.  Now can you use the number you found to find another?  That one can be the image of $2$ and so on.

A: $\{a < x < b\}$ is not empty so there is a number $x_0$ in the set so $a< x_0 < b$.  But is $\{a < x < x_0\}$ Empty?  Nope for the same reason you gave.  So there is a number $x_1$ such that $a < x_1 < x_0 < b$.  Repeat inductively to get an infinite number of these $x_i$ all of which are in $\{a < x < b\}$
or… you have found the midpoint of $a$ and $b$ is $\frac{a+b}2$.  What is the midpoint of $a$ and $\frac{a+b}2$?  What is the midpoint between $a$ and that midpoint?  And between $a$ and the midpoint of that?


text:
Q: Windows 7 installation Bootable usb not detected while installing alongside windows 10 I am trying to install windows 7 side by side with windows 10, as I am tired of headache that windows 10 gives me and also dont want to lose original windows copy from which I upgraded to windows 10.
My system is 64 bit, so after searching on google I found out that I need to install 64 bit windows 7 iso on GPT partition with UEFI enabled, Legacy and CSM enabled, Secure boot disabled, USB 3.0 port status before boot set to Auto mode.
I used Rufus program to make bootable usb disk, using FAT 32 as file system and Target platform as GPT with UEFI. But even after following all instructions, My laptop is not booting from USB disk, I have set booting order in legacy and UEFI as USB first. Even when I manually select booting device as USB drive (which is recognised and shown in available boot devices prior to boot) then it says "No bootable device found".
Then I tried to install windows 7 ,by running windows 7 iso while in windows 10. But no matter which windows 7 iso image I use , It always says "Use the other installation disc that says 64-bit. When you insert it, Windows Setup will restart automatically". I have downloaded various windows 7 iso (almost all more than 3 gb in size and claimed to be 64 bit, also checked for various signs that proves this iso was of 64 bit, e.g. size more than 3 gb, presence of bootmgr.efi file etc.), also why everyone will upload 32 bit win7 iso claiming it as 64bit as I have downloaded 5-6 such ISO and Everytime my laptop says use other 64 bit iso.
After further research someone suggested to go in sources folder in iso media and from there launch setup.exe file, to my surprise it worked and windows 7 set up started and files were loaded, but again before installation it said this is 32 bit windows 7 try other disc.
So please suggest any way to find windows 7 64 bit iso that can be installed alonside windows 10 and also reasons why windows 7 bootable usb is not booting and why it always detects every 64 bit winiso as 32 bit ?
Thanks in advance.

A: The best you can do is to create a separate partition while in your windows 10, and name that partition something obvious as "windows 7" make sure the partition is about 15-20 Gb in size. Then, making sure you have the correct .iso file for windows 7, use this tool to create a bootable usb. Then, as you already said, enable legacy support in your BIOS, and the change the boot order to boot from your usb first. When you successfully boot,  choose to "custom install" and select the partition that you created.


text:
Q: Check constraints not working on a query/view with join We have a view described as the following :
CREATE view [dbo].[PriceHourlyView]
AS
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2018 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2017 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2016 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2015 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2014 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2013 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2012 WITH (NOLOCK)

Each of the tables has a check constraint as follows for each year except for the current table without year specified :
ALTER TABLE [dbo].[PriceHourly2017]  WITH CHECK ADD  CONSTRAINT [CK_PriceHourly2017_Timestamp] CHECK  (([timestamp]>='2017-01-01' AND [timestamp]<='2017-12-31 23:59'))

When this view is queried by itself the check constraints limit the tables being searched. The execution plan looks like this :
SELECT
  *
FROM PriceHourlyview
WHERE nodeid = 24511
AND TimeStamp BETWEEN '2017-05-17' AND '2017-05-24'

Now when I join on this table on the timestamp field the query no longer uses the check constraints and uses every table to check for the data.
SELECT
  *
FROM ShapeProfileDetails s WITH (NOLOCK)
LEFT JOIN PriceHourlyView p WITH (NOLOCK)
  ON s.TimeStamp = p.Timestamp
  AND s.EffectiveDate BETWEEN '2017-05-17' AND '2017-05-24'
WHERE NodeId = 24512
--AND s.EffectiveDate BETWEEN '2017-05-17' AND '2017-05-24'

I know I'm not querying the same field in the joined example and assuming that's the issue but that is the field I need to query for the correct results. I'm wondering if there is anyway to hint or force the query to use the correct check constraints. Or what is the best practice on joining to try and utilize these check constraints.

A: Okay, as discussed we know that EffectiveDate and TimeStamp are nearly the same. I would try to do something like this. Technically it's the same query, but we will let know SQL Server that it can use constraints (just subtract and add one day on the edges of BETWEEN).
SELECT * FROM ShapeProfileDetails s WITH (NOLOCK)
JOIN PriceHourlyView p WITH (NOLOCK)
   ON s.TimeStamp = p.Timestamp
AND s.EffectiveDate BETWEEN '2017-05-17' AND '2017-05-24'
AND s.TimeStamp BETWEEN '2017-05-16' AND '2017-05-25'
WHERE NodeId = 24512


text:
Q: Best way to upgrade from Magento ver. 1.9.1.0 to ver. 1.9.2.4?
*

*I am not ready to upgrade my live production store to Magento 2.1.0 yet. Would you think it would be a good idea to upgrade from my current version 1.9.1.0 to the latest pre-2.x version (1.9.2.4) and why?

*What is the best way to do this upgrade? I have a software installation program in cPanel called SOFTACULOUS (and they sent me a link saying an upgrade is available)....I assume it would also be possible to do a "one-click" kind of an upgrade by using Magento Connect? But I read somewhere that "By default the Connect Manager is used to upgrade 3rd party extensions and not core magento" - how do I do this then? Download some kind of a patch and simply upload those files using FTP?
Any suggestions are greatly appreciated!

A: It depends on how much customizations do you have? what extensions?
It may be a good move to 1.9.2.4 as it will fix some bugs & security issues.
BUT it can produce other bugs too! because some files are being overwritten.
No Migration Tool can transfer the extensions safely. They only migrate the data. Like:
"LitExtension: Magento to Magento Migration Tool"
You should check your extensions, their compatibility issues,  1.9.2.4 release notes  &
 Consider is it worth for your shop to do this or not.
You may need a developer support in case of the extensions failure. So remember to backup everything first.


text:
Q: Image first in CSS with responsive I'm using bootstrap 'featurette' feature. On the page there is a text on the left and image on the right. when you shrink the browser size, they go on top of each other, with the text at the top and the image at the bottom. How do I change this so that the image is frist and then the writing underneath?
Ad example is here http://getbootstrap.com/examples/carousel/
If you notice the feature part you will see what I mean when you resize.
I have tried changing the float position as thats the only thing I can think of but it didnt work.
P.s just to clarify, I still want them the same place when over 756px (or whatever the size is) but just want the image at the top when it changes size in the example above.

A: You should use display:flex property to the container for both and use order property for the elements for example is below. Try changing the order of the elements and have a look.

.elements-container{
  background: #000;
  width: 100%;
  height: 500px;
  display: flex;
 }
.text-box{
  order: 2;
  width: 200px;
  height: 200px;
  color: #ffffff;
  background: #ff0000;
  display: block;
 }
.image-box{
  order: 1;
  width: 200px;
  height: 200px;
  display: block;
 }

This is text


text:
Q: Open file from NERDtree in specific window (or last active) In VIM I've got 4 windows opened and a NERD tree like this:

So, whenever I try to open the file from NERD, it's opened in first buffer (topleft pos). Sometimes in other buffers.
Is there a way to open a file in bottom right position ? Mb there are workarounds ?
Maybe I can force NERDtree to open file in last active window ? At the moment, it doesn't work this way :(
UPD: It looks like the problem is in hidden buffers.
When the buffer was opened in one window, and then replaced by another - if you try to open the very first in another window, you'll get it opened in the window it was opened in the very first time.

A: I'm using NERD tree 4.1.0 on Vim 7.2 and NERDTree does open files in the last active window by default.
From the docs:

Default key: o
Map option: NERDTreeMapActivateNode
Applies to: files and directories.
If a file node is selected, it is opened in the previous window.

But hitting enter when the file is selected has the same effect.


text:
Q: EntityBase and IAggregateRoot Reference not found? I am trying build a repository, so I found this link explained very well but I got error

Error 1   The type or namespace name 'EntityBase' could not be found
  (are you missing a using directive or an assembly reference?)
Error 2   The type or namespace name 'IAggregateRoot' could not be found
  (are you missing a using directive or an assembly reference?)

My Code is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Linq.Expressions;

namespace DapperAndSQLite
{
    public interface IRepository<T> where T : EntityBase, IAggregateRoot
    {
        void Add(T item);
        void Remove(T item);
        void Update(T item);
        T FindByID(Guid id);
        IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
        IEnumerable<T> FindAll();
    }
}

Here is Screenshot (To show the assembly or something is missing)

Am I missing Something ?

A: You haven't added the Interface IAggregateRoot and EntityBase in your project. Referenced article has source code hosted on github here.
Add the interface and base class from here.

A: 1) You should never and ever put repository interfaces at Infrastructure projects, they belong to Domain.
2) This EntityBase and the IAggregateRoot should stay inside the Domain project.
3) You must add Domain project Reference to the Infrastructure.DapperAndSQLite and implement this repositories.


text:
Q: Wordpress - changing name of attribute in links I am using WooCommerce in Wordpress and have a site such as https://example.com/shop/producer/myproducer/ but I would like to change /shop/producer/ into something else, like brands (as I have already site example.com/brands and I would like breadcrumbs to direct me there). How can I do that without changing the attribute name of "producer" for products in WooCommerce?

A: you need to go to importation --> permalink and for there you can set your link name. But i think you have yet did the write choice that is Posta Name.
Also, you can go in your page, post or product page and change the permalink name for there (on the top just down to the title), if you want change the "sub permalink", you need change or the name of your category or the permalink in your primary page.


text:
Q: Jest test fail: "● default root route" I'm trying to write Jest tests for a Fastify project. But I'm stuck with the example code failing with an ambiguous error: "● default root route".
// root.test.ts
import { build } from '../helper'

const app = build()

test('default root route', async () => {
  const res = await app.inject({
    url: '/'
  })
  expect(res.json()).toEqual({ root: true })
})

// helper.ts
import Fastify from "fastify"
import fp from "fastify-plugin"
import App from "../src/app"

export function build() {
  const app = Fastify()

  beforeAll(async () => {
    void app.register(fp(App))
    await app.ready()
  })

  afterAll(() => app.close())

  return app
}

// console error:
 FAIL  test/routes/root.test.ts (8.547 s)
  ● default root route

A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that .unref() was called on them.

What am I doing wrong?

A: After running --detectOpenHandles, Jest reported that open ioredis connections were timing out.
I hooked up ioredis instances to Fastify lifecycle with fastify-redis and the test passed.


text:
Q: SPO Content Type Inheritance and Copying Content between Lists and Sites Let's imagine I got 2 sites on SPO as follows:

*

*/sites/sales

*/sites/projects

Let's also imagine I would have 3 content types (in content type hub) with the following inheritance

*

*Case

*

*Offer

*

*Project

Workflow 1:
In /sites/sales we would have 2 lists based on custom content types. One for Cases Content Type, another for Offers Content Type. When a Case reaches a certain status, the workflow would copy the item to the Offers list while the original Case Item would remain in the Cases list.
Question 1:
Since the Cases is based on Case content type whereas Offers list is based on Offer content type (which inherits from Case content type), is it possible to copy such base content type to a list based on a derived content type?
Workflow 2:
When the item in the Offer list is marked approved by client, the content would be again copied to another list. This time residing on another site /sites/projects. The list on that site of course would host items based on Project content type which inherits Offer content type.
Question 2:
Is it possible to copy content between lists located on different sites?
Question 3:
Or am I completely thinking this the wrong way?


text:
Q: Working with non recursive lists So I've been working with lists recently.
I want to make a non recursive function name: int list -> int, that returns the difference between the highest and lowest number in a list.
Is there a simple way of doing it with maybe list.fold, list.filter or list.exist?
I guess i can do it with list.max and list.min, but i want to try with some other functions.
Any help?

A: To you mean something like this?
let distanceMinMax xs =
    let (min,max) = List.fold (fun (min, max) x -> ((if x < min then x else min), (if x > max then x else max)))
                              (System.Int32.MaxValue, System.Int32.MinValue)
                              xs
    (max - min)

Tested in the REPL:
> distanceMinMax [1;-1;2;5;7;-3];;
val it : int = 10

Hint: The empty list [] is not supported:
> distanceMinMax [];;
val it : int = 1


text:
Q: Can SSL context options be set when using Twisted endpoints? I am writing a server in Python+Twisted that uses the endpoints [1] to allow configuring the listening connection.  The documentation doesn't show any obvious (to me!) way to set options for an SSL context object using an endpoint string.  I poked around in the source, and it looks like the IStreamServerEndpoint object returned for an SSL connection has something like a _context attribute I could fiddle with, but that seems kind of kludgy.  I was wondering if there is some way for me to set the SSL context options without having to hack the endpoint internals.  (I want to set the context up to be able to verify a client certificate).
Thanks,
Carl
[1] https://twistedmatrix.com/documents/current/core/howto/endpoints.html

A: twisted.internet.endpoints.SSL4ServerEndpoint accepts an argument to its initializer, sslContextFactory.  This object is used to create the TLS context used by connections established to that server endpoint.
If you supply your own context factory then it can configure the context objects in any way you like prior to giving them back to the endpoint.


text:
Q: How can I hide scrollbar for ScrollView in NativeScript? I've been looking back and forth on how can I hide scrollbar for a ScrollView in NativeScript Angular from the html file rather than typescript or JavaScript but I couldn't find it.
What have I tried already:

*

*This thread shows a way to do it by accessing the native API but it's different for both iOS and Android. I'm looking for a cross platform solution.

*I've used this plugin but again I'm looking for a much simpler way like some sort of a attribute <ScrollView> tag.

Environment:
Node: 10.16
npm: 6.9.0
NativeScript: 5.4.0

A: I've found a way to achieve this. Use following approach:
<ScrollView scrollBarIndicatorVisible="false">
...
</ScrollView>

I hope that you found it usefull. Reference API

Followings have been tested:
Platforms: Android, iOS
Frameworks: NativeScript - Angular, JavaScript, TypeScript
NativeScript Version: 3, 4, 5


text:
Q: Do different horses have different speeds? All the horses I see available at the different stables cost 1000 gold.  Do they all have similar qualities, or are some faster than others as it was in Oblivion?

A:
All horses in Skyrim have the same speed and hardiness,they are all draft types that resemble a Clydesdale, and all cost 1000 septims.

Source:
Wikia

A: There is one horse in Skyrim that, while unable to run faster than regular horses, can sprint further.

 After reaching a certain point in the Dark Brotherhood quest line, you're given access to Shadowmere. Shadowmere seems to be able to sprint for longer distances than regular horses, and is also much harder, if not impossible, to kill.

A: Yes, they are all the same except Shadowmere (acquired after 4/5/3 missions from the Dark Brotherhood. He can climb mountains that other creatures can't (or at least other horses and players).


text: Q: Indication of remaining time to format an external HDD Is there any way to see how long it will still take to format an external hard drive? I used Disk Utility to do so, and it now just tells me "Formatting...", without any indication of the progress. I chose quick format, so expected it to take minutes. But it already took >20 min, for a 2 TB drive.


text:
Q: How to use explicit package.swift in root of project (Xcode doesn't know about it) Is there a way I can use package.swift in an Xcode project? I have written a package.swift file which is being read/ understood by swift build, but it looks like Xcode still doesn't know about this file. I don't want to use the built-in Swift Packages tab because I don't know how Xcode handles that (e.g. where do the contents get version controlled?).
I have a feeling I'm asking something impossible, as using a project package.swift may be mutually exclusive to XCode.
I did read Use swift package manager on existing xcode project but the answer here recommended using the Xcode swift package manager feature, which is what I am trying not to use.

A: To use a Swift package as an Xcode project, just open the Package.swift directly.  Xcode will create a workspace (in comments, I said a project, but it's a workspace) in the package's .swiftpm directory.  There won't be any project settings, because you do that by editing the Package.swift file, and files are always sorted.  Other than that, it's pretty much like working in an Xcode project, including debugging and testing.
Of course there are the other modes of using a package
You can just drag the Package.swift file into your Xcode project, if it's a local package.  You'll also need to add it as a dependency in your General settings, just as you would any framework.  That's not the same as the "Add Package Dependency" feature.  It's the same Project Settings -> Target -> Frameworks & Libraries that you use for any traditional framework.
If you do it that way, the package is part of the Xcode project.
If the package is already under it's own git repo, Xcode will prompt you which repo you want to do things like "push" or whatever, though commit just applies to whatever repo the files being committed belong to... so if you change some app code and package code, and commit them both at the same time, the app code would go into the app's repo, and the package code would go to the package's repo.
If the package isn't under source control and you relocate it to your project folder, I think the project's repo will take responsibility for those sources, though you might have to explicitly check them in Xcode's commit (or git add from the command line).
I'm not sure how it handles it, if it's in an unrelated folder and not in its own repo.
If it's a remote package, which is different, you need to add it as a package dependency.  No getting around that for remote packages.

A: I don't think this is possible. If you use a Swift package (and therefore you have a package.swift, you won't get the rich menus provided by Xcode.
I'm hoping interoperability will come in the future, like how Android Studio and Gradle config files (build.gradle) work together. Swift packages and Xcode projects do not work together at all.


text:
Q: Search company name on yahoo finance and get back ticker in python i would like to automate the task of getting the ticker of a certain company by looking it up on yahoo finance.
For example:
Search for "bmw" on yahoo finance
return "bmw.de"
is this possible? Many thanks


text:
Q: Is $|A| > |B|$? Let $A=\bigcup_{i\in I_A}A_i$ where $I_A$ is the index set of $A$ and such that $A_i \cap A_j=\emptyset$ for any $i,j\in I_A$. Similarly, let $B=\bigcup_{j\in I_B}B_j$ where $I_B$ is the index set of $B$ and such that $B_i \cap B_j=\emptyset$ for any $i,j\in I_B$. Suppose:

*

*For every $i\in I_A$ and every $j\in I_B$, $|A_i|>|B_j|$.

*$|I_A|>|I_B|$.

Can we conclude that $|A|>|B|$? I think we can, but I don't know how to prove it unfortunately. There is definitely an injection from $B$ to $A$. I assumed that there is a bijection from $B$ to $A$ for reductio. But after this, I'm not sure how to proceed.

A: No.  For instance, suppose $|I_A|=\aleph_1$ and $|A_i|=\aleph_\omega$ for each $i$, while $|I_B|=\aleph_0$ and for each $n\in\mathbb{N}$, there is one $j$ such that $|B_j|=\aleph_n$.  Then $|A|=\aleph_1\cdot\aleph_\omega=\aleph_\omega$ but $|B|=\aleph_\omega$ as well since $|B|\geq\aleph_n$ for each $n$.
In general, we will have $|B|\leq|I_B|\cdot\kappa$ where $\kappa=\sup_j |B_j|$, and $|A|\geq |I_A|\cdot \kappa$ since $|A_i|\geq\kappa$ for each $i$.  However, if $\kappa\geq |I_A|$ and no $|A_i|$ is strictly greater than $\kappa$, then $|A|$ and $|B|$ will both be equal to $\kappa$ as long as $\kappa$ is infinite, as in the example above.


text:
Q: Adapter for a spinner makes NullPointerException I made an array list in one of my value's folder, now when i want to adapt it to the spinner by retrieving it from the source folder it says  NullPointerException:
 spinner = (Spinner) findViewById(R.id.spinner);

    ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.worker,android.R.layout.simple_list_item_1);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);

Messages in LogCat:
 Caused by: android.content.res.Resources$NotFoundException: String array resource ID #0x7f090001 at android.content.res.Resources.getStringArray(Resources.java:527) at com.example.hay.myapplication.UserCreatingActivity.onCreate(UserCreatingActivity.java:46) at android.app.Activity.performCreate(Activity.java:5990) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:227

A: Try giving the ArrayAdapter a type:
ArrayAdapter<String> adapter = ArrayAdapter.createFromResource(this, R.array.worker, android.R.layout.simple_spinner_item);

A: Try to flip the two last parameters in createFromRessource:
Replace:
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.worker,android.R.layout.simple_list_item_1);

By:
ArrayAdapter<String> adapter = ArrayAdapter.createFromResource(this, android.R.layout.simple_list_item_1, R.array.worker);

In your code:
    spinner = (Spinner) findViewById(R.id.spinner);

    ArrayAdapter<String> adapter = ArrayAdapter.createFromResource(this, android.R.layout.simple_list_item_1, R.array.worker);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);

A: since you have the exception:
 `Caused by: android.content.res.Resources$NotFoundException: String array resource ID #0x7f090001 at

I see that your problem is the last value inside the createFromResource() method:
 ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.worker,android.R.layout.simple_list_item_1);

the last value must be the array:
 ArrayAdapter adapter = ArrayAdapter.createFromResource(this,android.R.layout.simple_list_item_1,R.array.worker);

A: change
 attr.xml

directory
from
...\app\src\main\res\values-w820dp

to
...\app\src\main\res\values


text:
Q: Error installing DroidCam in Ubuntu 20.04 I want to use my phone camera as a webcam in my computer with Ubuntu. I read that DroidCam is the easiest way...
So, I tried following the official script: https://www.dev47apps.com/droidcam/linuxx/
cd /tmp/
wget https://files.dev47apps.net/linux/droidcam_latest.zip
echo "fb7d7fa80a8e47a98868941939104636 droidcam_latest.zip" | md5sum -c --
# OK?
unzip droidcam_latest.zip -d droidcam && cd droidcam
sudo ./install

However, the video device is not installed, nothing found if I check this:
lsmod | grep v4l2loopback_dc
My terminal is asking for the path of the public key but I left it empty as suggested:
$ sudo ./install
Webcam parameters: '640' and '480'
Building v4l2loopback-dc.ko
make: Entering directory '/tmp/droidcam/v4l2loopback'
make -C /lib/modules/5.4.0-33-generic/build M=/tmp/droidcam/v4l2loopback modules
make[1]: Entering directory '/usr/src/linux-headers-5.4.0-33-generic'
  CC [M]  /tmp/droidcam/v4l2loopback/v4l2loopback-dc.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC [M]  /tmp/droidcam/v4l2loopback/v4l2loopback-dc.mod.o
  LD [M]  /tmp/droidcam/v4l2loopback/v4l2loopback-dc.ko
make[1]: Leaving directory '/usr/src/linux-headers-5.4.0-33-generic'
make: Leaving directory '/tmp/droidcam/v4l2loopback'
Secure Boot is enabled, attempting to sign the driver
please specify signing key location (or leave empty to sign manually later)
You can Google 'secure boot' for your distro

Enter the path of the public key:
Enter the path of the private key:
Adding uninstall script
Moving driver and executable to system folders
+ cp v4l2loopback/v4l2loopback-dc.ko /lib/modules/5.4.0-33-generic/kernel/drivers/media/video/
+ cp droidcam /usr/bin/
+ cp droidcam-cli /usr/bin/
+ set +x
Registering webcam device
insmod: ERROR: could not insert module /lib/modules/5.4.0-33-generic/kernel/drivers/media/video/v4l2loopback-dc.ko: Operation not permitted
warning: insmod failed
Running depmod
make: Entering directory '/tmp/droidcam/v4l2loopback'
make -C /lib/modules/5.4.0-33-generic/build M=/tmp/droidcam/v4l2loopback clean
make[1]: Entering directory '/usr/src/linux-headers-5.4.0-33-generic'
  CLEAN   /tmp/droidcam/v4l2loopback/Module.symvers
make[1]: Leaving directory '/usr/src/linux-headers-5.4.0-33-generic'
make: Leaving directory '/tmp/droidcam/v4l2loopback'
Done

If I run DroidCam in my phone and then in Ubuntu... the following message popups in Ubuntu:

Droidcam video device not found (/dev/video[0-9]). Did it install
  correctly? If you had a kernel update, you may need to re-install.

How can I Secure Boot Module Signing in Ubuntu 20.04? Could the issue be related with this? Any idea or alternative solution to Droidcam would be really appreciate it : )

A: This did it for me:
sudo apt-get install linux-generic
sudo apt-get install v4l2loopback-dkms
sudo modprobe v4l2loopback

Got the solution from here modprobe v4l2loopback fails on Ubuntu
During the install of v4l2loopback-dkms I had to do the 'Enroll MOK' process (it guided me automatically).
After this I uninstalled and reinstalled Droidcam and the webcam was registered with no error


text:
Q: Incremental control field - Cursor I'm trying to create a simple restore cursor that will be used when I have the need to restore multiple databases.
Each database have simple recovery model and all are named using the following format: DBname_AAAAMMDD_FULL
I have came up with a dynamic script that will do the job for a single istance, but it's not incrementing the data field on my cursor.
Here is what I have tried so far:
DECLARE @SQL VARCHAR(MAX)
DECLARE @DATE DATETIME  = '20170926'
DECLARE @DATE_CHAR CHAR(9) =  CONVERT(CHAR(9),@DATE,112)
DECLARE @DBName VARCHAR(MAX) = 'MyDB_'
DECLARE @DBFileName VARCHAR(MAX)
SELECT @DBNAME = (@DBNAME + @DATE_CHAR)
SELECT @DBName
SELECT @DBFileName = ('' + @DBNAME+'' +'_FULL_FRM.BAK') --This should match the physical file name
SELECT @DBFILENAME

WHILE (SELECT @DATE ) <= '20170930'
BEGIN
   PRINT @DATE
   SET @DATE = (@DATE +1)
   IF (SELECT @DATE) > '20170930'
      BREAK
   ELSE
      CONTINUE
END

And this piece of code, but haven't got either to work.
DECLARE @SQL VARCHAR(MAX)
DECLARE @DATE DATETIME  = '20170926'
DECLARE @DATE2 DATETIME
DECLARE @DATE_CHAR CHAR(9) =  CONVERT(CHAR(9),@DATE,112)
DECLARE @DBName VARCHAR(MAX) = 'MYDB_'
DECLARE @DBFileName VARCHAR(MAX)
SELECT @DBNAME = (@DBNAME + @DATE_CHAR)
--23 = aaaa-mm-dd
--112 = aaaammdd
SELECT @DBName
SELECT @DBFileName = ('' + @DBNAME+'' +'_FULL_FRM.BAK') --This should tch the physical file name
SELECT @DBFILENAME

DECLARE Employee_Cursor CURSOR FOR
SELECT @DATE
WHERE @DATE < '20170930'
OPEN Employee_Cursor;
FETCH NEXT FROM Employee_Cursor;
WHILE @DATE <= '20170930'
   BEGIN
   SELECT @DATE = @DATE+1
   PRINT @DATE
       FETCH NEXT FROM Employee_Cursor;
    END;
CLOSE Employee_Cursor;
DEALLOCATE Employee_Cursor;
GO

A: Got my query to work, without using a cursor, thanks to GarethD and his useful information provided here: While loop in SQL Server 2008 iterating through a date-range and then INSERT
What I needed was a loop that increased date by 1 day so I could get the correct names of our backups. This query may not be the best optimized, but it works.
It's still a WIP and is useless as now, but i'll finish tomorrow:
DECLARE @SQL VARCHAR(8000)
DECLARE @DATE DATETIME  = '20170926'
DECLARE @TARGET_DATE DATETIME = '20171001'
DECLARE @CURRENTDATE DATETIME = @DATE
DECLARE @DATE_CHAR CHAR(9)
DECLARE @DBName VARCHAR(255) = 'MyDB_'
DECLARE @DBFileName VARCHAR(255)
DECLARE @DB_PATH VARCAR(8000)

SET @CurrentDate = @Date

WHILE ( @DATE < @TARGET_DATE)
BEGIN
        BEGIN
            SET @DBName = 'MyDB_'
            SET @DATE = (@DATE +1)
            SET @DATE_CHAR =   CONVERT(CHAR(9),@DATE,112)
            SELECT @DBNAME = (@DBNAME + @DATE_CHAR)
            SELECT @DBFileName = ( @DBNAME +'_FULL_FRM.BAK') --This should match the physical file name
            SELECT @SQL = 'USE ''[master]'' RESTORE DATABASE ' + @DBNAME + 'FROM DISK ''D:\BKP_PATH\' + @DBFileName + 'WITH FILE =1 '
        END

SELECT @SQL
END
GO

Here what I've got so far:


text:
Q: Ajax POST can't seem to authenticate with Devise Devise refuses to authenticate me when sending an ajax POST request.
What have I missed?

*

*rails (4.1.6)

*devise (3.4.1)

*jquery-rails (2.3.0)

*jquery-ui-rails (5.0.3)

Controller
class SeenEpisodesController < ApplicationController

  before_filter :authenticate_user! #Devise

  def mark_episode
    #do stuff
    respond_to do |format|
      format.js
    end
  end

end

Javascript
Trying both with setting a header and a payload.
$.ajax({
  type: "POST",
  url: url,
  dataType: "script",
  data: {
    authenticity_token: encodeURIComponent($('meta[name="csrf-token"]').attr('content'))
  },
  beforeSend: function(xhr) {
    xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
  }
});

I have also tried without setting the tokens myself. jquery_ujs sets the header for me!
Yes I have <%= csrf_meta_tags %> in my layout.

Javascript manifest
//= require jquery
//= require jquery_ujs #Have tried with or without

Rails console output
Processing by SeenEpisodesController#mark_episode as JS
  Parameters: {"mark"=>"1", "episode_id"=>"887795", "season_id"=>"65577"}
Completed 401 Unauthorized in 9ms

Started GET "/account/sign_in.js" for 192.168.0.10 at 2015-02-28 19:44:18 +0100
Processing by Devise::SessionsController#new as JS

Dev tools network output

A: %253D - try to decode this part of your authenticity_token. It will equal to =. So, seems like you have encoded authenticity_token incorrectly (twice).

A: You don't need to do encodeURIComponent when posting with jQuery. jQuery encodes the data for you anyway, which is leading to your data being encoded twice which will result in invalid authenticity token being submitted.


text:
Q: Performance while using pandas_udf in pyspark with huge dataframe I have a problem while using pandas udf in pyspark, it troubles me so long.
Background
I have a dataframe like this:
+---+-----+----+-----+
|key|month|col1|col2 |
+---+-----+----+-----+
|  a| 1909| 4.2|-0.25|
|  a| 1910|  2 | null|
|  b| 1908| 3.2| 0.7 |
|  b| 1909| 2.1| 1.2 |
+---+-----+----+-----+

In the dataframe, each different key has multiple rows. For each key, I need to calculate something base on col1 / col2, like avg(col1), max(col2) and so on. So the expected result is:
+---+---------+---------+---------+---------+
|key|avg(col1)|max(col1)|avg(col2)|max(col2)|
+---+---------+---------+---------+---------+
|  a|      3.1|      4.2|    -0.25|    -0.25|
|  b|     2.65|      3.2|     0.95|      1.2|
+---+---------+---------+---------+---------+

In this case, I can achieve my goal by using functions in pyspark.sql.functions:
from pyspark.sql import functions as func
dataframe.groupBy("key").agg(
    func.avg("col1"),
    func.avg("col2"),
    func.max("col1"),
    func.max("col2")
)

But what I need to do is more complicated than avg or max. For example, I need to calculate the maximium amount decreased: max(of x(2)-x(1), x(3)-x(2),………,x(p)-x(p-1)), where the x(i) means the value of a column at the ith month for each key.
So the result is base on the indicated column month and the value column. So I use pandas_udf to do this:
from pyspark.sql import functions as func

columns =["col1", "col2"]

def _mad(key, pdf):
    pdf = pdf.sort_values(by="month")  # sort the values by the month
    transformed = [pd.Series(key, ["key"])]
    transformed.append((-pdf[columns].diff()).max())
    res = pd.DataFrame(pd.concat(transformed, ignore_index=True)).T
    return res
# the udf return a pandas dataframe which have the schema I expected
schema = StructType(...)
transform_udf = func.pandas_udf(_mad, schema, func.PandasUDFType.GROUPED_MAP)
data.groupby("key").apply(transform_udf)

But I found this pandas_udf has a very low performance. Notice that this dataframe is very big that has about 3 billion rows: there are 5 Billion different key and each key has 6 rows, and 300 columns. It takes me about 5 hours to finished the job. The dataframe is shuffled into 5000 partitions after groupby and I used 1600 cores. It's unacceptabled and I do more experiments to compared the performance between pandas_udf and pyspark.sql.functions while calculate the avg.
Experiments
Here is the code:
# the version1
dataframe.groupBy("key").agg(
    func.avg("col1")
)

# the version2
def _avg(key, pdf):
    transformed = [pd.Series(key, ["key"])]
    transformed.append(pdf["col1"].mean())
    res = pd.DataFrame(pd.concat(transformed, ignore_index=True)).T
    return res
schema = StructType(...)
transform_udf = func.pandas_udf(_avg, schema, func.PandasUDFType.GROUPED_MAP)
data.groupby("key").apply(transform_udf)

# the version3
def _do_nothing(key, pdf):
    pdf.columns = range(len(pdf.columns))
    return pdf.iloc[0:1]
schema = StructType(...)
transform_udf = func.pandas_udf(_do_nothing, schema, func.PandasUDFType.GROUPED_MAP)
data.groupby("key").apply(transform_udf)

*

*Version 1

The version1 is very quickly, it takes me about 2 mins 9 secs to finish the job.
Stage0: read the raw data and shuffling into 5000 partitions, cost 2.4 min. The Input size is 406G and shuffle write is 42G.
Stage1: calculate the avg, cost 9 secs

*

*Version 2

Stage0 cost about 30mins to read the data and shuffling. It seems that it need to read the whole dataset into memory thought I need only three columns("key", "month", "col1"), the shuffle write is more bigger  than 42G.
Stage1 takes about 5 hours.

*

*Version 3

the cost is very similar to version 2, although the udf do nothing and just return the first row of the pdf. So the time is cost in Serialization?
Question
So it seems that it's very expensive to use pandas udf in pyspark, because of the Serialization? Is there any other ways? The fully functions I need is below:

*

*avg

*max

*min

*cav, the current vs average: x(1)/mean(of x(1), x(2),…..x(p))

*ltr, the ratio of average in the recent p months to average in recent q months: mean(of x(1), x(2),…….x(p))/mean(of x(1), x(2),……….x(q))

*mad, the maximium amount decreased: max(of x(2)-x(1), x(3)-x(2),………,x(p)-x(p-1))

*mai, the maximium amount increased: max(of x(1)-x(2),x(2)-x(3), ……, x(p-1)-x(p))

*mcd, the maximium consecutive decreasing months: max( of r_ind - l_ind, where x(I_ind)

*mci, the maximium consecutive increasing months: max( of r_ind - l_ind, where x(I_ind)>x(I_ind +1)>…>x(r_ind))

*msn, the month since the most recent positive value:
=0 if value of most recent month is positive
=1 if value of 2nd most recent month is positive and most recent month is non positive.
=2 if value of 3rd most recent month is positive and most recent 2 months are non positive. ....
=p-1 if the oldest month is positive and all p-1 recent months are non positive
=p if all months are non positive

*msx, the month since the most recent maXimium value:
=0 if value of most recent month is the maximum or all months are a non 0 constant
=1 if value of 2nd most recent month is maximum  .........
=p-1 if the oldest month is the maximum
=p if all months are constant 0

*num, the number of positive  months

*cmx, the current vs maximium ratio: x(1)/max(of x(1),x(2),….x(p))

Here is part of my current code:
def _derivative(data, primary_key, period_key, num_period, transform_funcs, keep_origin, selected_columns):
    def _transform(key, pdf):
        pdf = pdf.sort_values(by=period_key)
        transformed = [pd.Series(str(key), [primary_key])]
        if keep_origin:
            for _, s in pdf[selected_columns].iterrows():
                transformed.append(s)
        for func_name, columns in transform_funcs.items():
            if func_name in ("msx", "msn"):
                mask = pd.DataFrame([(range(num_period - 1, -1, -1))] * len(columns)).T
                fn = lambda pdf, columns: TRANSFORM_FUNC[func_name](pdf, columns, mask)
            elif func_name == "ltr":
                fn = lambda pdf, columns: TRANSFORM_FUNC[func_name](pdf, columns, 3)
            else:
                fn = TRANSFORM_FUNC[func_name]
            transformed.append(fn(pdf, columns))
        res = pd.DataFrame(pd.concat(transformed, ignore_index=True)).T
        return res

    fields = [StructField(primary_key, StringType())]
    if keep_origin:
        for i in range(num_period, 0, -1):
            fields.extend([StructField("{}_h{}".format(column, i), FloatType()) for column in selected_columns])
    for func_name, columns in transform_funcs.items():
        for column in columns:
            fields.append(StructField("{}_{}_0{}M".format(column, func_name.upper(), num_period), FloatType()))
    schema = StructType(fields)
    transform_udf = func.pandas_udf(_transform, schema, func.PandasUDFType.GROUPED_MAP)
    return data.groupby(primary_key).apply(transform_udf)

def _avg(pdf, columns):
    res = pdf[columns].mean()
    return res

def _cav(pdf, columns):
    res = (pdf[columns].iloc[-1] / (pdf[columns].mean()))
    return res

def _ltr(pdf, columns, q):
    res = (pdf[columns].iloc[-q:].mean() / pdf[columns].mean())
    return res

def _mad(pdf, columns):
    return (-pdf[columns].diff()).max()

def _mai(pdf, columns):
    return pdf[columns].diff().max()

def _max(pdf, columns):
    return pdf[columns].max()

def _mcd(pdf, columns):
    diff = -pdf[columns].diff()
    diff[diff > 0] = 1.0
    diff[diff != 1] = 0
    cur = pd.Series(diff.iloc[0])
    mcd = []
    for i in range(pdf.shape[0]):
        cur = (cur + 1) * diff.iloc[i]
        mcd.append(cur)
    return pd.concat(mcd, axis=1).max(axis=1)

def _mci(pdf, columns):
    diff = pdf[columns].diff()
    diff[diff > 0] = 1.0
    diff[diff != 1] = 0
    cur = pd.Series(diff.iloc[0])
    mcd = []
    for i in range(pdf.shape[0]):
        cur = (cur + 1) * diff.iloc[i]
        mcd.append(cur)
    return pd.concat(mcd, axis=1).max(axis=1)

def _min(pdf, columns):
    return pdf[columns].min()

def _msn(pdf, columns, mask):
    pdf = pdf[columns]
    pdf[pdf > 0] = 1
    pdf[pdf != 1] = np.nan
    res = (pdf * mask.values).min()
    return res.fillna(pdf.shape[0])

def _msx(pdf, columns, mask):
    pdf = pdf[columns]
    pdf[pdf != pdf.max()] = np.nan
    pdf[~pdf.isna()] = 1
    res = (pdf * mask.values).min()
    return res.fillna(pdf.shape[0])

def _num(pdf, columns):
    return (pdf[columns] > 0).sum()

def _cmx(pdf, columns):
    return pdf[columns].iloc[-1] / (pdf[columns].max())

TRANSFORM_FUNC = {
    'avg': _avg,
    'cav': _cav,
    'ltr': _ltr,
    'mad': _mad,
    'mai': _mai,
    'max': _max,
    'mcd': _mcd,
    'mci': _mci,
    'min': _min,
    'msn': _msn,
    'msx': _msx,
    'num': _num,
    'cmx': _cmx
}

if __name__ == "__main__":
    primary_key = "key"
    period_key = "month"
    num_period = 6
    transform_funcs = {
        'avg': ['col1', 'col2', ...],
        'max': ['col1', 'col2', ...],
        ...
    }
    keep_origin = True
    selected_columns = ['col1', 'col2', ...]
    _derivative(data, primary_key, period_key, num_period, transform_funcs, keep_origin, columns)

Also, I tried to change the raw dataframe into something like this and than use a udf rather than pandas_udf:
rdd = dataframe.rdd
dataframe2 = rdd.map(...).toDF()
# dataframe2 may looks like below
+---+--------+-------+-------+-------+
|key||col1_m1|col1_m2|col2_m1|col2_m2|
+---+--------+-------+-------+-------+
|  a|       2|    4.2|   null|  -0.25|
|  b|     2.1|    3.2|    1.2|    0.7|
+---+--------+-------+-------+-------+

# than use a udf
dataframe2.select(avg_udf(func.struct(['col1_m1', 'col1_m2', ...])), udf2(...), ...)
# udf may looks like this
def avg_udf(row):
    return float(np.mean(row))

This works better than the pandas_udf but it's still very slowly. Is there any other ways? Thanks all:)