Monday, June 28, 2021

Posts from Recent Questions - Stack Overflow for 06/28/2021

View this email in your browser
Updates from https://stackoverflow.com/questions

Recent Questions - Stack Overflow



In the 06/28/2021 edition:

How to create an sql script to update data and run in production environment in Spring boot

By Aditi Agrawal on Jun 28, 2021 04:01 am

I am naive to springboot, I have a table users(name, password) , I want to update table details in production environment in springboot, so that whenever anybody else pulls the code and run server in their local machine, the data is updated for them also, I need to run the script only once. Please help me out with this.


Read in browser »
share on Twitter

How to use one config file in C++ Boost with a sink per applicationß

By Thomas Lehmann on Jun 28, 2021 04:01 am

I can easily create a config file to send messages to console, to logfile, to DebugView and to Eventlog but I didn't found out how to configure it that - as shared config file - Application "A" has 4 different sink sections than Application "B".

  1. Is that possible?
  2. How to implement that? (any links?)

My basic setup in the main function is following:

std::ifstream logConfiguration(getCwd() + "\\test-logging.ini");  try {      boost::log::init_from_stream(logConfiguration);      boost::log::add_common_attributes();      boost::log::core::get()->add_global_attribute("Scope", boost::log::attributes::named_scope());  }  catch (std::exception e) {      APS_XTRACE(error) << e.what() << std::endl;      return 1;  }  

Kind Regards, Thomas


Read in browser »
share on Twitter

BLE over node.js: Cannot intercept dev_disconnected() event

By Erez Buchnik on Jun 28, 2021 04:01 am

I have examined many BLE stacks, and have found the DBUS-based https://github.com/chrvadala/node-ble to be very stable on Linux (Debian on ARM) for multi-device ad-hoc connection establishment & notifications.

My use-case involves multiple devices which may sporadically disconnect, and I need to intercept the disconnection event - or as it appears in the Bluetooth logs:

src/adapter.c:dev_disconnected()  

How can I assign a callback on this event using node-ble? I mean, something similar to the callback for intercepting notifications (once registered to a Notifications characteristic), e.g.:

characteristic.on('valuechanged', buffer => {    console.log(buffer);  });  

Alternatively, is it possible to intercept those events through a separate process, natively based on DBUS/BLUEZ?


Read in browser »
share on Twitter

JQ Case insensitive contains

By Fight Daily on Jun 28, 2021 04:01 am

So I had problem, Does JQ contains support case insensitive matching? Example

.user | contains("thinking")  

Filter ^

{    "id": "1338268256814161923",    "user": "Thinking of going through the Venmo transactions on my feed and liking all of them just to create a little sense of vulnerability"  }  

Output : false

Desired output : True


Read in browser »
share on Twitter

Interview Question: Can you manipulate this list of tuples to get a new list representing how many tuples are within smaller grids?

By Zachary on Jun 28, 2021 04:01 am

You are given a list of tuples/pairs. Each tuple/pair has an x-coordinate and y-coordinate (in the form of integers). An example of a list would be [(2, 64), (5,12), (3, 78), (480, 98),...]. The tuples/pairs represent coordinates of points on a given image of size 2560px x 1920px (width x height). Your overall end goal is to produce a new list containing key-value pairs. Here are more details on how to go about obtaining these key-value pairs:

For visualization purposes, the image containing all the points will look like thisenter image description here You are to analyse the given image and coordinates in grids (see green/orange/red/blue boxes). Within each grid, count how many coordinates are contained within the grid and create a key-value pair using the center of the square/grid as the key and the number of points within the square/grid as the value.

enter image description here Each grid is to overlap 1/3 of the previous grid and will look something like this once it is stacked properly. The centere of each colored grid/square has been provided respectively.

enter image description here Visually, the new image should look like that with the grids/squares removed, while the coordinates of the center has been kept.

enter image description here End result, a new image can be visually represented with the list of key-value pairs

Note: The size of the grids can be specified by you but your code must make this aspect easily edited.


Read in browser »
share on Twitter

