Thursday, May 26, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


how do i get `sort` and `bool => should` query to work in tandem?

Posted: 26 May 2022 01:48 AM PDT

I have the following query for fetching all products, what i'am trying to achieve is keep the out of stock products I.E. products with stock_sum = 0 at the bottom :-

{    "sort": [      {        "updated_at": {          "order": "desc"        }      }    ],    "size": 10,    "from": 0,    "query": {      "bool": {        "should": [          {            "range": {              "stock_sum": {                "gte": 1,                "boost": 5              }            }          }        ]      }    }  }  

But with the above query sort keeps to completely override should , which is show its suppose to behave i guess, a couple of things that i tried are changing the should to must in this case the out of stock products, are left out completely (thats not what i want, i still want the out of stock products at the bottom).

Another approach is remove sort , and then the should query seems to have an effect , but again i need the sort. so my question is how do i get sort and bool => should query to work in tandem ? I.E. yes sort by updated_at but also keep the stock_sum = 0 at the bottom ?

Border-bottom covered by selection background

Posted: 26 May 2022 01:47 AM PDT

ins {    text-decoration: none;    border-bottom: 0.16em solid red;  }    ::selection {    background: gray;  }
<p><ins>This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line.</ins></p>

ins {    text-decoration: none;    border-bottom: 0.16em solid red;  }
<p><ins>This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line.</ins></p>

Select text in the first snippet, the border-bottom is covered by selection background, which doesn't appear in the second snippet.

Azure DevOps Project Now Showing up in Visual Studio 2019

Posted: 26 May 2022 01:47 AM PDT

I am trying to access my Azure DevOps repo using Visual Studio 2019 from a VM. But projects were not getting listed even after login. Previously the Projects used to visible. But now it is not showing up. But I could access the repo from the Visual Studio 2019 installed in my laptop.enter image description here

Internal Server Error 500 When Trying To Run PHP AJAX CRUD Application

Posted: 26 May 2022 01:47 AM PDT

I am working on a CRUD app and I am using PHP, JQuery(AJAX) and MySQL as the databse, i am using XAMPP on Ubuntu 22.04.

Have have written my code and when i try to run it i get a 500 Error and the web browser says that the error is in my file that is responsible for handling the CRUD operation.

I have searched online and it seems to be a CORS issue, but when i try to implement the solutions provided in other posts that are here, none of them fix my solution at all. How do i fix this problem?

The Ajax/Jquery script in the index.php file:

      $(document).ready(function() {          $("#parcel_form").submit(function(e){            e.preventDefault();            $.ajax({              type : "POST",              url : "process.php",              data : $("#parcel_form").serialize(),              dataType: "json",              success : function(response){                console.log(response);              }            });          });         });      </script>  

The code responsible for CRUD operations:

  include 'config.php';        if (isset($_POST['sender'])) {        $sender = $_POST['sender'];      $reciever = $_POST['reciever'];      $parcel_type = $_POST['parcel_type'];      $weight = $_POST['weight'];        $sql = "INSERT INTO `parcels`(`sender`, `reciever`, `parcel_type`, `weight`) VALUES ('$sender', '$reciever', '$parcel_type', '$weight')";      $message = "Record created sucessfully.";        $result = $conn->query($sql);      if ($result) {          $response = array('status' => true, 'message' => $message);      }else {          $response = array('status' => false, 'message' => $conn->error);      }        echo json_encode($response);  }    ?>   

The config file:

  $servername = "localhost";  $username = "root";  $password = "";  $database = "parcel_manager";    $conn = new mysqli($servername, $username, $password, $database);  if(conn->connect_error){      die("Connection Failed: ".conn->connect_error);  }  ?>  

How to clear installed widgets on iOS app

Posted: 26 May 2022 01:46 AM PDT

In last version of iOS app we have implemented widget feature, but in the coming release we have decided to remove the widget extension.

If the user has already added widget to his Home Screen and when ever user updates his/her application with latest code that does not contain widget extension, still user is able to view blank widget.

Is there any way to clear/remove widgets programatically from main app.

Advanced number formatting with incrementing suffix- javascript

Posted: 26 May 2022 01:47 AM PDT

I need some help with my function. I am new to coding and this task is part of Coderslang apprentice level tasks.

