text:
Q: Recycler view does not show I have a recycler view with grid layout that displays cards with an image, title, description and price but it does not show anything.
The data is fetched correctly, I am assuming there must be an error in the layout files but I don't know what it is.
Here is the fragment code
package io.keepcoding.androidfinalproject.ui.products

import android.app.SearchManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.*
import android.widget.SearchView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import io.keepcoding.androidfinalproject.R
import io.keepcoding.androidfinalproject.domain.Product
import io.keepcoding.androidfinalproject.repository.DataManager
import io.keepcoding.androidfinalproject.utils.CustomViewModelFactory
import io.keepcoding.androidfinalproject.utils.Status
import android.Manifest
import android.util.Log
import android.widget.Toast
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.GridLayoutManager
import io.keepcoding.androidfinalproject.ui.main.ClientActivity
import kotlinx.android.synthetic.main.fragment_products.*

/**
 * A simple [Fragment] subclass.
 * Use the [Products.newInstance] factory method to
 * create an instance of this fragment.
 */
class ProductsFragment : Fragment() {

    private val viewModel: ProductsFragmentViewModel by lazy {
        val factory = CustomViewModelFactory(requireActivity().application,
            DataManager())
        ViewModelProvider(this, factory).get(ProductsFragmentViewModel::class.java)
    }

    private val LOCATION_PERMISSION_REQUEST_CODE = 2000

    private var latitude: Double = 51.507351

    private var longitude: Double = -0.127759

    private var selectedRadius : Int = 1000

    private var productViewModels: List<Product>? = null

    private var productsAdapter: ProductsAdapter? = null

    var productsInteractionListener: ProductInteractionListener? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is ProductInteractionListener){
            productsInteractionListener = context
        } else
            throw IllegalArgumentException("Context does not implement product interaction listener")
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_products, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        this.setUpRecyclerView()
        this.prepRequestLocationUpdates()
        this.fetchData()
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.products_search, menu)
        activity?.let { activity ->
            val searchViewItem = menu.findItem(R.id.action_search)
            val searchManager = activity.getSystemService(Context.SEARCH_SERVICE) as SearchManager
            val searchView = searchViewItem.actionView as SearchView
            searchView.queryHint = "Search products"
            searchView.setSearchableInfo(searchManager.getSearchableInfo(activity.componentName))
            searchView.isIconifiedByDefault = false
            searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {

                override fun onQueryTextSubmit(p0: String?): Boolean {
                    return false
                }

                override fun onQueryTextChange(newText: String?): Boolean {
                    var text = newText?.toLowerCase()
                    text?.let {
                        viewModel.searchProducts(selectedRadius, latitude, longitude, it)
                    }
                    return true
                }
            })
        }
        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        selectedRadius = when(item.itemId) {
            R.id.one_radius -> 1000
            R.id.two_radius -> 2000
            R.id.three_radius -> 3000
            R.id.four_radius -> 4000
            else -> {
                5000
            }
        }
        return super.onOptionsItemSelected(item)
    }

    private fun setUpAdapter() {
        context?.let { context ->
            productsAdapter = ProductsAdapter(context) {
                this.productsInteractionListener?.goToProductDetail()
            }
            productViewModels?.let { products ->
                productsAdapter?.setData(products)
            }
        }
    }

    private fun setUpRecyclerView(){
        productsList.layoutManager = GridLayoutManager(context, 3)
        productsList.addItemDecoration(DividerItemDecoration(context, GridLayoutManager.VERTICAL))
    }

    private fun setUpObservers() {
        viewModel.getProducts().observe(viewLifecycleOwner, Observer { products ->
            when(products.status){
                Status.SUCCESS -> {
                    productViewModels = products.data
                    Log.    d("PRODUCTS", productViewModels.toString())
                    this.setUpAdapter()
                    productsList.visibility = View.VISIBLE
                    loadingView.visibility = View.INVISIBLE
                    retry.visibility = View.INVISIBLE
                }
                Status.LOADING -> {
                    productsList.visibility = View.INVISIBLE
                    loadingView.visibility = View.VISIBLE
                    retry.visibility = View.INVISIBLE
                }
                Status.ERROR -> {
                    productsList.visibility = View.INVISIBLE
                    loadingView.visibility = View.INVISIBLE
                    retry.visibility = View.VISIBLE
                }
            }
        })
    }

    private fun setUpListeners(){
        TODO("Set up retry button listener")
    }

    private fun fetchData() {
        viewModel.fetchProducts(selectedRadius, latitude, longitude)
        this.setUpObservers()
    }

    private fun prepRequestLocationUpdates() {
        if (ContextCompat.checkSelfPermission(requireActivity().application, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            requestLocationUpdates()
        } else {
            val permissionRequest = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
            requestPermissions(permissionRequest, LOCATION_PERMISSION_REQUEST_CODE)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        when(requestCode){
            LOCATION_PERMISSION_REQUEST_CODE -> {
                if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    requestLocationUpdates()
                } else {
                    Toast.makeText(requireActivity().application, "Unable to update location without permission", Toast.LENGTH_LONG).show()
                }
            } else -> {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults)
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    private fun requestLocationUpdates(){
        viewModel.getLocationData().observe(viewLifecycleOwner, Observer { location ->
            latitude = location.latitude
            longitude = location.longitude
        })
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @return A new instance of fragment Products.
         */
        @JvmStatic
        fun newInstance() =
            ProductsFragment()
    }
}

And the adapter
package io.keepcoding.androidfinalproject.ui.products

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import io.keepcoding.androidfinalproject.R
import io.keepcoding.androidfinalproject.domain.Product
import kotlinx.android.synthetic.main.product_item.view.*

class ProductsAdapter(val context: Context, val productClickListener: ((Product) -> Unit)? = null) : RecyclerView.Adapter<ProductsAdapter.ProductHolder>(){

    private var productItems : List<Product> = listOf<Product>()

    private var productsInteractionListener: ((View) -> Unit)? = {
        if(it.tag is Product){
            productClickListener?.invoke(it.tag as Product)
        } else {
            throw IllegalArgumentException("Product item view's tag is not set to a Product object")
        }
    }

    fun setData(productItems: List<Product>){
        this.productItems = productItems
        notifyDataSetChanged()
    }

    inner class ProductHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
        var product: Product? = null
            set(value) {
                field = value
                itemView.tag = field
                field?.let {
                    Glide.with(context)
                        .load(it.photos?.get(0))
                        .apply {
                            RequestOptions()
                                .placeholder(R.drawable.ic_launcher_background)
                        }.into(itemView.productImage)
                    itemView.productTitle.text = it.name
                    itemView.productDesc.text = it.description
                    itemView.productPrice.text = (it.price?.toDouble()?.div(100)).toString()
                }
            }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.product_item, parent, false)
        return ProductHolder(view)    }

    override fun getItemCount(): Int {
        return this.productItems.size
    }

    override fun onBindViewHolder(holder: ProductHolder, position: Int) {
        val product = productItems.get(position)
        holder.product = product
        holder.itemView.setOnClickListener(productsInteractionListener)
    }

}

And the layout files
Fragment layout

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".ui.products.ProductsFragment"
     android:layout_height="match_parent"
    android:layout_width="wrap_content"
    >
        <include
            android:id="@+id/loadingView"
            layout="@layout/view_loading"
            />
        <include
            android:id="@+id/retry"
            layout="@layout/view_retry"
            android:visibility="invisible"
            />
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/productsList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="invisible"
            />

</FrameLayout>

Item layout
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="400dp"
    >
    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            >
            <ImageView
                android:id="@+id/productImage"
                android:layout_width="match_parent"
                android:layout_height="250dp"
                />
            <TextView
                android:id="@+id/productTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:maxLines="1"
                />
            <TextView
                android:id="@+id/productDesc"
                android:layout_width="match_parent"
                android:layout_height ="wrap_content"
                android:maxLines="4"
                />
            <TextView
                android:id="@+id/productPrice"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:maxLines="1"
                android:layout_gravity="bottom|end"
                />

        </LinearLayout>
    </androidx.cardview.widget.CardView>
</GridLayout>

And one of the included layouts in the fragment layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="wrap_content">

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="@string/loading"
        android:textSize="20sp"
        />
</LinearLayout>

A: Miss this line
productsList.adapter = productsAdapter


text:
Q: Преобразовать строки таблицы БД в колонки Помогите из исходной таблицы, где обозначения расположены в одной колонке,

с помощью SQL получить следующую таблицу, где эти же обозначения распределены по двум колонкам, но в одной строке

A: Если значений для reference не более двух, то для любой СУБД:
select reference, min(destination) destination1,
nullif(max(destination),min(destination)) destination2
from tbl
group by reference;

redpajama_set_name: RedPajamaStackExchange


text:
Q: IIS matches the rule but IIS rewrite module says the rule doesn't match I'm having an issue with a rule being applied correctly on my site.
The rule is:
(^((?!\/bundles\/).)*[^\/]$)

The action is to append a slash to the end of this, using:
<action type="Redirect" url="{R:0}/" redirectType="Temporary" />

I try the following url:
http://example.com:9999/bundles/bundle.js
And IIS redirects me to http://example.com:9999/bundles/bundle.js/
But I go to IIS Manager, go to IIS Rewrite, select this rule, go to test, put the url in, click test, and it says that it's not a match.
If it's not a match, why is it still redirecting?

A: I created the same rule and it is redirecting. So, it is working as not expected: your rule (^((?!\/bundles\/).)*[^\/]$) match to http://example.com:9999/bundles/bundle.js
The problem in your rule. Correct rule is (^((?!bundles\/).)*[^\/]$). I removed slash before bundles. Because when request is coming into rule, it is comparing rule with path bundles/bundle.js (without starting slash)


text:
Q: time data doesn't match format specified when it seemed to be match I have dataframe in pandas that has two dates columns:
>>>ID  name    start        end
0  12  Tik     1/6/2020    None
1  32  Tak     12/31/2019  None
2  45  Tek     9/1/2019   1/30/2020
3  78  Tok     9/1/2019   1/29/2020