How do I create a scheduled task using my python script

By aerris 1001 on Jun 28, 2021 04:01 am
try:      subprocess.call([ 'start', 'cmd', '/k', '/CREATE /SC DAILY /TN "footask" /TR "\\C:Users\\AeRRis\\Desktop\\FinalYearProject-master\\Main.exe" /ST 15:38'])      logger.info("Successfully written scheduled task")  except Exception as e:      print(e)      logger.exception("Unable to create scheduled task")  

I am trying to run an executable that contains the above python3 script. The executable is tasked to create a scheduled task from the command line. However, I am receiving the following error code : [WinError 2] The system cannot find the file specified Is inputting the absolute path not correct? I have tried inputting directly into the cmd line and it works well, but running it as an executable provides the error above.


Read in browser »
share on Twitter

Chain equality operator in javascript

By Sarah on Jun 28, 2021 04:01 am

I am new in js and I have a question about how chain equality works in js. For example in python if you have: a, b = 1, 2
a == b == False //False
Because it converts to: (a == b) and (b == False) So, finally it is False.

But when I try this in js: console.log(1==2==false) // true

I got "true". I don't know why and how it is worked in js. could you please help me out?


Read in browser »
share on Twitter

Django - expected type pk, received str [Many to many]

By Jirro Reo on Jun 28, 2021 04:01 am

I have a webapp where we can create communities with django as a backend, but when i try to send a POST to create a community, I get:

community_configuration: ["Incorrect type. Expected pk value, received str."]

My POST:

{  title: knkn kn .k jbjnmn,  logo: [object File],  is_active: true,  description: test,  welcome_message: Welcome message,  org_id: 114,  community_configuration: About us,Community news,FAQs,Supporters,Resources,  }  

Here are my serializers:

class MicroConfigurationSerializer(serializers.ModelSerializer):        class Meta:          model = MicroConfiguration          fields = [              'name',          ]        def to_representation(self, instance):          return instance.name      class CommunityConfigurationSerializer(serializers.ModelSerializer):      micro_configurations = MicroConfigurationSerializer(many=True, read_only=True)        class Meta:          model = CommunityConfiguration          fields = '__all__'      class CommunitySerializer(serializers.ModelSerializer):      logo = serializers.SerializerMethodField()      organisation = serializers.SerializerMethodField()      community_configuration = CommunityConfigurationSerializer()        class Meta:          model = Community          fields = (              ...              etcetc              ...          )  

Heres my model:

class MicroConfiguration(core_models.BaseModel):      name = models.CharField(max_length=32, unique=True)      permissions = models.ManyToManyField(Permission)        def __str__(self):          return self.name      class CommunityConfiguration(core_models.BaseModel):      name = models.CharField(max_length=32)      micro_configurations = models.ManyToManyField(MicroConfiguration)      permission_group = models.ForeignKey(          Group,          on_delete=models.SET_NULL,          null=True      )        def __str__(self):          return self.name      class Community(core_models.BaseModel):      accounts = models.ManyToManyField(          settings.AUTH_USER_MODEL,          through='associates.AccountCommunity',          through_fields=('community', 'account')      )      goals = models.ManyToManyField(Goal, through='associates.CommunityGoal')      type = models.ManyToManyField(CommunityType, through='CommunityAttribute')      communities = models.ManyToManyField(          'self',          through='associates.CommunityCommunity',          symmetrical=False,      )      crossposts = models.ManyToManyField(          Action,          through='activities.CommunityCrosspost',          through_fields=('community', 'action'),          related_name='communities',      )        title = models.CharField(max_length=64)      logo = models.ImageField(null=True, blank=True)      intro_media = models.ForeignKey(          'associates.MediaStore',          null=True,          on_delete=models.SET_NULL      )      website_url = models.CharField(max_length=256, blank=True)      is_invite_only = models.BooleanField(default=False)      description = models.TextField(blank=True)      intro_message = models.TextField(blank=True)      welcome_message = models.TextField(blank=True)      signup_autojoin = models.BooleanField(default=False)        community_configuration = models.ForeignKey(          CommunityConfiguration,          default=1,          null=True,          on_delete=models.SET_NULL,          help_text='Do not edit directly, create a new custom config instead, \              as it is reference by difference community.',      )        objects = models.Manager()      associates = AssociationManager()        @property      def url(self):          return reverse(              'communities:detail',              kwargs={                  'id': self.id,              }          )        class Meta:          verbose_name = 'Community'          verbose_name_plural = 'Communities'        def __str__(self):          return self.title  