Implement a function that If n < 1000, it should be rounded to a single digit after a decimal point Else, to cut down the length of a number, we need to use letters 'K', 'M', 'B', 'T' to represent thousands, millions, billions or trillions. We're not really interested in being super precise here. If the number exceeds 999.99T it becomes 1.00aa, after 999.99aa goes 1.00ab. When the number gets as high as 999.99az it will next turn into 1.00ba and so on. The bold text is where I am having an issue, I am not sure how best to write this function and need help. Below is what I have tried so far but I am failing two parts of the test- The function formatNumber should work properly for numbers less than 999az. And the function formatNumber should not cut trailing zeros.

My code so far:

export const formatNumber = (n) => {    let number = n;    let suffix = [97, 92];    let newNumber = "";      if (n < 1000) {          return n.toFixed(1);        } else if (n < 1000000) {            return (n / 1000).toFixed(2) + 'K';        } else if (n < 1000000000) {            return (n / 1000000).toFixed(2) + 'M';         } else if (n < 1000000000000) {            return (n / 1000000000).toFixed(2) + 'B';        } else if (n < 1000000000000000){            return (n / 1000000000000).toFixed(2) + 'T';        }       while (number > 1000) {      (number /= 1000);      if (suffix[1] < 122) {        suffix[1]++;      } else {        suffix[0]++;        suffix[1] = 97      }     }      const stringNumber = String(number);    const i = stringNumber.indexOf(".");        if (i >= 0) {      newNumber = stringNumber.substring(0, i) + "." + stringNumber.substring(i + 1, i + 3);    } else {      newNumber = stringNumber + ".00";    }             return newNumber + String.fromCharCode(suffix[0]) + String.fromCharCode(suffix[1]);  }    

I have searched this forum and others and am struggling, any help would be appreciated. I feel that either I am over complicating the thought process or I'm missing something obvious. Is it my while loop? I have tried number.toFixed and number.toExponential without luck

input yes or no or any other it will print "Invalid Input" only. how to fix?

Posted: 26 May 2022 01:47 AM PDT

Following code If we input "yes" It should print "Hello" , If input is "no" It should print "bye" , If input other one It should print "Invalid Input".

but the problem is if we input yes or no or any other it will print "Invalid Input" only.

Can we solve this using only else if statements? plz help.

import java.util.*;    public class hello{            public static void main (String[] args) {          Scanner sc = new Scanner(System.in);                    System.out.print(" Input yes or no : ");          String ans = sc.nextLine();                                      if (ans == "yes") {              System.out.println(" Hello ");              }              else if (ans == "no") {                  System.out.println(" bye ");                  }else {                      System.out.println(" Invalid Input ");                      }                    System.out.print(ans);                }  }  

Prompting/Displaying a Filter box for a specific column

Posted: 26 May 2022 01:46 AM PDT

I need a code which selects the column and displays the Filter box as shown in the below image("This is a filter dropdown which allows us to select the list of values").

I want a code which follows the following steps

  1. Select column A
  2. Prompts us the Filter box as shown in the below picture for us to manually select the data
  3. Later, Run the rest part of the code

I have a code already in place but its prompts for an Input box with the values("Manually") to be entered in it. But this is not the one which I want.

Please find the below reference image and the code as-well.

Sub Filer_Box()    Dim uiDeptToShow As String    uiDeptToShow = Application.InputBox("Show which Department", Type:=2)  If uiDeptToShow = "False" Then Exit Sub: Rem Cancel pressed    Range("A1:M1").Select    Selection.AutoFilter    Selection.AutoFilter Field:=1, Criteria1:="=" & uiDeptToShow, Operator:=xlAnd    End Sub  

enter image description here

c# is there a DebuggerDisplay equivalent to format class members?

Posted: 26 May 2022 01:47 AM PDT

The DebuggerDisplay attribute allows to show a custom "value" or interpretation for entire class. This is good, but is there a possibility to force also displaying a standard type member (ie. UInt32) to a hexadecimal value?

There are 2 reasons I want this

  • some of my members has meaning in hex only (addresses, bit masks)
  • the hex formatting is global in C# IDE so I have to toggle manually quite often