I'm trying to convert those dates into datetime to be in format of Y-m-d e.g that 12/31/2019 will be 2019-12-31 :
df[['start','end']] =df[['start','end']].apply(pd.to_datetime, format=''%Y-%m-%d'')

but whenever I run this I get error:

ValueError: time data 1/6/2020 doesn't match format specified

I have tried than to specify the format to be like the given date (e.g (d-m-Y):
df[['start','end']] =df[['start','end']].apply(pd.to_datetime, format=''%d-%m-%Y'')

>>>ValueError: time data '1/6/2020' does not match format '%d-%m-%Y' (match)

I have tried to break it as suggest in the first answer here: How to change the datetime format in pandas
and to first conver to  datetime and then use strftime but in the first line I got the error that Ineed to specify the format.
I can't find any reason why is this happen, maybe is because the day and month do not have two digits?
my end goal is to convert those date columns into %Y-%m-%d format

A: *

*The issue seems to be the use of two sets of quotes around the format

*

*''...''

*The format parameter of pandas.to_datetime specifies the current format of the column, not the desired format.

*

*The format of these dates is '%m/%d/%Y'
import pandas as pd

# setup the dataframe
df = pd.DataFrame({'ID': [12, 32, 45, 78], 'name': ['Tik', 'Tak', 'Tek', 'Tok'], 'start': ['1/6/2020', '12/31/2019', '9/1/2019', '9/1/2019'], 'end': [None, None, '1/30/2020', '1/29/2020']})

# convert to datetime
df[['start','end']] = df[['start','end']].apply(pd.to_datetime, format='%m/%d/%Y')

# display(df)
   ID name      start        end
0  12  Tik 2020-01-06        NaT
1  32  Tak 2019-12-31        NaT
2  45  Tek 2019-09-01 2020-01-30
3  78  Tok 2019-09-01 2020-01-29


text:
Q: Extracting data from old Mac resource files What utility or tool that runs which under Mac OS X 10.6 can I use to extract data (icon images and strings, etc.) from old Mac OS 7 (and earlier) resource files/resource forks?  (...files created using ResEdit.)

A: Rezycle might work for you. Let us know.

A: On OSX you can access the raw resource fork of a file like this:
cp resource_file/..namedfork/rsrc  resource_fork

There's also the system utilities DeRez/Rez (available in OSX 10.7 and as mention by @marc as part of Xcode tools on newer MacOS versions) which allows for extraction of resource fork data into a form for use by the Rez resource compiler  - e.g. extract icon data from an Icon file:
DeRez -only icns Icon^M > icon

It should be noted that the resulting files from both of the above commands require additional processing to convert the resources to a suitable form.
See related question on Icon files.

A: Abet slightly unstable, the resource editor Rezilla runs under 10.7.4.


text:
Q: Java Data Mining connectionFactory to postgreSQL I'm working on a datamining project that will use my database Postgres (9.1) as Datasource. I've already found Java JDM a very interesting API that can serve my project. However, right from the start, i couldn't create a Connection (or ConnectionFactory) to my database. I have tried the jdbc connection but JDM seems to be implemented only for Oracle Database.
Is there anyone who can point me a way around to get to this ?
Thanks in advance.


text:
Q: Too many connections (New Error) Ok, I change my connection factory code, I'm using PoolProperties class and now I'm getting this error:

Data source rejected establishment of connection,  message from server: "Too many connections"

In my InsertandGetObject Method I log a message in order to test that the connection is closing and it is, I also debbug on server.
Any ideas for this issue? :s
This is my connection Pool:
    public static Connection getConnection() throws DatabaseConnectionException {

    PoolProperties p = new PoolProperties();
    p.setName("jdbc/MetaData");
    p.setUrl("jdbc:mysql://localhost:3306/db_name");
    p.setDriverClassName("com.mysql.jdbc.Driver");
    p.setUsername("root");
    p.setPassword("");
    p.setInitialSize(3);
    p.setMaxActive(10);
    p.setMaxIdle(8);
    p.setMinIdle(2);
    p.setRemoveAbandoned(true);
    p.setMaxWait(10000);

    Connection conn = null;

    try {

        DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource(p);

        conn = dataSource.getConnection();

    } catch (SQLException e) {
        LOGGER.debug("MSJ SQLExp: " + e.getMessage());
        throw new DatabaseConnectionException(e);

    }

    return conn;
}

This is the method that close the connection:
    public Concept insertAndGetObject(Concept object) throws SQLException,
        DatabaseConnectionException {
    try {

        connection = ConnectionFactory.getConnection();
        connection.setAutoCommit(false);
        statement = connection.prepareStatement(INSERT_CONCEPTS);
        statement = ConceptMapperUtil.setStatementParameters(statement,
                object);
        statement.executeUpdate();
        connection.commit();
        LOGGER.debug("Inserted concept row ");
    } catch (SQLException e) {
        connection.rollback();

        if (e.getErrorCode() == SQL_INSERT_ERROR_CODE) {
            LOGGER.debug("Concept already exists!");
        } else {
            throw e;
        }

    } finally {
        object = findConceptByUniqueFk(object.dataSource.getIdDataSource(),
                object.conceptType.getIdConcept(),
                object.idMetadataVersion.getIdMetaDataVersion());
        DbUtil.close(statement);
        // connection.setAutoCommit(true);
        DbUtil.close(connection);
    }
    return object;
}

A: With new DataSource(PoolProperties) you do not create a "DataSource object wrapping a connection" (as stated in the ApiDocs). Instead, you create a pool of connections (also mentioned in the ApiDocs, but at the top: "The DataSource simply wraps a ConnectionPool ..."). I verified this in, what I think is, the source code (see line 108 of DataSourceProxy).
Consequently, closing a Connection only returns it to the pool (so it can be re-used), it does not actually close the connection (unless you see the connection actually being closed on the database server, in which case I'm wrong). Solution is to create 1 DataSource object and re-use it for each getConnection() call. Close the DataSource/ConnectionPool when the application no longer needs a database connection.


text:
Q: Android Studio: Failed to find: 'com.android.support:support-v4:19.1.0' I want to build an app in Android Studio with the support library but I get the following error when adding the dependency for the support library:
Error:Failed to find: com.android.support:support-v4:19.1.0

Here is my build.gradle file
apply plugin: 'com.android.application'

android {
    compileSdkVersion 19
    buildToolsVersion '20'

    defaultConfig {
        applicationId "sample.myapplication"
        minSdkVersion 15
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    buildTypes {

        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:support-v4:19.1.0'

}

I have downloaded the support library via the sdk manager.

A: Ok, found the problem. The Android support repository was missing. After installing and restarting Android Studio it worked.

A: If you are using Android Studio, then as an addition to changing the build.gradle file manually, you can also lookup the dependency via the library dependencies under the Project Structure menu item.

Double clicking that dependency will generate this line in build.gradle:
dependencies {
    compile 'com.android.support:support-v13:+'
}

And also, if you are wondering what this library is about, it's described at the developer pages at developer.android.com; Support Library.

A: My Android Studio version is 1.1. I select tools->Android->SDK Manager, check the Android Support Library then click Install packages, solved this issue.

A: In my case the solution was as simple as running Build:Make Project.  No amount of gradle syncing or clearing caches would do it.  Of course, that required getting my project into a state where it would build successfully.

A: In my case I needed to add Google Maven repository.
It shows as part of the error in Android Studio and only needed to click on it to add itself.
Then Gradle built the project on its own.

A: Following the instruction here helped me. For whatever reason when I had to reinstall the latest version of android studio the initial download of the extras section android support library failed. I simply retried it. Followed the steps mentioned and verified it was added to the build.gradle file and did a rebuild project and good to go.
http://developer.android.com/tools/support-library/setup.html


text:
Q: Segmentation fault (core dumped) with sieve algorithm I've been trying to implement the sieve algorithm using the following code:
#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector <int> primes; //all the primes found
    int theLimit = 10E5;

    void sieve (vector <int> &primes, int theLimit); //declaring the function
    sieve (primes, theLimit);

    return 0;
}

void sieve (vector <int> &primes, int theLimit) {
    const int SIZE = theLimit + 1;
    bool oddNonPrimes[SIZE]; //the array that tells you that tells you if the number that represents the current index is a non-prime or not

    for (int i = 0; i < theLimit; ++i) //setting all the array indicies to false
        oddNonPrimes[i] = false;

    primes.push_back(2);

    for (int i = 3; i < theLimit; i += 2){ //start searching for primes,we start with the number 3 and check all odd numbers only
        if (!oddNonPrimes[i]){
             int currNum = i;
             primes.push_back(currNum);
             for (int factor = 2; currNum <= theLimit; ++factor){
                currNum *= factor;
                oddNonPrimes[currNum] = true;
                currNum = i;
            }
        }
    }

}

I've tried lowering the size to make sure I'm not using too much memory but it still didn't work.I've also tried searching for an answer but I haven't found any.
What could be causing the Seg fault?and why?

A: First of all i would like to tell that the for loop which is been run for searching for all the primes should all the primes by seeing if(!oddNonPrimes[i]) is true or not should be done only for sqrt(theLimit) as it would lead to less complexity.
below is a sieve method that i would like you to refer to.
#include<bits/stdc++.h>
using namespace std;

bool *primality=new bool[10000010];
long long int *p = new long long int[1000001];
int main(){
    long long count=0;
    for(long long int i=0; i<10000010; i++)
        primality[i]=true;
    for(int i=2; i<10010; i++)
        if(primality[i])
            for(long long j=i*i; j<10000010; j+=i)
                primality[j]=false;
            for(int i=2; i<10000010; i++)
               if(primality[i]){
                   p[count]=i;
                   count++;
               }
 }

This has been taken just from one of my codes . i think it would help you. :)

A: First,Sorry for wasting your time.
I should have used:
for (int factor = 2; (currNum * factor) <= theLimit; ++factor)

Instead of:
for (int factor = 2; currNum <= theLimit; ++factor)

Otherwise when the currNum is big and then multiplied by the factor,it might become larger than the limit and thus it tries to access an index beyond the array's size.


text:
Q: Why does == not raise 'TypeError not supported' when all methods return NotImplemented? Why does the == operator return a value when all the comparison dunder methods are returning NotImplemented?  Other operators (<, <=,...) would raise a TypeError in the same situation.
To give an example, consider the following classes :
class Foo:
    pass
    def __eq__(self, other):
        print('Foo __eq__', self, other)
        return NotImplemented

    def __ne__(self, other):
        print('Foo __ne__', self, other)
        return NotImplemented

class Bar:
    pass
    def __eq__(self, other):
        print('Bar __eq__', self, other)
        return NotImplemented

    def __ne__(self, other):
        print('Bar __ne__', self, other)
        return NotImplemented

We have the following behavior:
# Foo __eq__ and Bar __eq__ called
assert not Foo() == Bar()

# Foo __eq__ called twice
f=Foo()
assert f==f

No exception raised. == seems to use the default implementation based on object identity if nothing else is available.
If I try the same experiment with < instead of == I'll end up with a TypeError exception :
# assuming __lt__ and __gt__ implemented in Foo and Bar to return NotImplemented
Foo() < Bar()
TypeError: '<' not supported between instances of 'Foo' and 'Bar'

What do I have to do if I want prevent == comparison between objects of a certain class?

A: I think the options would be (a) return False, like float('NaN') does, or (b) raise an exception in __eq__ for an inappropriate comparison.

A: As highlighted in this answer equality doesn't raise an exception but uses a different fallback. So first it tries to compare the classes as you give, then because it is not implemented it tries the swapped version for equality (the reason for calling it twice). Then it falls back to identity comparison
eq -> same objects? -> True, else False

ne -> different objects? True, else False


text:
Q: If I buy XCode 4 on the app store, can I do iOS development? I want to get into iOS development, and I didn't know if I NEED to do the $99/year registration just to play around with the SDK and XCode 4. I know you need that to submit apps to the store, but if I just want to do my own personal programming, can I just buy XCode? Thanks guys, it is just that $99 is a big step to play around with something I might end up not pursuing that much.

A: You can buy Xcode, but you'll be limited to development in the iOS simulator. The $99 fee is required to install on actual devices for testing.


text:
Q: How can I verify if a datetime object in php is different than 0? In my php code I have a variable:
$mytime = 0;

later on in code when I'm going through several if statements, at some point I'm adding to this variable a new datetime object:
$mytime = new DateTime($input);

however, this situation varies - sometimes I'm adding this value and sometimes I'm not touching this variable at all. And then in my code I have an if statement:
if($mytime != 0)

and when this variable has a datetime type, I'm getting an error:
Object of class DateTime could not be converted to string

How can I change - either my declaration of $mytime or the if statement - so that everything works fine here?
Thanks!

A: DateTime is an object. To check for errors after parsing the date ($input) you should use a try / catch statement
try {
    $mytime = new DateTime($input);
} catch (Exception $e) {
    // ERRORS HERE
    print_r(DateTime::getLastErrors());
}

A: You can serialize($mytime) to convert the object to a string first, before comparing. So, something like this in your if statement would work:
if (serialize($mytime) != 0)


text:
Q: Angularjs datatables - rowCallback event can someone help me with rowCallback. Problem is, I have a table, and you can click anywhere on table row for open info for clicked item. On first TD I set check box. But when I check checkbox, I don't want to open info.
Here is image for better explanation

my code
var vm = this;
    vm.selected = {};
    vm.selectAll = false;
    vm.toggleAll = toggleAll;
    vm.toggleOne = toggleOne;

    var titleHtml = '<input type="checkbox" ng-model="showCase.selectAll" ng-click="showCase.toggleAll(showCase.selectAll, showCase.selected)">';

    function getUserTokenFromLocalStorage(localStorage) {
        var authData = [];
        for (key in localStorage) {
            if (key == "ls.authorizationData") {
                authData = localStorage[key];
            }

        }

        var jsonObj = JSON.parse(authData);
        return jsonObj.token;
    };

    var vm = this;
    vm.message = '';
    vm.someClickHandler = someClickHandler;
    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withOption('ajax', {
            // Either you specify the AjaxDataProp here
            // dataSrc: 'data',
            url: serviceBase + 'test',
            type: 'POST',
            headers: {
                'xtoken': 'Bearer ' + getUserTokenFromLocalStorage(localStorage)
            }
        })
        // or here
        .withDataProp('data')
        .withOption('processing', true)
        .withOption('serverSide', true)
        .withOption('rowCallback', rowCallback)
        .withOption('createdRow', function(row, data, dataIndex) {
            // Recompiling so we can bind Angular directive to the DT
            $compile(angular.element(row).contents())($scope);
        })
        .withOption('headerCallback', function(header) {
            if (!vm.headerCompiled) {
                // Use this headerCompiled field to only compile header once
                vm.headerCompiled = true;
                $compile(angular.element(header).contents())($scope);
            }
        })
        .withPaginationType('full_numbers')

    vm.dtColumns = vm.dtColumns = [
        DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable()
        .renderWith(function(data, type, full, meta) {
            vm.selected[full.id] = false;
            return '<input type="checkbox" ng-model="showCase.selected[' + data.id + ']" ng-click="showCase.toggleOne(showCase.selected)">';
        }), //don't change state when click on this TD, only check checkbox.
        DTColumnBuilder.newColumn('id').withTitle('ID'),
        DTColumnBuilder.newColumn('type').withTitle('Type'),
        DTColumnBuilder.newColumn('city').withTitle('City'),
        DTColumnBuilder.newColumn('country').withTitle('Country'),
        DTColumnBuilder.newColumn('last_report_dt').withTitle('Last report'),
        DTColumnBuilder.newColumn('hardware_version').withTitle('HW version'),
        DTColumnBuilder.newColumn('rpi_image_version').withTitle('Image version'),
        DTColumnBuilder.newColumn('software_version').withTitle('Code version'),
        DTColumnBuilder.newColumn('internal_note').withTitle('Internal note'),
        DTColumnBuilder.newColumn(null).withTitle('Info').notSortable()
        .renderWith(function(data, type, full, meta) {
            vm.selected[full.id] = false;
            return 'Info';
        }),
    ];

    function toggleAll(selectAll, selectedItems) {
        for (var id in selectedItems) {
            if (selectedItems.hasOwnProperty(id)) {
                selectedItems[id] = selectAll;
            }
        }
    }

    function toggleOne(selectedItems) {
        for (var id in selectedItems) {
            if (selectedItems.hasOwnProperty(id)) {
                if (!selectedItems[id]) {
                    vm.selectAll = false;
                    return;
                }
            }
        }
        vm.selectAll = true;
    }

    function someClickHandler(info) {
        vm.message = info.id;
        $location.path('info/' + info.id);

    }

    function rowCallback(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
        // Unbind first in order to avoid any duplicate handler (see https://github.com/l-lin/angular-datatables/issues/87)
        $('td', nRow).unbind('click');
        $('td', nRow).bind('click', function() {
            $scope.$apply(function() {
                vm.someClickHandler(aData);
            });
        });
        return nRow;
    }

}

A: Have had this issue myself. I think your approach is a little bit backwards. You declare the td click handler inside rowCallback, just to be able to pass the id. Instead I will recommend this :

*

*Add a no-click class to the first column to prevent click :
DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable()
  .withClass('no-click')
  .renderWith(function(data, type, full, meta) {
     vm.selected[full.id] = false;
     return '<input type="checkbox" ng-model="showCase.selected[' + data.id + ']" ng-click="showCase.toggleOne(showCase.selected)">';
   }),

*Change the rowCallback to do nothing but injecting the id as attribute to the row :
function rowCallback(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
   $(nRow).attr('data-id', aData.id);
}

*Create a delegated event handler on the td's to replace both the event handler inside rowCallback and your someClickHandler() :
$('#tableid').on('click', 'tbody td:not(.no-click)', function() {
  var id = $(this).parent().attr('data-id');
  vm.message = id;
  $location.path('info/' + id);
})


text:
Q: Dynamic Subdomains - ColdFusion 11 Anyone know a way to create dynamic subdomains in coldfusion 11 without having to add them to a dns server?
I want to be able to redirect each of my clients in a personalized subdomain every time they log in to my system.
ex: client1.example.com client2.example.com

A: This works if your site is hosted in a Windows IIS server.
If you are using IIS then the following can help you. Use loops and conditions as your requirements.
<!--- Provide you IIS SiteName --->
<cfset siteName = "Your IIS Site Name">
<!--- Your new domain address --->
<cfset newSiteBinding = "client2.example.com">
<!--- your port address --->
<cfset newSitePort = 80>
<cfset fileID = createUUID()>
<cfsavecontent variable="ex"><cfoutput>cd %windir%\system32\inetsrv
%windir%\system32\inetsrv\APPCMD set site /site.name: #siteName# /+bindings.[protocol='http',bindingInformation='*:#newSitePort#:#newSiteBinding#']</cfoutput>
</cfsavecontent>
<cffile  action = "write"
    file = "E:\#fileID#.bat"
    output = "#ex#"
/>

<cfexecute  name="E:\#fileID#.bat"
    arguments="/c set"
    variable="data"
    timeout="10"
/>

<cffile  action = "delete"
    file = "E:\#fileID#.bat"
>

What we are basically doing is that we are creating a .bat file and executing it using cfexecute. Please note that you need to be careful with the paths because the Directory structure might be different in your server.
.BAT file content Example
cd %windir%\system32\inetsrv
%windir%\system32\inetsrv\APPCMD set site /site.name: example /+bindings.[protocol='http',bindingInformation='client2.example.com:80:*']

How the command works. Notice the + at /+bindings?
That means adding a new binding and /-bindings tries to remove an existing binding.


text:
Q: sum Data from column 1 where falls between range in column 2 I'm fairly new to PL-SQL so could use a bit of help.
Table#1 contains:
LoanIntersestRates
------------------
4.5
4.0
3.5
3.0
2.5

Table #2 Contains:
ActualInterestRate  LoanAmt
-----------------------------
4.6                 356258.00
4.7                 387958.25
2.6                 485658.25
3.65                500562.00
4.1                 434135.25
2.65                756254.02
4.5                 286325.02

What I need to do is get a sum of the loanAmt where the ActualInterestRate is Exactly what is in table one.
Also, Need to sum up the loadAmts where the actualInterestrate is 1-50 points above each of the LoanInterestRates, 50-100 points above each of the LoanInterestRates and 100+ points above each of the LoanInterestRates.
Any help on this would be greatly appreciated. Thanks in advance!

A: Use the following query if you want to get the sum for rates mentioned in table 1
select lr.interest,sum(amount) from loaninterestrates lr, loaninterestamounts la
where lr.interest = la.interest
group by lr.interest

For step - 2 to find the sum for ranges use this
select la1.intrange,sum(la1.amount)from
(
select la.interest,la.amount,case when Remainder(la.interest*10,10) < 0 or Remainder(la.interest*10,10) = 5
                  then to_char(FLOOR(la.interest) + 0.5) || '-' || to_char(FLOOR(la.interest) + 1.0)
            else to_char(FLOOR(la.interest)) || '-' || to_char(FLOOR(la.interest) + 0.5 )
            end as intrange
        from loaninterestamounts la

  ) la1
 group by la1.intrange

sqlfiddle here: http://sqlfiddle.com/#!4/92f15/8

A: hi I have some misunderstanding your question but please check my sql
with t1 as
 (select 4.5 as lir
    from dual
  union all
  select 4.0
    from dual
  union all
  select 3.5
    from dual
  union all
  select 3.0
    from dual
  union all
  select 2.5 from dual),
t2 as
 (select 4.6 as air, 356258.00 as la
    from dual
  union all
  select 4.7, 387958.25
    from dual
  union all
  select 2.6, 485658.25
    from dual
  union all
  select 3.65, 500562.00
    from dual
  union all
  select 4.1, 434135.25
    from dual
  union all
  select 2.65, 756254.02
    from dual
  union all
  select 4.5, 286325.02 from dual),
t1_d as
 (select lir as lir_low, lead(lir) over(order by lir) as lir_high from t1)
select t1_d.lir_low, sum(la) as sum_la
  from t1_d, t2
 where t2.air >= t1_d.lir_low
   and ((t2.air < t1_d.lir_high) or (t1_d.lir_high is null))
 group by t1_d.lir_low


text:
Q: How to move a button from an array of buttons by mouse? C# I'm really new to C# coding.
I got an array of buttons and I want to move the button I'm left clicking by mouse. Any advice?
private void CreateTable(Button[] Tabla)
     {
         int horizotal = 45;
         int vertical = 45;

         for (int i = 0; i < Tabla.Length; i++)
         {
             Tabla[i] = new Button();
             Tabla[i].BackColor = Color.Azure;
             Tabla[i].Size = new Size(45, 45);
             Tabla[i].Location = new Point(horizotal, vertical);
              if ((i == 14) || (i == 29) || (i == 44) || (i == 59) || (i == 74) ||
                   (i == 89) || (i == 104) || (i == 119) || i == 134 || i == 149 || i == 164 || i == 179 || i == 194 || i == 209)
              {
                   vertical = 45;
                   horizotal = horizotal + 45;
              }
              else
                 vertical = vertical + 45;
              this.Controls.Add(Tabla[i]);
          }
    }

This is the code that creates my buttons.

A: First of all, you add mouseeventhandler your buttons then you declare the mouseeventshandler like this.
 private void CreateTable(Button[] Tabla)
 {
     int horizotal = 45;
     int vertical = 45;

     for (int i = 0; i < Tabla.Length; i++)
     {
         Tabla[i] = new Button();
         Tabla[i].BackColor = Color.Azure;
         Tabla[i].Size = new Size(45, 45);
         Tabla[i].Location = new Point(horizotal, vertical);
          if ((i == 14) || (i == 29) || (i == 44) || (i == 59) || (i == 74) ||
               (i == 89) || (i == 104) || (i == 119) || i == 134 || i == 149 || i == 164 || i == 179 || i == 194 || i == 209)
          {
               vertical = 45;
               horizotal = horizotal + 45;
          }
          else
             vertical = vertical + 45;
          Tabla[i].MouseDown += new MouseEventHandler(button_down);//adding Down handler
          Tabla[i].MouseMove += new MouseEventHandler(button_move);//adding Move handler
          this.Controls.Add(Tabla[i]);
      }
}
    private void button_down(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            starting.X = e.Location.X;
            starting.Y = e.Location.Y;
        }
    }

    private void button_move(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            ((Button)sender).Left += e.Location.X - starting.X;
            ((Button)sender).Top += e.Location.Y - starting.Y;
        }
    }

