postgresql – Using the Dart/Flutter Postgres Package to store dates and null dates needs two separate commands

I am using the Postgres Package (On the pub.dev site) to UPDATE records in a very simple database. It has two fields: a Text field prime key named number, and a Date field named date_of_birth.

If the date_of_birth is a valid DateTime string then all is well (as can be seen from the code below). But if date_of_birth is unknown (so I set to null) the UPDATE fails:

import 'package:postgres/postgres.dart';
void main() async {
  final conn = PostgreSQLConnection(
   'localhost',
    XXXXX,
    'XXXXX',
    username: 'XXXXX',
    password: 'XXXXX',
  );

  await conn.open();

  DateTime dob = DateTime.now();

  var results;
  results = await conn.query('''
    UPDATE account_details
    SET date_of_birth = '$dob'
    WHERE number = '123123'
  ''');

  await conn.close();
}

If I set:

dob = null;

The program fails with the error:

Unhandled exception:
PostgreSQLSeverity.error 22007: invalid input syntax for type date: "null"

So I need to include a check on the dob field and the program now looks like this:

  DateTime dob = DateTime.now();
  dob = null;

  var results;
  if (dob == null) {
    results = await conn.query('''
    UPDATE account_details
    SET date_of_birth = null
    WHERE number = '123123'
  ''');
  } else {
    results = await conn.query('''
    UPDATE account_details
    SET date_of_birth = '$dob'
    WHERE number = '123123'
  ''');
  }

That works fine for my simple database, but in my real App. I have a number of date fields in one table. So I have to do a check for each possible combination of those date values – writing a code block for each!

Can anyone tell me how I can UPDATE both null and a valid date using a single statement please?

java – Como verificar se uma Referencia no firebaseDatabase é null

Quero criar um nó no database do firebase, mas apenas uma vez por mes.
Por isso quero salvar apenas se a referencia for null, mas nao sei como fazer.

public void salvarGestao(String data){
        String email = ConfiguracaoFirebase.getFirebaseAutenticacao().getCurrentUser().getEmail();
        String idUsuario = Base64Custom.codificarBase64(email);
        String mesAno = DataCustom.mesAnoEscolhido(data);
        DatabaseReference databaseReference = ConfiguracaoFirebase.getFirebaseDatabase()
                .child("gestao")
                .child(idUsuario)
                .child(mesAno);

        if(databaseReference==null){
            databaseReference.setValue(this);
        }
    }

laravel – Call to a member function getRelationExistenceQuery() on null

el error se produce al intentar ejecutar los seeds.

este es el error detallado:

 at vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php:49
45|         $method = $this->canUseExistsForExistenceCheck($operator, $count)
46|                         ? 'getRelationExistenceQuery'
47|                         : 'getRelationExistenceCountQuery';
48|

49| $hasQuery = $relation->{$method}(
50| $relation->getRelated()->newQueryWithoutRelationships(), $this
51| );
52|
53| // Next we will call any given callback as an “anonymous” scope so they can get the

  +3 vendor frames

4 database/factories/UserFactory.php:59
IlluminateDatabaseEloquentModel::__callStatic()

  +6 vendor frames

11 (internal):0
IlluminateDatabaseEloquentFactoryBuilder::IlluminateDatabaseEloquent{closure}()

esta es la factory:

use AppUser;
use AppCategory;
use AppProduct;
use AppTransaction;
use AppSeller;
use FakerGenerator as Faker;
use IlluminateSupportStr;

$factory->define(User::class, function (Faker $faker) {
    static $password;
    return (
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => Str::random(10),
        'verified' => $verificado = $faker->randomElement((User::USUARIO_VERIFICADO, User::USUARIO_NO_VERIFICADO)),
        'verification_token'=> $verificado == User::USUARIO_VERIFICADO ? null : User::generarVerificationToken(),
        'admin' => $faker->randomElement((User::USUARIO_ADMINISTRADOR, User::USUARIO_REGULAR)),
    );
});

$factory->define(Category::class, function (Faker $faker) {
    return (
        'name' => $faker->word,
        'description'=> $faker->paragraph(1),
    );
});

$factory->define(Product::class, function (Faker $faker) {
    return (
        'name' => $faker->name,
        'description'=> $faker->paragraph(1),
        'quantity'=> $faker->numberBetween(1, 10),
        'status'=> $faker->randomElement((Product::PRODUCTO_DISPONIBLE, Product::PRODUCTO_NO_DISPONIBLE)),
        'image'=> $faker->randomElement(('1.jgp', '2.jgp', '3.jgp')),
        'seller_id'=> User::all()->random()->id,
    );
});