[DebuggerDisplay("{_value,h}")]   public abstract class DataField  {    [DebuggerBrowsable(DebuggerBrowsableState.Never)]    private UInt32 _value;                  // display this member in debugger permanent as HEX     public UInt32 ConstMask { get; set; }   }  

One option I see is to declare ConstMask as a class and apply DebuggerDisplay formatting as well, but this will affect my performances and I guess is not a good option to do that just for debug purposes.

Thanks in advance for hints,

what to fill for null values of object/string datatype with some random texts in a dataframe

Posted: 26 May 2022 01:47 AM PDT

open this link for imageI have a dataset of zomato, in which there is a column called cuisines (it consists data like ex: 'North Indian, South Indian, Mithai, Street Food, Desserts' and any other random combination of cuisines. My question is , there are some null values in cuisines column and what method/ what would be a good fit for replacing these null values?

Thanks,

Css html custom background lines

Posted: 26 May 2022 01:47 AM PDT

design i'm working with have lines and icons in various sections on bg. Is there a best way to do it with css/html? enter image description here

Hiding header of UITableView

Posted: 26 May 2022 01:47 AM PDT

I have TableView with invisible header. I already tried unsuccessfully to hide the header with:

tableView.tableHeaderView = .init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))

tableView.tableHeaderView?.removeFromSuperview()

tableView.tableHeaderView = nil

But I found out that if you call a multitask or manually change the theme to dark/light, this header disappears

Here is an example

So, is this a bug, or I missing something?

Why does printf output characters instead of data? [duplicate]

Posted: 26 May 2022 01:48 AM PDT

Why does printf output characters instead of data? Looking at the code, you can relatively understand what I want to do, but it is unclear why the output is like this

#include <vector>  #include <string>  #include <cstdio>    class Person  {  public:      Person(const std::string& name, uint16_t old)          : m_Name(name)          , m_Old(old)       {      }    public:      std::string GetName() const { return m_Name; }      uint16_t GetOld() const { return m_Old; }    private:      std::string m_Name;      uint16_t m_Old;  };    int main()  {      std::vector<Person> person = { Person("Kyle", 26), Person("Max", 20), Person("Josiah", 31) };      for (uint16_t i = 0; i < person.size(); ++i)      {          printf("Name: %s Old: %u\n", person[i].GetName(), person[i].GetOld());      }      return 0;  }      > // output  >     Name: Ь·╣ Old: 1701607755   >     Name: Ь·╣ Old: 7889229   >     Name: Ь·╣ Old: 1769172810  

why `git rebase` following commit date as result? [closed]

Posted: 26 May 2022 01:47 AM PDT

I wanna to use git rebase to update the source branch after releasing the app, however, I encounter the following issue. The commit date presents in alphabetical order. (e.g. A is older than B)

Original: Original

After running git rebase develop: after rebase

Expected: expected

I have used git rebase before, but not working like this time. Can anyone explain to me the reason, thank you.

MySQL update unique value returns Error Code: 1062. Duplicate entry

Posted: 26 May 2022 01:48 AM PDT

I have a problem with updating the unique column value in the table.

I have a customer table and I have a separate customer_address table where the customer can have one primary address and others. The primary address is the main address to which the goods are delivered. Customers can have many addresses but one must be primary.

When I try to update I get the message: Error Code: 1062. Duplicate entry '0-3' for key 'primary_UNIQUE'