sender is caller of the handler and we know it is a button. So we can use it like this. ı think this code is perfect for you but your problem is using buttons for letter. You can use picturebox for letter and theyare more proper than buttons. Finally I think you should declare field your buttons array.


text:
Q: Cannot add #if compiler(>=5.0) in `AppDelegate.m` file: Trying to add a block in the AppDelegate.m file
#if compiler(>=5.0)
if (@available(iOS 13.0, *)) {
    // do something...
}
#endif

The error showed is:

Function-like macro 'compiler' is not defined

A: The following is a Swift compile-time directive:
#if compiler(>=5.0)
...
#endif

It makes no sense to use this in an Objective-C file, AppDelegate.m. In an Objective-C source, it will result in the "Function-like macro 'compiler' is not defined" error.
So, if you want a runtime check for iOS 13, just remove the #if, e.g.:
if (@available(iOS 13.0, *)) {
    ...
}

See Marking API Availability in Objective-C.

A couple of observations (given that you tagged this with swift):

*

*In Swift, the compile-time pattern is:
 #if swift(>=5.0)
 ...
 #endif

Or
 #if compiler(>=5.0)
 ...
 #endif

This pattern is generally only used when writing third-party libraries where you need to offer backward support to developers who are compiling your library with earlier versions of Swift.
See The Swift Programming Language: Compiler Control Statements

*The following is an Objective-C runtime check for OS version:
if (@available(iOS 13.0, *)) {
    // do something...
}

The equivalent Swift pattern is:
if #available(iOS 13.0, *) {
    ...
}

These are useful when writing code that is targeting multiple iOS versions, but you want to conditionally run code using iOS 13+ API.

*To make it confusing, Swift does have an @available construct, but it is for marking a class, extension, or method as being available only for devices running a particular OS version, but is not used in conjunction with an if test. E.g. let's say you are defining some function that should only be available to iOS 13 and later:
@available(iOS 13.0, *)
func someMethod() {
    ...
}

This is compile-time construct is to tell the compiler to not complain about iOS 13 API within this function if your app happens to support earlier iOS versions. You are effectively telling the compiler "hey, I know this has code inside it that only works with iOS 13 and later, but don't worry, because I'll only call it when the device in question is running iOS 13 or later."

A: There are many things wrong that you did in your code example:

*

*#if is a preprocessor macro. You can only use it outside the scope of anything, just like the import statement. If you are using it the way it should be used, then you can't use that if statement there.

*@available cannot be used inside of an if statement. It can only be used to represent if a particular class/struct/func is available for said OS version and up, but not fragments of code. For that, use this instead:
if #available(iOS 13.0, *) {
  // Do something.
}

A: If you want to check the Swift compiler version specifically, you can use #if swift. To check for iOS version during runtime, you need to use #available, the @ version if used to mark types/functions only available on said versions.
#if swift(>=5.0)
if #available(iOS 13,*) {
    //do something
}
#endif


text:
Q: How do I change the output to an equilateral triangle of numbers? I managed to code something that gives me the desired output in a right triangular form. I'm kind of lost on what I must modify to change it into a equilateral triangle
Here's the code:
#include <stdio.h>
#include <stdlib.h>

int main()
{
int i, j, rows;
printf("This is a program that generates a equilateral triangle of n height. \n");
printf("Enter the height of the equilateral triangle: \n");
scanf ("%d",&rows);

while (rows <= 1 )
{
    printf("Invalid output, it takes two or more rows to produce a triangle.\n");
    printf("Enter the number of rows for the increasing triangle: \n");
    scanf("%d", &rows);
}

printf("The triangle is as follows: \n");
for  (i = 1; i <= rows; i++)
{
    for (j =1; j <= rows; j++)  {
     printf("  ");
    }
    for (j = 1; j <= i;j++) {
        printf("%d", i);
    }
    printf("\n");
}
return 0;
}

A: The logic of your for loop must be modifies to get an equilateral triangle. The below code works, The outer most for loop I have used is to print the numbers in a new line every time after completing the inner loops the outer loop prints a new line. The first inner loop isto print the space for an equilateral triangle and the second inner loop is to print the numbers.
#include <stdio.h>
#include <stdlib.h>

int main()
{
int x,y, rows;
printf("This is a program that generates a equilateral triangle of n height. \n");
printf("Enter the height of the equilateral triangle: \n");
scanf ("%d",&rows);

while (rows <= 1 )
{
    printf("Invalid output, it takes two or more rows to produce a triangle.\n");
    printf("Enter the number of rows for the increasing triangle: \n");
    scanf("%d", &rows);
}

printf("The triangle is as follows: \n");
for(x=1; x<=rows; ++x)
    {

        for(y=x; y<=rows; ++y)
        {
            printf(" ");
        }

        for(y =1; y<=((2*x)-1); ++y)
        {
            printf("%d",x);
        }
        // Print new line
        printf("\n");
    }
return 0;
}

