Tuesday, March 1, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Permutation funtion print array but the array that returns is empty

Posted: 01 Mar 2022 12:46 AM PST

I need some heplp with this function that make permutations from an array pointer in input. Here is the code.

int* permute(int *new_arr,int st,int ls)      {          int i=0;          if(st==ls)          {  //If I print here the array it works  //         int k;  //            for(k=0;k<ls;k++)  //            {  //                printf("%d ",new_arr[k]);  //            }  //        printf("\n");         return new_arr;// if I return here the array is empty      }          else          {              for(i=st;i<ls;i++)              {                  swap(new_arr+st,new_arr+i);                  permute(new_arr,st+1,ls);                  swap(new_arr+st,new_arr+i);              }          }  }  int main()  {      int m, n, * arr, ** mat;      int size, i;   printf("Enter the number of columns(n):");      if ((scanf("%d",&n) != 1) || (n < 1)) {        puts("invalid value for columns");        return -1;      }      m = n;      //m=numero di righe n=numero di colonne            size = m*n;      if (((arr = malloc(size * sizeof(int))) == NULL) ||          ((mat = malloc(m * sizeof(int))) == NULL)) {        puts("not enouh memory");        exit(-1);      }            for (i = 0; i < m; ++i) {        if ((mat[i] = malloc(n * sizeof(int))) == NULL) {          puts("not enouh memory");          exit(-1);        }      }      input_array (arr,size);      print_array (arr,size);      array_to_matrix(mat, arr, m, n);      print_matrix(mat, m, n);                      for (i = 0; i < m; ++i)        free(mat[i]);      free(mat);        int nrighe = factorial(n);      int *new_array;      int st=0,k=0,j;      if (((new_array = malloc((n*nrighe) * sizeof(int))) == NULL) ||          ((mat = malloc((n*nrighe) * sizeof(int))) == NULL)) {        puts("not enouh memory");        exit(-1);      }       for (i = 0; i < m; ++i) {        if ((mat[i] = malloc((n*nrighe) * sizeof(int))) == NULL) {          puts("not enouh memory");          exit(-1);        }      }      for(j=1; j<n+1;j++)      {          new_array[k] = j;          printf("newarray[%d",k);          printf("]= %d",j);          k++;      }      free(arr);            if ((arr = malloc((n*nrighe) * sizeof(int))) == NULL) {        puts("not enouh memory");        exit(-1);      }            printf("\nPermutations of dimension: %d\n", n);      arr = permute(new_array,st,n);        k=0;      for(k=0;k<n;k++)      {          printf("%d ",arr[k]);      }      printf("\n");            free(arr);      free(new_array);      return 0;  }  

When I print the array like the section in the comments it works.It prints all the permutation that it has found. The problem is when I try to print it from the return function, in the main() function, i take the array returned from the permute() function and after with a for loop I try to print it, but it that says it's empty; the loop doesn't print the corrects values. I can't understand why. Can someone help me please?

How to switch a button click event sender from code behind to MVVM?

Posted: 01 Mar 2022 12:46 AM PST

I have a button with its Click event on the code-behind, something like this: private void ButtonManager_OnClick(object sender, RoutedEventArgs e) { var addButton = sender as FrameworkElement; } In case I move to MVVM and no code-behind, I use a Command class with Execute, something like this: public override void Execute(object? parameter) { // sender? } How should I manage the "sender as.." that was used in code-behind?

ReferenceError : UAParser is not defined

Posted: 01 Mar 2022 12:46 AM PST

The below code throws the error :

var parser = new UAParser();  

enter image description here

Even though in the console it is working fine and I can able to see the results.

enter image description here

Just curious why the error occurs and How to remove the error from console since it is working fine.

Parse linux disk usage using regex

Posted: 01 Mar 2022 12:46 AM PST

So I want to determine my ubuntu disk usage After run the command df -h this is my output:

final static String diskSpace =          "Filesystem      Size  Used Avail Use% Mounted on\n" +                  "udev            2.0G     0  2.0G   0% /dev\n" +                  "tmpfs           396M  5.6M  390M   2% /run\n" +                  "/dev/vda1        49G   45G  4.0G  92% /\n" +                  "tmpfs           2.0G   84K  2.0G   1% /dev/shm\n" +                  "tmpfs           5.0M     0  5.0M   0% /run/lock\n" +                  "tmpfs           2.0G     0  2.0G   0% /sys/fs/cgroup\n";  

So this is my function that get the output, find the relevant line (starts with /dev/vda1) and try to parse the value 92% (in my example):

void getDiskUsage() {      String pattern = "\\b(?<!\\.)(?!0+(?:\\.0+)?%)(?:\\d|[1-9]\\d|100)(?:(?<!100)\\.\\d+)?%";        String[] arr = diskSpace.split("\n");      for (String line : arr) {          if (line.startsWith(fileSystemName)) {              System.out.println(line);              boolean matcher = Pattern.matches(pattern, line);              break;          }      }  }  

My only problem is that my pattern that checked with https://regex101.com/ and find the value 92% failed to find it here and my var matcher is false

Configure IP on Local Computer (JAVA)

Posted: 01 Mar 2022 12:46 AM PST

function not running when called code mostly copyed from video

Posted: 01 Mar 2022 12:46 AM PST

I'm trying to request Bluetooth permissions, however it is skipping the function that asks for the permission, and just shows the text saying Bluetooth Permission Denied. the code:

class MainActivity : AppCompatActivity() {      lateinit var perms_button: Button      private val BLUETOOTH_PERM_CODE = 123      override fun onCreate(savedInstanceState: Bundle?) {          super.onCreate(savedInstanceState)          setContentView(R.layout.activity_main)          perms_button = findViewById(R.id.perms_button)            perms_button.setOnClickListener {              checkPermission(Manifest.permission.BLUETOOTH, BLUETOOTH_PERM_CODE)//this is supposed to run the function that requests permissions          }      }            private fun checkPermission(permission: String, requestCode: Int) {// this is the function that doesn't run               if (ContextCompat.checkSelfPermission(this@MainActivity, permission) == PackageManager.PERMISSION_DENIED) {                  ActivityCompat.requestPermissions(this@MainActivity, arrayOf(permission), requestCode)              } else {                  Toast.makeText(this@MainActivity, "Permission Granted already", Toast.LENGTH_LONG).show()              }          }            override fun onRequestPermissionsResult(              requestCode: Int,              permissions: Array<out String>,              grantResults: IntArray          ) {              super.onRequestPermissionsResult(requestCode, permissions, grantResults)                if (requestCode == BLUETOOTH_PERM_CODE) {                  if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {                      perms_button.setText("Permission Granted")                      Toast.makeText(this@MainActivity, "Bluetooth Permission Granted", Toast.LENGTH_SHORT).show()                  }else {                      Toast.makeText(this@MainActivity, "Bluetooth Permission Denied", Toast.LENGTH_SHORT).show()                  }              }           }      }  

link to the video I got the code from: https://youtu.be/_2fo2Z6O5D4 I'm unsure if the problem has to do with the changes I had to make for my app(It always the changes you made)

thanks in advance for any help.

how to remove untranslatable characters from a string in teradata

Posted: 01 Mar 2022 12:46 AM PST

I am new to Teradata and I was querying to one table, but I am getting result as SELECT Failed 6706 The string contains an untranslatable character.

I don't know which column is having untranslatable character.

Can anyone help me how to find the untranslatable character and remove that.

eg:- string:- 'boys sizes S-3XL, 28-36. girlss sizes S-3X. Kids NB-5T,Sleeperwear XS-XL. Mens wear The Find, slippers.'

output should be:- boyss sizes S-3XL, 28-36. girlss sizes S-3X. Kids NB-5T,Sleeperwear XS-XL. Mens wear The Find, slippers.

to display cols in vutify at the same line and aligned col with nex row

Posted: 01 Mar 2022 12:46 AM PST

I am working on project with vutify I have created a layout. I want cols to display side by side as the figma at the same line. Here is my result until now. enter image description here

I am sharing my code I want that col-2 doesn't go out, but to aligned at the same line with next row.

.box-contact {      background: url("./../assets/img/homepage-image/background.png");      width: 692%;      height: 105px;    }
<template>      <v-container grid-list-lg class="prodotti-cataloghi">         <v-row>              <v-col cols="12" md="5" lg="6" class="ma-0 pa-0">                  <h5>Prodotti </h5>              </v-col>                            <!--<v-divider vertical class="vertical  hidden-sm-and-down ">  </v-divider>          -->                 <v-col cols="12" md="6" lg="6"  class="ma-0 pa-0">                                   <div class="box-contact text-center hidden-sm-and-down  d-flex flex-wrap">                           <p class="white--text">Lorem ipsum? Contattaci. +xx xxx xxxxx </p>                            <a class="phone-contact">                          <img src="./../assets/img/homepage-image/Phone.png">                          </a>                                    </div>               </v-col>         </v-row>         </v-container>         </template>

Next in the secondly col I have made css to add background image in class .box-contact but you can add what you want. but secondly shouldn't to go out it should aligned with next row I don't know if it is problem with width of image or problem with cod. Any idea?

Uncaught TypeError: Return value of Illuminate\Container\Container::offsetGet()

Posted: 01 Mar 2022 12:46 AM PST

Hello I have problems with this error function Container::offsetGet() from vendor/laravel/framework/src/Illuminate/Container/Container.php:1417. Btw I'm using laravel 9 with php 8. Can you help me find the solution. Thankyou

Is it undefined behavior to compare a character array char u[10] with a string literal "abc"

Posted: 01 Mar 2022 12:46 AM PST

I came across this question on SO, and this answer to the question. The code is as follows:

int main()  {        char u[10];      cout<<"Enter shape name ";      cin>>u;      if(u=="tri") //IS THIS UNDEFINED BEHAVIOR because the two decayed pointers both point to unrelated objects?      {          cout<<"everything is fine";      }      else      {          cout<<"Not fine";      }      return 0;  }  

I have read in the mentioned answer that, both u and "tri" decay to pointers to their first element. My question is that, now is comparing these two decayed pointers undefined behavior because these pointers point to unrelated objects? Or the program is fine/valid(no UB) and because the pointers have different values, the else branch will be executed?

Http get request from local file

Posted: 01 Mar 2022 12:45 AM PST

So I've made a simple .html file and a simple .js script. It's very simple, just a button that should make an http.get request once pressed. The get request does get created once I press the button, I also get a response from the request (code 200, can see the data in debugger) but I also get a 304-blocked code(blocked by CORS). I'm using jquery ajax to create the request.

My question is - I can create get requests from local file, but I can not use the data I get back... Why is that and how do I fix it?

Optimising model.parameters and custom learnable parameter together using torch.optim gives non-leaf tensor error

Posted: 01 Mar 2022 12:45 AM PST

Framework: PyTorch

I am trying to optimise a custom nn.parameter(Temperature) used in softmax calculation along with the model parameters using a single Adam optimiser while model training. But doing so gives the following error:

ValueError: can't optimize a non-leaf Tensor

Here is my custom loss function:

class CrossEntropyLoss2d(torch.nn.Module):      def __init__(self, weight=None):          super().__init__()          self.temperature = torch.nn.Parameter(torch.ones(1, requires_grad=True, device=device))          self.loss = torch.nn.NLLLoss(weight)          self.loss.to(device)            def forward(self, outputs, targets):          T_logits = self.temp_scale(outputs)          return self.loss(torch.nn.functional.log_softmax(T_logits, dim=1), targets)        def temp_scale(self, logits):          temp = self.temperature.unsqueeze(1).expand(logits.size(1), logits.size(2), logits.size(3))          return logits/temp   

. . . . . . Here is the part of training code:

criterion = CrossEntropyLoss2d(weight)  params = list(model.parameters()) +list(criterion.temperature)  optimizer = Adam(params, 5e-4, (0.9, 0.999),  eps=1e-08, weight_decay=1e-4)  

Error:

File "train_my_net_city.py", line 270, in train  optimizer = Adam(params, 5e-4, (0.9, 0.999),  eps=1e-08, weight_decay=1e-4)  File "/home/saquib/anaconda3/lib/python3.8/site-packages/torch/optim/adam.py", line 48, in __init__  super(Adam, self).__init__(params, defaults)  File "/home/saquib/anaconda3/lib/python3.8/site-packages/torch/optim/optimizer.py", line 54, in __init__  self.add_param_group(param_group)  File "/home/saquib/anaconda3/lib/python3.8/site-packages/torch/optim/optimizer.py", line 257, in add_param_group  raise ValueError("can't optimize a non-leaf Tensor")  ValueError: can't optimize a non-leaf Tensor  

Checking the variable for leaf gives true:

print(criterion.temperature.is_leaf)  True  

The error arises due to the criterion.temperature parameter and not due to model.parameters. Kindly help!

Upgrading timescaledb from 2.3.0 to 2.6.0

Posted: 01 Mar 2022 12:45 AM PST

I have timescaledb 2.3.0 and PostgreSQL 13.5 installed in my Linux Ubuntu 18.04 and I would like to upgrade to timescale 2.6.0.

When giving the following command in postgreSQL:

ALTER EXTENSION timescaledb UPDATE;  

I get the following message:

extension "timescaledb" has no update path from version "2.3.0" to version "2.4.0"  

Any hint how I should proceed?

Thanks,

Bernardo

Is there a way to load sheets with a specific regex with pandas.read_excel()

Posted: 01 Mar 2022 12:45 AM PST

Is there a way to load sheets with a specific regex with pandas.read_excel() ?

Maybe with the parameter sheet_name But can't figure how...

Example of regex :

regex_sheet = "\s*[d^D][A^a][y^Y]\D*\s*[1-9]\s*"  

Does sb have an idea ?

How to set PYTHONPATH for all tools in Vscode (on Windows)?

Posted: 01 Mar 2022 12:45 AM PST

I have a folder abc in my project root and I'd like to make all tools on VScode work with import abc. The only way I found to make it work is to put the full absolute path PYTHONPATH=<fullpath_to_workfolder> in the .env file. But ideally I'd like to use relative paths to the workfolder.

How can I do that?

All suggestions I found (also here) somehow do not work. ${workspaceFolder} is empty. PYTHONPATH=. does not work. Ideally I'd configure a single PYTHONPATH and not for every tool (terminal, notebooks, mypy, ...). And even my solution for whatever reason duplicates PYTHONPATH=<fullpath_to_workfolder>;<fullpath_to_workfolder> on Windows when I inspect this variable in my code. I believe on Linux I did not have issues.

Jquery Datepicker beforeShowDay not displaying tooltip and not assigning class in return

Posted: 01 Mar 2022 12:44 AM PST

I'm trying to color the background of certain days in an embedded datepicker (not in an input field) and fire a tooltip on hover on those same colored days but is not doing anything. I checked in the console and the tooltips messages are there but not in the calendar, and also the background color is not been applied. I tried just applying a background color without the tooltip using only 'return {Classes: "activeClass"}' and it works but is not what I need. Any help is very much appreciated.

The date arrays and text for the tooltips are been generating with PHP.

Here is my code:

    <style>          .activeClass{              color: #fff;              background-color: #339966;           }              </style>        <script>          var active_dates = ["4/10/2022", "5/1/2022", "5/29/2022", "6/26/2022", "7/10/2022", "7/24/2022", "8/7/2022", "8/21/2022", "9/11/2022", "9/25/2022", "10/9/2022", "10/16/2022", "11/6/2022", "12/25/2022", ];           var tooltips = [];          tooltips[new Date('4/10/2022')] = 'DBL: 1689.00/ TWN: 1689.00'; tooltips[new Date('5/1/2022')] = 'DBL: 1729.00/ TWN: 1729.00'; tooltips[new Date('5/29/2022')] = 'DBL: 1799.00/ TWN: 1799.00'; tooltips[new Date('6/26/2022')] = 'DBL: 1799.00/ TWN: 1799.00'; tooltips[new Date('7/10/2022')] = 'DBL: 1799.00/ TWN: 1799.00'; tooltips[new Date('7/24/2022')] = 'DBL: 1799.00/ TWN: 1799.00'; tooltips[new Date('8/7/2022')] = 'DBL: 1799.00/ TWN: 1799.00'; tooltips[new Date('8/21/2022')] = 'DBL: 1799.00/ TWN: 1799.00'; tooltips[new Date('9/11/2022')] = 'DBL: 1729.00/ TWN: 1729.00'; tooltips[new Date('9/25/2022')] = 'DBL: 1729.00/ TWN: 1729.00'; tooltips[new Date('10/9/2022')] = 'DBL: 1689.00/ TWN: 1689.00'; tooltips[new Date('10/16/2022')] = 'DBL: 1689.00/ TWN: 1689.00'; tooltips[new Date('11/6/2022')] = 'DBL: 1689.00/ TWN: 1689.00'; tooltips[new Date('12/25/2022')] = 'DBL: 1689.00/ TWN: 1689.00';            var date = new Date();          date.setDate(date.getDate()+1);          $('#date_pick').datepicker({                   showOtherMonths: true,              selectOtherMonths: true,              startDate: date,              format: 'mm/dd/yyyy',              todayHighlight: false,              beforeShowDay: function(date){                  var d = date;                  var curr_date = d.getDate();                  var curr_month = d.getMonth() + 1; //Months are zero based                  var curr_year = d.getFullYear();                  var formattedDate = curr_month + "/" + curr_date + "/" + curr_year                  if ($.inArray(formattedDate, active_dates) != -1){                        var tooltip = tooltips[date];                       return [true, "activeClass",tooltip],                      console.log(tooltip);                    }                  return;              }          });      </script>  

Any one know about this why Sometime dispatchEvent is working or sometime not? [closed]

Posted: 01 Mar 2022 12:45 AM PST

My issue is a sometimes dispatchEvent is working sometimes not anyone knows about this?

Here is my JavaScript code :

a.dispatchEvent('try');

Java arraylist find missing fields using streams

Posted: 01 Mar 2022 12:45 AM PST

I have this below code. Two sets of arraylist. How do I use streams to iterate and compare itemlist_a and itemlist_b to detect that c and d is missing in itemlist_b? Of course I can use the traditional for loop, but is there a different way to achieve using streams or something else?

import java.util.ArrayList;  import java.util.List;        class item {          String name;        public item(String name) {          this.name = name;      }  }    public class Test {      public static void main(String[] args) {          List<item> itemlist_a = new ArrayList<item>();          itemlist_a.add(new item("a"));          itemlist_a.add(new item("b"));            List<item> itemlist_b = new ArrayList<item>();          itemlist_b.add(new item("a"));          itemlist_b.add(new item("b"));          itemlist_b.add(new item("c"));          itemlist_b.add(new item("d"));      }  }  

JSON HttpWebRequest always returns 400

Posted: 01 Mar 2022 12:45 AM PST

I tried to make a request to test if people should be able to pay on invoice.

I've never made an API call with JSON data before so i read through some documentations and stack overflow questions and found this thread right here, which was pretty promissing: How to post JSON to a server using C#?

The code where i attempt to do this is the one posted below:

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://service-zs.riskcube.ch/api/v1/RiskCube/claim");          request.ContentType = "application/json";          request.Method = "POST";          request.Headers.Add("X-API-KEY", "123"); //Replace with the API KEY given from CreditForm          if (creditReformModel != null)          {              string postData = JsonConvert.SerializeObject(creditReformModel);              using (var streamWriter = new StreamWriter(request.GetRequestStream()))              {                  streamWriter.Write(postData);              }          }            HttpWebResponse response = (HttpWebResponse)request.GetResponse();  

I tried to implement the answer to the question but sadly i always get a 400 bad request error when i try to send the httpRequest.

enter image description here

The error message says: System.Net.WebException: "The remoteserver responded with an error: (400) bad request"

Those are the details to the exception:

System.Net.WebException    HResult=0x80131509    Message = The remote server returned an error: (400) Invalid request.    Source = <The exception source cannot be evaluated.>.    Stack monitoring:  <The exception stack monitor cannot be evaluated.>.  

That's the model i'm trying to serialize and add to the httpWebRequest:

    internal class CreditReformModel      {          public string ShopId { get; set; }          public string OrderProcessId { get; set; }          public string IpAddress { get; set; }          public string MacAddress { get; set; }          public string CustomerId { get; set; }          public CreditReformAddressModel ShippingAddress { get; set; }          public CreditReformAddressModel BillingAddress { get; set; }      }        internal class CreditReformAddressModel      {          public string Type { get; set; }          public string BusinessName { get; set; }          public string FirstName { get; set; }          public string LastName { get; set; }          public string Co { get; set; }          public string Street { get; set; }          public string HouseNumber { get; set; }          public string PostCode { get; set; }          public string LocationName { get; set; }          public string Country { get; set; }          public string Email { get; set; }          public string Phone { get; set; }          public string DateOfBirth { get; set; }      }  

That's the requested data in the API documentation:

{    "shopId": "20071992",    "orderProcessId": "ref001",    "ipAddress": null,    "macAddress": null,    "customerId": "cus001",    "billingAddress": {      "type": "Consumer",      "businessName": null,      "firstName": "Martin",      "lastName": "Früh",      "co": null,      "street": "Funkenbüelstrasse",      "houseNumber": "1",      "postCode": "9243",      "locationName": "Jonschwil",      "country": "CH",      "email": null,      "phone": null,      "dateOfBirth": null    },    "shippingAddress": null,    "orderAmount": 1200  }  

Does someone know why this happens?

If you need more code or information just say it and i edit the question.

Concatenate elements of an array Javascript

Posted: 01 Mar 2022 12:45 AM PST

I have a list of hrefs with product data:name and it's id. First of all i removed prod Id that i'll use as separate variable. After this, the remained part of href should be used to get the product name.

var prodHref = document.querySelectorAll('.widget-products-list-item-label');    var allHref = [];     for(var i=0;i<prodHref.length;i++){    allHref.push(prodHref[i].href.split('/')[5])    }    var prodName = [];     for(var i=0;i<allHref .length;i++){    prodName.push(allHref [i].slice(0, -1))    }        var prodNameNew=[];    for(var i=0;i<prodName .length;i++){    prodNameNew.push(prodName[i].slice(0, -1))    }  

So, the final result is on the attached screen. N

How i have concatenate all the elements of each array in order to get new arrays in the following format: Nokia G20 4 64 Albastru, Motorola G60 gri etc Thank You

enter image description here

Laravel9 with Vue2

Posted: 01 Mar 2022 12:46 AM PST

I installed Laravel and Vuejs with commands

laravel new blog

composer require laravel/ui

php artisan ui vue

npm install vue-router

npm install

app.js

  window.Vue = require('vue').default;  import router from "./router/router";  const app = new Vue({      el: '#app',      router  });  

router/router.js

import VueRouter from 'vue-router'    Vue.use(VueRouter)    const routes = [      {          path: '/',          name: 'Home',          component: () => import('../components/ExampleComponent.vue')      }  ]    const router = new VueRouter({      mode: 'history',      base: process.env.BASE_URL,      routes  })    export default router  

It gives an error when I execute this command ‍npm run watch

export 'default' (imported as 'VueRouter') was not found in 'vue-router' (possible exports: NavigationFailureType, RouterLink, RouterView, START_LOCATION, createMemoryHistory, createRouter, createRouterMatcher, createWebHashHistory, createWebHistory, isNavigationFailure, matchedRouteKey, onBeforeRouteLeave, onBeforeRouteUpdate, parseQuery, routeLocationKey, routerKey, routerViewLocationKey, stringifyQuery, useLink, useRoute, useRouter, viewDepthKey)    WARNING in ./resources/js/router/router.js 11:17-26  export 'default' (imported as 'VueRouter') was not found in 'vue-router' (possible exports: NavigationFailureType, RouterLink, RouterView, START_LOCATION, createMemoryHistory, createRouter, createRouterMatcher, createWebHashHistory, createWebHistory, isNavigationFailure, matchedRouteKey, onBeforeRouteLeave, onBeforeRouteUpdate, parseQuery, routeLocationKey, routerKey, routerViewLocationKey, stringifyQuery, useLink, useRoute, useRouter, viewDepthKey)    WARNING in ./resources/js/components/ExampleComponent.vue?vue&type=template&id=299e239e (./node_modules/babel-loader/lib/index.js??clonedRuleSet-5.use[0]!../node_modules/vue-loader/dist/templateLoader.js??ruleSet[1].rules[2]!../node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./resources/js/components/ExampleComponent.vue?vue&type=template&id=299e239e) 6:30-48  export 'createStaticVNode' (imported as '_createStaticVNode') was not found in 'vue' (possible exports: default)    WARNING in ./resources/js/components/ExampleComponent.vue?vue&type=template&id=299e239e (./node_modules/babel-loader/lib/index.js??clonedRuleSet-5.use[0]!../node_modules/vue-loader/dist/templateLoader.js??ruleSet[1].rules[2]!../node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./resources/js/components/ExampleComponent.vue?vue&type=template&id=299e239e) 10:9-19  export 'openBlock' (imported as '_openBlock') was not found in 'vue' (possible exports: default)    WARNING in ./resources/js/components/ExampleComponent.vue?vue&type=template&id=299e239e (./node_modules/babel-loader/lib/index.js??clonedRuleSet-5.use[0]!../node_modules/vue-loader/dist/templateLoader.js??ruleSet[1].rules[2]!../node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./resources/js/components/ExampleComponent.vue?vue&type=template&id=299e239e) 10:23-42  export 'createElementBlock' (imported as '_createElementBlock') was not found in 'vue' (possible exports: default)    WARNING in ./node_modules/vue-router/dist/vue-router.esm-bundler.js 1852:4-15  export 'onUnmounted' (imported as 'onUnmounted') was not found in 'vue' (possible exports: default)    WARNING in ./node_modules/vue-router/dist/vue-router.esm-bundler.js 1853:4-17  export 'onDeactivated' (imported as 'onDeactivated') was not found in 'vue' (possible exports: default)    WARNING in ./node_modules/vue-router/dist/vue-router.esm-bundler.js 1854:4-15  export 'onActivated' (imported as 'onActivated') was not found in 'vue' (possible exports: default)    WARNING in ./node_modules/vue-router/dist/vue-router.esm-bundler.js 1867:52-70  export 'getCurrentInstance' (imported as 'getCurrentInstance') was not found in 'vue' (possible exports: default)    WARNING in ./node_modules/vue-router/dist/vue-router.esm-bundler.js 1871:25-31  export 'inject' (imported as 'inject') was not found in 'vue' (possible exports: default)```  

Does VIM definition of 'inner-word' change based upon context?

Posted: 01 Mar 2022 12:46 AM PST

I'm trying to figure out why the same key pattern viw appears to behave differently in separate contexts

I have two buffers where the cursor is [ ]

In one a javascript file:

import {[f]oo, bang} from './utilities'  

visual selection: foo

The other, :help

"inner word", select [count] words (see |word|).  White space between words is counted too.  When used in Visual linewise mode "iw" switches to  Visual characterwise [m]ode.  

visual selection: mode.

I'm confused why in the first the inner-word excludes the punctuation character comma , and the second includes the punctuation .

What accounts for this inconsistency?

PostgreSQL 12 authentication error - could not connect to the server

Posted: 01 Mar 2022 12:46 AM PST

I have a postgresql 12.2 database on a Red Hat linux 8.4 OS, this database is part of a pgpool cluster. When I run the following command to check the cluster status: psql -h -p 9999 -U postgres -c 'show pool_nodes'

it gives the below error after I enter the password: Click here for the error

I am sure that the password is correct, what might be the issue here? I checked pg_hba.conf file and I have this entry already: host all all <DB_IP_ADDRESS> md5 I tried other methods as well like "trust", but still no luck.

Can someone help me on this please?

How to use shell functions in a script

Posted: 01 Mar 2022 12:45 AM PST

I have a shell function that I am trying to call from my zsh script but it is not finding the function. I assume this is because the script has no context to the environment? How do I get the script to utilize the shell functions?

$ function foo { echo bar }  $ foo  bar  

In my my_script.zsh file I have:

#!/usr/bin/zsh    echo Foo  foo  

But when I run this I get:

$ ./my_script.zsh  Foo  ./my_script.zsh:4: command not found: foo  

Is there any way I can use my shell functions inside of my scirpt?

3D Pictures dont load Java

Posted: 01 Mar 2022 12:45 AM PST

I tried to show some Blockarts in a 3D Generator. But i cant figure out this error:

javax.imageio.IIOException: Can't read input file!  at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1310)  at Texture.load(Texture.java:20)  at Texture.<init>(Texture.java:15)  at Texture.<clinit>(Texture.java:29)  at Game.<init>(Game.java:45)  at Game.main(Game.java:103)  javax.imageio.IIOException: Can't read input file!  

When i start the Programm, the whole World appears with Black Blocks: Screen shot after Starting Programm

Im doing want to do a 3D engine, where you can just walk around in rooms. So this Blocks arent rendering for me.

This is my Code:

Class:Texture

import java.awt.image.BufferedImage;  import java.io.File;  import java.io.IOException;  import javax.imageio.ImageIO;    public class Texture {    public int[] pixels;    private String loc;    public final int SIZE;    public Texture(String location, int SIZE) {      loc = location;      this.SIZE = SIZE;      pixels = new int[SIZE * SIZE];      load();  }    private void load() {      try {          BufferedImage image = ImageIO.read(new File(loc));          int w = image.getWidth();          int h = image.getHeight();          image.getRGB(0, 0, w, h, pixels, 0, w);      } catch (IOException e) {          e.printStackTrace();      }  }    public static Texture wood = new Texture("block1.png", 64);  public static Texture brick = new Texture("block2.png", 64);  public static Texture bluestone = new Texture("block3.png", 64);  public static Texture stone = new Texture("block1.png", 64);  

}

Class Game:

import java.awt.Color;  import java.awt.Graphics;  import java.awt.image.BufferStrategy;  import java.awt.image.BufferedImage;  import java.awt.image.DataBufferInt;  import java.util.ArrayList;  import javax.swing.JFrame;    public class Game extends JFrame implements Runnable{     private static final long serialVersionUID = 1L;   public int mapWidth = 15;   public int mapHeight = 15;   private Thread thread;   private boolean running;   private BufferedImage image;   public int[] pixels;   public ArrayList<Texture> textures;   public Camera camera;   public Screen screen;   public static int[][] map =          {                 {1,1,1,1,1,1,1,1,2,2,2,2,2,2,2},                 {1,0,0,0,0,0,0,0,2,0,0,0,0,0,2},                 {1,0,3,3,3,3,3,0,0,0,0,0,0,0,2},                 {1,0,3,0,0,0,3,0,2,0,0,0,0,0,2},                 {1,0,3,0,0,0,3,0,2,2,2,0,2,2,2},                 {1,0,3,0,0,0,3,0,2,0,0,0,0,0,2},                 {1,0,3,3,0,3,3,0,2,0,0,0,0,0,2},                 {1,0,0,0,0,0,0,0,2,0,0,0,0,0,2},                 {1,1,1,1,1,1,1,1,4,4,4,0,4,4,4},                 {1,0,0,0,0,0,1,4,0,0,0,0,0,0,4},                 {1,0,0,0,0,0,1,4,0,0,0,0,0,0,4},                 {1,0,0,0,0,0,1,4,0,3,3,3,3,0,4},                 {1,0,0,0,0,0,1,4,0,3,3,3,3,0,4},                 {1,0,0,0,0,0,0,0,0,0,0,0,0,0,4},                 {1,1,1,1,1,1,1,4,4,4,4,4,4,4,4}            };  public Game() {      thread = new Thread(this);      image = new BufferedImage(640, 480, BufferedImage.TYPE_INT_RGB);      pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();      textures = new ArrayList<Texture>();      textures.add(Texture.wood);      textures.add(Texture.brick);      textures.add(Texture.bluestone);      textures.add(Texture.stone);      camera = new Camera(4.5, 4.5, 1, 0, 0, -.66);      screen = new Screen(map, mapWidth, mapHeight, textures, 640, 480);      addKeyListener(camera);      setSize(640, 480);      setResizable(false);      setTitle("3D Engine");      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      setBackground(Color.black);      setLocationRelativeTo(null);      setVisible(true);      start();  }  private synchronized void start() {      running = true;      thread.start();  }  public synchronized void stop() {      running = false;      try {          thread.join();      } catch(InterruptedException e) {          e.printStackTrace();      }  }  public void render() {      BufferStrategy bs = getBufferStrategy();      if(bs == null) {          createBufferStrategy(3);          return;      }      Graphics g = bs.getDrawGraphics();      g.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);      bs.show();  }  public void run() {      long lastTime = System.nanoTime();      final double ns = 1000000000.0 / 60.0;//60 times per second      double delta = 0;      requestFocus();      while(running) {          long now = System.nanoTime();          delta = delta + ((now-lastTime) / ns);          lastTime = now;          while (delta >= 1)//Make sure update is only happening 60 times a second          {              //handles all of the logic restricted time              screen.update(camera, pixels);              camera.update(map);              delta--;          }          render();//displays to the screen unrestricted time      }  }  public static void main(String [] args) {      Game game = new Game();  }  

}

change if else Structure to a loop [duplicate]

Posted: 01 Mar 2022 12:45 AM PST

I have the following ifelse structure which works fine for me. However, now I have to add some lines and I was wondering, if there is a way to change it to a loop, to reduce the lines of code.

if     ($class_number == 0) {$klassliste = array();}                elseif ($class_number == 1) {$klassliste = array(1);}               elseif ($class_number == 2) {$klassliste = array(1,2);}             elseif ($class_number == 3) {$klassliste = array(1,2,3);}           elseif ($class_number == 4) {$klassliste = array(1,2,3,4);}         elseif ($class_number == 5) {$klassliste = array(1,2,3,4,5);}       elseif ($class_number == 6) {$klassliste = array(1,2,3,4,5,6);}     elseif ($class_number == 7) {$klassliste = array(1,2,3,4,5,6,7);}   

How do I add timestamp to Cognos 11 file written to share folder

Posted: 01 Mar 2022 12:45 AM PST

I have a file that is written by Cognos 11 to a shared folder. Problem is that each time Cognos writes the file, it uses the exact same file name. Subsequent outputs fail if the file name already exists. So, I need something line a timestamp added to the name to uniquely identify the file.

There are 2 setting2 for email attachments to set up the file name with a timestamp. These are emf.dls.attachment.timestamp.enabled and emf.dls.attachment.timestamp.format. They do not affect a file name that is written to a network folder.

Does anyone know how to do this?

Extending wiremock to store request response in DB

Posted: 01 Mar 2022 12:46 AM PST

I am trying to write an extension where in I can store the request and response in the database. I extended PostActionServe, now there are 2 problems

  1. After starting the mock server, I submitted the post request to http://localhost:8089/__admin/mappings but neither doAction or doGlobalAction get invoked.

  2. Now if i hit the end point /some/thing then only doGlobal Action gets invoked.

I was hoping that the moment i submit the request to mappings API it should invoke this extension and i can store the request and response in DB.

Below is the code

import com.github.tomakehurst.wiremock.WireMockServer;

import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;

public class Main {        public static void main(String... args) {          WireMockServer wireMockServer = new WireMockServer(wireMockConfig()                  .extensions(new RequestRecorder()).port(8089)); //No-args constructor will start on port 8080, no HTTPS          wireMockServer.start();      }  }      import com.github.tomakehurst.wiremock.core.Admin;  import com.github.tomakehurst.wiremock.extension.Parameters;  import com.github.tomakehurst.wiremock.extension.PostServeAction;  import com.github.tomakehurst.wiremock.stubbing.ServeEvent;    public class RequestRecorder extends PostServeAction {      public static final String EXTENSION_NAME = "db-request-recorder";        @Override      public void doAction(final ServeEvent serveEvent, final Admin admin, final Parameters parameters) {            System.out.println(serveEvent.getRequest());          System.out.println(serveEvent.getResponseDefinition());      }        @Override      public void doGlobalAction(ServeEvent serveEvent, Admin admin) {          System.out.println(serveEvent.getRequest());          System.out.println(serveEvent.getResponseDefinition());      }      @Override      public String getName() {          return EXTENSION_NAME;      }  }    class MainTest {        public static void main(String... aergs) {          CloseableHttpClient httpClient = HttpClientBuilder.create().build();          try {              HttpPost request = new HttpPost("http://localhost:8089/__admin/mappings");              StringEntity params = new StringEntity("{\n" +                      "    \"request\": {\n" +                      "        \"method\": \"GET\",\n" +                      "        \"url\": \"/some/thing\"\n" +                      "    },\n" +                      "    \"response\": {\n" +                      "        \"status\": 200,\n" +                      "        \"body\": \"Hello world!\",\n" +                      "        \"headers\": {\n" +                      "            \"Content-Type\": \"text/plain\"\n" +                      "        }\n" +                      "    }\n" +                      "}");              request.addHeader("content-type", "application/x-www-form-urlencoded");              request.setEntity(params);              HttpResponse response = httpClient.execute(request);          } catch (Exception ex) {          } finally {              // @Deprecated httpClient.getConnectionManager().shutdown();          }      }  }  

How to get rid of from SpreadOperator performance warning that was given by Detekt while using Spring Boot?

Posted: 01 Mar 2022 12:46 AM PST

Recently, I added Detekt analyzer to my application.

After I runned detekt (./gradlew detekt), I got SpreadOperator warning in my main class of application.

Warning on code: runApplication<MessCallsApplication>(*args)

You can read about SpreadOperator warning here: [SpreadOperator Warning][2]

my main class:

@SpringBootApplication(exclude = [RedisAutoConfiguration::class])  @EnableCircuitBreaker  @EnableScheduling  class MyApplication {        companion object : KLogging()  }    fun main(args: Array<String>) {      Thread.setDefaultUncaughtExceptionHandler { _, exception ->          MessCallsApplication.logger.error(exception) { "Uncaught exception" }      }        runApplication<MessCallsApplication>(*args)  }  

Question is, What is the best practice to get rid of from that SpreadOperator warning? Or is it impossible?

spyder mysql connector python

Posted: 01 Mar 2022 12:45 AM PST

I am having trouble with mysql-connector for python 2.7 while using the Anaconda Spyder IDE. Although the code below works in Python Gui, i get the following error in spyder: 'ImportError: No Module named mysql.connector'.

Here is the code:

import mysql.connector  conn=mysql.connector.connect(user='root',password='xxxxx',host='localhost',database='xxxxx')  mycursor=conn.cursor()    mycursor.execute("""SELECT Ir FROM FinProg where ProgCatId = 4""")  obrrate = mycursor.fetchall().  

I downloaded mysql connector on spyder via command line with this: 'conda install mysql-python'.

Does spyder require a different syntax to use mysql-connector? How can I use mysql-connector for spyder?

1 comment:

  1. E-Techbytes: Recent Questions - Stack Overflow >>>>> Download Now

    >>>>> Download Full

    E-Techbytes: Recent Questions - Stack Overflow >>>>> Download LINK

    >>>>> Download Now

    E-Techbytes: Recent Questions - Stack Overflow >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete