text:
Q: Why I am Getting an error when i run this test class..? Error Message System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, TargetX_Eventsb.preInsertOrgEvent: execution of BeforeInsert
caused by: System.NullPointerException: Attempt to de-reference a null object
(TargetX_Eventsb)
: []
Stack Trace Class.StudentAppointmentControllerTest.studentAppointmentTestCase: line 52, column 1
@isTest(SeeAllData=True)
private class StudentAppointmentControllerTest{

    public static testmethod void studentAppointmentTestCase(){

    // Create common test Accounts
    List<Account> testAccounts = new List<Account>();
    Account acc = new Account(Name ='TestAccount');
    testAccounts .add(acc);
    insert testAccounts;

    // Create common test Contacts
    List<Contact> testContacts = new List<Contact>();
    contact c = new contact(lastname ='TestContact');
    testContacts.add(c);
    insert testContacts ;

    List<TargetX_Eventsb__OrgEvent__c> orgEventList = new list<TargetX_Eventsb__OrgEvent__c>();
    TargetX_Eventsb__OrgEvent__c orgEvent1 =new TargetX_Eventsb__OrgEvent__c();
    orgEvent1.name = 'test event';
    orgEvent1.TargetX_Eventsb__Start_Date_Time__c = system.now();
    orgEvent1.TargetX_Eventsb__End_Date_Time__c = system.now() + 2;
    orgEvent1.TargetX_Eventsb__type__c = 'Alumni Reception';
    orgEvent1.TargetX_Eventsb__Color__c = '1C62CF';
    orgEvent1.TargetX_Eventsb__unlimited_attendees__c = true;
    orgEvent1.TargetX_Eventsb__Email_Sender__c = 'Use Default';
    orgEvent1.TargetX_Eventsb__Time_Zone__c = 'America/New_York';
    orgEvent1.TargetX_Eventsb__Event_Cost__c = 1.11;
    orgEvent1.TargetX_Eventsb__max_attendees__c = 30;
    orgEvent1.TargetX_Eventsb__Map_URL_Text__c = 'click here for directions';
    orgEvent1.TargetX_Eventsb__scan_before__c = 1.0;
    orgEvent1.TargetX_Eventsb__scan_after__c = 1.0;
    orgEventList.add(orgEvent1);
    insert orgEvent1;
    orgEventList.add(orgEvent1);

    TargetX_Eventsb__OrgEvent__c orgEvent2 =new TargetX_Eventsb__OrgEvent__c();
    orgEvent2.name = 'test event2';
     orgEvent1.TargetX_Eventsb__Start_Date_Time__c = system.now()-1;
    orgEvent1.TargetX_Eventsb__End_Date_Time__c = system.now() + 2;
    orgEvent2.TargetX_Eventsb__Color__c = '1C62CF';
    orgEvent2.TargetX_Eventsb__unlimited_attendees__c = true;
    orgEvent2.TargetX_Eventsb__Email_Sender__c = 'Use Default';
    orgEvent2.TargetX_Eventsb__Time_Zone__c = 'America/New_York';
    orgEvent2.TargetX_Eventsb__Event_Cost__c = 1.11;
    orgEvent2.TargetX_Eventsb__Event_Cost__c = 1.11;
    orgEvent2.TargetX_Eventsb__max_attendees__c = 30;
    orgEvent2.TargetX_Eventsb__Map_URL_Text__c = 'click here for directions';
    orgEvent2.TargetX_Eventsb__scan_before__c = 1.0;
    orgEvent2.TargetX_Eventsb__scan_after__c = 1.0;
    insert orgEvent2;
    orgEventList.add(orgEvent2);

    insert  orgEventList;

    list<TargetX_Eventsb__ContactScheduleItem__c>  csiList = new list<TargetX_Eventsb__ContactScheduleItem__c>();

    TargetX_Eventsb__ContactScheduleItem__c csi1 = new TargetX_Eventsb__ContactScheduleItem__c();
    csi1.TargetX_Eventsb__OrgEvent__c = orgEvent1.id;
    csi1.TargetX_Eventsb__Contact__c = c.id;
    csi1.TargetX_Eventsb__Confirmed__c = true;
    csi1.Type__c = 'Student';
    insert csi1;
    csiList.add(csi1);

    TargetX_Eventsb__ContactScheduleItem__c csi2 = new TargetX_Eventsb__ContactScheduleItem__c();
    csi2.TargetX_Eventsb__OrgEvent__c = orgEvent1.id;
    csi2.TargetX_Eventsb__Contact__c = c.id;
    csi2.TargetX_Eventsb__Confirmed__c = true;
    csi2.Type__c = 'Professor';
    insert csi2;
    csiList.add(csi2);
    insert csiList;

    StudentAppointmentController studentAppctrl = new StudentAppointmentController();
    studentAppctrl.eventOrgId = csi1.id;
    studentAppctrl.cancelRegistration();
    studentAppctrl.backToLogin();

}

}

A: Couple of quick observations
1. You have this code
orgEventList.add(orgEvent1);
insert orgEvent1;
orgEventList.add(orgEvent1);

orgEvent1 is now added in Database. You are adding this OrgEvent1 in List twice.
2. You are adding to the list another object
insert orgEvent2;
orgEventList.add(orgEvent2);

orgEvent2 is added in Database.
3. Now you are again adding this list in database
insert  orgEventList;

Since you have already added its individual objects, what is the need for inserting again. This will result in error.
I am not sure this is causing the problem you reported, please share the complete code with line numbers


text:
Q: How can I change the activity's background color from other activity? I need to change the background colors of MainActivity ConstraintLayout. I have a second activity called selectcolors where I have buttons that when they are clicked it would change the MainActivity background color.
I need a method to change the background color of main activity from the second activity's each button of each color respectively.
    package com.example.kidscalculator;

    import androidx.appcompat.app.AppCompatActivity;

    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;

    public class selectcolors extends AppCompatActivity {
    private TextView textSelect;
    private Button buttonWhite;
    private Button buttonYellow;
    private Button buttonRed;
    private Button buttonBlue;
    private Button buttonGreen;
    private Button buttonOrange;
    private Button buttonPurple;
    private Button buttonBlack;
    private Button buttonGrey;
    private Button buttonOrangeLight;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_selectcolors);

            textSelect = (TextView)findViewById(R.id.textSelect);
            buttonWhite = (Button)findViewById(R.id.buttonWhite);
            buttonYellow = (Button)findViewById(R.id.buttonYellow);
            buttonRed = (Button)findViewById(R.id.buttonRed);
            buttonBlue = (Button)findViewById(R.id.buttonBlue);
            buttonGreen = (Button)findViewById(R.id.buttonGreen);
            buttonOrange = (Button)findViewById(R.id.buttonOrange);
            buttonPurple = (Button)findViewById(R.id.buttonPurple);
            buttonBlack = (Button)findViewById(R.id.buttonBlack);
            buttonGrey = (Button)findViewById(R.id.buttonGrey);
            buttonOrangeLight = (Button)findViewById(R.id.buttonOrangeLight);

            buttonWhite.setOnClickListener(new View.OnClickListener() {
                @Override
        public void onClick(View v) {
               //Set Main Activity ConstraintLayout Background White
        }
    });

    buttonYellow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             //Set Main Activity ConstraintLayout Background Yellow
        }
    });

    buttonRed.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //etc.
        }
    });

    buttonBlue.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

    buttonGreen.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

    buttonOrange.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

    buttonPurple.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

    buttonBlack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

    buttonGrey.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

    buttonOrangeLight.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        }
    });
}
}

A: One thing you can do is.
In selectcolors class for every button assign id or name so that main activity knows which color is clicked. And use intent to go to MainActivity.
In selectcolors.class
for all the button clicks
Intent intent = new Intent(getApplicatioinContext(),MainActivity.class); intent.putExtra("color","Red"); startActivity(intent)
similary for all the buttons.
In MainActivity.class
String bgcolor = "";
in onCreate()
if (getIntent().getExtras() != null || getIntent().getExtras().containsKey("color")) { bgcolor= getIntent().getExtras().getString("color");}
if (bgcolor.equals("red")){ (layout_id).setBackground(context.getResources().getDrawable(R.drawable.red)); }
Do same for all other buttons as well.

A: You can use code as follows
From Mainactivity start the selectcolors activity as follows:
Intent intent  = new Intent(this,selectcolors.class);
startActivityForResult(intent,1234);

Now in selectcolors  activity whenever you select any color i.e your onClick..
just add following snippet
Intent intent = new Intent();
intent.putExtra("selectedColor",<Your selected color>); // Suppose you are passing color as #aabbcc i.e hex string
setResult(1234,intent);

Now in mainactivity write following snippet
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
      if(requestCode == 1234){
         String yourSelectedColor = data.getStringExtra("selectedColor");
         Intent myIntent = new Intent(this,Mainactivity.class);
         myIntent.putExtra("selectedColor",yourSelectedColor);
         finish(); // Finish this activity
         startActivity(myIntent);

      }

}

And then finally in onCreate of main
in onCreate()
if (getIntent().getExtras() != null || getIntent().getExtras().containsKey("selectedColor")) {
 bgcolor= getIntent().getExtras().getString("selectedColor");
(layout_id).setBackground(Color.parseColor(bgcolor));

}

A: Why a whole another activity for this simple purpose? Use a dialog instead.
The Dialog way:

*

*create xml layout with color buttons as you have created the activity layout.

*in MainActivity inside onCreate() find the root ConstraintLayout view. For example ConstraintLayout constraintLayout = findViewById(R.id.rootConstraint_MainActivity);

*Create a dialog class as follow:

public class DialogColorPicker extends DialogFragment implements View.OnClickListener{
    private static final String TAG = "ColorPickerDialog";
    private static int colorRed = Color.RED;
    private static int colorGreen = Color.GREEN;
    private static int colorYellow = Color.YELLOW;
    private static int colorBlue = Color.BLUE;

    private DialogColorPickerListener listener;

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        View view = View.inflate(getContext(), R.layout.fragment_color_picker, null);
        Button btn_red = view.findViewById(R.id.btn_red_fragment);
        Button btn_green = view.findViewById(R.id.btn_green_fragment);
        Button btn_yellow = view.findViewById(R.id.btn_yellow_fragment);
        Button btn_blue = view.findViewById(R.id.btn_blue_fragment);

        btn_red.setOnClickListener(this);
        btn_green.setOnClickListener(this);
        btn_yellow.setOnClickListener(this);
        btn_blue.setOnClickListener(this);

        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(view)
                .setTitle("Choose Color");

        return builder.create();
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
        case R.id.btn_red_fragment:
            listener.onConfirm(colorRed);
            break();
        case R.id.btn_green_fragment:
            listener.onConfirm(colorGreen);
            break();
        case R.id.btn_yellow_fragment:
            listener.onConfirm(colorYellow);
            break();
        case R.id.btn_blue_fragment:
            listener.onConfirm(colorBlue);
            break();
    }

    public void setListener(DialogColorPickerListener listener) {
        this.listener = listener;
    }

    public interface DialogColorPickerListener {
        void onConfirm(int selectedColor);
    }
}

