Monday, May 9, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Truncate older logs after the log file size reaches a particular size

Posted: 09 May 2022 03:54 AM PDT

I've my application running on one of the Docker containers in AWS Fargate(serverless compute engine) where I'm using a bind volume to tee application logs as follows:

/app.bin 2>&1 | tee /logs/app.log

The AWS bind volumes can grow maximum up to 200 GB, so I want to truncate the older logs once the size of my log file i.e. app.log reaches to some specific number(let's say 190 GB).

Any ideas on how do we achieve this log-rotation? I figured out that maybe I can use logrotate command along with tee. What are the other ways? How should I do it?

How is Phong Shading implemented in GLSL?

Posted: 09 May 2022 03:54 AM PDT

I am implementing a Phong Shader in GLSL for an assignment, but I don't get the same specular reflection as I should. The way I understood it, it's the same as Gouraud Shading, but instead of doing all the calculations in the vertex shader, you do them in the fragment shader, so that you interpolate the normals and then apply the phong model at each pixel. As part of the assignment I had to develop also the Gouraud shader and that works as supposed and I thought you just needed to put the vertex shader code into the fragment shader, but that doesn't seem to be the case. My vertex shader code:

#version 420 core    in vec3 vPos;  in vec3 vNorm;  uniform mat4 PV, MV, VMatrix, W;    out vec3 normalInterp;  out vec3 vertPos;    void main(){    vec4 vertPos4 = MV * vec4(vPos, 1.0);    vertPos = normalize(vertPos4.xyz);    normalInterp = mat3(transpose(inverse(MV))) * vNorm;    //normalInterp = vNorm;    gl_Position = PV * vec4(vPos, 1.0f);  }  

My fragment shader code:

#version 420 core    in vec3 normalInterp;  // Surface normal  in vec3 vertPos;       // Vertex position  in vec3 lightPos;  uniform vec3 light;  uniform vec3 ka;   // Ambient reflection coefficient  uniform vec3 kd;   // Diffuse reflection coefficient  uniform vec3 ks;   // Specular reflection coefficient  uniform float alfa; // Shininess  uniform mat4 VMatrix, W, PV, MV;  uniform vec3 Ia;  uniform vec3 Id;  uniform vec3 Is;  uniform vec3 eye;  out vec4 fColor;    void main() {    //vec3 v = normalize(vec3(MV* vec4(vertPos, 1.0)));    //vec3 N = normalize(mat3(transpose(inverse(MV)))*normalInterp);    vec3 l = normalize(mat3(VMatrix)*light);    vec3 N = normalize(normalInterp);    vec3 L = normalize(l - vertPos);    vec3 V = normalize(-vertPos); // Vector to viewer    vec3 R = normalize(reflect(-L, N));      float diffuse = max(dot(N, L), 0.0);    float specAngle = max(dot(R, V), 0.0);    float specular = pow(specAngle, alfa);      fColor = vec4(ka * Ia +                        diffuse * kd * Id +                        specular * ks * Is, 1.0);    }  

What I do in the vertex shader is that I simply transform the vertex position into view coordinates and I apply the transpose inverse of the model view matrix to the vertex normal. Then, in the fragment shader I apply just the view transform to the light position and use these coordinates to calculate the vectors needed in the Phong model. I have taken inspiration from https://www.cs.toronto.edu/~jacobson/phong-demo/, but it doesn't quite cut it and I'm out of ideas on what could be wrong. The lighting is almost correct, but some specular light is missing. All the parameters have been tested, so I would assume it's the light's position that is wrong, however I have no idea why my code wouldn't work when it does so in the other shader. Also, I know this isn't the most efficient way of doing it (pre-computing the normal matrix would be faster), I'm just trying to first get it to work properly.

finding multiple strings in shell scripts

Posted: 09 May 2022 03:54 AM PDT

I am trying to find Error:, Error :, ERROR:, ERROR : in a given file, if found then go to if block if not found then go to else block. Below is the logic i had written to perform this operation.

    --file.sh      #!/bin/bash      file='file.log'      text=`cat $file`      echo $text      if [[ ${text} = *Error:* ||${text} = *ERROR:*|| ${text} = *ERROR :* || ${text} = *Error :* || $? -ne 0 ]]; then      STATUS=1      echo "=> string found."       else      echo "=> no string found."       fi  

seems like this logic is having issues as its returing below error.

syntax error near `:*'  

Can someone please help me in resolving this issue.

React Native and React Native Paper: call function inside another functional component

Posted: 09 May 2022 03:53 AM PDT

I have a functional component that does a fetch call and setState inside its component:

componentScreen.tsx

...    function ComponentScreen(screen: any) {      ...        const loadScreen = async (newExpandedId: string | number) => {          setRefreshing(true);            if (expandedId === newExpandedId) {            setExpandedId(undefined);          } else {            setExpandedId(newExpandedId);          }            const abortController = new AbortController()   // creating an AbortController            fetch(environment.apiUrl, {            signal: abortController.signal, // passing the signal to the query          }).then((response) => {              return response.json();          })          .then(data => {              ...                setRefreshing(false);                ...          })          .catch(error => {              setRefreshing(false);              if (error.name === 'AbortError') return     // if the query has been aborted, do nothing              throw error          })            return () => {              abortController.abort()           }      }            ...  }  export default ComponentScreen  

In another file, I have a Appbar.Header component from React Native Paper and I need to call the function "loadScreen" inside a "onPress" prop of a <Button>:

header.tsx

...    return (<Appbar.Header>      ...      <View>          ...          <Button icon="refresh" mode="text" onPress={() => HOW_TO_CALL_LOADSCREEN_HERE? }>Refresh data</Button>      </View>  </Appbar.Header>);    ...  

The question is very similar to this already posted but it hasn't been answered and I'm still kinda new to React Native.

How to enter input seperated by semi colon by using setInputMask()

Posted: 09 May 2022 03:53 AM PDT

My goal is to display only files which user wants to see. For instance, "*.h; *.txt" as an input should shows the only *.h and *.txt files in selected folder. The program works for only one input(ie. *.h) The code:

QString mask = ",";   QStringList stringList(ui->lineEdit->text());  ui->lineEdit->setInputMask(mask);    QFileInfoList fileList = qdir.entryInfoList(QStringList() << stringList, QDir::Files, QDir::Size);  

The program display when the users enter input only one type of file: enter image description here

But it does not display when the users enter input as *.h; *.cpp enter image description here

Best regards!

Scrape Data from Realtime Search Trends Google in R or Python

Posted: 09 May 2022 03:53 AM PDT

I want to scrape https://trends.google.com/trends/trendingsearches/realtime?geo=US&category=t for all the keywords that are shown over there. I tried gtrendsr library but its not possible to scrape realtime search trends with this package. Can anyone please guide me is it possible to scrape this in R or python ? and How?

Thanks in advance!

Nginx on docker with php-fpm container custom header isn't working

Posted: 09 May 2022 03:54 AM PDT

I have a basic setup of nginx container and a php container running a symfony app which reads a custom header, however since i moved it to nginx from apache the header is always blank, or rather outputs the number 1 instead of the value it's supposed to.

So if i have this basic code in sysmfony:

$token = $request->headers->has('X-AUTH-TOKEN');  

The value of $token outputs as "1" instead of "LOGIN" which i had put in the headers of the request for the X-AUTH-TOKEN header:

Accept: application/json  Accept-Encoding: gzip, deflate, br  Accept-Language: en-GB,en-US;q=0.9,en;q=0.8  Authorization: Basic  Connection: keep-alive  Content-Length: 60  Content-Type: application/json  Host: localhost:4343  Origin: http://localhost:4200  Referer: http://localhost:4200/  sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"  sec-ch-ua-mobile: ?0  sec-ch-ua-platform: "macOS"  Sec-Fetch-Dest: empty  Sec-Fetch-Mode: cors  Sec-Fetch-Site: same-site  User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36  X-AUTH-TOKEN: LOGIN  

I haven't a clue why this is happening, i'm learning nginx as i want to move over from apache, so here is the nginx config:

server {      listen       4343;      listen  [::]:4343;        index index.php index.html;        if (!-e $request_filename) {          rewrite ^(.+)$ /index.php?q=$1 last;      }      error_page 404 /index.php;      root   /usr/share/nginx/html/api/public;            location ~ \.php$ {              try_files $uri =404;              fastcgi_split_path_info ^(.+\.php)(/.+)$;              fastcgi_pass ecare-php:9000;              fastcgi_index index.php;              include fastcgi_params;              fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;              fastcgi_param PATH_INFO $fastcgi_path_info;          }        # deny access to apache .htaccess      location ~ /\.ht {          deny all;      }  }  

Why this function always returns 'nofile' [duplicate]

Posted: 09 May 2022 03:53 AM PDT

I want this function to return the url of the file.

fileUpload(file: any): string {    const contentType = file.type;    let imgurl = 'nofile';    const bucket = new S3({      accessKeyId: 'aaaa',      secretAccessKey: 'aaa',      region: 'eu-central-1',    });    const params = {      Bucket: 'namebucket',      Key: file.name,      Body: file,      ACL: 'public-read',      ContentType: contentType    };      bucket.upload(params, (err: any, data: any) => {      console.log('File Uploaded.', data.Location);      imgurl = data.Location;      console.log(data.lolcation);      return imgurl;    });      return imgurl;  }  

But the second return, always returns the imgurl = 'nofile';

I need to return the data.Location.

What I am doin wrong?

Error During add condition columns in Python pandas

Posted: 09 May 2022 03:54 AM PDT

ds['myinv'].apply(lambda x: x=ds['New Invoice number'] if ds['New Invoice number'].notnull() else x=ds['Invoice number_x'] )

                  ^  

SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

Python pip update and installation errors

Posted: 09 May 2022 03:54 AM PDT

Im trying upgrade pip but its error or smth i'm new at python

Requirement already satisfied: pip in c:\program files\windowsapps\pythonsoftwarefoundation.python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages (22.0.4)  

How to manipulate combined list of three lists by its third list values

Posted: 09 May 2022 03:53 AM PDT

I have combined 3 different lists to make one combined list and now I am trying to manipulate the combined list by its third list values.

I would like to remove all lists with 0 as their 3rd value except for the ones that are between nonzero 3rd values.

Combined list:

[(20100101, 1, 0), (20100101, 2, 0), (20100101, 3, 0), (20100101, 4, 0), (20100101, 5, 0), (20100101, 6, 0), (20100101, 7, 0), (20100101, 8, 0), (20100101, 9, 0), (20100101, 10, 0), (20100101, 11, 0), (20100101, 12, 0), (20100101, 13, 0), (20100101, 14, 0), (20100101, 15, 0), (20100101, 16, 0), (20100101, 17, 0), (20100101, 18, 0), (20100101, 19, 0), (20100101, 20, 0), (20100101, 21, 0), (20100101, 22, 0), (20100101, 23, 0), (20100101, 24, 0), (20100102, 1, 0), (20100102, 2, 0), (20100102, 3, 0), (20100102, 4, 0), (20100102, 5, 0), (20100102, 6, 0), (20100102, 7, 0), (20100102, 8, 0), (20100102, 9, 0), (20100102, 10, 1), (20100102, 11, 0), (20100102, 12, 0), (20100102, 13, 1), (20100102, 14, 1), (20100102, 15, 1), (20100102, 16, 1), (20100102, 17, 0), (20100102, 18, 1)]  

and the desired output would be:

[(20100102, 10, 1), (20100102, 11, 0), (20100102, 12, 0), (20100102, 13, 1), (20100102, 14, 1), (20100102, 15, 1), (20100102, 16, 1), (20100102, 17, 0), (20100102, 18, 1)]  

Any help would be really great! Thank you

andorid ViewGroup childs isn't resized after onMeasure

Posted: 09 May 2022 03:53 AM PDT

I want to create my own ViewGroup with ViewImage and some other views. I do this as follows (i have removed adding of other views for simplyfing the example):

class TestWidget @JvmOverloads constructor(    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0  ) : ConstraintLayout(context, attrs, defStyleAttr) {      init {      addViews()    }            private fun addViews() {      val backgroundView = ImageView(context)      backgroundView.setImageDrawable(resources.getDrawable(R.drawable.kitten)) // image is 640x640 px      addView(backgroundView)    }  }  

I put this widget into xml as follows:

<?xml version="1.0" encoding="utf-8"?>  <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:layout_margin="10dp">        <com.test.TestWidget          android:layout_width="match_parent"          android:layout_height="wrap_content"/>    </FrameLayout>  

The result is perfect:

enter image description here

Now i want to make my TestWidget always square. For that i am override onMeasure as follows (for portrait layout):

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {    super.onMeasure(widthMeasureSpec, heightMeasureSpec)    setMeasuredDimension(measuredWidth, measuredWidth)  }  

And after that my cat becomes broken:

enter image description here

As you can see, my widget's height becomes equal to its width, but the ImageView is not redrawn, and is cut off. I want to remove that empty space above the ImageView.

I tried to fix this behaviour with different ways: setting layout params to backgroundView with constraint, call invalidate() and requestLayout() from onSizeChanged() callback, but nothing helps. What i am doing wrong?

Is it required and/or preferred to wrap C enum items in parenthesis , and if so, what's the utility?

Posted: 09 May 2022 03:55 AM PDT

Which one is to use?

typedef enum  {    item_1  = 1,    item_2  = 5,    item_2  = 8,    item_2  = 10,  } formA_typeDef;  

or

typedef enum  {    item_1  = (1),    item_2  = (5),    item_2  = (8),    item_2  = (10),  } formB_typeDef;  

I personally think that the first, A_typeDef; is the adequate format to use, unless the value to assign to the item isn't a simple integer, but a combination of #define such as:

#define REG1 0xFFF7U  #define REG2 0xFFFFU    typedef enum  {    item_1  = (REG1 | REG2 | 0x00U),    item_2  = (REG1 | REG2 | 0x01U),    item_2  = (REG1 | REG2 | 0x02U),    item_2  = (REG1 | REG2 | 0x03U),  } formC_typeDef;  

How to render Array of coordinates for line map using OpenLayers?

Posted: 09 May 2022 03:53 AM PDT

I have a endpoint /geomap_data/ that I am using to return customer_sites in the console log in browser which shows the following which is Sites Coordinates, Customer coordinates:

0: "[53.50119612705815, -1.1270833894501477], [53.34474, -3.01101]"  1: "[53.50119612705815, -1.1270833894501477], [53.34474, -3.01101]"  2: "[52.04061648544843, -0.6655072691644374], [51.90829, -0.5127]"  3: "[52.04061648544843, -0.6655072691644374], [51.90829, -0.5127]"  4: "[52.04061648544843, -0.6655072691644374], [51.90829, -0.5127]"  

I am able to render a map with 1 line using the code below with fake coordinates:

 $(document).ready(function(){          var customer_sites = [];          $.ajax({              dataType: 'json',              url: '/geomap_data/',              success: function(json) {                  console.log('Moo')                  customer_sites = json;              },              async:false          });            console.log(customer_sites);            var map = new ol.Map({          target: 'GeoMap',          layers: [            new ol.layer.Tile({              source: new ol.source.OSM()            })          ],          view: new ol.View({            center: ol.proj.fromLonLat([3.8, 51.1]),            zoom: 10          })        });        var myView = map.getView();        var myStyle = new ol.style.Style({          stroke: new ol.style.Stroke({            color: 'blue',            width: 5          })        });        var myVectorSource = new ol.source.Vector();        var point1 = ol.proj.transform([3.8, 51.20], 'EPSG:4326', 'EPSG:3857');        var point2 = ol.proj.transform([4, 51], 'EPSG:4326', 'EPSG:3857');        var points = [point1, point2];        var myLine = new ol.geom.LineString(points);                var myproj = myView.getProjection();        var length = ol.sphere.getLength(myLine);                var segment = new ol.Feature({          geometry: myLine,          style: myStyle        });                myVectorSource.addFeature(segment);        // Create vector layer attached to the vector source.        var vectorLayer = new ol.layer.Vector({          source: myVectorSource,          style: myStyle        });                // Add the vector layer to the map.        map.addLayer(vectorLayer);        });  

I know I can convert the customer_sites json into Geojson using the below code:

geojsonObject = {      'type': 'FeatureCollection',      'crs': {          'type': 'name',          'properties': {              'name': 'EPSG:3857',          },      },      'features': [          {              'type': 'Feature',              'geometry': {                  'type': 'MultiLineString',                  'coordinates': customer_sites              },          }      ]  };  

And then I should be able to read the GeoJson and add it to the vector layer using the following:

var vectorLayer = new ol.layer.Vector({      source: new ol.source.Vector({          features: new ol.format.GeoJSON().readFeatures(geojsonObject)      }),  

But the the customer_sites does not work..

I think because the coordinates "[53.50119612705815, -1.1270833894501477], [53.34474, -3.01101]" are the wrong way around and they are not in a nested array? Althoguh i'm not 100% sure

Thanks!

Convert irregular array of arrays into an array

Posted: 09 May 2022 03:53 AM PDT

I have an array of values and an array of arrays of indices that looks like this (the real arrays are way bigger):

import numpy as np    A = np.array([np.array([0,1,2]),np.array([0,4]),np.array([1,3,5])])    B = np.array([5,10,3,7,8,4])    for a in A:        np.max(B[a])  

The endgame would be to remove the loop to save some computing time, but the main issue is that the irregularities in size in the A array keeps me from doing a simple C=B[A]. Is there a way out?

How to create a widget to work with the API?

Posted: 09 May 2022 03:55 AM PDT

I have the logic of working with the API in the same file with the body for the data it receives. How can I put the Future function, which takes the data into a separate file, correctly? My Future code:

//fetch data from API    Future<List<CurrencyModel>?> _fetchCurrency() async {      currencyList = [];      final response = await http.get(        Uri.parse(            'https:...'),      );      if (response.statusCode == 200) {        List<dynamic> values = [];        values = json.decode(response.body);        if (values.isNotEmpty) {          for (int i = 0; i < values.length; i++) {            if (values[i] != null) {              Map<String, dynamic> map = values[i];              currencyList.add(                CurrencyModel.fromJson(map),              );            }          }          setState(() {            currencyList;          });        }        return currencyList;      } else {        throw Exception('Failed to load currencies');      }    }

Unhandled Exception: FormatException: Unexpected end of input (at character 1) in flutter (in shared_preferences)

Posted: 09 May 2022 03:53 AM PDT

I'm making a task book, on a flutter, in this project I will use a lot of packages that I have not worked with before (this is not my first question on this project). My goal is to create tasks to add to the status (finished, not finished), and save them locally on the device. I wrote code (with some packages to help me figure it out) that does it all. But the problem arose when downloading questions from the local repository when starting the application. I have an error not to decode the data (in the repository I save a list of our tasks and status). Maybe someone faced such a problem I will be grateful for your help)

import 'dart:async';  import 'dart:convert';  import 'package:flutter/material.dart';  import 'package:shared_preferences/shared_preferences.dart';  import 'package:testjob/jsonTodo.dart';  void main() {    runApp(MaterialApp(      home: App(),    ));  }        class _strikeThrough extends StatelessWidget {    final String todoText;    final bool todoCheck;    _strikeThrough(this.todoText, this.todoCheck) : super();      Widget _widget() {      if (todoCheck) {        return Text(          todoText,          style: TextStyle(            fontSize: 22.0,          ),        );      } else {        return Text(          todoText,          style: TextStyle(fontSize: 22.0),        );      }    }      @override    Widget build(BuildContext context) {      return _widget();    }  }    class App extends StatefulWidget {    @override    AppState createState() {      return AppState();    }  }    final ValueNotifier<ThemeMode> _notifier = ValueNotifier(ThemeMode.light);    class AppState extends State<App> {          bool valText = true;    var IconsType = Icons.wb_sunny;      late Color ColorType = Colors.black;      var textController = TextEditingController();    var popUpTextController = TextEditingController();      List<TodoInfo> WidgetList = [];      @override    void dispose() {      textController.dispose();      popUpTextController.dispose();      super.dispose();    }      @override    void initState() {      getSP();      super.initState();    }      Future<void> addToSP(List<List<TodoInfo>> tList) async {      final prefs = await SharedPreferences.getInstance();      prefs.setString('todoLists', jsonEncode(tList));    }      void getSP() async {      final prefs = await SharedPreferences.getInstance();      final List<dynamic> jsonData =      jsonDecode(prefs.getString('todoLists') ?? '');      if (jsonData.isNotEmpty) {        for (var data in jsonData) {          final d = TodoInfo.fromJson(data);          WidgetList.add(d);        }        setState(() {});      }    }          @override    Widget build(BuildContext context) {      return ValueListenableBuilder<ThemeMode>(          valueListenable: _notifier,          builder: (_, mode, __) {            return MaterialApp(                theme: ThemeData.light(),                darkTheme: ThemeData.dark(),                themeMode: mode, // Decides which theme to show, light or dark.                home: Scaffold(                  appBar: AppBar(                    title: Text("Список задач"),                    actions: <Widget>[                      IconButton(                          icon: Icon(IconsType, color: ColorType),                          onPressed: () => {                            if (_notifier.value == ThemeMode.light)                              {                                _notifier.value = ThemeMode.dark,                                IconsType = Icons.dark_mode,                                ColorType = Colors.white,                              }                            else                              {                                _notifier.value = ThemeMode.light,                                IconsType = Icons.wb_sunny,                                ColorType = Colors.black,                              }                          })                    ],  //backgroundColor: Colors.orange[500],                    iconTheme: IconThemeData(color: Colors.white),                  ),                  body: Column(                    crossAxisAlignment: CrossAxisAlignment.center,                    children: <Widget>[                      Container(                        child: Row(                          mainAxisAlignment: MainAxisAlignment.center,                          children: <Widget>[                            const Text(                              "Tasks",                              style: TextStyle(                                fontSize: 70.0,                                fontWeight: FontWeight.bold,                                color: Colors.black,                              ),                            ),                            IconButton(                              color: Colors.black,                              iconSize: 70,                              constraints: const BoxConstraints(),                              padding: EdgeInsets.fromLTRB(30.0, 10.0, 30, 10.0),                              icon: const Icon(Icons.add_outlined),                              onPressed: () {                                if (textController.text                                    .replaceAll(" ", "")                                    .isNotEmpty) {                                  WidgetList.insert(0,  TodoInfo(todoText:textController.text.replaceAll(" ", ""), todoCheck: false ));                                  addToSP;                                  setState(() {                                    valText = true;                                    textController.clear();                                  });                                } else {                                  setState(() {                                    valText = false;                                  });                                }                              },                            )                          ],                        ),                      ),                      Container(                        width: MediaQuery.of(context).size.height * 0.45,                        child: TextField(                          style: TextStyle(                            fontSize: 22.0,  //color: Theme.of(context).accentColor,                          ),                          controller: textController,                          cursorWidth: 5.0,                          autocorrect: true,                          autofocus: true,  //onSubmitted: ,                        ),                      ),                      Align(                          child: (valText == false)                              ? Align(                              child: Text(("Задача пустая"),                                  style: TextStyle(                                      fontSize: 25.0, color: Colors.red)),                              alignment: Alignment.center)                              : Align(                              child: Text(                                (""),                              ),                              alignment: Alignment.center)),                      Expanded(                        child: ReorderableListView(                          children: <Widget>[                            for (final widget in WidgetList)                              GestureDetector(                                key: Key(widget.todoText),                                child: Dismissible(                                  key: Key(widget.todoText),                                  child: CheckboxListTile(                                    controlAffinity:                                    ListTileControlAffinity.leading,  //key: ValueKey("Checkboxtile $widget"),                                    value: widget.todoCheck,                                    title: _strikeThrough(                                        widget.todoText, widget.todoCheck),                                    onChanged: (checkValue) {  //_strikethrough toggle                                      setState(() {                                        if (!checkValue!) {                                          widget.todoCheck = false;                                        } else {                                          widget.todoCheck = true;                                        }                                      });                                    },                                  ),                                  background: Container(                                    child: Icon(Icons.delete),                                    alignment: Alignment.centerRight,                                    color: Colors.redAccent,                                  ),                                  direction: DismissDirection.endToStart,                                  movementDuration:                                  const Duration(milliseconds: 200),                                  onDismissed: (dismissDirection) {  //Delete Todo                                    WidgetList.remove(widget);                                  },                                ),                              )                          ],                          onReorder: (oldIndex, newIndex) {                            setState(() {                              if (newIndex > oldIndex) {                                newIndex -= 1;                              }                              var replaceWiget = WidgetList.removeAt(oldIndex);                              WidgetList.insert(newIndex, replaceWiget);                            });                          },                        ),                      )                    ],                  ),                ));          });    }  }    class TodoInfo {    String todoText;    bool todoCheck;      TodoInfo({      required this.todoText,      required this.todoCheck,    });      factory TodoInfo.fromJson(Map<String, dynamic> json) {      return TodoInfo(todoText: json["todoText"], todoCheck: json["todoCheck"]);    }      factory TodoInfo.fromMap(Map<String, dynamic> map) =>        TodoInfo(          todoText: map["todoText"] ?? '',          todoCheck: map["todoCheck"] ?? '',        );      Map<String, dynamic> toJson() {      return {"todoText": todoText, "todoCheck": todoCheck};    }      @override    String toString() => '{todoText: $todoText, todoCheck: $todoCheck}';  }  

My erorr

E/flutter (30831): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: FormatException: Unexpected end of input (at character 1)  E/flutter (30831):   E/flutter (30831): ^  E/flutter (30831):   E/flutter (30831): #0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1404:5)  E/flutter (30831): #1      _ChunkedJsonParser.close (dart:convert-patch/convert_patch.dart:522:7)  E/flutter (30831): #2      _parseJson (dart:convert-patch/convert_patch.dart:41:10)  E/flutter (30831): #3      JsonDecoder.convert (dart:convert/json.dart:506:36)  E/flutter (30831): #4      JsonCodec.decode (dart:convert/json.dart:157:41)  E/flutter (30831): #5      jsonDecode (dart:convert/json.dart:96:10)  E/flutter (30831): #6      AppState.getSP (package:testjob/main.dart:85:5)  E/flutter (30831): <asynchronous suspension>  E/flutter (30831):   

Pass json data to JavaScript without creating new object

Posted: 09 May 2022 03:53 AM PDT

I am querying json data from database then performing some filtering and further procedures. After that I want to display that data on map, so I am passing it through JSInterop to JavaScript. Everything seems to be working except that on each method execution I am getting new map on my webpage. So after executing method 4 times, I am having 4 maps on web page.

Please comment, if additional code is necessary...

Index.razor:

<div>    <select id="layer-select" style="visibility:hidden;">      <option value="osm" selected>Open Street Map</option>    </select>      <div class="card-body p-0">      <div id="map"></div>      <div id="popup" class="ol-popup">        <a href="#" id="popup-closer" class="ol-popup-closer"></a>        <div id="popup-content"></div>      </div>    </div>  </div>  

Index.razor.cs:

[Inject] IJSRuntime JSRuntime { get; set; }  ...    private async Task UpdateData()  {    this.SelectedDate = this.SelectedDate.Value.AddDays(1);      this.FilteredDataRecords = this.DataRecords     .Where(w => w.TimeNow.Date == SelectedDate.Value.Date && (w.Latitude != 0 || w.Longitude != 0))     .OrderBy(o => o.TimeNow)     .ToList();      string jsonData = JsonSerializer.Serialize(this.FilteredDataRecords);      await JSRuntime.InvokeAsync<object>("olMap.showMap", jsonData);  }  

map.js:

window.olMap = {    showMap: function (jsonData) {        var HereLayers = [        {          base: 'base',          type: 'maptile',          scheme: 'osm',        },      ];        ...        var vectorLayer = new ol.layer.Vector({       source: loadMarineData(JSON.parse(jsonData)), //JSON.parse(jsonData)        visible: true,        style: new ol.style.Style({          stroke: new ol.style.Stroke({ color: '#d12710', width: 4 })        })      });        var map = new ol.Map({        overlays: [overlay],        target: 'map',        layers: layers,        view: new ol.View({          center: ol.proj.fromLonLat([25.2849, 60.0917]),          zoom: 8        })      });        map.addLayer(vectorLayer);      map.addLayer(nauticLayer);       ....        var select = document.getElementById('layer-select');        function onChange() {        var scheme = select.value;        for (var i = 0, ii = layers.length; i < ii; ++i) {          layers[i].setVisible(HereLayers[i].scheme === scheme);        }      }        select.addEventListener('change', onChange);        onChange();    }  };  

Geolocation get country name

Posted: 09 May 2022 03:53 AM PDT

I was wondering if there is a simple way to retrive the country name of the given city.

Meaning that I will provide the city name and it will give me back the country.

For now the only thing I can think of is reversegeo, but it only gives me the short for the country and I need the full name.

def reverseGeocode(coordinates):      result = rg.search(coordinates,mode=1)      print(result)        cord= (36.8968908,30.7133233)  reverseGeocode(cord)  

Results:

[{'lat': '36.90812', 'lon': '30.69556', 'name': 'Antalya', 'admin1': 'Antalya', 'admin2': '', 'cc': 'TR'}]  

Is there anyway to do it? or maybe to get the full name somehow?

Is it possible to check if some type doesn't exist in a parameter pack

Posted: 09 May 2022 03:55 AM PDT

I'm working on a C++14 project and I just wrote a function with parameter pack.

template <typename... Args>  void func(Args&&... args) {      ...  }  

The args should contain only int or std::string, it can't be any other types.

Is there any way to do the check at compile time? Maybe something as below?

template <typename... Args, std::enable_if_t<???* = nullptr>  void func(Args&&... args) {      ...  }  

How to use the Ternary operator for the (if else-if) statement or use two or more conditions in Solidity?

Posted: 09 May 2022 03:53 AM PDT

I want to do using Ternary Operator in the same condition

function fun(uint _value) public pure returns(string memory)     {         string memory _return;         if(_value > 100){             _return = "Greater than 100";         }else if(_value < 100){             _return = "Lower than 100";         }else{             _return = "Equal to 100";         }           return _return;     }  

Improve performance of SQL query

Posted: 09 May 2022 03:54 AM PDT

I have a slow performing query which I am at a loss on how I could make more efficient. SQL isn't my speciality, but currently this query is taking about 3 seconds on average to run. I've run an execution plan on it in SMMS, and it recommended an index which I created. 3 seconds isn't awful currently, however I only have my own test data in (about 9,000 transactions, 22,000 transfers...). When I have a lot more people using this this will grow massively, and I don't want the execution time for this query to balloon substantially...

The intention of the query, is to return any transfers (and some information on their related transaction), which are of either type 0 or 1, which do not have a price stored for them in token prices (a price stored for anything within 3 hours would be a match, outside of 3 hours isn't a match - its 3 hours either side), where the number of attempts stored in the TokenPriceAttempts table is either 0, or <5 AND most recent is at least a week ago. tl;dr: return transfers, type 0 or 1, which don't have a price yet, and haven't had a recent (within the last week) attempt stored, or have no recent attempts, and have fewer than 5 total attempts.

Here is my query:

    SELECT          [t1].[Id],          [t1].[TransactionId],          [t1].[From],          [t1].[To],          [t1].[Value],          [t1].[Type],          [t1].[ContractAddress],          [t1].[TokenId],          [t2].[Hash],          [t2].[Timestamp]      FROM          -- Now, this pre-query is left-joined to token price attempts          -- so ALL Transfers of type < 2 are considered          (              SELECT                  [t1].[Id],                  coalesce( COUNT([tpa].[Created]), 0 ) [Attempts],                  MAX([tpa].[Created]) [MaxCreated]              FROM                  [dbo].[Transfers] [t1]                  LEFT JOIN [dbo].[TokenPriceAttempts] [tpa]                      ON [t1].[Id] = [tpa].[TransferId]              WHERE                  [t1].[Type] < 2              GROUP BY                  [t1].[Id]          ) [PQ]      -- Now, we can just directly join to transfers for the rest      JOIN [dbo].[Transfers] [t1]          ON [PQ].[Id] = [t1].[Id]          -- and the rest from the WITH CTE construct      LEFT JOIN [dbo].[Transactions] [t2]          ON [t1].[TransactionId] = [t2].[Id]      LEFT JOIN [dbo].[TokenPrices] [tp]          ON [t1].[ContractAddress] = [tp].[ContractAddress]              AND [tp].[Timestamp] >= DATEADD(HOUR, - 3, [t2].[Timestamp])              AND [tp].[Timestamp] <= DATEADD(HOUR, 3, [t2].[Timestamp])      WHERE          ABS( DATEDIFF( SECOND, [tp].[Timestamp], [t2].[Timestamp] )) IS NULL          AND          (              [PQ].[Attempts] = 0              OR              (                  [PQ].[Attempts] < 5                  AND DATEDIFF(DAY, [PQ].[MaxCreated], CURRENT_TIMESTAMP ) >= 7              )          )  

And my execution plan (Not sure the best way to post this?): EDIT 1: There is a paste of the execution plan XML at the bottom. enter image description here

Finally, each of the referenced tables...

dbo.Transfers

CREATE TABLE [dbo].[Transfers]  (      [Id] INT NOT NULL PRIMARY KEY IDENTITY,      [TransactionId] INT NOT NULL,      [From] NVARCHAR(42) NOT NULL,      [To] NVARCHAR(42) NOT NULL,      [Value] NVARCHAR(256) NOT NULL,      [ValueDecimals] INT NOT NULL,      [Type] TINYINT NOT NULL,      [ContractAddress] NVARCHAR(42) NOT NULL,      [TokenId] NVARCHAR(256) NULL,       CONSTRAINT [FK_Transfers_Transactions] FOREIGN KEY ([TransactionId]) REFERENCES [Transactions]([Id])  )    GO    CREATE INDEX [IX_Transfers_Type] ON [dbo].[Transfers] ([Type])  

dbo.TokenPriceAttempts

CREATE TABLE [dbo].[TokenPriceAttempts]  (      [Id] INT NOT NULL PRIMARY KEY IDENTITY,      [TransferId] INT NOT NULL,      [Created] DATETIME2 NOT NULL DEFAULT CURRENT_TIMESTAMP,       CONSTRAINT [FK_TokenPriceAttempts_Transfers] FOREIGN KEY ([TransferId]) REFERENCES [Transfers]([Id])  )  

dbo.Transactions

CREATE TABLE [dbo].[Transactions]  (      [Id] INT NOT NULL PRIMARY KEY IDENTITY,      [Hash] NVARCHAR(66) NOT NULL,      [BlockNumber] INT NOT NULL,      [Timestamp] DATETIME2 NOT NULL,      [From] NVARCHAR(42) NOT NULL,      [To] NVARCHAR(42) NULL,      [GasPaid] NVARCHAR(256) NOT NULL,       CONSTRAINT [AK_Transactions_Hash] UNIQUE ([Hash])  )    GO    CREATE INDEX [IX_Transactions_BlockNumber] ON [dbo].[Transactions] ([BlockNumber])  

dbo.TokenPrices

CREATE TABLE [dbo].[TokenPrices]  (      [Id] INT NOT NULL PRIMARY KEY IDENTITY,      [ContractAddress] NVARCHAR(42) NOT NULL,      [Timestamp] DATETIME2 NOT NULL,      [PriceEth] DECIMAL(38,18) NOT NULL,      [PriceUsd] DECIMAL(38,18) NOT NULL,      [PriceGbp] DECIMAL(38,18) NOT NULL,      [PriceEur] DECIMAL(38,18) NOT NULL,      [PriceCad] DECIMAL(38,18) NOT NULL,      [PriceAud] DECIMAL(38,18) NOT NULL,      [PriceJpy] DECIMAL(38,18) NOT NULL,      [PriceNzd] DECIMAL(38,18) NOT NULL,      [PriceSgd] DECIMAL(38,18) NOT NULL,      [PriceNok] DECIMAL(38,18) NOT NULL,      [PriceSek] DECIMAL(38,18) NOT NULL,      [PriceZar] DECIMAL(38,18) NOT NULL,      [Created] DATETIME2 NOT NULL DEFAULT CURRENT_TIMESTAMP  )    --CA - CAD - Canada  --US - USD - United States  --AU - AUD - Australia  --JP - JPY - Japan  --NZ - NZD - New Zealand  --SG - SGD - Singapore  --AT - EUR - Austria  --BE - EUR - Belgium  --DE - EUR - Germany  --FI - EUR - Finland  --FR - EUR - France  --GR - EUR - Greece  --IT - EUR - Italy  --NL - EUR - Netherlands  --NO - NOK - Norway  --PT - EUR - Portugal  --ES - EUR - Spain  --CH - SEK - Switzerland  --GB - GBP - United Kingdom  --ZA - ZAR - South Africa  

EDIT 1:

Here is the plan XML: https://pastebin.pl/view/d82f6aef

PasteThePlan here

How to different calculation on different granularity?

Posted: 09 May 2022 03:54 AM PDT

I want to achieve the following:

example

The idea is to calculate the sum product in the following scenario:

  • When calculating the subtotal (that is on the Level1 granularity) the formula is: the sum of Wieght2 * Amount.
  • When calculating the grand total, the formula is: the sum of Wieght1 * subtotal.

How can I achieve that in DAX?!

How to invert a bit of a packed array

Posted: 09 May 2022 03:53 AM PDT

logic [4:0] count_zeros;  logic [2:0] id;  integer i;  logic [7:0] [15:0] vld;    always@*   begin    count_zeros = 5'b0;    for (i=0; i<2; i=i+1)   count_zeros = count_zeros + ~vld[id][i];  end  

For an input as d8, I get count_zeros as 1e. My expected output is 2. What is wrong in the above snippet?

~ is a bitwise negation and ! is logical negation. Where am I going wrong?

Why isn't an IEC 60559 conformant implementation required to define __STDC_IEC_559__ (to 1)?

Posted: 09 May 2022 03:53 AM PDT

The C (C99+) standard requires (though implicitly) a conforming implementation to define __STDC__ to 1.

However, the C standard does not require an IEC 60559 conformant implementation to define __STDC_IEC_559__ (to 1).

Consequences:

#if __STDC__ != 1  /* non-conforming implementation */  

No comments:

Post a Comment