I've been stuck with this for hours, any help?


Read in browser »
share on Twitter

Save JSON in Local Storage after the fetch

By Smithy on Jun 28, 2021 04:01 am

Sorry if this was posted a lot, I read through several articles but could not find the solution. So, I'm fetching a large JSON from this API, and I would like to cache the response somehow in the localStorage, so the next time the page loads, the scripts first checks if there is an object with the requested ID inside the JSON, and renders the content if there is one - and if there isn't, goes of to the API to fetch it.

I was thinking of setting up two fetch() functions, and this is what I have:

   fetch(url + id)          .then((response) => {              localStorage.setItem('myResponse', response);          })          .catch((error) => {              console.log(error);          })  

Then, check if there is something saved inside the localStorage, and if it is good, use it to render the HTML, if not, go on to another fetch to get it from the API.

  if(localStorage) {       createHTML(localStorage.myResponse);    } else {       fetch(url + id)           .then(response => response.json())           .then(data => createHTML(data))    }  

But, in the first fetch, if I use JSON.stringify(response), it just shows it as an empty object, so it the localStorage it looks like: myResponse - {}. If I do console.log(response.json()); on the first fetch, it shows Promise {<pending>}.

I've tried to make something out of that, but without results...any help much appreciated!


Read in browser »
share on Twitter

How to give table name as variable in for loop select statement in SQL oracle

By Lochana Liyange on Jun 28, 2021 03:58 am
  T_TABLE_N := UPPER(TABLE_N);     FOR ATTRIBUTE_ IN (SELECT HEADER_NAME FROM T_TABLE_N                        GROUP BY HEADER_NAM )  

Here, I use the T_TABLE_N table as a variable. But it wasn't taken as a table

How to solve this problem


Read in browser »
share on Twitter

Create a neested dictionary with default values by using a lists

By PParker on Jun 28, 2021 03:58 am

Ho can I create a neested python dictionary from a list?

The desired dict is:

result_dict = {              'car': None,              'industryPredictions': {'a': None,                                      'b': None},              'bike': None,              'payment': None  }  

I know how to create the first part:

keys = ['car','bike','payment']  dict1 = {el:None for el in keys}    >> dict1  {'bike': None, 'car': None, 'payment': None}  

But how can I make a neested dictionary with a list?


Read in browser »
share on Twitter

Iterate over two uneven lists and stop once the second list ends

By B A C H A S H on Jun 28, 2021 03:40 am

I have two lists, a list of languages (long list) and a list of word (has 6 items). I need to print each word next to a language but stop it once all 6 items are printed.

at first, I ran this code and it works fine (print 6 times), but as far as I add new a language, it would the last item in (texts) and that added language.

langs = ['russian', 'spanish', 'german', 'italian', 'english', 'english']  texts = ['technology', 'communism', 'community', 'university', 'computer', 'politics']    for a, lang in enumerate(langs, start=1):      for b, text in enumerate(texts, start=1):          if b == a:              break      print(text, '->', lang)    

I think it is very easy, but I could not figure it out yet.


Read in browser »
share on Twitter

Python script runs ~18x times slower inside Docker container vs on host linux system

By Oromë on Jun 28, 2021 03:37 am

We have a python script that runs approximately 18 times slower inside a docker container vs on the host machine itself and we are unsure why.

Time on host machine:

real    1m11.259s  user    0m56.310s  sys     0m25.712s  

Time inside docker container:

real    18m0.026s  user    8m45.265s  sys     9m44.172s  

Now I did find a blog post talking about the --security-opt seccomp=unconfined option which seems to have caused a lot of speedupds with other people, so I tried it with that too:

real    18m13.239s  user    8m44.130s  sys     9m58.418s  

So no improvement for us there. Container was run with the following arguments: docker run --rm -it --security-opt seccomp=unconfined -v /home/{user}/temp:/tmp -w /tmp

Python version: 2.7.16 (customer requirement, nothing we can do about it at this time)

No docker settings have been changed, so the container should have full access to the host's resources. Anything specific that could be causing this, or ideas where to start looking for the issue?


Read in browser »
share on Twitter

Alamofire Default Generic Response

By oyurtturk on Jun 28, 2021 03:35 am

There is a default generic 'Response' class on Retrofit. What is similar to Alamofire?

In the current structure, there is a generic request structure that takes a serializable into it, but I want to use the default response object directly without giving a type.

I'd like to get some other advice as well. I don't have much experience in swift, I would appreciate it if you could evaluate it from this perspective.


Read in browser »
share on Twitter

How to display the last element using join python

By Gjsks on Jun 28, 2021 03:31 am

python's join method ignores the last element in the list, but I want to be able to display without problems, look at my code:

import re  estoque = [0,1,20,0]  estoque_formated = '\n'.join([str(elem) for elem in estoque])  tamanho = [20, 34, 34.5, 40]  joined = f' Em estoque: {estoque_formated[0]}\n'.join(["Tamanho: " + str(elem) for elem in tamanho])  print(joined)  

The output of the script I want is this:

 Tamanho: 20 Em estoque 0   Tamanho: 34 Em estoque 1   Tamanho: 34.5 Em estoque 20   Tamanho: 40 Em estoque 0    

Obs, notice that the sizes are displayed, but it always takes the index 0 of the variable estoque_formated how can I get the first index and add it? Example starting from 0 and going to 1 then 2...etc? Well, I need to solve the problem with the index as I said, and to get it I was able to display the size and value of the estoque_formated variable even though it's the last element, I want to modify the script as little as possible.


Read in browser »
share on Twitter

Add Multiple Sheets in a workbook using npm XLSX in ReactJS

By ImranNaqvi on Jun 28, 2021 03:30 am

I'm following This Tutorial to generate excel reports. Now the guy in tutorial did his best to explain each step and I successfully created excel report following his steps. Now my problem is, I want to generate multiple sheets in one workbook. you know like 'Sheet1' | 'Sheet2' .... Any help will be greatly appreciated. Thanks

enter image description here


Read in browser »
share on Twitter

Deploying Django + Vuejs in containers (AWS Elastic Beanstalk)

By lbris on Jun 28, 2021 02:24 am

I'm developing an app with Django and Vuejs and the time has come to test deployment related things. My app will be deployed several times (1 instance per future customer) so I'd like to use containers for faster deployments and removal of virtual machine maintenances.

The thing is :

I do not now how to build the vuejs part in production.

The Django backend is supposed to serve the bundle assets and, while I see on the AWS documentation that I can migrate, collect static files,... a Django application when the container starts, I do not know when/where I'm supposed to build the vuejs part in order to let Django collect the built things.

Can someone help me on this ?

When/where/how should I build the vuejs part ?

Note that Django and Vuejs are integrated this way : whatever the URL, Django serves the Vuejs SPA. And the Vuejs SPA consumes the Django API made with Django Rest Framework.

Thanks in advance for your help.

If more information is needed I will edit this post.


Read in browser »
share on Twitter

I need to reduce the number of arcs between nodes by choosing the closests with sort

By TOMÁS LECAROS on Jun 28, 2021 02:05 am

I am working on a tsp problem, as it takes a long time to execute I decided to try to reduce the number of arcs by choosing only the 5 closest places for each node. I started using sort to resolve my problem but I don't understand much in how to use it. my code is:

   n = 21  # Houses     N = [i for i in range(n)]     df = pd.DataFrame({        "coord_x": list_coord_x,        "coord_y": list_coord_y      })       arcs = [(i, j) for i in N for j in N if i != j]     D = {(p, j): abs(df["coord_x"][p]-df["coord_x"][j]) + abs(df["coord_y"][p]-df["coord_y"][j]) for p, j in arcs}  # Distances for each arc  