A: A very little  change will make your code perfect '
1.make your second for loop as        for(j=rows-i;j>0;j--)
2.Add a space after the element      printf("%d ",i);
or refer this code:                                                                                `    #include <stdio.h>
#include <stdlib.h>
int main()
{
    int i, j, rows;
    printf("This is a program that generates a equilateral triangle of n height.
    \n");
    printf("Enter the height of the equilateral triangle: \n");
    scanf ("%d",&rows);

 while (rows <= 1 )
{
      printf("Invalid output, it takes two or more rows to produce a
               triangle.\n");
      printf("Enter the number of rows for the increasing triangle: \n");
      scanf("%d", &rows);
}

      printf("The triangle is as follows: \n");
      for  (i = 1; i <= rows; i++)
      {
            for (j =rows-i;j>0; j--)
            {
                  printf(" ");
            }
           for (j = 1; j <= i;j++)
           {
                 printf("%d ",i);
           }
                 printf("\n");
       }
           return 0;
      }`


text:
Q: Pyside2 - Linenumbers in codeeditor incorrect when changed font family/size I looked at this code editor example from the official Qt5 website https://doc.qt.io/qt-5/qtwidgets-widgets-codeeditor-example.html. It is written in C++ but I implemented it in Python using Pyside2.
The example code works fine as is, however, when I try to change the font family and size of the QPlainTextEdit things start getting messy. I've tried to tweak a lot of different fields like using the fontMetrics to determine to height etc.
Here is a minimal example to reproduce the problem
import sys
import signal
from PySide2.QtCore import Qt, QSize, QRect
from PySide2.QtGui import QPaintEvent, QPainter, QColor, QResizeEvent
from PySide2.QtWidgets import QWidget, QPlainTextEdit, QVBoxLayout
from PySide2 import QtCore
from PySide2.QtWidgets import QApplication

FONT_SIZE = 20
FONT_FAMILY = 'Source Code Pro'

class PlainTextEdit(QPlainTextEdit):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.init_settings_font()

    def init_settings_font(self):
        font = self.document().defaultFont()

        font.setFamily(FONT_FAMILY)
        font.setFixedPitch(True)
        font.setPixelSize(FONT_SIZE)
        self.document().setDefaultFont(font)

class LineNumberArea(QWidget):
    TMP = dict()

    def __init__(self, editor):
        super().__init__(editor)
        self._editor = editor

        self._editor.blockCountChanged.connect(lambda new_count: self._update_margin())
        self._editor.updateRequest.connect(lambda rect, dy: self._update_request(rect, dy))

        self._update_margin()

    def width(self) -> int:
        # we use 1000 as a default size, so from 0-9999 this length will be applied
        _max = max(1000, self._editor.blockCount())
        digits = len(f'{_max}')
        space = self._editor.fontMetrics().horizontalAdvance('0', -1) * (digits + 1) + 6
        return QSize(space, 0).width()

    def _update_line_geometry(self):
        content_rect = self._editor.contentsRect()
        self._update_geometry(content_rect)

    def _update_geometry(self, content_rect: QRect):
        self.setGeometry(
            QRect(content_rect.left(), content_rect.top(), self.width(), content_rect.height())
        )

    def _update_margin(self):
        self._editor.setViewportMargins(self.width(), 0, 0, 0)

    def _update_request(self, rect: QRect, dy: int):
        self._update(0, rect.y(), self.width(), rect.height(), self._editor.contentsRect())

        if rect.contains(self._editor.viewport().rect()):
            self._update_margin()

    def _update(self, x: int, y: int, w: int, h: int, content_rect: QRect):
        self.update(x, y, w, h)
        self._update_geometry(content_rect)

    # override
    def resizeEvent(self, event: QResizeEvent) -> None:
        self._update_line_geometry()

    # override
    def paintEvent(self, event: QPaintEvent):
        painter = QPainter(self)
        area_color = QColor('darkgrey')

        # Clearing rect to update
        painter.fillRect(event.rect(), area_color)

        visible_block_num = self._editor.firstVisibleBlock().blockNumber()
        block = self._editor.document().findBlockByNumber(visible_block_num)
        top = self._editor.blockBoundingGeometry(block).translated(self._editor.contentOffset()).top()
        bottom = top + self._editor.blockBoundingRect(block).height()
        active_line_number = self._editor.textCursor().block().blockNumber() + 1

        # font_size = storage.get_setting(Constants.Editor_font_size).value
        font = self._editor.font()

        while block.isValid() and top <= event.rect().bottom():
            if block.isVisible() and bottom >= event.rect().top():
                number_to_draw = visible_block_num + 1

                if number_to_draw == active_line_number:
                    painter.setPen(QColor('black'))
                else:
                    painter.setPen(QColor('white'))

                font.setPixelSize(self._editor.document().defaultFont().pixelSize())
                painter.setFont(font)

                painter.drawText(
                    -5,
                    top,
                    self.width(),
                    self._editor.fontMetrics().height(),
                    int(Qt.AlignRight | Qt.AlignHCenter),
                    str(number_to_draw)
                )

            block = block.next()
            top = bottom
            bottom = top + self._editor.blockBoundingGeometry(block).height()
            visible_block_num += 1

        painter.end()

if __name__ == "__main__":
    app = QApplication(sys.argv)

    signal.signal(signal.SIGINT, signal.SIG_DFL)

    window = QWidget()
    layout = QVBoxLayout()
    editor = PlainTextEdit()
    line_num = LineNumberArea(editor)

    layout.addWidget(editor)
    window.setLayout(layout)

    window.show()

    sys.exit(app.exec_())

One of the biggest issues are that there seems to be a top margin offset in the plaintext exit which I'm unable to dynamically get in the linenumber widget.
And when setting the editor font to the painter the numbers will not be drawn the same size!?
Does anyone know how to adjust the line numbers to the same horizontal level as the corresponding text and also get them to be the same size in a dynamic way, meaning that if the font will be set to something else they should all be adjusted automatically.

A: The problem comes from the fact that you're using two fonts for different purposes: the widget font and the document font.
Each font has different aspects, and its alignment might differ if you consider those fonts as base for drawing coordinates.
Since you're drawing with the document font but using the widget font as reference, the result is that you'll have drawing issues:

*

*even with the same point size, different fonts are drawn at different heights, especially if the alignment of the text rectangle is not correct (also note that you used an inconsistent alignment, as Qt.AlignRight | Qt.AlignHCenter will always consider the right alignment and defaults to top alignment)

*you're using the widget font metrics to set the text rectangle height, which differs from the document's metrics, so you'll limit the height of the drawing.

Unlike other widgets, rich text editors in Qt have two font settings:

*

*the widget font;

*the (default) document font, which can be overridden by a QTextOption in the document;

The document will always inherit the widget font (or application font) for the default, and this will also happen when setting the font for the widget at runtime, and even for the application (unless a font has been explicitly set for the widget).
Setting the font for the editor is usually fine for simple situations, but you have to remember that fonts propagate, so children widget will inherit the font too.
On the other hand, setting the default font for the document will not propagate to the children, but, as explained above, can be overridden by the application font if that's changed at runtime.
The simplest solution, in your case, would be to set the font for the editor widget instead of the document. In this way you're sure that the LineNumberArea (which is the editor's child) will also inherit the same font. With this approach you don't even need to set the font of the painter, as it will always use the widget font.
In case you want to use a different font and still keep correct alignment, you have to consider the baseline position of the font used for the document, and use that reference for the baseline of the widget font. In order to do that, you have to translate the block position with the difference of the ascent() of the two font metrics.


text:
Q: ec2 waitfor timesout after 2 minutes I have a simple lambda function that checks the instance status but it timesout. I have set timeout to 2 minutes. The role has all the permissions on EC2.
    ec2.waitFor('instanceRunning', {InstanceIds: ['someinstanceid'], DryRun:true}, function(err, data) {
      if (err)
      {
            console.log(err);
            context.fail(err);
      }
      else
      {
            console.log(data);
            context.succeed(data);
      }
    });

A: To anyone that came here riding on google:
It is possible to configure the behavior of waitFor like this:
let params = {
    InstanceIds: ["i-1234567890"],
    //Waiter configuration
    $waiter: {
        maxAttempts : 1000,
        delay: 10
    }
};

EC2.waitFor("instanceRunning", params, function(error, data){
    /***/
}.bind(this));

Here I configured check delay for 10 seconds, at max 1000 attempts, that is like 166 min.
Note that all maxAttempts need to fail so you know that instance actually failed to start, so you probably want to use this carefully.


text:
Q: The checkmark isn't properly aligned with vote counts in the new beta sites Oh, déjà vu?
The problem appears on the new beta theme too. Just noticed while cutting an image.

And, just by the way: the check mark in the accepted state is aligned properly. Which makes the check mark shift a bit to the right left when I accept.

How could I forget about the gif??