CREATE TABLE `customer_address` (        `id` int(11) NOT NULL AUTO_INCREMENT,        `name` varchar(45) DEFAULT NULL,        `address` varchar(525) NOT NULL,        `customer_id` int(11) NOT NULL,        `primary` tinyint(4) DEFAULT '0',        `created_at` timestamp NULL DEFAULT NULL,        `updated_at` timestamp NULL DEFAULT NULL,        PRIMARY KEY (`id`),        UNIQUE KEY `primary_UNIQUE` (`primary`,`customer_id`),      ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8  

My plan was that all non-primary addresses have a value of 0, and only the primary address has a value of 1.

id   |  name        |      address             |     customer_id   |   primary  ------------------------------------------------------------------------------         '2',  'Store 1',     'Address name 24',           '3',                '0'  '3',  'Wholesale',   'Address name 24',           '3',                '1'  '4',  'Store 2',     'Address name 24',           '1',                '0'  '5',  'Wholesale 3', 'Address name 24',           '1',                '1'  

How I try to change primary address:

First, I need to update id = 3 and set primary to 0. This will cause Duplicate entry

UPDATE customer_address SET primary = 1 WHERE id=2;  UPDATE customer_address SET primary = 0 WHERE id=3;  

Is there another way to solve this?

Find the missing numbers in the given array

Posted: 26 May 2022 01:46 AM PDT

Implement a function which takes an array of numbers from 1 to 10 and returns the numbers from 1 to 10 which are missing. examples input: [5,2,6] output: [1,3,4,7,8,9,10]

C++ program for the above approach:

#include <bits/stdc++.h>     using namespace std;      // Function to find the missing elements     void printMissingElements(int arr[], int N)   {            // Initialize diff         int diff = arr[0] - 0;            for (int i = 0; i < N; i++) {                // Check if diff and arr[i]-i             // both are equal or not             if (arr[i] - i != diff) {                    // Loop for consecutive                 // missing elements                 while (diff < arr[i] - i) {                     cout << i + diff << " ";                     diff++;                 }             }         }   }  

Driver Code

int main()   {         // Given array arr[]         int arr[] = { 5,2,6 };            int N = sizeof(arr) / sizeof(int);            // Function Call         printMissingElements(arr, N);         return 0;   }   

How to solve this question for the given input?

How to display a list of a model in a C# console application

Posted: 26 May 2022 01:47 AM PDT

I am new to C# and I have been struggling to do the following: I'm trying to List a list in a console application, I have a model called "TeamModel"

public class TeamModel  {      public int Id { get; set; }      public string TeamName { get; set; }      public List<PersonModel> TeamMembers { get; set; } = new List<PersonModel>();        public TeamModel()      {        }  }  

In my main class I have the following:

class Program   {      static void Main(string[] args)      {         List<TeamModel> TeamOne   = new List<TeamModel>(){new TeamModel() { Id =1, TeamName = "x's Team", TeamMembers  = null}};         List<TeamModel> TeamTwo   = new List<TeamModel>(){new TeamModel() { Id =2, TeamName = "y's Team", TeamMembers  = null}};         List<TeamModel> TeamThree = new List<TeamModel>(){new TeamModel() { Id =3, TeamName = "z's Team", TeamMembers  = null}};           List<List<TeamModel>> listOfTeams = new List<List<TeamModel>> (){TeamOne,TeamTwo,TeamThree};           foreach (List<TeamModel> list in listOfTeams)          {         Console.WriteLine(list);         }        }    }  

Now when I run the program I expect the result to be:

1,x's Team ,

2,y's Team ,

3,z's Team

Instead what I'm getting is

System.Collections.Generic.List`1[TeamModel]

System.Collections.Generic.List`1[TeamModel]

System.Collections.Generic.List`1[TeamModel]


If I change the foreach to :

       foreach (List<TeamModel> list in listOfTeams)          {         Console.WriteLine(String.Join(", ", list));         }  

I get this: TeamModel TeamModel TeamModel

I appreciate your help and I hope my explanation was clear ^_^

Async function await not awaiting

Posted: 26 May 2022 01:46 AM PDT

I have an async function to upload a video using MultipartRequest. When I call my async function 'uploadVideo', by:

bool success =await uploadVideo(video,1);  

The video is uploaded but it runs the next functions before finishing the upload. Why is the await is not awaiting?

static Future<bool> uploadVideo(File video, int userID) async {    var uri = Uri.parse('https://example.com/uploadFile');    Map<String, String> headers = {    "Content-Type": "application/json",    'Accept': 'application/json',  };    var request = http.MultipartRequest("POST", uri);    request.fields['userID'] = userID.toString();    request.headers.addAll(headers);    Uint8List data = await video.readAsBytes();  List<int> list = data.cast();    request.files.add(  await http.MultipartFile.fromBytes('File', list, filename: '.mp4'),  );    final response = await request.send();    if (response.statusCode == 200) {    return true;  }  return false;  

}

Got Pairs of array using swift algorithm but need unique pairs first

Posted: 26 May 2022 01:48 AM PDT

Using swift-algorithms package

pairs = Array(list.combination(ofCount: 2))  

but need unique pairs to be first in that array and rest of the pairs later in this combination. For eg. In this case for list= [1,2,3,4] what happens is pairs = [[1,2], [1,3], [1,4],[2,3],[2,4],[3,4] but i need that pairs = [[1,2],[3,4],[2,3],[1,4],[1,3],[2,4] and similar for more elements in list.

To explain , requirment is that in first 4 pairs of pairs = [[1,2],[3,4],[2,3],[1,4],[1,3],[2,4], we need any list element to be available twice in the pair for the first 4 pairs in pairs array.

Have tried adjacentPairs() in the same swift-algorithms package but i need unique pairs first.

for example 12 elements requirement will be [1,2],[3,4],[5,6],[7,8],[9,10],[11,12],[12,1],[2,3],[4,5],[6,7],[8,9],[10,11] these are 12 pairs, and each list element is available twice.

`req.session.user` is `undefined` when using `express-session` and `connect-mongo`

Posted: 26 May 2022 01:48 AM PDT

I've created a react app that runs on port:3000 and an express app that runs on port:3001. I am using express-session and connect-mongo to handle user sessions. When I set a user session in /login it was recorded in MongoDB as expected. But when I query for req.session.user later in a different path/route, for example /channels it returns undefined.

This is how my app.js looks

const express = require('express');  const app = express();  const http = require('http');  const server = http.createServer(app);  const {Server} = require("socket.io");  const io = new Server(server);  const port = process.env.PORT || 3001;  const cors = require("cors");  const path = require('path');  const session = require('express-session');  const bodyParser = require('body-parser');  const oneDay = 1000 * 60 * 60 * 24;  const MongoStore = require('connect-mongo');  const md5 = require('md5');  const hash = '=:>q(g,JhR`CK|acXbsDd*pR{/x7?~0o%?9|]AZW[p:VZ(hR%$A5ep ib.&BLo]g';    app.use(session({      secret: hash,      saveUninitialized: false,      resave: false,      store: MongoStore.create({          mongoUrl: 'mongodb://localhost:27017/chat',          ttl: 14 * 24 * 60 * 60 // = 14 days. Default      })  }));    app.use(      cors({          origin: true,          credentials: true,          optionsSuccessStatus: 200      }));    // create application/json parser  const jsonParser = bodyParser.json({limit: '50mb'})    // create application/x-www-form-urlencoded parser  const urlencodedParser = bodyParser.urlencoded({limit: '50mb', extended: false})    app.post('/login', jsonParser, (req, res) => {      db.users.find({email: req.body.email}).toArray().then(user => {          if (user.length < 1) {              res.send({success: false, error: 'NOT_FOUND', message: 'Invalid login info!'});          } else {              user = user[0];              if (user.password === req.body.password) {                  db.users.updateOne({"email": user.email}, {$set: {"online": "1"}}).then(ret => {                      req.session.user = user.email;                      req.session.userdata = user;                      res.json(<=user data=>);                  });              }          }      })  });    app.post('/channels', async (req, res) => {      if (!req.session.user) {// THIS IS ALWAYS TRUE; EVEN AFTER SUCCESSFUL LOGIN          res.json({logout: true});          return;      }      const user = JSON.parse(req.session.userdata);      const channels = db.channels.find({contacts: {$all: [user._id]}}).toArray().then(channels => {          let allch = {};          channels.map(function (channel) {              channel.id = channel._id.toString();              channel.notif = 0;              allch[channel.id] = channel;          });          res.json(allch);      });  });  

How to use Bootstraps utilities to create the badge to show on top of image

Posted: 26 May 2022 01:48 AM PDT

I am attaching an image, because I can't seem to get the positioniong correct. I've been with it all day but can't get it to look like the image attached.

<div class="col-lg-6 ps-0">        <img src="img/image-file.jpg" class="img-fluid w-100 h-100 " alt="Cool image">       <div>the badge text </div>    </div>  

See the image here.

How to call one service from another with parameter and get response

Posted: 26 May 2022 01:47 AM PDT

Currently, I have two services running at different endpoints. For example (this is not my real scenario):

StudentService  CheckHomeWorkService  

CheckHomeWorkService can be used from many services (For example TeacherService, WorkerService). It has one controller with CheckHomeWork action. It has some parameters:

HomeWorkNumber (int)  ProvidedSolution (string).   

It will return success or failed.

Now, In my StudentService, I have a controller with SubmitHomeWork Action. It needs to check homework using CHeckHomeWorkService and save results to a database. How can I implement this?

I was using Ocelot Api GateWay but it can 'redirect' to another service and I need to save the result of the response to the database

Laravel PDF Exports: How to export data based by id

Posted: 26 May 2022 01:47 AM PDT

I wanted to export the data based by id so it doesn't get all the data in the database, so example if the site is "http://127.0.0.1:8000/pengajuan/3" the "/3" is the 'submission_id' i wanted to export from, here's my code:

Controller

public function exportpdf()      {          $submissionDetail = SubmissionDetail::all();                $pdf = PDF::loadview('pengajuan_detail.pdf',['submissionDetail'=>$submissionDetail]);          return $pdf->stream();      }  

SubmissionDetail.php

<?php    namespace App;    use Illuminate\Database\Eloquent\Model;    class SubmissionDetail extends Model  {      protected $fillable = [          'submission_id', 'nama_barang', 'image_path', 'jumlah', 'harga_satuan', 'harga_total', 'keterangan',      ];      public function submission()      {          return $this->belongsTo('App\Submission');      }        public function negotiation()      {          return $this->hasOne('App\Negotiation');      }        public function realization()      {          return $this->hasOne('App\Realization');      }  }  

How to do it?

How to send a message through TCP protocol to a TCP server using gen_tcp in Elixir?

Posted: 26 May 2022 01:48 AM PDT

I have 2 elixir applications.

In one of them I create a TCP server which listens on the port 8080 for packets. I know that it is defined correctly, because I connected to it with telnet and everything was working fine.

The problem appears when I try to connect to this TCP server from my other Elixir application.

That's how I connect to it

host = 'localhost'  {:ok, socket} = :gen_tcp.connect(host, 8080, [])  

Not sure about the options that I should specify tho.

When trying to connect to it I get in the logs of the application with TCP server:

00:21:11.235 [error] Task #PID<0.226.0> started from MessageBroker.Controller terminating  ** (MatchError) no match of right hand side value: {:error, :closed}      (message_broker 0.1.0) lib/message_broker/network/controller.ex:110: MessageBroker.Controller.read_line/1      (message_broker 0.1.0) lib/message_broker/network/controller.ex:101: MessageBroker.Controller.serve/1      (elixir 1.12.3) lib/task/supervised.ex:90: Task.Supervised.invoke_mfa/2      (stdlib 3.12) proc_lib.erl:249: :proc_lib.init_p_do_apply/3  Function: #Function<0.126110026/0 in MessageBroker.Controller.loop_acceptor/1>      Args: []  

At the line with

{:ok, data} = :gen_tcp.recv(socket, 0)  

Any ideas, suggestions?

Getting an error while reading CSV file and writing into it using Julia

Posted: 26 May 2022 01:48 AM PDT

My code:

#Directory of the project  PrDir = @__DIR__  # Creation of CSV file  global csvfile = touch(joinpath(PrDir, "newfile.csv"))  # Getting rows into csv   df = DataFrame(ID=1:4, Fullname=["1201.atr", "3333.atr", "4444.atr", "5555.atr"], creation_date=["2022-05-19T12:41:10.643", "2022-05-19T12:41:10.643", "2022-05-19T12:41:10.643", "2022-05-19T12:41:10.643"], size = ["3254", "3254", "3254", "3254"])  CSV.write(csvfile, df)  for row in CSV.Rows(csvfile)      intsize = parse(Int64, row.size)      println(row.ID, row.FullName,row.creation_date, intsize)  end  CsvDeleting()  #######################################################  function CsvDeleting()      v = nothing      GC.gc()      rm(joinpath(PrDir, "newfile.csv"), force=true)  end  

And I don't get any errors. Problems appear when i do the same thing in function. The problem is related to the expression CSV.write(csvfile, dbframe), or to the usage of function CsvDeleting(), if i use it during running the code. Sometimes it works correctly... What should I do to fix it? enter image description here

How can i retrieve one specific field from Firestore collection's document without doing in it via the uid document?

Posted: 26 May 2022 01:48 AM PDT

as I mentioned in the title, im trying to pull data from a specific field, the idea is the user is typing a certain number in the search bar, if the number (car license number) exist the user can contact the car owner.

what im trying to do is checking this field throughout all users.enter image description here

my current code :

   func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {        if searchText == "" {                    carNumberLbl.text = ""      }else {          getData ()      }  }    func getData (){      let docRef = db.collection("Users").document("2MHOob4kgh8JOu6UXxfb")      docRef.getDocument { (document, error) in                    if let document = document, document.exists {              let carNumber = document.get("car_license")              self.carNumberLbl.text = carNumber as! String              print(carNumber)          }else          {              print("Couldn't find data")          }      }  }  

Update i changed the field's data in firestore from String to Int,then i did this:

  func getDataSpecificField (){            db.collection("Users").whereField("car_license", isLessThan: 10000000)          .getDocuments() { (querySnapshot, err) in              if let err = err {                  print("Error getting documents: \(err)")              } else {                  for document in querySnapshot!.documents {                      self.carNumberLbl.text = document.data() as? String                      print("\(document.documentID) => \(document.data())")                  }              }      }  }  

which printed the entire collection: enter image description here

RESTful convention to update resource by id or by type and language

Posted: 26 May 2022 01:48 AM PDT

Currently my GET request by type and language can return only one document:

GET /documents?type=invitation&language=en    id: 50  text: "I would like to invite..."  

What is a correct restful convention to update resource?

PUT /documents?type=invitation&language=en  

?? Or maybe I should update resource only by id?

PUT /documents/50  

How to add imagick extension to xamppfiles Mac M1

Posted: 26 May 2022 01:46 AM PDT

I am attempting to install imagick and use it on my php project via xampp on Mac M1, i manage to install it using below steps

git clone https://github.com/Imagick/imagick  cd imagick  phpize && ./configure  make  sudo make install  

And got the path of the imagick.so after building.

/bin/sh /Applications/XAMPP/xamppfiles/htdocs/imagick/imagick/libtool --mode=install cp ./imagick.la /Applications/XAMPP/xamppfiles/htdocs/imagick/imagick/modules  cp ./.libs/imagick.so /Applications/XAMPP/xamppfiles/htdocs/imagick/imagick/modules/imagick.so  cp ./.libs/imagick.lai /Applications/XAMPP/xamppfiles/htdocs/imagick/imagick/modules/imagick.la  

Now i am trying to add it on my php.ini file using below methods

extension="imagick.so"  

and

extension="/Applications/XAMPP/xamppfiles/htdocs/imagick/imagick/modules/imagick.so"  

and

extension=/Applications/XAMPP/xamppfiles/htdocs/imagick/imagick/modules/imagick.so  

after restarting the xampp and tried none of it worked, meaning it does not appear on my phpinfo modules and cannot instantiate new Imagick(); any advice

Multiple outputs to same csv file in Powershell

Posted: 26 May 2022 01:47 AM PDT

I'm trying to export my firewall rules that are specified in multiple group policy objects and would like to include the Name of the GPO in the exported file. So I tried to take my string variable $Policy and jam it into the csv file each time a new gpo is parsed but all I'm getting is the gpo name and not the fields from Get-NetFirewallRule. Of course if I remove the $policy | Out-File $env:temp\gpos.csv -Append -Force line then I get all of the fields from Get-NetFirewallRule - but they're all on a large csv file and I can't determine their source GPO.

  foreach ($policy in $PolicyObjects) {  $GPO = Open-NetGPO -PolicyStore "contoso.com\$policy"  $policy | Out-File $env:temp\gpos.csv  -Append -Force  Get-NetFirewallRule -GPOSession $GPO  |   Select Name,  DisplayName,  DisplayGroup,  @{Name='Protocol';Expression={($PSItem | Get-NetFirewallPortFilter).Protocol}},  @{Name='LocalPort';Expression={($PSItem | Get-NetFirewallPortFilter).LocalPort}},  @{Name='RemotePort';Expression={($PSItem | Get-NetFirewallPortFilter).RemotePort}},  @{Name='RemoteAddress';Expression={($PSItem | Get-NetFirewallAddressFilter).RemoteAddress}},  Enabled,  Profile,  Direction,  Action | Export-CSV $env:temp\gpos.csv -Append -Force  }  Start-Process notepad $env:temp\gpos.csv   

Switching between different JDK versions in Windows

Posted: 26 May 2022 01:48 AM PDT

I'm working on few projects and some of them are using different JDK. Switching between JDK versions is not comfortable. So I was wondering if there is any easy way to change it?

I found 2 ways, which should solve this problem, but it doesn't work.

First solution is creating a bat files like this:

@echo off  echo Setting JAVA_HOME  set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_72  echo setting PATH  set PATH=C:\Program Files\Java\jdk1.7.0_72\bin;%PATH%  echo Display java version  java -version  pause  

And after running this bat, I see right version of Java. But when I close this CMD and open a new one and type "java -version" it says that I still have 1.8.0_25. So it doesn't work.

Second solution which I found is an application from this site. And it also doesn't work. The same effect as in the first solution.

Any ideas? Because changing JAVA_HOME and PAHT by: Win + Pause -> Advanced System Settings -> Environment Variables -> and editing these variables, is terrible way...

No comments:

Post a Comment