$factory->define(Transaction::class, function (Faker $faker) {
    
    $vendedores= Seller::has('products')->get()->random();
    $comprador= User::all()->except($vendedores->id)->random();
    return (
        'quantity'=> $faker->numberBetween(1, 3),
        'buyer_id'=> $comprador->id,
        'product_id'=> $vendedores->products->random()->id,
    );
});

este es el seed:

use IlluminateDatabaseSeeder;
use AppUser;
use AppCategory;
use AppProduct;
use AppTransaction;

public function run()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');
        User::truncate();
        Product::truncate();
        Category::truncate();
        Transaction::truncate();
        DB::table('category_product')->truncate();

        $cantidadusuarios= 200;
        $cantidadcategorias= 30;
        $cantidadproductos= 1000;
        $cantidadtransacciones= 1000;

        factory(User:: class, $cantidadusuarios)->create();
        factory(Category:: class, $cantidadcategorias)->create();
        factory(Product:: class, $cantidadtransacciones)->create()->each(
            function($producto)
            {
                $categorias= Category::all()->random(mt_rand(1, 5))->pluck('id');
                $producto->categories()->attach($categorias->first());
            }
        );
        factory(Transaction:: class, $cantidadtransacciones)->create();

    }

Why not in does not return values with null values in my select query on postgresql 11?

I have the following sql script:

CREATE temporary table if not EXISTS the_values (
 key SERIAL,
 value INTEGER NULL 
);

insert into the_values(value) values (null),(1),(null),(2),(3),(4),(5),(6),(10),(null),(null);

select * from the_values where value not in (1,2,3,4,5,6,10); 

And I noticed that the query:

select * from the_values where value not in (1,2,3,4,5,6,10); 

Does not return the rows having value NULL, and that, caught my attention. Therefore, I want to know why that happens. I am interested more about the technical aspect of this phenomenon rather that the obvious solution:

select * from the_values where value not in (1,2,3,4,5,6,10) or value IS NULL; 

magento2 – Magento 2 API: Extension Attribute with null value not showing

I’m retrieving from the Magento API an order by its increment_id attribute like this:

http://mystore.com/rest/V1/orders?searchCriteria(filter_groups)(0)(filters)(0)(field)=increment_id&searchCriteria(filter_groups)(0)(filters)(0)(value)=1200040527&searchCriteria(filter_groups)(0)(filters)(0)(condition_type)=eq

I have added a plugin to add a custom attribute to the Order items like this (etc/di.xml):

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="MagentoSalesApiOrderRepositoryInterface">
        <plugin name="order_custom_extension_attribute"
                type="MyVendorSalesPluginOrderRepositoryPlugin"/>
    </type>
</config>

And then adding the custom attribute (is_gift_card) to the OrderItem like this (etc/extension_attributes.xml)

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
    <extension_attributes for="MagentoSalesApiDataOrderItemInterface">
        <attribute code="is_gift_card" type="boolean"/>
    </extension_attributes>
</config>

Finally my plugin to add the extension attribute to the order items in the afterGet and afterGetList:

    public function __construct(
         MagentoSalesApiDataOrderExtensionFactory $extensionFactory
    ) {
        $this->extensionFactory = $extensionFactory;
    }

    public function afterGet(MagentoSalesApiOrderRepositoryInterface $subject, MagentoSalesApiDataOrderInterface $order)
    {
        return $this->addExtensionAttributes($order);
    }

    public function afterGetList(MagentoSalesApiOrderRepositoryInterface $subject, MagentoSalesApiDataOrderSearchResultInterface $searchResult)
    {
        $orders = $searchResult->getItems();

        foreach ($orders as &$order) {
           $order = $this->addExtensionAttributes($order);
        }

        return $searchResult;
    }

    private function addExtensionAttributes($order){

        $items = $order->getAllItems();
        foreach ($items as $item){
            $giftCard = $item->getData('is_gift_card');
            
            $extensionAttributes = $item->getExtensionAttributes();
            $extensionAttributes = $extensionAttributes ? $extensionAttributes : $this->extensionFactory->create();
            $extensionAttributes->setIsGiftCard($giftCard);
            $item->setExtensionAttributes($extensionAttributes);
        }

        return $order;
    }
}

The thing is that is_gift_card is added to the extension_attribute segment IF that attribute has any value, but it is not showing at all if it has a null value.

Is this a normal behaviour from the Magento API?