My goal is to reduce the arcs to the closest 5 so that the program runs faster. My arcs in this example are:

    arcs = [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (0, 10), (0, 11), (0, 12), (0, 13), (0, 14), (0, 15), (0, 16), (0, 17), (0, 18), (0, 19), (0, 20), .................................., (20, 3), (20, 4), (20, 5), (20, 6), (20, 7), (20, 8), (20, 9), (20, 10), (20, 11), (20, 12), (20, 13), (20, 14), (20, 15), (20, 16), (20, 17), (20, 18), (20, 19) ]  

And I want for example:

   reduced_arcs = [(0, 1), (0, 7), (0, 8), (0, 10), (0, 14), (1, 3), ....., (20, 3), (20, 4), (20, 10), (20, 11), (20, 12)]  

Because those arcs are the closest between them.


Read in browser »
share on Twitter

SpringBoot with XSSFilter fails to authenticate due to missing CSRF Token

By jkasper on Jun 28, 2021 02:02 am

I'm using a springboot thymeleaf application with csrf enabled. In order to prevent my application from the XSS Vulnerability I added a filter following this tutorial. I have copied the files for XSSFilter, XSSRequestWrapper and XSSUtils as is from here. Possibly the only new thing that I have added in my strip function is this code:

String returnValue = Jsoup.clean(value, Whitelist.none());  returnValue = Parser.unescapeEntities(returnValue, true);  return returnValue;  

I had to add this because Jsoup clean was adding amp; in place of &.

I have a login page for my application and only if the user is successfully authenticated, is he allowed in. The application works absolutely fine without the filter. However, when I add the filter the application won't login and won't show any error whatsoever. Here is my index.html in which thymeleaf inserts the csrf token:

<html xmlns:th="http://www.thymeleaf.org"     xmlns:sec="http://www.thymeleaf.org/extras/spring-security">     <head id="Head1" >        <title>Home</title>        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>        <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE11"/>        <meta name="_csrf" th:content="${_csrf.token}"/>        <meta name="_csrf_header" th:content="${_csrf.headerName}"/>        <link rel="stylesheet" th:href="@{css_page_specific/index.css}">        <link rel="stylesheet" th:href="@{css_general/toggle-button-modern.css}">        <script type="text/javascript" th:src="@{commons.js}"></script>     </head>     <form method="post" id="init-form2" th:action="@{/login}"  style="max-width: 350px; margin: 0 auto;">     <div class="form-group">        <input type="text" name="username" id="ad-auth-username" placeholder="id">     </div>     <div class="form-group">        <input type="password" name="password" id="ad-auth-password" placeholder="Password">     </div>      

Here is my Login Controller:

      @Controller  public class LoginController {        @GetMapping("/login")      public String showLoginForm(Model model) {            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();          if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {              return "login";          }            return "redirect:/";      }        @GetMapping("/logout")      public String logoutPage(HttpServletRequest request, HttpServletResponse response) {          Authentication auth = SecurityContextHolder.getContext().getAuthentication();          if (auth != null){              new SecurityContextLogoutHandler().logout(request, response, auth);          }          return "redirect:/";      }  }  