*in MainActivity.class outside the onCreate()
public void openColorPickerDialog(View v) {
        DialogColorPicker colorPicker = new DialogColorPicker();
        colorPicker.setListener(new DialogColorPicker.DialogColorPickerListener(){
            @Override
            public void onConfirm(int selectedColor) {
                //Handle your color change from here;
                constraintLayout.setBackgroundColor(selectedColor);
            }
        });
        colorPicker.showNow(getSupportFragmentManager(), "ColorPicker");
    }

Hope this will work. And better way to handle.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to color/remove the separator between last and second to last row in a SwiftUI List? I'm using simple SwiftUI Lists such as
List {
  Text("A")
  Text("A")
  Text("A")
}

I've already managed to remove the standard dividers by adding UITableView.appearance().separatorColor = .clear, however there seems to be another slim light gray divider between the last and second to last element:

How can I remove this divider or change its color?

A:
I've already managed to remove the standard dividers by adding
  UITableView.appearance().separatorColor = .clear

Use instead
UITableView.appearance().separatorStyle = .none

A: You can use ScrollView with ForEach instead of default List. It will be without default styling, and you can define your own style.
struct ContentView: View {
    @State private var words = (1...50).map{ String($0) }
    var body: some View {
        GeometryReader { geometry in
            ScrollView {
                ForEach(self.words, id: \.self) { word in
                    Text(word)
                }
                    .frame(width: geometry.size.width)
            }
        }
    }
}


text:
Q: 4G Modem Huawei HiLink - can't connect Modem Huawei E3372H
Changed firmware from windows with special program, it should be now (I don't know how to check if it is really so):
WEBUI_17.100.06.00.03_Hilink_v7r2_9x25

When I connect it in my Linux Mint XFCE:

*

*nothing visually happens on the screen

*no device seen in Modem Connection

*GUI modem indicator blinks green (frequently)

*I don't see any new device beside my normal ethernet port available in add
connection settings, trying to add ethernet connection

*I tried to add ethernet connection, but I don't see any new device beside my normal ethernet port available in add connection settings

*http://192.168.1.1 - doesn't connect

*I see device in lsusb:

lsusb
  Bus 001 Device 010: ID 12d1:1c05 Huawei Technologies Co., Ltd. Broadband stick (modem on)

How can I setup internet throw modem?
What are my next steps?


text:
Q: Returning ClickOnce version doesn't work when launching application on startup from the Windows Registry I'm using the following code with System.Deployment to return the ClickOnce version of my .NET 3.5 C# application:
public string version
{
    get
    {
        System.Reflection.Assembly _assemblyInfo = System.Reflection.Assembly.GetExecutingAssembly();
        string ourVersion = string.Empty;

        if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
        {
            ourVersion = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
        }
        else
        {
            if (_assemblyInfo != null)
            {
                ourVersion = _assemblyInfo.GetName().Version.ToString();
            }
        }
        return ourVersion;
    }
}

If I launch the application normally (from the Start menu, for example), this value is always returned correctly. However, if I start the application automatically with Windows using a registry key, the application returns the default hardcoded value of 1.0.0.0.
If I close the automatically-started application and re-open it manually, it then returns the correct ClickOnce version number again.
Any ideas on why this might be? Here is the code I'm using to set the registry key:
string keyName = "MyApp";
string assemblyLocation = Assembly.GetExecutingAssembly().Location;
Util.SetAutoStart(keyName, assemblyLocation);

And
public class Util
{
    private const string RUN_LOCATION = @"Software\Microsoft\Windows\CurrentVersion\Run";

    /// <summary>
    /// Sets the autostart value for the assembly.
    /// </summary>
    /// <param name="keyName">Registry Key Name</param>
    /// <param name="assemblyLocation">Assembly location (e.g. Assembly.GetExecutingAssembly().Location)</param>
    public static void SetAutoStart(string keyName, string assemblyLocation)
    {
        RegistryKey key = Registry.CurrentUser.CreateSubKey(RUN_LOCATION);
        key.SetValue(keyName, assemblyLocation);
    }

    /// <summary>
    /// Returns whether auto start is enabled.
    /// </summary>
    /// <param name="keyName">Registry Key Name</param>
    /// <param name="assemblyLocation">Assembly location (e.g. Assembly.GetExecutingAssembly().Location)</param>
    public static bool IsAutoStartEnabled(string keyName, string assemblyLocation)
    {
        RegistryKey key = Registry.CurrentUser.OpenSubKey(RUN_LOCATION);
        if (key == null)
            return false;

        string value = (string)key.GetValue(keyName);
        if (value == null)
            return false;

        return (value == assemblyLocation);
    }

    /// <summary>
    /// Unsets the autostart value for the assembly.
    /// </summary>
    /// <param name="keyName">Registry Key Name</param>
    public static void UnSetAutoStart(string keyName)
    {
        RegistryKey key = Registry.CurrentUser.CreateSubKey(RUN_LOCATION);
        key.DeleteValue(keyName);
    }
}

A: I've isolated the problem. I won't pretend to understand exactly how ClickOnce works, but basically, if you launch the executable file directly it won't run in "ClickOnce mode". This means it won't check for updates and won't get the correct version number (since it isn't actually network deployed).
The best solution I've found so far is to point to the ClickOnce .appref-ms file rather than the .exe file. This file is like a shortcut of sorts, and is in the start menu.
Here's the code I'm using to get the location of my app's .appref-ms file:
string allProgramsPath = Environment.GetFolderPath(Environment.SpecialFolder.Programs);
string shortcutPath = Path.Combine(allProgramsPath, keyName);
shortcutPath = Path.Combine(shortcutPath, keyName) + ".appref-ms";

And then I combine that with my previous code to set that location in the registry.


text:
Q: On IISNODE, nodejs application cann't connect to DB recycle or inactive process shutdown For some reason which I do not know why node application is not able to reconnect DB after recycle. the connection can be done after IISNode application manual restart. Below is my server.js file which did not find anything wrong in it;
const http = require('http');
var openHttpConnections = {};
var httpServer;
const dbOperationsWPool = require('./api/dbLib/dbOperationsWPool');

const compression = require('compression');
const helmet = require('helmet')
require('dotenv').config({
    path: __dirname + '\\mynode.env'
});
const dbPoolConfig = require("./dbPoolConfig");
const config = require('./config'); // get our config file
const bodyParser = require('body-parser');
var express = require('express'),
    cors = require('cors'),
    app = express();
// port = process.env.PORT || 4600;

const verifyToken = require('./api/lib/verifyToken');
app.use(helmet());
app.use(compression());
app.use(cors());
app.options('*', cors());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.set('superSecret', config.secret);

var authRoutes = require('./api/routes/authRoutes');
authRoutes(app); //register the route
var wsRoutes = require('./api/routes/wsRoutes');
wsRoutes(app);
// const wsVerifyToken = require('./api/lib/verifyWebServiceToken');
// app.use(wsVerifyToken);
app.use(verifyToken); // Yeri değiştirilmemeli. bu satırdan sonra oluşan routes token aranacaktır

const commonRoutes = require('./api/routes/commonRouter');
commonRoutes(app);
var izinRoutes = require('./api/routes/ikRoutes');
izinRoutes(app);

var satinalmaRoutes = require('./api/routes/satinalmaRoutes');
satinalmaRoutes(app);
var finansRoutes = require('./api/routes/finansRoutes');
finansRoutes(app);

var reportRoutes = require('./api/routes/reportRoutes');
reportRoutes(app);

app.use(handleError);
httpServer = http.Server(app);
app.use(function (req, res) {
    res.status(404).send({
        url: req.originalUrl + ' not found'
    })
});
httpServer.on('connection', function (conn) {
    var key = conn.remoteAddress + ':' + (conn.remotePort || '');
    openHttpConnections[key] = conn;
    conn.on('close', function () {
        delete openHttpConnections[key];
    });
});
httpServer.on('error', (err) => {
    console.log("Caught flash policy server socket error: ")
    console.log(err.stack)
});
/// create pool
dbOperationsWPool.createPool(dbPoolConfig).then(function () {
        // IS_NODE_PROD
        var port = 4900;
        if (process.env.IS_NODE_PROD === 'true' || process.env.IS_NODE_TEST === "true") {
            port = process.env.PORT;
        }

        httpServer.listen(port, function () {
            console.log('Webserver listening on localhost:' + port);
        });

    })
    .catch(function (err) {
        console.error('Error occurred creating database connection pool', err);
        console.log('Exiting process');
        process.exit(0);
    });

//app.listen(port);
//console.log('Onay RESTful API server started on: //' + port);

function handleError(err, req, res, next) {
    //console.error(err);
    res.status(500).send({
        error: 'Hata oluştu Erp yardım masasına başvurunuz'
    });
    shutdown(); //process would usually be restarted via something like https://github.com/foreverjs/forever
}

function shutdown() {
    console.log('Shutting down');
    dbOperationsWPool.terminatePool()
        .then(function () {
            console.log('node-oracledb connection pool terminated');
            console.log('Exiting process');
            process.exit(0);
        })
        .catch(function (err) {
            console.error('Error occurred while terminating node-oracledb connection pool', err);
            console.log('Exiting process');
            process.exit(0);
        });

    for (key in openHttpConnections) {
        openHttpConnections[key].destroy();
    }
}

the only line which might be suspicious is the shutdown function which termenates the pool. Any help is appreciated.


text:
Q: Do I still need database in setting multiple alarms or reminders? So I'm developing this Android application which has many features, and one of them is the workout reminder. We used firebase database in setting up login authentication, and the user's information.
Now for the last feature, I made a workout reminder which consists of Task Name and Time which also has a notification and. It only sets one alarm and I assume that if I applied and displayed it in a Recycler View, it will set multiple alarms. Unfortunately, it doesn't. When the reminder is displayed in the Recycler View, and when I restart the application, the reminder is gone.
I just want to humbly ask if I need to store it in a database and then retrieve it?
Thank you in advance!
Here is my code below:
public class AlertReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    NotificationHelper notificationHelper = new NotificationHelper(context);
    NotificationCompat.Builder nb = notificationHelper.getChannel1Notification(reminderAddFragment.getTitle(), reminderAddFragment.getMessage());
    notificationHelper.getManager().notify(1, nb.build());
}

}
 private void startAlarm(Calendar cal) {
    AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(getActivity(), AlertReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 1, intent, 0);

    alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
}

A: Solved it by setting different requestCode everytime I set an alarm.
private void startAlarm(Calendar cal) {
    AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(getActivity(), AlertReceiver.class);
    final int id = (int) System.currentTimeMillis();
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), id, intent, PendingIntent.FLAG_MUTABLE);

    alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
}

A: Yes, you need to persist the state of alarms set by your app and display the same to the user. Once set we cannot retrieve the alarms set by the system at the app level. All we can do is dump them using adb shell using:
adb shell dumpsys alarm > alarms_dump.txt