text:
Q: Message sent to deallocated instance in iPhone I am new to iPhone,
I am creating NSURLConnection as suggested by apple here
but my app crashes when i Dismiss my view, i have tried concept of NSZombieEnabled which shows me -[CALayer release]: message sent to deallocated instance 0x68b8f40
I am displaying a webpage in Webview, When users clicks on download link in the webview then shouldStartLoadWithRequest method will be called inside this method i am creating NSURLConnection.
here is my code snippet,
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data1
{
    [receivedData appendData:data1];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);

    DirPath=[self applicationDocumentsDirectory];

     NSLog(@"DirPath=%@",DirPath);
    [receivedData writeToFile:DirPath atomically:YES];

    UIAlertView* Alert = [[UIAlertView alloc] initWithTitle:@"Download Complete !"
                                                         message:nil delegate:nil
                                               cancelButtonTitle:@"OK"
                                               otherButtonTitles:nil];
    [Alert show];
    [Alert release];

    // release the connection, and the data object
    [connection release];
    [receivedData release];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error1
{
    [connection release];
    [receivedData release];

    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error1 localizedDescription],
          [[error1 userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {

    //CAPTURE USER LINK-CLICK.

            Durl=[[url absoluteString]copy];

            //Checking for Duplicate .FILE at downloaded path....

            BOOL success =[[NSFileManager defaultManager] fileExistsAtPath:path];
            lastPath=[[url lastPathComponent] copy];

            if (success) //if duplicate file found...
            {
                UIAlertView* Alert = [[UIAlertView alloc] initWithTitle:@"This FILE is already present in Library."
                                                                     message:@"Do you want to Downlaod again ?" delegate:self
                                                           cancelButtonTitle:nil
                                                           otherButtonTitles:@"Yes",@"No",nil];
                [Alert show];
                [Alert release];

            }
            else  //if duplicate file not found directly start download...
            {
                // Create the request.
                NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:Durl]
                                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                      timeoutInterval:60.0];

                // create the connection with the request and start loading the data
                NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
                if (theConnection) {
                    // Create the NSMutableData to hold the received data.
                    receivedData = [[NSMutableData data] retain];
                } else {
                    NSLog(@"Inform the user that the connection failed.");
                }

    return YES;
}

Any help will be appreciated.

A: Make sure that in your implementation of dealloc you are resetting the delegate to nil. Another place for doing so would be viewWillDisappear:.
The reason for your app to crash / access a zombie is that the UIWebView instance will possibly be trying to call back the viewController even though it has already been deallocated. To prevent that, you have to set the delegate of that UIWebView back to nil before the viewController goes out of scope. That is a general issue when working with delegation prior to iOS5's ARC implementation. iOS5 finally offers weak references, those actually nil themselves once their instance is getting deallocated.
Example A:
- (void)dealloc
{
    [...]
    _webView.delegate = nil;
}

Example B:
- (void)viewWillDisappaer:(BOOL)animated
{
    [super viewWillDisappaer:animated];
    _webView.delegate = nil;
}

Edit:
After reading your question once again, I realised that the zombie is a UIView or a UIControl since the message is sent to a CALayer. Make sure your problem actually is related to the web view by temporarily removing all webView related code.

A: I think issue with this  NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
You are creating an instance of NSURLConnection with delegate self, when you dismiss the view everything get deallocated on that view. But when the NSURLConnection tries to call it's delegate method crash will occur.
So you need to set the delegate of NSURLConnection to nil in your viewWillDisappear for doing this, you need to create object of NSURLConnection in interface.
@interface yourClass
{
   NSURLConnection *theConnection;
}
@end

in .m
theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

- (void)viewWillDisappaer:(BOOL)animated
{
    [super viewWillDisappaer:animated];
    theConnection.delegate = nil;
}


text:
Q: Lazarus - How to control the color of a textbox that is disabled (i.e., Enabled := false) When data is to be viewed only, I'm disabling the text boxes on the form.
But during this time, the text is not very readable as it's very light.
Is there a way to change the color of these textboxes instead of using the default colors for DISABLED objects?
Subsequently, I presume this will apply to all objects - list boxes, drop down combos, date inputs, etc., but for now it's only for the textboxes.
Thanks!

A: From my own question, the purpose of disabling text boxes was to leave them locked to prevent user changes. However, the disabled text boxes were not readable.
The solution is NOT to change the colour of dsabled objects but to leave it locked. And the easiest way of doing this is to just change the ReadOnly property to true. Thus when ever there's a need to lock a text box, I can set the property like this example.
MyTextBox.ReadOnly := True;

Now the control remains white or whatever other colour and at the same time it is not editable by the user.
Strange, how simple this was and I hadn't figured this out earlier :)


text:
Q: Checkbox value not being set In my database there's a bool fiedd called IsAvailable.In my edit function i wanted to fill that checkbox is IsAvailable or not but in here always checkbox not filled.
($("#chkcomp").prop('checked') == msg._prodlng[0].IsAvailable);

but
msg._prodlng[0].IsAvailable // this one returns true or false correctly according to database value

A: The correct syntax to set prop is:
$('el').prop('property','value');

So use,
$("#chkcomp").prop('checked',msg._prodlng[0].IsAvailable);


text:
Q: 'NoneType' object is not subscriptable - openCV I am facing an error when trying to run the same code in new jupyter notebook
I am practicing on Hand gesture code, sometimes able to run code and when I try t run the same code in new notebook it is showing an error
import numpy as np
import cv2
import math

capture = cv2.VideoCapture(0)
while capture.isOpened():
    ret, frame = capture.read()
    cv2.rectangle(frame, (100, 100), (300, 300), (0, 255, 0), 0)
    crop_image = frame[100:300, 100:300]
    blur = cv2.GaussianBlur(crop_image, (3, 3), 0)
    hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)

TypeError                                 Traceback (most recent call
last)
<ipython-input-5-fc124576a5ed> in <module>
 14     # Get hand data from the rectangle sub window
 15     cv2.rectangle(frame, (100, 100), (300, 300), (0, 255, 0), 0)
 ---> 16     crop_image = frame[100:300, 100:300]
 17
 18     # Apply Gaussian blur

TypeError: 'NoneType' object is not subscriptable

A: This happens sometimes when the current kernal fails. Try restarting the kernal before running the code.
Alternatively, you can use the imutils python module for accessing a video stream, it works pretty well in my experience.
pip install command:
pip install imutils

Hope this helps, goodluck.


text: Q: How we can I get all credentials from jenkins as an environment variables? I am trying to get all credentials using credentials(), stored in the folder. But due to interpolation and masking issues, those credentials are visible on UI, which is not secure. So, is there any way where I can load all the credentials?


text:
Q: Checking Visited Websites with javascripts Hello I am walking through the code which check if a user has visited websites before. and the code is as follows

 Visited

 Not visited

When I check the colors of at the browser. it has changed visually but it has not change at document.write(color) showing rgb(0,0,238) still.
So, the problem I am facing and question would like to ask are is as follow :

*

*Why does color does not change in value showing rgb(0,0,238) at document.write() although it changed visually?

*'else' is not seemed to working here unless I replaced it with if (color == rgb(0,0,238) so why it happened there?

so please kindly help me the above problem. Many thanks in advance

A: Checking the color of :visited in JavaScript has been a security/privacy vulnerability that was closed long ago. That is why the underlying values have not changed.


text:
Q: Do I have to use integration to solve this exercise? everybody, I am doing an exercise but I am not quite sure if the way I am going to resolve is the right one. Can I have your advice on it, please?
Exercise:
Thanks to the new acquisition of advanced equipment, a company estimates that its customers will vary at a rate of f(t), where t is the number of years since the acquisition of this new equipment. If this company is right, how many customers will it have increased 16 years after this new acquisition?
What I think I should do is, I calculated the integral of f(t) from 0 to 16.


text:
Q: C++ No-repeat random number generator I need to create algorithm implementation in C++ to generate random numbers to f.e table without repeat and list.
I created something code like that but it's stop working when I put n=32769 in console program stop working. When i put number in range 0-32768 it's works. Any idea what is wrong in this code?
While compilation i had no errors/warnings.
#include <stdio.h>
#include <iostream>
#include <ctime>

int main()
{
    clock_t start = clock();
    int n;
    std::cout << "n:";
    std::cin >> n;
    bool *used_numbers = new bool[n];
    memset(used_numbers, false, sizeof(used_numbers[0]) * n);
    int *permutation = new int[n];
    srand(unsigned(std::time(NULL)));
     int rnd_number;

    for (int i = 0; i < n; i++)
    {
        rnd_number = rand() % n;
        if (!used_numbers[rnd_number])
        {
            permutation[i] = rnd_number;
            used_numbers[rnd_number] = true;
        }
        else
            i--;
    }
    std::cout << "Permutation: \n ";
    for (int k = 0; k < n; k++)
    {
        std::cout << permutation[k] << " ";
    }
    std::cout << std::endl;

    printf("[Debug]: %lu ms\n", clock() - start);

    getchar();
    system("pause");
    return 0;
}

A: rand() % n

will never give you a number larger than RAND_MAX. RAND_MAX is the range of the numbers generated by rand().
If you use a value of n larger than RAND_MAX, you will loop forever after you draw the first RAND_MAX numbers. Simply, there's no numbers left to draw.
You need to improve your solution to be able to generate larger numbers, or use something better like shuffling a larger list of numbers.
Your algorithm has many issues, but an immediate simple fix would be:
rnd_number = (rand() * (RAND_MAX + 1) + rand()) % n;

A: I just want to state some other solutions to the following problems, which may work faster (or with some shorter code) (in some cases).
Imagine the case where you need all the elements of the set {0, 1, .., n - 1}, probability of choosing the last non-chosen element(in last iteration) is equal to 1/n, expected value is then n iterations for picking only one element.

*

*vector<int> p;
for(int i = 0; i < n; i++) p.push_back(i);
random_shuffle(p.begin(), p.end();

and then you can take first K elements of vector p (or whole vector, if you need the whole permutation).

*In every iteration, you can pick a random number i between 1 and numbers_left (N - numbers_already_chosen), and then take i-th number that hasn't been already picked. It may also be inefficient, but using some binary search + binary indexed tree, you could get to O(Nlog^2N), maybe even better.

A: If you need to generate a sequence of non-crypto-safe numbers without a repeat then you can utilize Linear-feedback shift register. Example generation 65535 items (adopted from Wiki):
#include <iostream>
#include <set>
#include <cassert>
#include <cstdint>

int main(void)
{
    // Any nonzero start state will work.
    const ::std::uint16_t start_state{0xACE1u};
    ::std::uint16_t lfsr{start_state};
    ::std::uint64_t period{0};
#ifndef NDEBUG
    ::std::set<::std::uint16_t> used_items{};
#endif // #ifndef NDEBUG
    do
    {
        // Get LSB (i.e., the output bit).
        bool lsb{0 != (lfsr & 1)};
        // Shift register
        lfsr >>= 1;
        // If the output bit is 1, apply toggle mask.
        if(lsb)
        {
            lfsr ^= 0xB400u;
        }
        // verify that current value has never appeared before
        assert(used_items.emplace(lfsr).second);
        std::cout << lfsr << "\n";
        ++period;
    }
    while(lfsr != start_state);
    ::std::cout << "period " << period << "\n";
    ::std::cout.flush();
    return 0;
}


text:
Q: Angularjs or JQuery ? Which one will compile first? In my application I am using both.I am curious which one will compile first?

A: Whichever the interpretor encounters first is executed first. The order matters, not the framework or its size. It is like first come first served.
Also, you shouldn't use "compile" word here as javascript is interpreted and not compiled.


text:
Q: Change an active slave of Linux network bonding interface without ifenslave command Linux supports bonding of multiple Ethernet network interfaces for extra reliability or load balancing.
Bonding driver used to be configured via ifenslave command, which has been deprecated (superseded by ip command from iproute2 toolkit), so ifenslave was removed from the kernel sources.
One particular feature of deprecated command which I can't find a modern equivalent for is changing an active slave of the bonding interface (assuming that bonding interface is operating in the active-backup mode).
For example, the following commands set eth0 network card as an active slave of bond0 interface:
ifenslave -c bond0 eth0
ifenslave --change-active bond0 eth0

Is there a way to change an active slave of Linux bonding interface using ip command from the iproute2 toolkit or, alternatively, via sysfs?

A: Create procedure for bonding interface:
# create the bonding interface with active-backup mode
ip link add name bond0 type bond mode active-backup

# add the under laying interfaces
# the interface, that has been added first, will be active
ip link set master bond0 dev eth1
ip link set master bond0 dev eth0

# enable the bonding interface
ip link set up dev bond0
ip address add 192.168.100.1/24 dev bond0

# check the results: detailed info and statistics of bond0
ip -s -s -d link ls dev bond0

# check the state of ALL under laying interfaces
# with statistics and details
ip -s -s -d link ls master bond0

# check the kernel logs
journalctl -kn 20

To change the active link for bonding device you should use this command:
ip link set dev bond0 type bond active_slave eth0

If you have gotten the error like RTNETLINK answers: invalid argument then check the dmesg or the journalctl -k outputs.
For brief help for options you can use ip link add type bond help command. It applies to any link type.
All values of current options of bond0 interface you can get with ip -d l ls dev bond0 command.


text:
Q: What does the window.onerror colno parameter represent? I need precision regarding the expected colno value of window.onerror.
The spec says:

The colno attribute must return the value it was initialized to. It represents the column number where the error occurred in the script.

The position the error occurred in the script is not clear to me. In the case of an undefined reference error for example, is it:
a) the start of the problematic reference or
b) the end of it, since the error is when trying to use an invalid reference ?
Refer to the code below.