Here is my web security config:

   @Override  protected void configure(HttpSecurity http) throws Exception {        http.requiresChannel().anyRequest().requiresSecure().and().authorizeRequests().antMatchers("/login","/css_general/**","/css_page_specific/**","/**/*.js","/**/*.css")          .permitAll()          .anyRequest()          .authenticated()          .and().formLogin(form -> form              .loginPage("/login")              .defaultSuccessUrl("/index.html")              .failureUrl("/login?error=true")          )          .sessionManagement().invalidSessionUrl("/login")          .and()          .httpBasic()         .and()      .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login").invalidateHttpSession(true).deleteCookies("JSESSIONID")              .permitAll()              .and()              .cors().disable()              .headers()              .xssProtection()              .and()              .contentSecurityPolicy("script-src 'self'");  }    @Override  public void configure(WebSecurity web) throws Exception {      web.ignoring().antMatchers("/css_general/**", "/css_page_specific/**","/resources/static/css_general/**","/resources/static/css_page_specific/**","/static/css_page_specific/**","/static/css_general/**");  }  

Now in my filter, if I don't put the xss stripping logic and put a breakpoint, I see it contains 3 parameters:

username, password and _csrf.  

enter image description here

This filter chain goes through and is ultimately allowed passed to csrfFilter which succeeds. I am able to successfully login.

However, if I put in the XSSFilter code, I don't see any of the 3 parameters being passed and ultimately the csrf filter fails and I stay on the login page without any error message. I know the filter is called for each request but I have checked every request and I just don't see these parameters being passsed and that's what I suspect is failing the csrfFilter.

enter image description here

How can I have the xss filter work and succesfully log in?

TLDR: Successfully able to authenticate without adding XSSFilter. Receiving 3 parameters in the filter - username, password and _csrf. Unable to authenticate and login after adding XSSFilter - Receiving 0 parameters in the filter.


Read in browser »
share on Twitter

PHP move uploaded files to directory

By programmer on Jun 28, 2021 01:51 am

I am posting files from python script to PHP from where I want to store them in a directory. I am scanning whole system for .rtx files and sending all of them to PHP. Below is my python script.

 url = 'http://localhost:9090/project/php/new.php'      driveStr = subprocess.check_output("fsutil fsinfo drives")      driveStr = driveStr.decode("utf-8")      driveStr = driveStr.strip().lstrip('Drives: ')      drives = driveStr.split()      print(drives)      mylist =      for drive in drives:            if os.path.isdir(drive):              p = os.walk(drive)              for i , dirs , files in p :                  for filename in files :                      if filename.endswith('rtx'):                            file_path = pathlib.PurePath(i, filename)                          print(file_path)                            mylist.append(file_path)        upload_file = [                      ("rtx_file" , (filename , open ( file_path , 'rb' ) , 'text/rtx'))                  ]                  response = requests.post ( url , files = upload_file )  

And below is my PHP script here I am receiving those files and moving them to directory.

    <?php      if(isset($_FILES['files']))  {      $target_path = "C:\wamp64\www\project\php\upload";        $target_path = $target_path . '/' . basename( $_FILES['files']['name']);      if(move_uploaded_file($_FILES['files']['tmp_name'], $target_path)) {          echo "The file ".  basename( $_FILES['files']['name'])." has been uploaded";      }      else{          echo "There was an error uploading the file, please try again!";      }          }  else  {      echo "no file uploaded";  }    ?>  

My issue is that it is not storing those files into specified directory. If anyone has any idea kindly guide me what is wrong. Thank You I follow this below link to implement my program. Python file upload to php Script


Read in browser »
share on Twitter

Redux Toolkit RTK Query sending query parameters

By Matt Herbstritt on Jun 28, 2021 01:46 am

How do you pass query parameters to the api using Redux Toolkit RTK Query?

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';    const baseUrl = 'xxxxxxx';    export const postsApi = createApi({    reducerPath: 'posts',    baseQuery: fetchBaseQuery({ baseUrl }),    endpoints: (builder) => ({      getPostsByYear: builder.query({        query: (start, end) => { // Why is 'end' always undefined???          return {            url: 'posts/',            params: { start, end },          };        },      }),      getPosts: builder.query({        query: () => 'posts/',      }),        getPostByID: builder.query({        query: (name) => `posts/${name}`,      }),    }),  });    export const { useGetPostsQuery, useGetPostsByYearQuery, useGetPostByIDQuery } = postsApi;  

When trying to pass parameters from the component only the start value seems to be recognised. year is updated by a select element within the <PostOptions/> component. It's using the useState hook. The value updates correctly and useGetPostsByYearQuery is called but the end parameter is always undefined. So, it seems I'm not defining the api endpoint correctly. Any advise? All I want it to do is send a request in the form http://xxx/posts?start=start&end=end.

I've even tried hard-coding a string value for the end parameter, e.g. useGetPostsByYearQuery(year, '2019'), but it still appears as undefined withing the api callback so I'm missing something more fundamental.

const Post = () => {      const year = useSelector((state) => state.postOptions.year);    const yearPlusOne = parseInt(year, 10) + 1;    const { data, error, isLoading } = useGetPostsByYearQuery(year, yearPlusOne);      return (      <SafeAreaView style={styles.container}>        <View style={styles.content}>          <PostHeading />          <PostOptions></PostOptions>        </View>      </SafeAreaView>    );  };    export default Post;  

Read in browser »
share on Twitter

I'm facing this error Cannot use object of type mysqli as array

By NÂdeem MÅlik on Jun 28, 2021 12:58 am

Controoler:

<?php    namespace App\Controllers;  use CodeIgniter\Controller;  use App\Models\Services;              class Detail extends Controller  {      public function nadeem($id)      {    $model= new Services();    $data= $model->select('text','title','image')->where('id',$id);  $nadeem['result'] =$data->get();    return view('service_detail',$nadeem);          }  }  

view:

<!DOCTYPE html>  <html>  <head>      <title>Service</title>  </head>  <body>        <?php if ($result) { foreach ($result as $key => $value)        { ?> <p><?php echo $value['text'];?></p> <?php } } ?>        </body>  </html>  

I'm facing this error

Cannot use object of type mysqli as array

How can solve this problem.


Read in browser »
share on Twitter

Count Groups of Objects in List

By Al Grant on Jun 27, 2021 10:31 pm

I have a list of objects and need to count the number of objects that have the same date, location and color:

public class Entity      public static void main(String args) {         List<Schedule> schedule = new ArrayList<Scheudle>();       schedule.add(new Schedule("12/12/2021", "Los Angeles", "Red", "Bob"));       schedule.add(new Schedule("12/12/2021", "Los Angeles", "Red", "Jimmy"));       schedule.add(new Schedule("12/12/2021", "Los Angeles", "Red", "Tim"));       schedule.add(new Schedule("12/12/2021", "Los Angeles", "Blue", "Mary"));       schedule.add(new Schedule("12/12/2021", "Los Angeles", "Green", "Jane"));       schedule.add(new Schedule("12/12/2021", "Los Angeles", "Green", "Jane"));       schedule.add(new Schedule("13/12/2021", "San Deigo", "Red", "Bob"));       schedule.add(new Schedule("13/12/2021", "San Deigo", "Green", "James"));       schedule.add(new Schedule("13/12/2021", "San Deigo", "Green", "Anne"));       schedule.add(new Schedule("14/12/2021", "Los Angeles", "Red", "James"));  }  

So for the above the totals would be for the number of people working each combination of date, location and color. i.e.:

  • 12/12/2021 Los Angeles Red - 3
  • 12/12/2021 Los Angeles Blue - 1
  • 12/12/2021 Los Angeles Green - 2
  • 13/12/2021 San Deigo Green - 2
  • 13/12/2021 San Deigo Red - 1
  • 14/12/2021 Los Angeles Red - 1

How can this be done?


Read in browser »
share on Twitter




Recent Articles:

Blazor Asp.Net Core Identity with custom user database
How to create a query using dynamic pivot?
Play store invalid apk signature flutter (APK integrity check failed)
Unable to show Play Store in-app Update Dialog
Unable to batch insert records into MSSQL DB using GORM: reflect: call of reflect.Value.Interface on zero Value
Twitter
Facebook
Website
Copyright © 2021 reader, All rights reserved.
You are receiving this email because you opted in via our website.

Our mailing address is:
reader
88 CELICA STREET
Davao 8000
Philippines

Add us to your address book


Want to change how you receive these emails?
You can update your preferences or unsubscribe from this list.

Email Marketing Powered by Mailchimp

No comments:

Post a Comment