text:
Q: Booting WDS Capture image on VM Gen2 Have problem booting capture image, created by Microsoft WDS management console. I have functional boot image (boot.wim) taken from WinServer 2012 R2 iso. This image works fine on Hyper-V Gen2 VM. But when I create capture image from working image, I am unable to boot and start the capture image on that same VM.
I have already made well-known fix of well-known MS bug (see this) -  Status: 0xc000000f durring boot. I dont get this error anymore. But have another one:
After the capture image is successfuly downloaded from WDS server (progress bar), it tries to start the image (Hyper-V logo and spinner) for a while, but than I got blank black screen.


text:
Q: How to hide navigation drawer when opening certain fragment? I'm pretty new in android development. I want to hide navigation drawer when user is not logged in. So basically, it will shown login fragment (better in full screen like Facebook android). And if user already logged in, navigation drawer will always shown.

MainActivity.java

public class MainActivity extends AppCompatActivity {

private DrawerLayout navDrawerLayout;
private Toolbar toolbar;
private ActionBarDrawerToggle navDrawerToggle;

private SharedPreferences pref;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    navDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    // Find our drawer view
    NavigationView navDrawerView = (NavigationView) findViewById(R.id.navdrawer_view);
    // Setup drawer view
    setupDrawerContent(navDrawerView);

    navDrawerToggle = setupDrawerToggle();

    pref = getPreferences(0);
    initFirstFrame();
}

private ActionBarDrawerToggle setupDrawerToggle() {
    return new ActionBarDrawerToggle(this, navDrawerLayout, toolbar, R.string.drawer_open,  R.string.drawer_close);
}

private void setupDrawerContent(NavigationView navDrawerView) {
    navDrawerView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    selectDrawerItem(menuItem);
                    return true;
                }

            });
}

public void selectDrawerItem(MenuItem menuItem) {
    // Create a new fragment and specify the fragment to show based on nav item clicked
    Fragment fragment = null;
    Class fragmentClass;
    switch(menuItem.getItemId()) {
        case R.id.events:
            fragmentClass = EventsFragment.class;
            break;
        case R.id.pengumuman:
            fragmentClass = NewsFragment.class;
            break;
        case R.id.edit_profil:
            fragmentClass = ProfileFragment.class;
            break;
        default:
            fragmentClass = EventsFragment.class;
    }

    try {
        fragment = (Fragment) fragmentClass.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Insert the fragment by replacing any existing fragment
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.frame_content, fragment).commit();

    // Highlight the selected item has been done by NavigationView
    menuItem.setChecked(true);
    // Set action bar title
    setTitle(menuItem.getTitle());
    // Close the navigation drawer
    navDrawerLayout.closeDrawers();
}

private void initFirstFrame(){
    Fragment fragment;
    if(pref.getBoolean(Constants.IS_LOGGED_IN,false)){
        fragment = new ProfileFragment();
    }else {
        fragment = new LoginFragment();
        // in this login fragment, navdrawer should be invisible, the toolbar too I guess
    }

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.frame_content,fragment);
    fragmentTransaction.commit();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return navDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}

// 'onPostCreate' called when activity start-up is complete after 'onStart()'
// NOTE! Make sure to override the method with only a single 'Bundle' argument
@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred
    navDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggles
    navDrawerToggle.onConfigurationChanged(newConfig);
}

}

A: This code in activity onCreate method will block drawer when you will have more than one fragment in stack:
 getSupportFragmentManager().addOnBackStackChangedListener(() -> {
        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        } else {
            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        }
    });

A: Define an interface say DrawerLocker:
interface DrawerLocker{
   public void setDrawerLocked(boolean shouldLock);
}