Thanks in advanced

java – Json Result from News API is null

 @Override
    protected String doInBackground(String... strings) {
        String result = HttpRequest.getExecute("http://newsapi.org/v2/everything?q=bitcoin&from=2020-05-30&sortBy=publishedAt&apiKey=myAPIkey");
        return result;
    }

I am getting a null response on passing this url even though the same url when opened on the browser shows a lot of stuff. I am getting a Null Pointer Exception. Please help. Below is my HttpRequest class.

HTTPRequest Class:

public class HttpRequest   {
public static String getExecute(String targetUrl)
{
    URL url;
    HttpURLConnection httpURLConnection = null;
    try
    {
        url = new URL(targetUrl);
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("GET");

        InputStream inputStream;
        if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK)

            inputStream = httpURLConnection.getErrorStream();
        else
            inputStream = httpURLConnection.getInputStream();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        StringBuffer response = new StringBuffer();
        while ( (line = bufferedReader.readLine()) != null)
        {
            response.append(line);
            response.append('r');

        }
        bufferedReader.close();
        return  response.toString();


    }
    catch (Exception e)
    {
     e.printStackTrace();
     return  null;
    }
    finally {
        if(httpURLConnection != null)
        {
            httpURLConnection = null;
        }
    }
}

}

Using viewBinding in Android outside Activity and Fragment should I assign null to binding instance?

I want to use viewBinding not directly in Fragment nor in Activity. So I am creating a simple view, wondering do I need to assign null to topicChipBinding or not because looking at this sample https://github.com/android/architecture-components-samples/blob/3cbd78e999e03bc3ed2eaf43865c48476647449a/ViewBindingSample/app/src/main/java/com/android/example/viewbindingsample/BindFragment.kt#L44 it says Consider not storing the binding instance in a field, if not needed. wondering how should I handle it here?

class Chip(val parent: ViewGroup) : XXXX {
private val topicChipBinding: TopicChipBinding = TopicChipBinding.inflate(
    LayoutInflater.from(parent.context),
    parent, false
)
private val buttonView: Button

init {
    buttonView = topicChipBinding.chip
    update(view)
}

fun setText(text: CharSequence) {
    buttonView.text = text
}

override val view: View
    get() = topicChipBinding.root

}

SQL SERVER Scope Identity returns null on Select Insert

Query:

INSERT INTO (Saturday).(dbo).(Storage)
Select
Name,
CASE
When ROW_NUMBER() over (order by Name) = 1 then @tree_drop_to 
Else (SELECT SCOPE_IDENTITY())
END
From CTE1 

Fatal error: Uncaught Error: Call to a member function getBackendModel() on null in magento 2.1

I am try to import customer vis csv but getting error Fatal error: Uncaught Error: Call to a member function getBackendModel() on null in via csv file. i am uploading 5000 customers but getting error.
when i upload 10 customer then getting this error "General system exception happened". both error getting on these conductions.

asp.net – HttpRequestMessage.GetClientCertificate() returns null in ASP Web API DelegatingHandler

I have an ASP Web Api (.Net Framework 4.6.1) which accepts client certificates. The requirement is to send a custom validation message in the response of a request that has an invalid certificate.
For example, if the certificate is missing I should send back “Client certificate is missing”, if the OCSP validation fails, I should send back “Certificate has been revoked”, etc.
This is the code:

 public class CertificateMessageHandler : DelegatingHandler
{
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
             var certificate = request.GetClientCertificate();
        }
}

I have a client application where I select what certificate I want to use, and it does a request to the web api application (which is hosted on another machine). If the certificate is valid, then request.GetClientCertificates() returns the certificate, otherwise, if the certificate is expired or self-signed, request.GetClientCertificates() return null.

I have disable the automatic CLR validation by the IIS:

netsh http show sslcert
netsh http delete sslcert ipport=0.0.0.0:443
netsh http add sslcert ipport=0.0.0.0:443 e104e... appid={4dc3e181-...} certstorename=My verifyclientcertrevocation=disable

I have set:

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesHTTPParametersSslBindingInfo.0.0.0:443DefaultSslCertCheckMode=1
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSecurityProvidersSCHANNELSendTrustedIssuerList=0

None of the above settings worked.

Note: a 3rd party that uses the web app might send a self-signed certificate and the business logic should reject the request for such certificates, therefore, the inclusion of the CA, that was used to sign the certificate, in the Trusted Root Store, isn’t possible.

Any help is appreciated on how to get the client certificate from the request.