window.onerror = function (message, filename, lineno, colno, error) {
console.log(colno);
}
// generate an "Uncaught ReferenceError"
generate.error;

The following recent browsers return 1 as the colno for the sample above.

*

*Firefox 51.0.1

*Chromium 53.0.2785.143

*Opera 43.0.2442.806

This would make me believe a) is right. However, as stated above, I find the spec ambiguous on this. In my mind, returning 9 (the position where the undefined generate ends) would also be valid. I would like some kind of authority on this matter.
What is the expected value of where an error occurred in JavaScript?


text:
Q: Returning false while connecting bio metric machine using C# I want to connect bio metric machine using C#. I am using zkemkeeper dll for connecting with machine
I have used connect_net method to connect with ip address and port
public partial class Form1 : Form
{
    public zkemkeeper.CZKEM machineObj = new zkemkeeper.CZKEM();
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        bool status = false;
        status = machineObj.Connect_Net("10.10.32.162", 5005);
        if (status)
        {
            MessageBox.Show("Connect to machine successfully");
        }
    }
}

Now this machineObj.Connect_Net always return false what is the reason behind  this any one have solution?
error code is -2

A: there was a long time ago when I dealt with it, I found some useful tips on code project in this post:

1) The connection is denied by firewall settings (on your system or a
  router): Check the firewall logs.
2) The device has a white or black list configuration that does not
  allow connections from your system's IP address: Check the
  configuration of the device and the log files (if such exist).
3) The packages are not routed when your system is not in the same
  subnet as the device: Configure port forwarding on the device's next
  gateway.

if your device as a white or blacklist configuration, you better start digging into your logs and device configuration.
Meanwhile start exploring your firewall as well, if there is any, to make sure you are not being blocked from connecting to the device.
edit: I saw your comment so this might be the cause of your issue.
the most common reason however, is the third because it is easier to miss, it is unnoticeable and does not catch the eye. Make sure your system is in the same subnet as the device. If not, configure your port forwarding on the device.


text:
Q: why is bash -e disabled within a function run with not (!) Note: If you are looking for a workaround because set -e does not work in a function, please go to "set -e" in a function. This question is about why it does not work as expected.
When the following is run on GNU bash, version 4.1.5(1)-release :
  set -ex

  PS4=' ${FUNCNAME[0]}: $LINENO: '

  function f() {
      set -e
      false
      echo $@
  }

  ! f why does it display ? It should stop because of -e
  f

It displays
 : 11: f why does it display '?' It should stop because of -e
 f: 6: set -e
 f: 7: false
 f: 8: echo why does it display '?' It should stop because of -e
why does it display ? It should stop because of -e
 : 12: f
 f: 6: set -e
 f: 7: false

I expect it to never go past the false, because -e means "exit when a command has a non zero exit status". I am aware that -e has a tricky behavior, as explained in http://mywiki.wooledge.org/BashFAQ/105 but I would like to understand what happens in this specific case. I am using -e and it proved most helpful in many very simple scenarios. This scenario is a little more tricky but if it can be explained I may use -e instead adding || exit 1 after each line.

A: While trying to solve a similar problem, I read the man page for set -e:

-e errexit
Exit immediately if a simple command exits with a non-zero
   status, unless the command that fails is part of an until or
   while loop, part of an if statement, part of a && or || list,
   or if the command's return status is being inverted using !.

Note the last bit about the return status being inverted. I guess the logical negation of function f must have an effect on the behaviour of set -e within that function.

A: Here's from the trap section of man bash (my emphasis):

If a sigspec is ERR, the command arg is executed whenever a simple command has a non-zero exit status, subject to the following conditions. The ERR trap is not executed if the failed  command is  part  of  the  command list immediately following a while or until keyword, part of the test in an if statement,  part  of  a command  executed in a && or || list, or if the command's return value is being inverted via !.  These are  the  same  conditions obeyed by the errexit option.

So ! command effectively disables the ERR trap inside command. I guess the reasoning is that you might not want a command exiting early if you are "kinda explicitly" checking the exit code after running it with !. Looks like bad design, since it can be used to effectively disable safeguards pretty much anywhere.

A: I can't precisely answer the why, but I found this snippet here:

On a slightly related note, by default bash takes the error status of the last item in a pipeline, which may not be what you want. For example, false | true will be considered to have succeeded. If you would like this to fail, then you can use set -o pipefail to make it fail.

And by updating your script as such:
function f() {
    echo $SHELLOPTS
    set -e
    set -o pipefail
    false
    echo "$@"
}

It seems to behave as you expect.
So my best guess for "why" (probably the same as yours by now), is that the ! causes the function to be handled in some sort of "pipe" mode.  Again... why ! means 'pipe', I guess I don't really know.  Maybe a better bash expert can answer that part for us.


text:
Q: Entity Framework Core 2.1 - Multiple Providers What is the right way to work with multiple providers?
My Example:
appsettings.json
{
  "ConnectionStrings": {
    "Sqlite": "Data Source=database.db"
  }
}

Startup.cs
public void ConfigureServices(IServiceCollection services)
{
     services.AddDbContext<DatabaseContext>(options =>
                    options.UseSqlite(Configuration.GetConnectionString("Sqlite")));
}

DatabaseContext.cs
public class DatabaseContext : DbContext
{
    public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options) { }
    public DbSet<TestModel> TestModel{ get; set; }
}

A easy way for multiple providers?

A: A solution with only one Context (Example for SQLite + MySQL + MSSQL + PostgreSQL (or others)):
appsettings.json
{
  // Add Provider and ConnectionStrings for your EFC drivers
  // Providers: SQLite, MySQL, MSSQL, PostgreSQL, or other provider...
  "Provider": "SQLite",
  "ConnectionStrings": {
    "SQLite": "Data Source=mydatabase.db",
    "MySQL": "server=localhost;port=3306;database=mydatabase;user=root;password=root",
    "MSSQL": "Server=(localdb)\\mssqllocaldb;Database=mydatabase;Trusted_Connection=True;MultipleActiveResultSets=true",
    "PostgreSQL": "Host=localhost;Database=mydatabase;Username=root;Password=root"
  }
}

Single DatabaseContext.cs
public class DatabaseContext : DbContext
{
        public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options) { }

        // add Models...
}

Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    // Check Provider and get ConnectionString
    if (Configuration["Provider"] == "SQLite")
    {
        services.AddDbContext<DatabaseContext>(options =>
            options.UseSqlite(Configuration.GetConnectionString("SQLite")));
    }
    else if (Configuration["Provider"] == "MySQL")
    {
        services.AddDbContext<DatabaseContext>(options =>
            options.UseMySql(Configuration.GetConnectionString("MySQL")));
    }
    else if (Configuration["Provider"] == "MSSQL")
    {
        services.AddDbContext<DatabaseContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("MSSQL")));
    }
    else if (Configuration["Provider"] == "PostgreSQL")
    {
        services.AddDbContext<DatabaseContext>(options =>
            options.UseNpgsql(Configuration.GetConnectionString("PostgreSQL")));
    }
    // Exception
    else
    { throw new ArgumentException("Not a valid database type"); }
}

Now we can do a singel migration
Add-Migration InitialCreate
Only edit every output of Add-Migration and add driver specific attributes:
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
        name: "Mytable",
        columns: table => new
        {
            Id = table.Column<int>(nullable: false)
            // Add for SQLite
            .Annotation("Sqlite:Autoincrement", true)
            // Add for MySQL
            .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn)
            // Add for MSSQL
            .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn)
            // Add for PostgreSQL
            .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
            // Or other provider...
            Name = table.Column<string>(maxLength: 50, nullable: false),
            Text = table.Column<string>(maxLength: 100, nullable: true)
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_Mytable", x => x.Id);
        });
    }

EDIT:
or you use string ID "DatabaseGenerated"
so you would not have to edit migrationBuilder and the add migration is multiple providers capable without ".Annotation"
EXAMPLE Model:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebApplication.Models
{
    public class Mytable
    {
        // This generate a String ID
        // No ID modification needed for providers
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public string Id { get; set; }

        // ....
    }
}