Implement this interface in your activity which contains the NavigationDrawer and override this method.
class YourActivity implements DrawerLocker{
...
...
public void setDrawerLocked(boolean enabled){
    if(enabled){
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    }else{
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
    }

}

Now in your Fragment's onCreateView, call this method like:
 ((DrawerLocker)getActivity()).setDrawerLocked(true);

In your Fragment's onDestroyView, re enable the drawer layout:
((DrawerLocker)getActivity()).setDrawerLocked(false);

A: This is all you need, check your destinations in if condition where you don't want the drawer to be

Single activity architecture, put below code in activity onCreate

private fun changeDrawerState() {
    val navHostFragment = supportFragmentManager
        .findFragmentById(R.id.nav_host_fragment) as NavHostFragment
    val drawer = findViewById<DrawerLayout>(R.id.drawer_layout)
    navHostFragment.navController.addOnDestinationChangedListener(listener = { _, destination, _ ->
        //set in case app asked for verify auth, signIn page drawer will be locked
        if (destination.id== R.id.signInFragment) {
            drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
        } else if (drawer.getDrawerLockMode(GravityCompat.START) != DrawerLayout.LOCK_MODE_UNLOCKED) {
            drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
        }
    })
}

GravityCompat.START based on your drawer open direction


text:
Q: Creating an iOS Swift Application that gets synonyms and definitions for words entered by the user I am working on an iOS application using Swift that takes a word from a user and finds the synonyms for that word. It then offers to find the definitions for each of those synonyms.
I have done a lot of research but I have been having trouble finding any simple way to just access a thesaurus or dictionary using Swift and get synonyms or definitions. I am not interested in using the UIReferenceLibraryViewController since Apple is against much use of that and I hope to post my application on the App Store. I am aware that there are some dictionaries out there that are built using Objective-C, but I would be unsure of how to implement those in my (currently) Swift-only application.
I have found one API for Oxford dictionaries here that provides implementation for Swift, but there are a few hurdles (such as pricing and app keys that I don't have yet) that I am unsure about and am therefore curious if there are any other methods out there.
If anyone is aware of a simple way to access a thesaurus or dictionary through Swift to simply get a list of synonyms for a word or a definition of a word, I would greatly appreciate it. If there are no simple ways to do this but there are good instructions for a more complicated way to go about doing this, those would also be appreciated. Thanks!

A: As you have mentioned 99% of the APIs are paid services or having limited features. But still the one that i would prefer using is

https://www.wordsapi.com/

With the basic version of wordsapi (unpaid version) you can make up to 2500 calls / day. I would suggest you to use the same till your app gets some recognition. Later, if you feel your app is about to make more load, you can update to the paid version which makes sense.
Just putting the sample request on how to make the same in swift. Replace the

MapKey

with your

wordsApiKey

let string = "https://wordsapiv1.p.mashape.com/words/stack/synonyms"
let url = NSURL(string: string)
let request = NSMutableURLRequest(URL: url!)
request.setValue("MapKey", forHTTPHeaderField: "X-Mashape-Key")
request.HTTPMethod = "GET"
let session = NSURLSession.sharedSession()

let request = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
    if let resp = response as? NSHTTPURLResponse {
        // Do what you want to do with your response.
    }
}
request.resume()

Putting the response that i got for the word "stack" that i tried to search for. (I tried out with curl command to get the response)
    {
  "word": "stack",
  "synonyms": [
    "smokestack",
    "push-down list",
    "push-down stack",
    "heap",
    "pile",
    "push-down storage",
    "push-down store",
    "batch",
    "deal",
    "flock",
    "good deal",
    "great deal",
    "hatful",
    "lot",
    "mass",
    "mess",
    "mickle",
    "mint",
    "mountain",
    "muckle",
    "passel",
    "peck",
    "plenty",
    "pot",
    "quite a little",
    "raft",
    "sight",
    "slew",
    "spate",
    "tidy sum",
    "wad"
  ]
}

There are other features apart from synonyms like antonyms, definition, examples etc., that you can use of it.
Hope this one helps.


text:
Q: Regular expression in python to fetch a line that starts with one string, in middle some other string and ends with different string this is my code :
 s="""
    [  8]   0.00-34.53  sec  0.00 Bytes  0.00 bits/sec                  receiver
    [SUM]   0.00-34.53  sec  2.11 GBytes   624 Mbits/sec                  sender
    [ 12]   0.00-34.53  sec  0.00 Bytes  0.00 bits/sec                  receive
    [SUM]   0.00-34.75  sec  0.00 Bytes  0.00 bits/sec                  sender
    [SUM]   0.00-34.53  sec  2.11 GBytes   824 Mbits/sec                  sender
    [SUM]   0.00-34.75  sec  0.00 Bytes  0.00 bits/sec                  sender
    """
   items=re.findall("^.[SUM].*sender",s,re.MULTILINE)
     for x in items:
     print(x)

which gives the output :
[SUM]   0.00-34.53  sec  2.11 GBytes   624 Mbits/sec                  sender
[SUM]   0.00-34.53  sec  2.11 GBytes   824 Mbits/sec                  sender
[SUM]   0.00-34.75  sec  0.00 Bytes  0.00 bits/sec                  sender
[SUM]   0.00-34.75  sec  0.00 Bytes  0.00 bits/sec                  sender

but i want to get the below output, that starts with string [SUM] and ends with string sender and should not display the line that has any 0.00 bytes and 0.00 bits/sec
[SUM]   0.00-34.53  sec  2.11 GBytes   624 Mbits/sec                  sender
[SUM]   0.00-34.53  sec  2.11 GBytes   824 Mbits/sec                  sender

A: This should work for you - you might want to make some tweaking for your specific needs:
In [151]: regex = "^(\[SUM\](?!.*(([0-9]+\.[0-9]{2}).*){3}.*0\.00).*sender)"

In [152]: items=re.findall(regex,s,re.MULTILINE)
     ...: for x in items:
     ...:     print(x)
     ...:
('[SUM]   0.00-34.53  sec  2.11 GBytes   624 Mbits/sec                  sender', '', '')
('[SUM]   0.00-34.53  sec  2.11 GBytes   824 Mbits/sec                  sender', '   0.00', '   0.00-34.53  sec  2.11')

A: With negative lookahead, you could use this regex:
reg = "^\s*\[SUM\]\s*[0-9\-\.]+\s+sec(?!\s+0\.00 Bytes).*sender.*"
items=re.findall(reg,s,re.MULTILINE)
for line in items:
    print(line)

The ?! indicates that the regex after should not be a match. More info


text:
Q: Hiding chart lines with no value How can I hide the lines that go below value 1 so the chart doesn't look like the one below?. My chart shows a product sales over period of time. Some products don't have enought data which produces weirdly looking charts.

I have added vAxis: { viewWindowMode: 'pretty' }  and this is helping to some extent to make it "pretty" but it isn't enough.
I've tried with data view and I thought that was the solution but the view is hiding some extra rows. My code for view where I convert the 0 row to date and trying to limit the min and max values:
let view = new google.visualization.DataView(dataYear);
            view.setColumns([{
                calc: function(dataYear, row) {
                    return new Date(dataYear.getValue(row, 0));
                },
                label: dataYear.getColumnLabel(0),
                type: 'date'
            }, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
            view.setRows(view.getFilteredRows([{
                column: 1,
                minValue: 1,
                maxValue: 500
            }]));

I am a bit confused how view exactly works after many tries of tweaking up different columns and min/maxValues. In addition, I can target only 1 column at a time with the view? Bonus question: I would like also to hide the data points that are with 0 value (the one appearing on the x axis)
My chart code:
function chartYear(dataYear) {
            // Display the total number of products sold for each chart/period
            function getSum(dataYear, column) {
                var total = 0;
                for (i = 0; i < dataYear.getNumberOfRows(); i++)
                    total = total + dataYear.getValue(i, column);
                return total;
            }
            let name = document.querySelectorAll('.google-visualization-table-tr-sel td')[2].textContent;
            let interval = 1;
            let dataRange = dataYear.getColumnRange(9);
            let vTicks = [];
            for (var i = dataRange.min; i <= dataRange.max + interval; i = i + interval) {
                vTicks.push(i);
            };

            var chart = new google.visualization.ChartWrapper({
                chartType: 'LineChart',
                containerId: 'chartYear',
                options: {
                    title: "6 months sales: " + name + "\nTotal: " + getSum(dataYear, 9),
                    curveType: "function",
                    pointsVisible: true,
                    pointSize: 5,
                    snapToData: true,
                    // pointBackgroundColor: '#FF0000',
                    titleTextStyle: {
                        fontName: 'Verdana',
                        fontSize: 13,
                        italic: true
                    },
                    vAxis: {
                        viewWindowMode: 'pretty',
                        ticks: vTicks,
                        minValue: 1
                    },
                    hAxis: {
                        // minValue: 1,  // THROWS ERROR a.getTime() is not a function
                        // viewWindowMode: 'pretty',
                        slantedText: 1,
                        slantedTextAngle: 60
                    },
                    series: {
                        0: {
                            color: '#DC3912'
                        },
                        1: {
                            color: '#FF9900'
                        },
                        2: {
                            color: '#109618'
                        },
                        3: {
                            color: '#990099'
                        },
                        4: {
                            color: '#bbe9ff'
                        },
                        5: {
                            color: '#43459d'
                        },
                        6: {
                            color: '#C60AD3'
                        },
                        7: {
                            color: '#1c91c0'
                        },
                        8: {
                            color: '#3366CC'
                        },
                    }
                }
            });

            var dateSlider = new google.visualization.ControlWrapper({
                'controlType': 'ChartRangeFilter',
                'containerId': 'chartRangeFilter',
                'options': {
                    filterColumnLabel: 'Dato',
                    ui: {
                        chartType: 'LineChart',
                        chartOptions: {
                            snapToData: true,
                            height: 50,
                            chartArea: {
                                width: '80%'
                            },
                            series: {
                                0: {
                                    color: '#DC3912'
                                },
                                1: {
                                    color: '#FF9900'
                                },
                                2: {
                                    color: '#109618'
                                },
                                3: {
                                    color: '#990099'
                                },
                                4: {
                                    color: '#bbe9ff'
                                },
                                5: {
                                    color: '#43459d'
                                },
                                6: {
                                    color: '#C60AD3'
                                },
                                7: {
                                    color: '#1c91c0'
                                },
                                8: {
                                    color: '#3366CC'
                                },
                            }
                        }
                    }
                }
            });
            var formatter_long = new google.visualization.DateFormat({
                pattern: 'yyyy-MM-dd'
            });
            formatter_long.format(dataYear, 0);

            google.visualization.events.addListener(chart, 'error', function(googleError) {
                google.visualization.errors.removeError(googleError.id);
            });

            let view = new google.visualization.DataView(dataYear);
            view.setColumns([{
                calc: function(dataYear, row) {
                    return new Date(dataYear.getValue(row, 0));
                },
                label: dataYear.getColumnLabel(0),
                type: 'date'
            }, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
            view.setRows(view.getFilteredRows([{
                column: 1,
                minValue: 0,
                maxValue: 500
            }]));

            var dashboard2 = new google.visualization.Dashboard(document.getElementById('dashboard2'));
            dashboard2.bind(dateSlider, chart);
            dashboard2.draw(view);

        }

The chart is drawn when the user clicks on a table row. I send the product id with ajax and get back data for this product. I can add the select handler if needed.


text:
Q: The number $2^{3^n}+1$ is divisible by $3^{n+1}$ and not divisible by $3^{n+2}$.
Prove that for every $n\in \mathbb N$, $2^{3^n}+1$ is divisible by $3^{n+1}$ and not divisible by $3^{n+2}$.

I was able to prove that $2^{3^n}+1$ is divisible by $3^{n+1}$ using induction.
First, I check whether the statement is true for $n=1$. The statement holds since:
$$2^{3^1}+1=9$$ $$3^{1+1}=9$$
Second, I assume that the statement is true for every $n\in \mathbb N$.
Finally, I take that $n=n+1$. From that, the original expression becomes $(2^{3^n})^3+1$, which is a sum of cubes, and the same as:
$$(2^{3^n}+1)((2^{3^n})^2-2^{3^n}+1)$$
As I assumed that $2^{3^n}+1$ is divisible by $3^{n+1}$, and one of the factors is $2^{3^n}+1$, the entire expression must be divisible by $3^{n+1}$, and so the statement is true for every $n\in \mathbb N$.
Now, I don't know how to prove that $2^{3^n}+1$ isn't divisible by $3^{n+2}$. Please explain how I can do so step-by-step, without using complicated terms.

A: Let
$$A_n = 2^{3^n}+1.$$
The claim holds for $n=0$, and since:
$$ A_{n+1} = (A_n-1)^3+1 = A_n^3 -3A_n(A_n-1) $$
we have that $\nu_3(A_{n+1}) = 1+\nu_3(A_n)$, since $9\mid A_n^3$ and $3\mid 3A_n$ but $3\nmid (A_n-1)$.


text:
Q: Failed to Deploy to Heroku Platform I am creating a html web form, from which I want the data to be stored into the local machine. While running the program it works fine on my local machine.
When I push the program to Heroku platform it fails.
   ----main file
   -------Procfile
   -------requirements.txt
   -------runtime.txt
   -------main.py
   -------static
   ----templates
   ------index.html
   ----static
   ------index_css.css

Procfile:
     web: gunicorn main:app

Requirements:
    flask==1.1.1
    flask-mysqldb==0.2.0
    gunicorn==19.9.0
    pyodbc==4.0.30

Runtime:
    python-3.7.2

Error While Deploying it on Heroku PLatform:
    Building wheel for pyodbc (setup.py): started
     Building wheel for pyodbc (setup.py): finished with status 'error'
     ERROR: Command errored out with exit status 1:
      command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-q2igx1jr/pyodbc/setup.py'"'"'; __file__='"'"'/tmp/pip-install-q2igx1jr/pyodbc/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-8r1wqs6z
          cwd: /tmp/pip-install-q2igx1jr/pyodbc/
     Complete output (16 lines):
     /app/.heroku/python/lib/python3.7/distutils/dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type'
       warnings.warn(msg)
     running bdist_wheel
     running build
     running build_ext
     building 'pyodbc' extension
     creating build
     creating build/temp.linux-x86_64-3.7
     creating build/temp.linux-x86_64-3.7/src
     gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DPYODBC_VERSION=4.0.30 -I/app/.heroku/python/include/python3.7m -c src/buffer.cpp -o build/temp.linux-x86_64-3.7/src/buffer.o -Wno-write-strings
     In file included from src/buffer.cpp:12:0:
     src/pyodbc.h:56:10: fatal error: sql.h: No such file or directory
      #include <sql.h>
               ^~~~~~~
     compilation terminated.
     error: command 'gcc' failed with exit status 1
     ----------------------------------------
     ERROR: Failed building wheel for pyodbc
     Running setup.py clean for pyodbc
     Building wheel for mysqlclient (setup.py): started
     Building wheel for mysqlclient (setup.py): finished with status 'done'
     Created wheel for mysqlclient: filename=mysqlclient-2.0.0-cp37-cp37m-linux_x86_64.whl size=100868 sha256=ffd0776f2d39a5405cc1ac1465a08f48ee9da558c172105866f17378a6edebbd
     Stored in directory: /tmp/pip-ephem-wheel-cache-5xsag9fy/wheels/80/87/ff/4ea9d03e0a265ef3a4a0cdf0cf1e4786c37665c4015b2ece83
   Successfully built flask-mysqldb mysqlclient
   Failed to build pyodbc
   Installing collected packages: Werkzeug, click, itsdangerous, MarkupSafe, Jinja2, flask, mysqlclient, flask-mysqldb, gunicorn, pyodbc
       Running setup.py install for pyodbc: started
       Running setup.py install for pyodbc: finished with status 'error'
       ERROR: Command errored out with exit status 1:
        command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-q2igx1jr/pyodbc/setup.py'"'"'; __file__='"'"'/tmp/pip-install-q2igx1jr/pyodbc/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-oz00635z/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.7m/pyodbc
            cwd: /tmp/pip-install-q2igx1jr/pyodbc/
       Complete output (16 lines):
       /app/.heroku/python/lib/python3.7/distutils/dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type'
         warnings.warn(msg)
       running install
       running build
       running build_ext
       building 'pyodbc' extension
       creating build
       creating build/temp.linux-x86_64-3.7
       creating build/temp.linux-x86_64-3.7/src
       gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DPYODBC_VERSION=4.0.30 -I/app/.heroku/python/include/python3.7m -c src/buffer.cpp -o build/temp.linux-x86_64-3.7/src/buffer.o -Wno-write-strings
       In file included from src/buffer.cpp:12:0:
       src/pyodbc.h:56:10: fatal error: sql.h: No such file or directory
        #include <sql.h>
                 ^~~~~~~
       compilation terminated.
       error: command 'gcc' failed with exit status 1
       ----------------------------------------
   ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-q2igx1jr/pyodbc/setup.py'"'"'; __file__='"'"'/tmp/pip-install-q2igx1jr/pyodbc/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-oz00635z/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.7m/pyodbc Check the logs for full command output.
Push rejected, failed to compile Python app.
Push failed

I am fairly new to Heroku and I don't know how to solve this error.

A: in Procfile you can change:
web: gunicorn main.wsgi


text:
Q: How to share files with coworkers via internet? Securely? I have number of co-workers in other countries. I would like to be able to setup something like shared network drive so that we can all access the files and work together. What's the best way of doing that? Do I need Lion server for that?

A: Why not use something like Dropbox?
There's also Sparkleshare which allows you to host files yourself.

A: OwnCloud lets you setup your own cloud server environment.


text:
Q: How to update a SQLite column with a value that is a function of the current time I have an IoT project that subscribes to sensor data via MQTT, saves the data to a local SQLite3 DB, does some processing on the data, then publishes a handful of new messages via MQTT every 60 seconds. I have one SQLite table whose schema is something like this (I've omitted irrelevant columns):
sensor
id integer PRIMARY KEY,
last_heard text (ISO String),
first_heard text (ISO String),
certainty real CHECK(certainty >= 0 and certainty <= 1),
is_monitored boolean

Each row in the table represents a unique sensor. certainty gets initialized at .5 when a sensor is first heard. For all sensors where is_monitored is True, every two minutes that the sensor is NOT heard, certainty needs to be decremented by .05.
In other words, for monitored sensors,
certainty = certainty - (.05 * ((time_now_minutes - last_heard_minutes) // 2))
How is this best accomplished in Python and/or SQLite3? Any help is greatly appreciated.
Here's what I've tried:

*

*I tried creating a View in the Database in order to have a computed column that held the amount of time unseen for each sensor/row which allowed me to compute the so-called "adjusted_certainty" as another column in the View. The problem with this approach was that you can't put constraints on computed columns in Views in SQLite, so the adjusted_certainty was going below 0, and it forced me to keep track of two versions of certainty from the Python code - the first being the writable certainty in the sensor table, and the second being the read-only adjusted_certainty in the View.

*In my Python script, I'm able to get all monitored sensors, calculate how long each of them hasn't been seen, and update their certainties accordingly. The problem is, I don't know when to do this. If I do it before my outgoing messages to MQTT are sent, it seems like weird race conditions occur and data gets out of order in either the database, my outgoing messages, or both. If I update the certainties afterwards, then they wouldn't be accurate in the outgoing messages.

A: Every two minutes, decrement the certainty of all rows which have not been heard for more than two minutes.
Be sure to store the timestamps in a format that is easy to do math on. For your purposes the Unix epoch time would be preferable. Math is easy and there's no time zone issues.
Use max to ensure certainty does not drop below zero.
update sensors
set certainty = max(certainty - 0.05, 0)
where last_heard < unixepoch() - 120
  and certainty > 0

Alternatively, you can calculate the certainty at any time using a similar query and the math you suggested.
create view sensor_certainty as
select
  *,
  max(
    0.5 - (floor((unixepoch() - last_heard) / 120) * 0.05),
    0
  ) as certainty
from sensors

And, finally, you can use a generated virtual column.
alter table sensors
  add column certainty
  generated always as
  max(
    0.5 - (floor((unixepoch() - last_heard) / 120) * 0.05),
    0
  )
  virtual
  CHECK(certainty >= 0 and certainty <= 1),


text:
Q: Need to convert HTML string into Text through python This is what I have!  I want a code in which I pass this whole string and get only the text part from it! This is not a page this is simply a string, just like HTML page in txt extension type. Please help me out all other solutions using beautiful soup which takes URL, but this not a webpage.
Any Help will be appreciated.
b'<!DOCTYPE HTML>\r\n

   \r\n

      \r\n
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      \r\n
      <title>TalentHire - Simplified Recruiting and Staffing</title>
      \r\n

   \r\n        \r\n

      \r\n

         \r\n

            \r\n

               \r\n

                  \r\n                \t

                     \r\n

                        \r\n

                           \r\n

                              \r\n

Position:  Azure Architect

                              \r\n\r\n

Location: San Antonio, Texas

                              \r\n\r\n

\r\nResponsibilities-

                              \r\n\r\n

Customer is implementing a new POS solution and this program is all about  doing the integration work for the new POS along with data migration and some new web app development.
\r\nAll the integration and web development work will be done using azure PaaS components.
\r\nResponsibilities are:
\r\n·         Provide Inputs to enterprise solution Architecture
\r\n·        Design secure integration solutions/Architecture
\r\n·        Implement best practices when using azure components
\r\n·        Work with 3rd party vendor architects on behalf of Customer to design integration solution
\r\n·        Provide recommendation to optimize azure cost
\r\n·        Recommendation and best practices on using various azure resources
\r\n·        Hands on set up of azure components and design patterns for development teams to follow. Hands on to .Net Technologies

                              \r\n\r\n

\r\nResponsible for technical solutioning and design the integration Solution in AZURE. Design, develop, and construct detailed Azure architecture. Understand current state gaps and propose secured solutions to ensure roadmap can adapt to changes and integrate with existing environment or propose changes to existing environment. Work with vendors and customers to understand new solutions’ limitations and capabilities. Work with internal delivery teams to ensure solutions align with roadmap and architecture. Lead a team of engineers and developers to design and build solutions."

                              \r\n\r\n

Regards,

                              \r\n\r\n

Manish Kumar

                              \r\n\r\n

Email-ID:manish.kumar1@idctechnologies.com

                              \r\n\r\n

Desk NO:315-994-1244

                              \r\n

                           \r\n\r\n

                           \r\n

                        \r\n

                     \r\n

                        \r\n
                        \r\n
                        \r\n

                     \r\n

                  \r\n

               \r\n

            \r\n            \r\n                \t

         \r\n

 To unsubscribe from future emails or to update your email preferencesclick here .

      \r\n

   \r\n

\r\n'

A: from bs4 import BeautifulSoup
data = """
b'<!DOCTYPE HTML>\r\n

   \r\n

      \r\n
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      \r\n
      <title>TalentHire - Simplified Recruiting and Staffing</title>
      \r\n

   \r\n        \r\n

      \r\n

         \r\n

            \r\n

               \r\n

                  \r\n                \t

                     \r\n

                        \r\n

                           \r\n

                              \r\n

Position:  Azure Architect

                              \r\n\r\n

Location: San Antonio, Texas

                              \r\n\r\n

\r\nResponsibilities-

                              \r\n\r\n

Customer is implementing a new POS solution and this program is all about  doing the integration work for the new POS along with data migration and some new web app development.
\r\nAll the integration and web development work will be done using azure PaaS components.
\r\nResponsibilities are:
\r\n·         Provide Inputs to enterprise solution Architecture
\r\n·        Design secure integration solutions/Architecture
\r\n·        Implement best practices when using azure components
\r\n·        Work with 3rd party vendor architects on behalf of Customer to design integration solution
\r\n·        Provide recommendation to optimize azure cost
\r\n·        Recommendation and best practices on using various azure resources
\r\n·        Hands on set up of azure components and design patterns for development teams to follow. Hands on to .Net Technologies

                              \r\n\r\n

\r\nResponsible for technical solutioning and design the integration Solution in AZURE. Design, develop, and construct detailed Azure architecture. Understand current state gaps and propose secured solutions to ensure roadmap can adapt to changes and integrate with existing environment or propose changes to existing environment. Work with vendors and customers to understand new solutions’ limitations and capabilities. Work with internal delivery teams to ensure solutions align with roadmap and architecture. Lead a team of engineers and developers to design and build solutions."

                              \r\n\r\n

Regards,

                              \r\n\r\n

Manish Kumar

                              \r\n\r\n

Email-ID:manish.kumar1@idctechnologies.com

                              \r\n\r\n

Desk NO:315-994-1244

                              \r\n

                           \r\n\r\n

                           \r\n

                        \r\n

                     \r\n

                        \r\n
                        \r\n
                        \r\n

                     \r\n

                  \r\n

               \r\n

            \r\n            \r\n                \t

         \r\n

 To unsubscribe from future emails or to update your email preferencesclick here .

      \r\n

   \r\n

\r\n'
"""

soup = BeautifulSoup(data, 'html.parser')

print(soup.text)

output:
b'

TalentHire - Simplified Recruiting and Staffing

Position:  Azure Architect
Location: San Antonio, Texas

Responsibilities-
Customer is implementing a new POS solution and this program is all about  doing the integration work for the new POS along with data migration and some new web app development.
All the integration and web development work will be done using azure PaaS components.
Responsibilities are:
·         Provide Inputs to enterprise solution Architecture
·        Design secure integration solutions/Architecture
·        Implement best practices when using azure components
·        Work with 3rd party vendor architects on behalf of Customer to design integration solution
·        Provide recommendation to optimize azure cost
·        Recommendation and best practices on using various azure resources
·        Hands on set up of azure components and design patterns for development teams to follow. Hands on to .Net Technologies

Responsible for technical solutioning and design the integration Solution in
AZURE. Design, develop, and construct detailed Azure architecture. Understand current state gaps and propose secured solutions to ensure roadmap can adapt to changes and integrate with existing environment or propose changes to existing environment. Work with vendors and customers to understand new solutions' limitations and capabilities. Work with internal delivery teams to ensure
solutions align with roadmap and architecture. Lead a team of engineers and developers to design and build solutions."
Regards,
Manish Kumar
Email-ID:manish.kumar1@idctechnologies.com
Desk NO:315-994-1244

 To unsubscribe from future emails or to update your email preferencesclick here .

'


text:
Q: CSS table td vertical-align text-top I have problem with vertical-align to text-top on tables
I have globally set at table td to vertical-align: middle.
Now I need to change only one td to vertical-align: text-top
The problem is, that all variant that I tested set vertical-align:text-top are shown as top only
("xxxx" in image is not at same line as "yyyy")
Only one variant is working as text-top, and that is change globally style of all td (I don't want this, I need to change only one td)
SEE IMAGES
Setting as local style is shown as top
local style http://aukro.svecpetr.com/style.png
Setting as class is shown as top
local style http://aukro.svecpetr.com/class.png
Changing global td has the right effect of text-top
local style http://aukro.svecpetr.com/global-style.png
EXAMPLE you could find at
https://zbozimat.cz/test.php
Could somebody help me?

A: Add this for div:
display: inline-block;
vertical-align: top;

And this for input:
display: inline-block;
vertical-align: top;

A: It is also possible to set the attr style on your td
<td style="vertical-align: top;">


text:
Q: Integral involving power of trigonometric functions I'm having a technical problem evaluating the following integral:
$$\int_{r=0}^1\int_{\theta=0}^{\pi \over2}  \cos^{2\epsilon -1}\theta \sin^{\epsilon-1}\theta e^{-ikr\sin^\epsilon\theta}d\theta dr$$
$\epsilon [0;\infty)$. Change of variable $t=\sin^\epsilon\theta$ brings the integral to the form (some constant coefficients are omitted):
$$\int_{r=0}^1\int_{t=0}^{1}  (1-t^{2 \over \epsilon})^{\epsilon -1} e^{-ikrt}dt dr$$
My main concern is the integration of the expression above with respect to t. I wasn't able to evaluate this integral by parts/change of variable or using calculus of residues. Expanding $e^{-ikrt}=\sum_{n=0}^\infty (-ikrt)^n/n!$, then we have the integral of the type $$\int_{t=0}^{1} t^n(1-t^{2/\epsilon})^{\epsilon-1}dt$$ Integrating the expression above we get:$$\epsilon\Gamma(\epsilon)*\Gamma({\epsilon\over 2}\left(n+1)\right)\over2\Gamma\left({\epsilon\over 2}(n+3))\right)$$
  and $$\int_{t=0}^{1} (1-t^{2 \over \epsilon})^{\epsilon -1} e^{-ikrt}dt =\sum_{n=0}^\infty{\epsilon\Gamma(\epsilon) \Gamma\left((n+1){\epsilon\over 2}\right)\over 2\Gamma(\left(n+3){\epsilon\over 2}\right)}{(-ikr)^n\over n!}$$
The last summation looks similar to the series expansion of hypergeometric function except it has $\epsilon/2$ in the argument of the gamma function and it seems that $\Gamma(kx)$ does not equal anything nice in terms of $\Gamma(x)$. Maybe I'm missing some clever change of variables or nice contour for residue calculation.
This integral arises when performing the Fourier transform of a superellipsoid.
EDIT
I decided to add a short connotation to this question. The original problem comes from physics and requires making a Fourier transform of a superellipsoid. I parametrized superellipsoid in the following manner: $$x=a*r*\cos^\eta\theta*\cos^\epsilon\phi,$$ $$y=b*r*\cos^\eta\theta*\sin^\epsilon\phi,$$
$$z=c*r*\sin^\eta\theta$$
Here $\sin^{\epsilon}\theta$ and $\cos^{\eta}\theta$ are signed functions i.e. $\sin^{\epsilon}\theta = sign(\sin\theta)*|\sin^{\epsilon}\theta|$.
The absolute value of the determinant of the Jacobian is $abc\epsilon\eta r^2\cos^{2\epsilon-1}\theta\sin^{\epsilon -1}\theta\cos^{\eta-1}\phi\sin^{\eta-1}\phi$.
Next, when performing Fourier transform direct vector k along z axis. Then we have in the region $\theta[0,\pi/2]$, $\phi[0,\pi/2]$:
$$abc\epsilon\eta\int_{r=0}^1 \int_{\theta=0}^{\theta = \pi/2}\int_{\phi=0}^{\pi/2}e^{-ikr\sin^{\epsilon}}r^2\cos^{2\epsilon-1}\theta\sin^{\epsilon-1}\theta\cos^{\eta-1}\phi\sin^{\eta-1}\phi dr d\theta d\phi$$
Integration with respect to $\phi$ gives ${1 \over 2^{\eta - 1}}_2F_1({1 \over 2}, {2 - \eta \over 2};{3 \over 2};1)$ and we left with the integral of the form like in the very beginning of this question. Parameters $\epsilon$ and $\eta$ bear similar geometric meaning, $\epsilon = 0$, $\eta = 0$ gives a rectangular shape, as $\epsilon$ and $\eta$ approach 1 the shape becomes more like normal ellipse and high values of $\epsilon$ and $\eta$ give shapes with pointy cornets like stars, see the illustration at Paul Bourke's web page. My intuition suggests that Fourier transform should depend on $\epsilon$ in the similar way as it depends on $\eta$.

A: $\int_0^1\int_0^\frac{\pi}{2}\cos^{2\epsilon-1}\theta~\sin^{\epsilon-1}\theta ~e^{-ikr\sin^\epsilon\theta}~d\theta~dr$
$=\int_0^1\int_0^\frac{\pi}{2}\cos^{2\epsilon-2}\theta~\sin^{\epsilon-1}\theta ~e^{-ikr\sin^\epsilon\theta}~d(\sin\theta)~dr$
$=\int_0^1\int_0^1(1-x^2)^{\epsilon-1}x^{\epsilon-1}e^{-ikrx^\epsilon}~dx~dr$
$=\int_0^1\int_0^1x^{\epsilon-1}(1-x^2)^{\epsilon-1}\cos krx^\epsilon~dx~dr-i\int_0^1\int_0^1x^{\epsilon-1}(1-x^2)^{\epsilon-1}\sin krx^\epsilon~dx~dr$
$=\int_0^1\int_0^1\sum\limits_{n=0}^\infty\dfrac{(-1)^nk^{2n}r^{2n}x^{(2n+1)\epsilon-1}(1-x^2)^{\epsilon-1}}{(2n)!}~dx~dr-i\int_0^1\int_0^1\sum\limits_{n=0}^\infty\dfrac{(-1)^nk^{2n+1}r^{2n+1}x^{(2n+2)\epsilon-1}(1-x^2)^{\epsilon-1}}{(2n+1)!}~dx~dr$
$=\int_0^1\int_0^1\sum\limits_{n=0}^\infty\dfrac{(-1)^nk^{2n}r^{2n}x^\frac{(2n+1)\epsilon-1}{2}(1-x)^{\epsilon-1}}{(2n)!}~d(x^\frac{1}{2})~dr-i\int_0^1\int_0^1\sum\limits_{n=0}^\infty\dfrac{(-1)^nk^{2n+1}r^{2n+1}x^\frac{(2n+2)\epsilon-1}{2}(1-x)^{\epsilon-1}}{(2n+1)!}~d(x^\frac{1}{2})~dr$
$=\int_0^1\int_0^1\sum\limits_{n=0}^\infty\dfrac{(-1)^nk^{2n}r^{2n}x^{\frac{(2n+1)\epsilon}{2}-1}(1-x)^{\epsilon-1}}{2(2n)!}~dx~dr-i\int_0^1\int_0^1\sum\limits_{n=0}^\infty\dfrac{(-1)^nk^{2n+1}r^{2n+1}x^{(n+1)\epsilon-1}(1-x)^{\epsilon-1}}{(2n+1)!}~dx~dr$
$=\int_0^1\sum\limits_{n=0}^\infty\dfrac{(-1)^nk^{2n}r^{2n}B\left(\dfrac{(2n+1)\epsilon}{2},\epsilon\right)}{2(2n)!}~dr-i\int_0^1\sum\limits_{n=0}^\infty\dfrac{(-1)^nk^{2n+1}r^{2n+1}B((n+1)\epsilon,\epsilon)}{(2n+1)!}~dr$
$=\int_0^1\sum\limits_{n=0}^\infty\dfrac{(-1)^n\Gamma(\epsilon)\Gamma\left(\dfrac{(2n+1)\epsilon}{2}\right)k^{2n}r^{2n}}{2\Gamma\left(\dfrac{(2n+3)\epsilon}{2}\right)(2n)!}~dr-i\int_0^1\sum\limits_{n=0}^\infty\dfrac{(-1)^n\Gamma(\epsilon)\Gamma((n+1)\epsilon)k^{2n+1}r^{2n+1}}{\Gamma((n+2)\epsilon)(2n+1)!}~dr$
$=\left[\sum\limits_{n=0}^\infty\dfrac{(-1)^n\Gamma(\epsilon)\Gamma\left(\dfrac{(2n+1)\epsilon}{2}\right)k^{2n}r^{2n+1}}{2\Gamma\left(\dfrac{(2n+3)\epsilon}{2}\right)(2n+1)!}\right]_0^1-i\left[\sum\limits_{n=0}^\infty\dfrac{(-1)^n\Gamma(\epsilon)\Gamma((n+1)\epsilon)k^{2n+1}r^{2n+2}}{\Gamma((n+2)\epsilon)(2n+2)!}\right]_0^1$
$=\sum\limits_{n=0}^\infty\dfrac{(-1)^n\Gamma(\epsilon)\Gamma\left(\dfrac{(2n+1)\epsilon}{2}\right)k^{2n}}{2\Gamma\left(\dfrac{(2n+3)\epsilon}{2}\right)(2n+1)!}-i\sum\limits_{n=0}^\infty\dfrac{(-1)^n\Gamma(\epsilon)\Gamma((n+1)\epsilon)k^{2n+1}}{\Gamma((n+2)\epsilon)(2n+2)!}$
Which relates to Fox–Wright function


text:
Q: Javascript make an image bounce around screen I have made code for a bouncing ball (using the arc() method on a canvas). I am wondering how to make an image bounce around the screen. Here is my previous code (note that the launchBall() function is going to be the function that runs the bouncing image):
<!DOCTYPE HTML>

Score: 0


text:
Q: Affect only element that is clicked in jQuery I have div with same class. When I click on box-one arrow, I want to slide box-two. Problem is because I have five boxes with same class and when I click on one it opens all boxes. How to affect click on arrow to open only box that is clicked?  Anyone can help?

Some text

Some text

.box-two { display: none; }

$('.box-one a.arrow').on('click', function(e) {
    e.preventDefault();
    ('.box-two').slideToggle(300);
});

A: You use closest to find just the .box-one containing the arrow that was clicked, then use next to affect only the .box-two that follows that .box-one:
$(".box-one a.arrow").on("click", function(e) {
    e.preventDefault();
    $(this).closest(".box-one").next().slideToggle(300);
});

Live Example:

$(".box-one a.arrow").on("click", function(e) {
    e.preventDefault();
    $(this).closest(".box-one").next().slideToggle(300);
});
.box-two { display: none; }

arrow

Some text

arrow

Some text

More to explore: The traversing category of the jQuery API documentation (actually, the entire API docs only take an hour or so to read).


text:
Q: Why does this flashlight lens have this shape? I pulled apart a flashlight and found a similar lens as the one shown below.

I assume that the light starts off as a "point source" somewhere inside and the curvature and/or shape of the "lens" makes parallel wavefronts (or rays) exit the flashlight in a somewhat collimated beam. Is this approximating correct? Almost all of the websites really didn't give any detailed information or was unclear that I found. I would love for someone to explain this in more detail if possible.

A:
The reflector focuses the light from the bulb which is a point source to a straight line.

A: The lens on the image is known as a Total Internal Reflection (TIR) lens. The benefit of this type of lens is to achieve a more controlled and uniform beam of light by principle of total internal reflection. For example in flashlights.
More information here: https://www.ledil.com/support/guide-to-tir-lenses/ and here https://www.opticsforhire.com/blog/what-is-a-tir-lens
NB - I'm not involved with LEDIL or Opticsforhire in any way, they simply have decent articles explaning the TIR lens.


text:
Q: Creating new types in Python using extensions I've read the documentation and coded up my own example based on their Noddy example:
https://docs.python.org/3.4/extending/newtypes.html
This is a bit of a departure from usingPy_BuildValue()to build arbitrary objects dynamically. It appears that the underlying assumption is that there's a C structure backing every object instance you want to create.
Is this really the only (best?) way to create new objects in Python? I was hoping to create a new object and declare members/types similar to how you would create tuples, lists, and dictionaries etc. It seems like it should be possible to declare a new type, declare members and their types, and then plug values in field-by-field w/o all this.
I can't even use the structure defined by the existing API of what I'm gluing because Python objects require the compulsoryPyObject_HEADfield. I have to define a new C structure, copy the relevant elements that were handed back to me from the API call. It just seems like a level of memory management on the C side that should be unnecessary.

A: Sure, there's another way to create types in Python. Perhaps you've seen it?
class Foo():
    def __init__(self):
        ....

I'm being a little glib, of course. But when exposing a C interface to Python, it's often a good idea to have a Python script doing much of the interfacing; after all, it's quicker to write Python code than CPython binding code. And if what you have is basically an opaque handle type and a set of C functions which create/operate on those handles, you can simply expose those functions as free functions, and use them from your Python-side binding code. (You might even be able to do it without writing a single line of CPython binding code, using ctypes.)

A: So, rather than creating a new type, I was reading up on manipulating tuples in piecewise fashion and there's a section onstruct sequences. This is sort of what I was originally envisioning:
https://docs.python.org/3.4/c-api/tuple.html
It doesn't have all the power that a new type provides, but for communicating struct-like objects back to the caller with named attributes, this seems like a pretty easy way to go.
I'm curious what you folks think about this...


text:
Q: example of a non-amenable l.c. group such that $C_r^*(G)$ satisfies the UCT Are there known any examples of non-amenable locally compact (or more restrictive, non-amenable discrete) groups $G$ for which the reduced group $C^*$-algebra $C_r^*(G)$ satisfies the universal coefficient theorem (UCT)? In this case, $C_r^*(G)$ is non-nuclear. For example,$G=\mathbb{F}_2$ the free non-abelian group in 2 generators is known to be non-amenable. However, $C^*(\mathbb{F}_2)$ is exact. However, I don't know whenever or not this $C^*$-algebra satisfies the UCT.
I am happy about any references, comments etc... Thanks

A: Both $C^\ast(\mathbb F_2)$ and $C^\ast_r(\mathbb F_2)$ satisfy the UCT. This is the special case of the following:
$\mathbf{Theorem}$. If $G$ and $H$ are countable, discrete, amenable groups, then $C^\ast(G\ast H)$ and $C^\ast_r(G \ast H)$ are $KK$-equivalent and satisfy the UCT.
$\mathbf{Proof}$. By Theorem 2.4 (c) in Cuntz' paper "$K$-theoretic amenability for discrete groups" it follows that $G\ast H$ is $K$-amenable and thus $C^\ast(G\ast H)$ and $C^\ast_r(G\ast H)$ are $KK$-equivalent. In the beginning of Section 3 of the same paper, Cuntz shows/remarks that $C^\ast(G\ast H)$ is $KK$-equivalent to the pull-back
\begin{equation}
C^\ast(G) \oplus_{\mathbb C} C^\ast(H) = \{ (x,y) \in C^\ast(G) \oplus C^\ast(H) : t_G(x) = t_H(y)\}
\end{equation}
via the trivial representations $t_G$ and $t_H$, so it suffices to show that this $C^\ast$-algebra satisfies the UCT. It fits into a short exact sequence
\begin{equation}
0 \to I(G) \to C^\ast(G) \oplus_{\mathbb C} C^\ast(H) \to C^\ast(H) \to 0
\end{equation}
where $I(G) = \mathrm{ker} \, t_G$ is the augmentation ideal. As $C^\ast(H)$ is nuclear the sequence is semi-split, so $C^\ast(G) \oplus_{\mathbb C} C^\ast(H)$ satisfies the UCT provided that $C^\ast(H)$ and $I(G)$ satisfy the UCT, by the 2-out-of-3-property for satisfying the UCT. $C^\ast(H)$ and $C^\ast(G)$ satisfy the UCT by Tu's theorem. As $I(G)$ fits into the split short exact sequence
\begin{equation}
0 \to I(G) \to C^\ast(G) \to \mathbb C \to 0,
\end{equation}
and as $C^\ast(G)$ and $\mathbb C$ satisfy the UCT, so does $I(G)$ which completes the proof. QED
Note that for the free group $\mathbb F_2 = \mathbb Z \ast \mathbb Z$ one does not need to use Tu's deep theorem to obtain UCT.
To my knowledge, the only known group $C^\ast$-algebras which do not satisfy the UCT, are $C^\ast_r(G)$ when $G$ is a countable, discrete group with property (T) and the Akemann-Ostrand property, see Skandalis' "Une Notion de Nuclearite en K-Theorie". By also assuming that the group is residually finite, one can show that $C^\ast(G)$ does not satisfy UCT.


text:
Q: When are arbitrary strings passed to test ambiguous I came across this construct to test whether the shell variable $foo, which could contain any arbitrary string, matched foo:
[ "x$foo" = "xfoo" ]

The purpose of prefixing with x was never explained.  This looks like an attempt to avoid errors that might arise when $foo contains strings special to test like =, -f, (, or !.  The GNU info manual indicates compound expressions involving -a and -o can lead to ambiguity, so I am primarily interested in simple (i.e., not compound) statements.  I had a hard time searching for more information on this.  I have not been able to devise an example of an arbitrary string that caused GNU test to fail in an unexpected manner, although I freely admit I'm not that clever.
My questions:

*

*What reasons are there to prefix parameter substitutions in test?

*Is there an example of a simple (i.e., not compound) statement involving naive parameter substitution (i.e., no prefix protection) that causes test to give unusual results?

I mostly use GNU tools on linux, but for the sake of portability, I am interested in whether test on other platforms as well.

A: > [ -f = -a -a -a ]
bash: [: argument expected

> [ -f = -a -a x ]

But:
[ x-f = x-a -a -a ]

doesn't work either although
[ -a ]

is fine.


text:
Q: Touchpad buttons have stopped working on Dell laptop Recently the lower two touchpad buttons on my Dell laptop have stopped working. There is a second set of touchpad buttons above the touchpad under the space bar and these are working as expected. However, I'd prefer to use the lower buttons as usual, as this is more ergonomic and what I'm accustomed to. If I plug in a USB mouse then that works as expected. It's just the lower touchpad buttons that have gone awry.
Can anyone suggest what I can do to diagnose the issue? Are there drivers that I can reinstall or upgrade that may have an effect?
Dell Latitude 7480, Ubuntu 18.04 LTS
Thanks in advance for any comments or suggestions!

A: You should see a check box under the mouse settings to enable and disable the touch pad.
see here

A: I fixed this by ordering a new part (the two buttons) and installing it into the laptop. Everything works as expected now, so this was a hardware malfunction rather than a configuration setting gone awry.


text:
Q: Ubuntu 16.04.0 final (Unity desktop / Kubuntu / GNOME) can not boot from Live USB on a Z170 Skylake (6th gen) I wanted to try Ubuntu 16.04 final on a brand new system:
A top-of-the-range AsRock Z170 ITX motherboard with i7 6700K CPU and GTX 970 connected via DVI-D.
When I choose to try Linux (not to install it), both in Uefi and in non-Uefi mode, the Ubuntu 64 bit version with Unity desktop shows the background correctly, but then a blinking message box appears saying error.
The error message is not very readable because it is blinking, but it seems to say "compiz crashed with SIGILL"
When I try Kubuntu 16.04.0 final 64 bit, the background appears for a fraction of as second and then the screen becomes black and nothing more happens.
When I try GNOME, I read "Nouveau failed to load".
This motherboard only has USB3 ports and no USB2 ports.
The USB key is FAT32 formatted, and is inserted in a USB 3.0 port. The USB key was created with Rufus in Windows.
The motherboard is setup to allocate 1GB of RAM to the integrated graphics, and is set to start up with the NVIDIA GPU rather than with the Integrated GPU.
[ - UPDATE - ] -
Thanks for the answers. Xubuntu 16.04.0 worked out of the box. Kubuntu 16.04.0 Live CD worked only with nomodeset, but I could not boot from the installed OS in any way (nor enter recoverymode).
So, in the end, the solution for me, was to set "Primary Display" to "onboard" in the UEFI "Chipset settings". As (K)Ubuntu 16.04.0 has got a kernel greater than 4.3, Intel integrated graphics worked with no effort. As my plan for the GTX 970 is KVM GPU-passthrough, I should not use the external GPU at boot.

A: According to this :
https://bugs.launchpad.net/ubuntu/+source/llvm-toolchain-3.8/+bug/1564156
This bug will be fixed in 16.04.1
All credit goes to Joakim Koed (joakimkoed) who came with a good option.
What you need to do is:
boot with nomodeset (press E after grub is booted and add nomodeset after quiet splash and press F10 (if I remember correctly)) now change to a terminal with CTRL + ALT + F2 or something.
wget http://koti.kapsi.fi/~tjaalton/skl/build2/libllvm3.8_3.8-2ubuntu1.1_amd64.deb
sudo dpkg -i libllvm3.8_3.8-2ubuntu1.1_amd64.deb
sudo reboot

Hope this helps.

A: I have exactly the same problem with Ubuntu 16.04, but with an ASUS Maximus VIII Gene motherboard. I used the same USB key with Xubuntu 16.04 and had no problem trying Xubuntu 16.04. The display functioned perfectly. This would seem to indicate that the problem lies with Unity.
This appears to be a recognized bug that will fixed in the 16.04.1 ISO. https://bugs.launchpad.net/ubuntu/+source/llvm-toolchain-3.8/+bug/1564156


text:
Q: Apply Doob's inequality to Brownian Motion Let $B_n$ be a brownian motion, apply Doob's inequality to show that:
$$\mathbb E\left(\sup_{\sigma \leq t \leq \tau} \left(\frac{B_t}{t}\right)^2\right)\leq \frac{4\tau}{\sigma^2}.$$
I know a result about Doob's inequality:
$$\mathbf{P} \left[ \sup_{0 \leq t \leq T} B_{t} \geq C \right] \leq \exp \left( - \frac{C^2}{2T} \right).$$
But I don't know how to apply.


text:
Q: Circular Buttons in a UIStackView ( iOS Swift ) My circular buttons in the UIStackView disfigure when the device changes.
I have made the buttons circular using corner radius on the storyboard.
What's the way to retain the circular shape of the button when resizing.
Currently, I am giving it a fixed width and height constraint.

A: Guessing without seeing your code:
You need to update the cornerRadius on the layer when resizing. Either make a subclass and override layoutSubviews or have the viewcontroller update the cornerRadius by overriding viewDidLayoutSubviews.
This is because layers do not support autolayout.


text:
Q: Why java date is not parsable? I am developing a mobile application using oracle MAF. Oracle MAF provides its date component and if I select a date then output is like : 2015-06-16T04:35:00.000Z for selected date Jun 16, 2015 10:05 AM.
I am trying to convert this format to "Indian Standard Time" with .ical (ICalendar Date format) which should be like 20150613T100500 for the selected date Jun 16, 2015 10:05 AM. I am using code below:
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
isoFormat.setTimeZone(TimeZone.getTimeZone("IST"));
String start_date_time = isoFormat.parse("20150616T043500000Z").toString();

But it returns date time as :
Tue Jun 16 04:35:00 GMT+5:30 2015

And should be like:
20150616T100500

A: You need to parse the value from 2015-06-16T04:35:00.000Z UTC to a java.util.Date
SimpleDateFormat from = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
from.setTimeZone(TimeZone.getTimeZone("UTC"));
Date start_date_time = from.parse("2015-06-16T04:35:00.000Z");

Which gives us a java.util.Date of Tue Jun 16 14:35:00 EST 2015 (for me).
Then, you need to format this in IST
SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
outFormat.setTimeZone(TimeZone.getTimeZone("IST"));
String formatted = outFormat.format(start_date_time);
System.out.println(formatted);

Which outputs 20150616T100500
Java 8 Time API
Just because it's good practice...
    // No Time Zone
    String from = "2015-06-16T04:35:00.000Z";
    LocalDateTime ldt = LocalDateTime.parse(from, DateTimeFormatter.ISO_ZONED_DATE_TIME);

    // Convert it to UTC
    ZonedDateTime zdtUTC = ZonedDateTime.of(ldt, ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("UTC"));

    // Convert it to IST
    ZonedDateTime zdtITC = zdtUTC.withZoneSameInstant(ZoneId.of("Indian/Cocos"));
    String timestamp = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss").format(zdtITC);
    System.out.println(timestamp);

nb: If I didn't parse the value to LocalDateTime, then convert it to UTC, I was out by an hour, but I'm open to knowing better ways

A: Supply format should be "yyyy-MM-dd'T'HH:mm:ss"
public static void main(String[] args) {
    SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    isoFormat.setTimeZone(TimeZone.getTimeZone("IST"));
    try {
        Date start_date_time = isoFormat.parse("2015-06-16T04:35:00.000Z");
        System.out.println(start_date_time);
        SimpleDateFormat output = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
        String formattedTime = output.format(start_date_time);
        System.out.println(formattedTime);
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

Output
Tue Jun 16 04:35:00 IST 2015
20150616T043500

A: A few additions to the format, and a correct TZ in the date string:
 SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz");
 isoFormat.setTimeZone(TimeZone.getTimeZone("IST"));
 String start_date_time = isoFormat.parse("2015-06-16T04:35:00.000CEST").toString();


text:
Q: Undefined method `each' for nil:NilClass Thanks in advance for any help you can provide!
For my Ruby on Rails website (1.8.7, 2.3.15) I'm trying to pull data from a MySQL table, but I'm running into an "Undefined Method" error. My goal with this code is to display a text list of all locations that fall within a certain latitude and longitudinal range.
Production.log:
ActionView::TemplateError (undefined method `each' for nil:NilClass) on line #31 of     app/views/its/map.html.erb:
28:
29:
30:

31: <% for masterlocation in @nearbylocations %>
32:
<%= masterlocation.nickname %>

33: <% end %>
34:

Map controller:
def map
@its = Its.find(params[:id])
if @its.user_id == current_user.id
@locations = Location.find(:all, :conditions => ["its_id = ?", params[:id]], :order => "order_num asc")
@mapscount = Saved.count(:all, :conditions => ['its_id = ?', params[:id]])
#@date_filter = Date.civil(params[:date_filter].values_at(:year, :month, :day))
#    debugger
respond_to do |format|
format.html # map.html.erb
format.xml  { render :xml => @its }
end
else
redirect_to '/'

@nearbylocations = Masterlocation.find(:all, :conditions => ["latitude > 25 AND latitude < 30 AND longitude > -75 AND longitude < -70", params[:id]], :order => ['nickname asc'])
end

Again, I appreciate your help!

A: This happens because @nearbylocations is nil where as it is expecting an Array
you can avoid this by using
<% for masterlocation in @nearbylocations %>

<%= masterlocation.nickname %>

<% end if @nearbylocations %>

I also notice that you are declared instance variable after redirecting.
Ideally
redirect_to '/'
@nearbylocations = Masterlocation.find(:all, :conditions => ["latitude > 25 AND latitude < 30 AND longitude > -75 AND longitude < -70", params[:id]], :order => ['nickname asc'])

should be
@nearbylocations = Masterlocation.find(:all, :conditions => ["latitude > 25 AND latitude < 30 AND longitude > -75 AND longitude < -70", params[:id]], :order => ['nickname asc'])
redirect_to '/'

But after redirection you can't use @nearbylocations so you have to use either render or declare it in redirected method.

A: ur getting a nill error cause ur @nearbylocations isnt getting evaluated since the 'if' condition is  executed and the Masterlocation query is in 'else'. u may move it out of the condition if the @nearbylocation is always needed.

A: the devil is here
:conditions => ["latitude > 25 AND latitude < 30 AND longitude > -75 AND longitude < -70", params[:id]]

this query gives nothing
you have @nearbylocations = nil
and than you receive undefined method error
what in :conditions doing params[:id]? i guess you forgot to delete it or you forgot to add ? to query in ""


text:
Q: Why does the Twitter app not share animated gifs? I recently noticed that when sharing an animated .gif that I generate from my app, the official Twitter app will only share it as a static image.
Previously, I thought everything was working because when I shared the same type of animated .gif with an unofficial Twitter app (Tweetcaster), it properly shared it as an animated .gif.
The thing I'm questioning is whether this is an issue on my end or with the official Twitter app?  I ask this because when sharing an animated .gif from the Android Gallery with the official Twitter app, it is also posted as a static .gif.
Here's the code in question:
public void shareGif(String path)
    {
        File file = new File(path);
        Uri uri = Uri.fromFile(file);

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/gif");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
        intent.putExtra(Intent.EXTRA_TEXT, "text");
        intent.putExtra(Intent.EXTRA_STREAM, uri);

        startActivity(Intent.createChooser(intent, "Choose a sharing option"));
    }

A: I was having the same issue as you. I was loading URIs from the drawables and for whatever it was not animating.
I fixed my problem by implementing a custom file provider and loaded GIFs from the assets folder.
Also it was very important to add this flag intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

A: Twitter supports looping GIFs. If your animated GIF doesn't loop and plays a single time, it will display as a static image.


text:
Q: HTML: How do I simply indent a form? I've searched and searched for what I thought would be a simple find but haven't found anything.  I have this form:
<form action="<?= htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES) ?>" method="post" enctype="multipart/form-data">
    <input type="file" name="thefile">
    <input type="submit" value="Upload File">

</form>

I want it indented so it doesn't touch the side of the area it's in, I've tried something like
 wrapped around it but didn't phase it.
How do I do I indent the form?
Thanks.

A: Please try the following (indented 60 pixels from the left margin)

#form1
{
padding-left:60px;
}
<form action="self.php" method="post" enctype="multipart/form-data" id=form1>
    <input type="file" name="thefile">
    <input type="submit" value="Upload File">

</form>

A: You can leverage margin like so:

.indented{
  margin-left:50px;
}
<form action="<?= htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES) ?>" method="post" enctype="multipart/form-data" class="indented">
    <input type="file" name="thefile">
    <input type="submit" value="Upload File">

</form>

However, if you just want the content to be indented, use padding like so:

.indented{
  padding-left:50px;
}
<form action="<?= htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES) ?>" method="post" enctype="multipart/form-data" class="indented">
    <input type="file" name="thefile">
    <input type="submit" value="Upload File">

</form>


text:
Q: Переменные Sass в create react app Как использовать переменные в компонентах. По разному менять пути? где-то будет ./../variables.scss, а в другом месте ./../../../variables.scss
http://prntscr.com/mkm63o
Есть способ почище?

A: Если у вас webpack, то воспользуйтесь resolve, тогда вы сможете сделать пути к файлам абсолютными, а не относительными.
Почитать можно тут

A: Вариант №1
Если все стили находятся в одной папке /styles используйте файлы сборщики, чтобы импортировать их единожды:
styles/index.scss
@import "./constants.scss";
@import "./mixins.scss";
@import "./reset.scss";

index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import "./styles/index.scss";

ReactDOM.render(<App />, document.getElementById("root"));

В таком случае Вам не понадобится импортировать переменные стилей в каждый файл отдельно.
Вариант №2
В случае если файлы стилей находятся в папке с каждым компонентом отдельно, и нужно импортировать общие переменные в них, можно использовать переменные окружения:
.env
SASS_PATH=src

любой файл со стилями
@import styles/variables.scss


text:
Q: How do I pass a (table) variable from a C# program to an SQL script I want to have a function in C# with an argument which will be a table name in an SQL script it reads from. The code looks something like this in C#:
    static void createTable(SqlConnection connection, String tableName, String fileName)
    {
      try
        {
            var fileContent = File.ReadAllText(fileName+".sql");
            var sqlQueries = fileContent.Split(new[] { " GO " }, StringSplitOptions.RemoveEmptyEntries);
            var cmd = new SqlCommand(fileName, connection);
            SqlParameter param = cmd.Parameters.Add("@toBeReplaced", tableName);
            connection.Open();
            foreach (var query in sqlQueries)
            {
                cmd.CommandText = query;
                cmd.ExecuteNonQuery();
            }
            connection.Close();
        }
        catch (SqlException e)
        {
            Console.WriteLine(e.ToString());
        }

    }

When this function runs, I want it to execute the script in fileName.sql where it inserts into the table 'tableName'. The .sql script looks like this:
    use myDatabase
     GO
    alter table TESTPersonsProject drop constraint FK_TESTPersonsProject_TESTproject
    alter table TESTSideResearch drop constraint FK_TESTSideResearch_TESTproject
    alter table TESTSamples drop constraint FK_TESTSamples_TESTproject
    alter table @toBeReplaced drop constraint PK_TESTProject
    alter table @toBeReplaced add tmp int;
     GO
    update @toBeReplaced set tmp=projectID where tmp is null
    alter table @toBeReplaced drop column projectID
    alter table @toBeReplaced add id_new int identity(1,1)
    alter table @toBeReplaced add constraint PK_TESTProject primary key (id_new)
    ...

I know I could let the function look ugly and just have the query as a string. However, I do want to keep it clean and be able to use this function for more than just one query.
How do I declare and use this passed variable so that this query can affect more than just one specified table?
p.s. I'm using SQL SERVER 2008

A: You can't use variables as table or column names in SQL. Column names and table names must be static.
The only way to do what you want to do is to generate the query through string concatenation. You can do the concatenation either in a stored procedure which uses EXECUTE to run the string query, or you can do it in C# and execute the string directly.
Either way, make sure that you validate your input, since both techniques are vulnerable to SQL injection.
See here: Table name as variable

A: You can't use parameters for table names in SQL Server, why not do the replace yourself since you're already reading in the query?
foreach (var query in sqlQueries)
{
    cmd.CommandText = query.Replace("@toBeReplaced", tableName);
    cmd.ExecuteNonQuery();
}

A: You should do something like this since you are not interested in SQL string concatenation.
use myDatabase
     GO
DECLARE @queryvarchar(MAX)

SET @query= '
    alter table TESTPersonsProject drop constraint FK_TESTPersonsProject_TESTproject
    alter table TESTSideResearch drop constraint FK_TESTSideResearch_TESTproject
    alter table TESTSamples drop constraint FK_TESTSamples_TESTproject
    alter table @toBeReplaced drop constraint PK_TESTProject
    alter table @toBeReplaced add tmp int;
     GO
    update @toBeReplaced set tmp=projectID where tmp is null
    alter table @toBeReplaced drop column projectID
    alter table @toBeReplaced add id_new int identity(1,1)
    alter table @toBeReplaced add constraint PK_TESTProject primary key (id_new)'

EXEC (@query)

But I believe you are making it more ugly this way than replacing in the C#.