Now ready for Update-Database

A: You may want to consider a utility like AdaptiveClient.  AdaptiveClient allows you to create a single DbContext with multiple provider-specific implementations of your services (MSSQL, MySQL, SQLite, etc).  AdaptiveClient injects the correct implementation based on the connection string in use.
AdaptiveClient also allows you to inject transport-specific service implementations.  For example many applications run both locally (same LAN as database server) and remotely (use WCF or REST). When running locally AdaptiveClient will inject an implementation of your service that talks directly to your database.  This gives a ~10x performance improvement.  When running remotely AdaptiveClient injects a WCF or REST implementation.
See also:
AdaptiveClient.EntityFrameworkCore
Demo Application
AdaptiveClient is available as a nuget package.
Disclaimer:  I am the author of AdaptiveClient.

A: Seimann's answer is good but I found working with migrations to be a pain. I wanted little or no manual work to get it working. I found the easiest way was to create a separate assembly for each provider and add an implementation of IDesignTimeDbContextFactory.
Another solution is to create a design time assembly but selecting which provider to use for migrations turned out to be difficult, at least until this feature is implemented here. I tried the suggested method of setting an environment variable before executing the migrations but I found using compiler constants to select the correct provider to be easier.
I organized this by creating a shared project to be used by all providers. Here is an example implementation that pulls your main projects configuration settings. This class will support both methods explained above so it can be simplified depending on your needs.
#if DEBUG
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;

namespace Database.DesignTime
{
    public class ApplicationDbContextDesignTimeFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
    {
        public ApplicationDbContext CreateDbContext(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                 .SetBasePath(Path.GetFullPath(@"..\MainProjectDirectory"))
                 .AddJsonFile("appsettings.json")
                 .AddJsonFile("appsettings.Development.json")
                 .Build();

            // Determine provider from environment variable or use compiler constants below
            var databaseProvider = Environment.GetEnvironmentVariable("DatabaseProvider");

#if SQLSERVER
            databaseProvider = "SqlServer";
#endif
#if POSTGRESQL
            databaseProvider = "PostgreSql";
#endif

            var connectionString = configuration.GetConnectionString($"{databaseProvider}Connection");

            var contextBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();

            switch (databaseProvider)
            {
#if SQLSERVER
                case "SqlServer":
                    contextBuilder.UseSqlServer(connectionString, dbOptions =>
                    {
                        dbOptions.MigrationsAssembly("Database.SqlServer");
                    });
                    break;
#endif

#if POSTGRESQL
                case "PostgreSql":
                    contextBuilder.UseNpgsql(connectionString, dbOptions =>
                    {
                        dbOptions.MigrationsAssembly("Database.PostgreSql");
                    });
                    break;
#endif

                default:
                    throw new NotSupportedException(databaseProvider);
            }

            return new ApplicationDbContext(contextBuilder.Options);
        }
    }
}

#endif

Then in your database migration project add the compiler constant for each provider. For example:
Database.SqlServer.csproj
<DefineConstants>SQLSERVER</DefineConstants>
Database.PostgreSql.csproj
<DefineConstants>POSTGRESQL</DefineConstants>
When you want to add migrations from within VS, open the Package Manager Console and select the migration project as the Default project. When executing the command, you need to specify the project containing the implementation of IDesignTimeDbContextFactory you want to use.
Add-Migration Initial -StartupProject "Database.SqlServer"
Now you can switch back to your main project and use it as normal. Just for reference this is my relevant appsettings.json and startup code.
{
  "DatabaseProvider": "SqlServer",
  "ConnectionStrings": {
    "SqlServerConnection": "Server=(localdb)\\mssqllocaldb;Database=DatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true",
    "PostgreSqlConnection": "Host=host;Database=DatabaseName;User ID=Test;Password=secrectPass"
}

            services.AddDbContext<ApplicationDbContext>(options =>
            {
                switch (Configuration["DatabaseProvider"])
                {
                    case "SqlServer":
                        options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection"), dbOptions =>
                        {
                            dbOptions.MigrationsAssembly("Database.SqlServer");
                        });
                        break;

                    case "PostgreSql":
                        options.UseNpgsql(Configuration.GetConnectionString("PostgreSqlConnection"), dbOptions =>
                        {
                            dbOptions.MigrationsAssembly("Database.PostgreSql");
                        });
                        break;
                }
            });

There is another suggested way to accomplish this as explained here but I found creating derived classes means the migration will only work for instances of the derived class and not the base class. So you would need to specify the derived class type in AddDbContext. The other method mentioned requires manual work which I want to avoid.


text:
Q: SQL Server filtered index "Estimated number of rows to be read" is size of full table I have a table in an Azure SQL database with ~2 million rows. On this table I have two pairs of columns that I want to filter for null - so I have filtered indexes on each pairs, checking for null on each column.
One of the indexes appears to be about twice the size of the other - (~400,000 vs ~800,000 rows).
However it seems to take about 10x as long to query.
I'm running the exact same query on both:
SELECT DomainObjectId
FROM DomainObjects
INNER JOIN
    (SELECT <id1> AS Id
     UNION ALL
     SELECT<id2> etc...
    ) AS DomainObjectIds ON DomainObjectIds = DonorIds.Id
WHERE C_1 IS NULL
  AND C_2 IS NULL

Where C_1/C_2 are the columns with the filtered index (and get replaced with other columns in my other query).
The query plans both involve an Index Seek - but in the fast one, it's 99% of the runtime. In the slow case, it's a mere 50% - with the other half spent filtering (which seems suspect, given the filtering should be implicit from the filtered index), and then joining to the queried IDs.
In addition, the "estimated number of rows to be read" for the index seek is ~2 million, i.e. the size of the full table. Based on that, it looks like what I'd expect a full table scan to look like. I've checked the index sizes and the "slow" one only takes up twice the space of the "fast" one, which implies it's not just been badly generated.
I don't understand:

*

*(a) Why so much time is spent re-applying the filter from the index

*(b) Why the estimated row count is so high for the "slow" index

*(c) What could cause these two queries to be so different in speed, given the similarities in the filtered indexes. I would expect the slow one to be twice as slow, based purely on the number of rows matching each filter.


text:
Q: Can get last message or listen to telegram channel with python-telegram -bot libarary? I want make an bot for reading a last message of telegram channel thats meaning listening to Target channel

A: It's not possible with this bot, otherwise, you need to handle message with this documentation.
In other way, with this other package, you will be able to get history of chat.


text:
Q: Why can't a struct impl await its task and get result when it can await its methods? In some cases it would be useful for a struct/object to be able to start some tasks and then allow struct users to stop these tasks and await for result. I could of course send result with channel or shared resource but using return value would be cleaner in many cases. Also I understand from experience in other async languages that it is good practice to always await your tasks at some point in code.
I cannot make the borrow checker to accept the following attempt to implement the idea over. Can someone explain it? and even better can I find a way out of it?

use tokio::time;
use tokio::task::JoinError;

struct S {
    pub task: tokio::task::JoinHandle<bool>,
}

impl S {
    pub async fn new() -> Self {
        let task = tokio::task::spawn(async {
            time::sleep(time::Duration::from_secs(10)).await;
            true
        });
        Self { task }
    }

    pub async fn join_and_get_result(&self) -> Result<bool, JoinError> {
        self.task.await // cannot move out of `self.task` which is behind a shared reference
    }
}

#[tokio::main]
async fn main() {
    let s = S::new().await;
    s.join_and_get_result().await;
    let result = s.task.await; // this is fine for borrow checker but requires to expose internal implementation
}

A: Calling .await on a task consumes the task. You can fix the error by making join_and_get_result take self and not &self, which will move S into the function making it possible to call .await on the task:
use tokio::task::JoinError;
use tokio::time;

struct S {
    pub task: tokio::task::JoinHandle<bool>,
}

impl S {
    pub async fn new() -> Self {
        let task = tokio::task::spawn(async {
            time::sleep(time::Duration::from_secs(10)).await;
            true
        });
        Self { task }
    }

    pub async fn join_and_get_result(self) -> Result<bool, JoinError> {
        self.task.await
    }
}

#[tokio::main]
async fn main() {
    let s = S::new().await;
    let result = s.join_and_get_result();
}

Playground

A: In addition to the other answers, it's also possible to await &mut JoinHandle<()>, i.e.:
struct Wrap {
    handle: tokio::task::JoinHandle<()>,
}

impl Wrap {
    async fn wait_for_result(&mut self) -> Result<(), tokio::task::JoinError> {
        (&mut self.handle).await
    }
}

#[tokio::main]
async fn main() {
    let mut wrap = Wrap {
        handle: tokio::spawn(async {}),
    };

    let _res = wrap.wait_for_result().await;
    drop(wrap); // wrap is not consumed, can be passed to drop()
}

Playground link
Note that when dealing with tokio::spawn & JoinHandle it's probably not desired to keep the JoinHandle around after awaiting it because another await will result in a panic:
thread 'main' panicked at 'JoinHandle polled after completion', /playground/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.18.2/src/runtime/task/core.rs:212:22

Playground link
It's e.g. useful when selecting both a JoinHandle and waiting for messages over some channel, i.e. something like
loop {
    tokio::select! {
        res = &mut handle => {
            // deal with task outcome
            break;
        },
        msg = chan.recv() => {
            // react to msg, continue waiting for task or next msg
        }
    }
}

A: In addition to https://stackoverflow.com/a/72582847/2033030 , Another way to do it if someone does not want to consume the struct is to put the task in an option and consume the option
use tokio::time;

struct S {
    pub task: Option<tokio::task::JoinHandle<()>>,
}

impl S {
    pub async fn new() -> Self {
        let task = tokio::task::spawn(async {
            time::sleep(time::Duration::from_secs(10)).await;
        });
        Self { task: Some(task) }
    }

    pub async fn join(&mut self) {
        if self.task.is_some() {
            let task = self.task.take();
            task.unwrap().await.ok();
        }
    }
}

#[tokio::main]
async fn main() {
    let mut s = S::new().await;
    s.join().await;
}