content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
sequence
answers_scores
sequence
non_answers
sequence
non_answers_scores
sequence
tags
sequence
name
stringlengths
30
130
Q: Type mismatch when setting startActivity() in Kotlin I'm new on Kotlin for programming Android mobile. I want to try to make my own movie list for my experiment from many tutorials and for Android mobile programming learning. So, I want to try to make Explicit Intent that started from movie lists that one of them are clicked into an movie information that I clicked. After I get movie datasets from JSON in MainActivity.kt, I use the code below in MainActivity.kt to MovieAdapter class (MovieAdapter.kt) val customAdapter = MovieAdapter(moviePoster, movieTitle, movieYear, movieGenre, movieDirectors, movieRunTime, movieRating, movieActors, movieOverview, this@MainActivity) recyclerView.setAdapter(customAdapter) And this is the MovieAdapter class (MovieAdapter.kt) class MovieAdapter(var moviePoster: ArrayList<String>, var movieTitle: ArrayList<String>, var movieYear: ArrayList<String>, var movieGenre: ArrayList<String>, var movieDirectors: ArrayList<String>, var movieRunTime: ArrayList<String>, var movieRating: ArrayList<String>, var movieActors: ArrayList<String>, var movieOverview: ArrayList<String>, var ctx: Context) : RecyclerView.Adapter<MovieAdapter.MyViewHolder>() Then in MovieAdapter.kt (MovieAdapter class) like in the code below override fun onBindViewHolder(holder: MyViewHolder, position: Int) { holder.moviePoster.tag = moviePoster[position] holder.movieTitle.text = movieTitle[position] holder.movieYear.text = movieYear[position] holder.movieGenre.text = movieGenre[position] val moviePosterDetail = moviePoster[position] val movieTitleDetail = movieTitle[position] val movieYearDetail = movieYear[position] val movieGenreDetail = movieGenre[position] val movieDirectorDetail = movieDirectors[position] val movieTimeDetail = movieRunTime[position] val movieRatingDetail = movieRating[position] val movieActorsDetail = movieActors[position] val movieDescriptionDetail = movieOverview[position] holder.itemView.setOnClickListener{ Intent(ctx, MovieDetail::class.java).also { it.putExtra("moviePoster", moviePosterDetail) it.putExtra("movieTitle", movieTitleDetail) it.putExtra("movieYear", movieYearDetail) it.putExtra("movieGenre", movieGenreDetail) it.putExtra("movieDirector", movieDirectorDetail) it.putExtra("movieTime", movieTimeDetail) it.putExtra("movieRating", movieRatingDetail) it.putExtra("movieActors", movieActorsDetail) it.putExtra("movieDescription", movieDescriptionDetail) startActivity(it) } } } In the startActivity(it) part, there is a error in below Type mismatch. Required: Context Found: Intent No value passed for parameter 'intent' No value passed for parameter 'options' But in other files when do startActivity(it) part (in MainActivity.kt file), no error detected here. So, why it is happened and how can I do this? And if I must to use context and options parameters in startActivity(), what should I do to fill the parameters in startActivity() function? A: I'm not able to run an XML/View based project atm, but the startActivity you are calling might be the ContextCompat or something. Since the name of your parameter is var ctx: Context where you passed the instance of your activity this@MainActivity Can you try using the ctx parameter calling the startActivity instead? Intent(ctx, MovieDetail::class.java).also { ... ... ctx.startActivity(it) }
Type mismatch when setting startActivity() in Kotlin
I'm new on Kotlin for programming Android mobile. I want to try to make my own movie list for my experiment from many tutorials and for Android mobile programming learning. So, I want to try to make Explicit Intent that started from movie lists that one of them are clicked into an movie information that I clicked. After I get movie datasets from JSON in MainActivity.kt, I use the code below in MainActivity.kt to MovieAdapter class (MovieAdapter.kt) val customAdapter = MovieAdapter(moviePoster, movieTitle, movieYear, movieGenre, movieDirectors, movieRunTime, movieRating, movieActors, movieOverview, this@MainActivity) recyclerView.setAdapter(customAdapter) And this is the MovieAdapter class (MovieAdapter.kt) class MovieAdapter(var moviePoster: ArrayList<String>, var movieTitle: ArrayList<String>, var movieYear: ArrayList<String>, var movieGenre: ArrayList<String>, var movieDirectors: ArrayList<String>, var movieRunTime: ArrayList<String>, var movieRating: ArrayList<String>, var movieActors: ArrayList<String>, var movieOverview: ArrayList<String>, var ctx: Context) : RecyclerView.Adapter<MovieAdapter.MyViewHolder>() Then in MovieAdapter.kt (MovieAdapter class) like in the code below override fun onBindViewHolder(holder: MyViewHolder, position: Int) { holder.moviePoster.tag = moviePoster[position] holder.movieTitle.text = movieTitle[position] holder.movieYear.text = movieYear[position] holder.movieGenre.text = movieGenre[position] val moviePosterDetail = moviePoster[position] val movieTitleDetail = movieTitle[position] val movieYearDetail = movieYear[position] val movieGenreDetail = movieGenre[position] val movieDirectorDetail = movieDirectors[position] val movieTimeDetail = movieRunTime[position] val movieRatingDetail = movieRating[position] val movieActorsDetail = movieActors[position] val movieDescriptionDetail = movieOverview[position] holder.itemView.setOnClickListener{ Intent(ctx, MovieDetail::class.java).also { it.putExtra("moviePoster", moviePosterDetail) it.putExtra("movieTitle", movieTitleDetail) it.putExtra("movieYear", movieYearDetail) it.putExtra("movieGenre", movieGenreDetail) it.putExtra("movieDirector", movieDirectorDetail) it.putExtra("movieTime", movieTimeDetail) it.putExtra("movieRating", movieRatingDetail) it.putExtra("movieActors", movieActorsDetail) it.putExtra("movieDescription", movieDescriptionDetail) startActivity(it) } } } In the startActivity(it) part, there is a error in below Type mismatch. Required: Context Found: Intent No value passed for parameter 'intent' No value passed for parameter 'options' But in other files when do startActivity(it) part (in MainActivity.kt file), no error detected here. So, why it is happened and how can I do this? And if I must to use context and options parameters in startActivity(), what should I do to fill the parameters in startActivity() function?
[ "I'm not able to run an XML/View based project atm, but the startActivity you are calling might be the ContextCompat or something.\nSince the name of your parameter is\nvar ctx: Context\n\nwhere you passed the instance of your activity\nthis@MainActivity\n\nCan you try using the ctx parameter calling the startActivity instead?\nIntent(ctx, MovieDetail::class.java).also {\n\n ...\n ...\n\n ctx.startActivity(it)\n}\n\n" ]
[ 0 ]
[]
[]
[ "android", "kotlin" ]
stackoverflow_0074677953_android_kotlin.txt
Q: Authentication error with bq-auth in rstudio but not within r terminal session I used to not having issues on this particular subject, but bigrquery::bq_auth is not working on my installed RStudio. Funnything is that within an R terminal session it works perfectly. All started when I updated the R to R version 4.2.2 (2022-10-31). This impacts me because I'm not being able to run a shiny application due to this problem. Does any one knows what am I missing or has any clue where to look for? At least for start, because I am lost. The code I am running is quite simple: json="The_file.json" bigrquery::bq_auth(path = jason) The message: *Error: Can't get Google credentials. Are you running bigrquery in a non-interactive session? Consider: Call bq_auth() directly with all necessary specifics. * As a matter of fact, I was just hoping to have the same answer in the R terminal session: The bigrquery package is requesting access to your Google account. Select a pre-authorised account or enter '0' to obtain a new token. Press Esc/Ctrl + C to cancel. A: Folks, I removed all packages and installed everything possible again. It worked. Sorry. I had tryed a lot and this last one ocurred me later. Regards all.
Authentication error with bq-auth in rstudio but not within r terminal session
I used to not having issues on this particular subject, but bigrquery::bq_auth is not working on my installed RStudio. Funnything is that within an R terminal session it works perfectly. All started when I updated the R to R version 4.2.2 (2022-10-31). This impacts me because I'm not being able to run a shiny application due to this problem. Does any one knows what am I missing or has any clue where to look for? At least for start, because I am lost. The code I am running is quite simple: json="The_file.json" bigrquery::bq_auth(path = jason) The message: *Error: Can't get Google credentials. Are you running bigrquery in a non-interactive session? Consider: Call bq_auth() directly with all necessary specifics. * As a matter of fact, I was just hoping to have the same answer in the R terminal session: The bigrquery package is requesting access to your Google account. Select a pre-authorised account or enter '0' to obtain a new token. Press Esc/Ctrl + C to cancel.
[ "Folks, I removed all packages and installed everything possible again. It worked. Sorry. I had tryed a lot and this last one ocurred me later. Regards all.\n" ]
[ 0 ]
[]
[]
[ "authentication", "bigrquery", "google_bigquery", "r", "rstudio" ]
stackoverflow_0074677863_authentication_bigrquery_google_bigquery_r_rstudio.txt
Q: @Component always null in spring boot I have two classes which are annotated as @Component @Component public class ClientMapper { public Client convert(ClientEntity clientEntity) { Client client = new Client(); BeanUtils.copyProperties(clientEntity, client); return client; } public ClientEntity convert(Client client) { ClientEntity clientEntity = new ClientEntity(); BeanUtils.copyProperties(client, clientEntity); return clientEntity; } } @Component public class OrderMapper { public Order convert(OrderEntity orderEntity) { Order order = new Order(); BeanUtils.copyProperties(orderEntity, order); return order; } public OrderEntity convert(Order order) { OrderEntity orderEntity = new OrderEntity(); BeanUtils.copyProperties(order, orderEntity); return orderEntity; } } I injected them into different services @Service @AllArgsConstructor public class ClientServiceImpl implements ClientService { private final ClientMapper clientMapper; private final ClientRepository clientRepository; @Service @AllArgsConstructor public class OrderServiceImpl implements OrderService { private final OrderMapper orderMapper; private final OrderRepository orderRepository; private final OrderNumberRepository orderNumberRepository; But all time my mappers is null. I don't create new Object of them using new command. Also with my repository interfaces everything is fine, so my way to inject my comments(@AllArgsContrustor) works correct. Little note, I have tests classes where I used @InjectMocks on my services classes. Can it be that my error occupied because of this annotation? @ExtendWith(MockitoExtension.class) public class OrderServiceTest { @Mock private OrderRepository orderRepository; @InjectMocks private OrderServiceImpl orderService; A: You are using MockitoExtension, spring won't create component of OrderMapper. If you need actual implementation. Use @Spy annotation of MockitoExtension. @ExtendWith(MockitoExtension.class) public class OrderServiceTest { @Mock private OrderRepository orderRepository; @Spy private OrderMapper orderMapper = new OrderMapper(); // Note: new OrderMapper() is optional as you have No Argument Constructor @InjectMocks private OrderServiceImpl orderService; Or as a practice @Mock is always best way to go instead of @Spy incase of Unit test.
@Component always null in spring boot
I have two classes which are annotated as @Component @Component public class ClientMapper { public Client convert(ClientEntity clientEntity) { Client client = new Client(); BeanUtils.copyProperties(clientEntity, client); return client; } public ClientEntity convert(Client client) { ClientEntity clientEntity = new ClientEntity(); BeanUtils.copyProperties(client, clientEntity); return clientEntity; } } @Component public class OrderMapper { public Order convert(OrderEntity orderEntity) { Order order = new Order(); BeanUtils.copyProperties(orderEntity, order); return order; } public OrderEntity convert(Order order) { OrderEntity orderEntity = new OrderEntity(); BeanUtils.copyProperties(order, orderEntity); return orderEntity; } } I injected them into different services @Service @AllArgsConstructor public class ClientServiceImpl implements ClientService { private final ClientMapper clientMapper; private final ClientRepository clientRepository; @Service @AllArgsConstructor public class OrderServiceImpl implements OrderService { private final OrderMapper orderMapper; private final OrderRepository orderRepository; private final OrderNumberRepository orderNumberRepository; But all time my mappers is null. I don't create new Object of them using new command. Also with my repository interfaces everything is fine, so my way to inject my comments(@AllArgsContrustor) works correct. Little note, I have tests classes where I used @InjectMocks on my services classes. Can it be that my error occupied because of this annotation? @ExtendWith(MockitoExtension.class) public class OrderServiceTest { @Mock private OrderRepository orderRepository; @InjectMocks private OrderServiceImpl orderService;
[ "You are using MockitoExtension, spring won't create component of OrderMapper.\nIf you need actual implementation. Use @Spy annotation of MockitoExtension.\n@ExtendWith(MockitoExtension.class)\npublic class OrderServiceTest {\n @Mock\n private OrderRepository orderRepository;\n @Spy\n private OrderMapper orderMapper = new OrderMapper(); // Note: new OrderMapper() is optional as you have No Argument Constructor\n @InjectMocks\n private OrderServiceImpl orderService;\n\nOr as a practice @Mock is always best way to go instead of @Spy incase of Unit test.\n" ]
[ 0 ]
[]
[]
[ "code_injection", "java", "javabeans", "spring" ]
stackoverflow_0074678175_code_injection_java_javabeans_spring.txt
Q: How to run html file on localhost3000? I have all my .js files and html linked to my server file. but when I lunch localhost3000, I get "cannot get/" I tried anything I though could be helpful but couldn't fix the problem. Anyone knows how to fix it? I have this for my server side const express = require('express'); const app = express(); app.listen(3000, () => console.log('listening at port 3000!')); app.use(express.static('codefreeze.html')); and I have this for client side <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script src="codefreeze.js"></script> <link rel="stylesheet" href="codefreeze.css"> <link href = "https://fonts.googleapis.com/css?family=Schoolbell&v1" rel="stylesheet"> <title>DIARY</title> </head> <body onload="Name()"> <h1>HELLO!</h1> <p>Welcome <span id="name"></span></p> <p id="date"></p> <script> document.getElementById("date").innerHTML = DATE(); </script> <div id="user"> <label id="lbl1">Passage #1</label><br> <textarea id="psg1" rows="10" cols="30"></textarea><br> </div> <button id="save" onclick="save()">SAVE</button> <button id="add" onclick="add()">ADD</button> <button id="delete" onclick="del()">DELETE</button> </body> </html> I know something I'm doing is wrong but I cannot seem to find what. A: It looks like you are trying to serve the codefreeze.html file using the express.static() middleware, but this middleware is not being used correctly. The express.static() middleware is used to serve static files, such as images, CSS, and JavaScript files, from a specified directory. It does not serve HTML files directly, so you will need to use a different approach to serve the codefreeze.html file. To fix this problem, you can use the app.get() method to define a route that will serve the codefreeze.html file when a GET request is sent to the root URL (/). This method takes two arguments: the path of the route (in this case, /) and a callback function that will be called when the route is matched. Here's an example of how you can use the app.get() method to serve the codefreeze.html file: const express = require("express"); const app = express(); app.listen(3000, () => console.log("listening at port 3000!")); // Define a route that will serve the codefreeze.html file app.get("/", (request, response) => { // Use the response.sendFile() method to send the codefreeze.html file response.sendFile(__dirname + "/codefreeze.html"); }); A: app.get("/", (req, res) => { response.sendFile(*your file path*); }); This should work
How to run html file on localhost3000?
I have all my .js files and html linked to my server file. but when I lunch localhost3000, I get "cannot get/" I tried anything I though could be helpful but couldn't fix the problem. Anyone knows how to fix it? I have this for my server side const express = require('express'); const app = express(); app.listen(3000, () => console.log('listening at port 3000!')); app.use(express.static('codefreeze.html')); and I have this for client side <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script src="codefreeze.js"></script> <link rel="stylesheet" href="codefreeze.css"> <link href = "https://fonts.googleapis.com/css?family=Schoolbell&v1" rel="stylesheet"> <title>DIARY</title> </head> <body onload="Name()"> <h1>HELLO!</h1> <p>Welcome <span id="name"></span></p> <p id="date"></p> <script> document.getElementById("date").innerHTML = DATE(); </script> <div id="user"> <label id="lbl1">Passage #1</label><br> <textarea id="psg1" rows="10" cols="30"></textarea><br> </div> <button id="save" onclick="save()">SAVE</button> <button id="add" onclick="add()">ADD</button> <button id="delete" onclick="del()">DELETE</button> </body> </html> I know something I'm doing is wrong but I cannot seem to find what.
[ "It looks like you are trying to serve the codefreeze.html file using the express.static() middleware, but this middleware is not being used correctly.\nThe express.static() middleware is used to serve static files, such as images, CSS, and JavaScript files, from a specified directory. It does not serve HTML files directly, so you will need to use a different approach to serve the codefreeze.html file.\nTo fix this problem, you can use the app.get() method to define a route that will serve the codefreeze.html file when a GET request is sent to the root URL (/). This method takes two arguments: the path of the route (in this case, /) and a callback function that will be called when the route is matched.\nHere's an example of how you can use the app.get() method to serve the codefreeze.html file:\nconst express = require(\"express\");\nconst app = express();\n\napp.listen(3000, () => console.log(\"listening at port 3000!\"));\n\n// Define a route that will serve the codefreeze.html file\napp.get(\"/\", (request, response) => {\n // Use the response.sendFile() method to send the codefreeze.html file\n response.sendFile(__dirname + \"/codefreeze.html\");\n});\n\n", "app.get(\"/\", (req, res) => {\n response.sendFile(*your file path*);\n});\n\nThis should work\n" ]
[ 0, 0 ]
[]
[]
[ "html", "javascript" ]
stackoverflow_0074678092_html_javascript.txt
Q: HTML Img tag and srcset attribute I am a bit confused about the use of srcset attribute in the HTML img tag. I read several tutorials on the Web but I think stuff doesn't work as these tutorial report. First of all, let's start with an easy example: <img src="assets/img/software-developer.jpeg" alt="Some Stuff" srcset="assets/img/software-developer-300.jpeg 300w, assets/img/software-developer.jpeg 450w"> I have two images: assets/img/software-developer.jpeg 450x450 pixels assets/img/software-developer-300.jpeg 300x300 pixels Now I use Chrome Developer Tools for tests, but whatever screen size I select I always see that assets/img/software-developer.jpeg is downloaded. I can see it in the Developer Tools Properties tab looking at the property currentSrc. Can anyone help me to understand why? I want that: for screen with size >= 450px then assets/img/software-developer.jpeg is downloaded for screen with size < 450px then assets/img/software-developer-300.jpeg is downloaded Another thing that it's not clear to me is: what happens with screen size < 300px? If the image with lowest width is assets/img/software-developer-300.jpeg that is 300x300 pixels, how I can modify the code to let it resize (become smaller in this case) to fit the viewport? For example, Developer Tools by defaul has Galaxy Fold device that has a width of 280 pixel. In this case, both the images don't fit the screen size: how I can define my srcset to let it resize in this situation? Web is full of information about this stuff, at a first read things are a bit confusing so I decided to start with small tests. The first tests I decided to work on is with srcset and check if the image downloaded is the one expected. It seems the tag doesn't work as expected. I know that I am missing something, hoping someone here can help to clarify. A: I think you are missing the sizes tag in there. sizes defines a set of media conditions (e.g. screen widths) and indicates what image size would be best to choose, when certain media conditions are true. The correct way to write the code to achieve would be <img src="assets/img/software-developer.jpeg" alt="Some Stuff" sizes="(max-width: 449px) 300px, 450px" srcset="assets/img/software-developer-300.jpeg 300w, assets/img/software-developer.jpeg 450w"> You can read more about it here https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#how_do_you_create_responsive_images A: I figure out the answer by myself. First of all, the srcset tag alone doesn't make too much sense, it must be always used in conjuction with sizes. The srcset tells the browser which imahes are available, for example: srcset="assets/img/software-developer-300.jpeg 300w, assets/img/software-developer.jpeg 450w" Basically this attributes tells to the browser: Hey there are two images you can use: assets/img/software-developer-300.jpeg 300 pixel wide assets/img/software-developer.jpeg 450 pixel wide Now you have to tell the browser to use the former for screen < 450 px and the latter for screen >= 450. You can do this with the attribute sizes: srcset="assets/img/software-developer-300.jpeg 300w, assets/img/software-developer.jpeg 450w" sizes="(max-width: 449px) 300px, (min-width: 450px) 450px" Basically, for screen up to 449px you can use the 300px image version, for screen starting from 450px you caan use the 450px version. The problem is that there are phone with screen size less than 300px (i.e. Gaalaxy Fold is 280px wide). On these screen the image is cropped and to avoid this you must tell the browser that if the screen size is less than 299px the image must be resized to 100vw. Now in my case, 100vw doesn't work properly so I just reduced it to 75vw.
HTML Img tag and srcset attribute
I am a bit confused about the use of srcset attribute in the HTML img tag. I read several tutorials on the Web but I think stuff doesn't work as these tutorial report. First of all, let's start with an easy example: <img src="assets/img/software-developer.jpeg" alt="Some Stuff" srcset="assets/img/software-developer-300.jpeg 300w, assets/img/software-developer.jpeg 450w"> I have two images: assets/img/software-developer.jpeg 450x450 pixels assets/img/software-developer-300.jpeg 300x300 pixels Now I use Chrome Developer Tools for tests, but whatever screen size I select I always see that assets/img/software-developer.jpeg is downloaded. I can see it in the Developer Tools Properties tab looking at the property currentSrc. Can anyone help me to understand why? I want that: for screen with size >= 450px then assets/img/software-developer.jpeg is downloaded for screen with size < 450px then assets/img/software-developer-300.jpeg is downloaded Another thing that it's not clear to me is: what happens with screen size < 300px? If the image with lowest width is assets/img/software-developer-300.jpeg that is 300x300 pixels, how I can modify the code to let it resize (become smaller in this case) to fit the viewport? For example, Developer Tools by defaul has Galaxy Fold device that has a width of 280 pixel. In this case, both the images don't fit the screen size: how I can define my srcset to let it resize in this situation? Web is full of information about this stuff, at a first read things are a bit confusing so I decided to start with small tests. The first tests I decided to work on is with srcset and check if the image downloaded is the one expected. It seems the tag doesn't work as expected. I know that I am missing something, hoping someone here can help to clarify.
[ "I think you are missing the sizes tag in there.\n\nsizes defines a set of media conditions (e.g. screen widths) and indicates what image size would be best to choose, when certain media conditions are true.\n\nThe correct way to write the code to achieve would be\n<img src=\"assets/img/software-developer.jpeg\" alt=\"Some Stuff\" sizes=\"(max-width: 449px) 300px, 450px\" srcset=\"assets/img/software-developer-300.jpeg 300w, assets/img/software-developer.jpeg 450w\">\n\nYou can read more about it here\nhttps://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#how_do_you_create_responsive_images\n", "I figure out the answer by myself. First of all, the srcset tag alone doesn't make too much sense, it must be always used in conjuction with sizes.\nThe srcset tells the browser which imahes are available, for example:\nsrcset=\"assets/img/software-developer-300.jpeg 300w, assets/img/software-developer.jpeg 450w\"\n\nBasically this attributes tells to the browser:\nHey there are two images you can use:\n\nassets/img/software-developer-300.jpeg 300 pixel wide\nassets/img/software-developer.jpeg 450 pixel wide\n\nNow you have to tell the browser to use the former for screen < 450 px and the latter for screen >= 450. You can do this with the attribute sizes:\nsrcset=\"assets/img/software-developer-300.jpeg 300w, assets/img/software-developer.jpeg 450w\" sizes=\"(max-width: 449px) 300px, (min-width: 450px) 450px\"\n\nBasically, for screen up to 449px you can use the 300px image version, for screen starting from 450px you caan use the 450px version. The problem is that there are phone with screen size less than 300px (i.e. Gaalaxy Fold is 280px wide). On these screen the image is cropped and to avoid this you must tell the browser that if the screen size is less than 299px the image must be resized to 100vw. Now in my case, 100vw doesn't work properly so I just reduced it to 75vw.\n" ]
[ 1, 0 ]
[]
[]
[ "css", "html" ]
stackoverflow_0074669259_css_html.txt
Q: Get the Last Inserted Id Using Laravel Eloquent I'm currently using the below code to insert data in a table: <?php public function saveDetailsCompany() { $post = Input::All(); $data = new Company; $data->nombre = $post['name']; $data->direccion = $post['address']; $data->telefono = $post['phone']; $data->email = $post['email']; $data->giro = $post['type']; $data->fecha_registro = date("Y-m-d H:i:s"); $data->fecha_modificacion = date("Y-m-d H:i:s"); if ($data->save()) { return Response::json(array('success' => true), 200); } } I want to return the last ID inserted but I don't know how to get it. Kind regards! A: After save, $data->id should be the last id inserted. $data->save(); $data->id; Can be used like this. return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200); For updated laravel version try this return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200); A: xdazz is right in this case, but for the benefit of future visitors who might be using DB::statement or DB::insert, there is another way: DB::getPdo()->lastInsertId(); A: If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID: $id = DB::table('users')->insertGetId([ 'email' => 'john@example.com', 'votes' => 0 ]); Refer: https://laravel.com/docs/5.1/queries#inserts A: For anyone who also likes how Jeffrey Way uses Model::create() in his Laracasts 5 tutorials, where he just sends the Request straight into the database without explicitly setting each field in the controller, and using the model's $fillable for mass assignment (very important, for anyone new and using this way): I read a lot of people using insertGetId() but unfortunately this does not respect the $fillable whitelist so you'll get errors with it trying to insert _token and anything that isn't a field in the database, end up setting things you want to filter, etc. That bummed me out, because I want to use mass assignment and overall write less code when possible. Fortunately Eloquent's create method just wraps the save method (what @xdazz cited above), so you can still pull the last created ID... public function store() { $input = Request::all(); $id = Company::create($input)->id; return redirect('company/'.$id); } A: **** For Laravel **** Firstly create an object, Then set attributes value for that object, Then save the object record, and then get the last inserted id. such as $user = new User(); $user->name = 'John'; $user->save(); // Now Getting The Last inserted id $insertedId = $user->id; echo $insertedId ; A: There are several ways to get the last inserted id. All are based on what method do you used when inserting. In your case you can get last Id like the following: $data->save(); $data->id; For others who need to know how can they get last inserted id if they use other insert methods here is how: Using create() method $book = Book::create(['name'=>'Laravel Warrior']); $lastId = $book->id; Using insertGetId() $id = DB::table('books')->insertGetId( ['name' => 'Laravel warrior'] ); $lastId = $id; Using lastInsertId() method $lastId = DB::getPdo()->lastInsertId(); Reference https://easycodesolution.com/2020/08/22/last-inserted-id-in-laravel/ A: In laravel 5: you can do this: use App\Http\Requests\UserStoreRequest; class UserController extends Controller { private $user; public function __construct( User $user ) { $this->user = $user; } public function store( UserStoreRequest $request ) { $user= $this->user->create([ 'name' => $request['name'], 'email' => $request['email'], 'password' => Hash::make($request['password']) ]); $lastInsertedId= $user->id; } } A: This worked for me in laravel 4.2 $id = User::insertGetId([ 'username' => Input::get('username'), 'password' => Hash::make('password'), 'active' => 0 ]); A: Here's an example: public static function saveTutorial(){ $data = Input::all(); $Tut = new Tutorial; $Tut->title = $data['title']; $Tut->tutorial = $data['tutorial']; $Tut->save(); $LastInsertId = $Tut->id; return Response::json(array('success' => true,'last_id'=>$LastInsertId), 200); } A: Use insertGetId to insert and get inserted id at the same time From doc If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID: By Model $id = Model::insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]); By DB $id = DB::table('users')->insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]); For more details : https://laravel.com/docs/5.5/queries#inserts A: For insert() Example: $data1 = array( 'company_id' => $company_id, 'branch_id' => $branch_id ); $insert_id = CreditVoucher::insert($data1); $id = DB::getPdo()->lastInsertId(); dd($id); A: Here is how we can get last inserted id in Laravel 4 public function store() { $input = Input::all(); $validation = Validator::make($input, user::$rules); if ($validation->passes()) { $user= $this->user->create(array( 'name' => Input::get('name'), 'email' => Input::get('email'), 'password' => Hash::make(Input::get('password')), )); $lastInsertedId= $user->id; //get last inserted record's user id value $userId= array('user_id'=>$lastInsertedId); //put this value equal to datatable column name where it will be saved $user->update($userId); //update newly created record by storing the value of last inserted id return Redirect::route('users.index'); } return Redirect::route('users.create')->withInput()->withErrors($validation)->with('message', 'There were validation errors.'); } A: Although this question is a bit dated. My quick and dirty solution would look like this: $last_entry = Model::latest()->first(); But I guess it's vulnerable to race conditions on highly frequented databases. A: After saving model, the initialized instance has the id: $report = new Report(); $report->user_id = $request->user_id; $report->patient_id = $request->patient_id; $report->diseases_id = $request->modality; $isReportCreated = $report->save(); return $report->id; // this will return the saved report id A: You can easily fetch last inserted record Id $user = User::create($userData); $lastId = $user->value('id'); It's an awesome trick to fetch Id from the last inserted record in the DB. A: After $data->save() $data->id will give you the inserted id, Note: If your autoincrement column name is sno then you should use $data->sno and not $data->id A: After saving a record in database, you can access id by $data->id return Response::json(['success' => true, 'last_insert_id' => $data->id], 200) A: In Laravel 5.2 i would make it as clean as possible: public function saveContact(Request $request, Contact $contact) { $create = $contact->create($request->all()); return response()->json($create->id, 201); } A: For Laravel, If you insert a new record and call $data->save() this function executes an INSERT query and returns the primary key value (i.e. id by default). You can use following code: if($data->save()) { return Response::json(array('status' => 1, 'primary_id'=>$data->id), 200); } A: You can do this: $result=app('db')->insert("INSERT INTO table..."); $lastInsertId=app('db')->getPdo()->lastInsertId(); A: $objPost = new Post; $objPost->title = 'Title'; $objPost->description = 'Description'; $objPost->save(); $recId = $objPost->id; // If Id in table column name if other then id then user the other column name return Response::json(['success' => true,'id' => $recId], 200); A: For get last inserted id in database You can use $data = new YourModelName; $data->name = 'Some Value'; $data->email = 'abc@mail.com'; $data->save(); $lastInsertedId = $data->id; here $lastInsertedId will gives you last inserted auto increment id. A: The shortest way is probably a call of the refresh() on the model: public function create(array $data): MyModel { $myModel = new MyModel($dataArray); $myModel->saveOrFail(); return $myModel->refresh(); } A: You can also try like this: public function storeAndLastInrestedId() { $data = new ModelName(); $data->title = $request->title; $data->save(); $last_insert_id = $data->id; return $last_insert_id; } A: Here it is how it worked for me, family_id is the primary key with auto increment I am using Laravel7 public function store(Request $request){ $family = new Family(); $family->family_name = $request->get('FamilyName'); $family->family_no = $request->get('FamilyNo'); $family->save(); //family_id is the primary key and auto increment return redirect('/family/detail/' . $family->family_id); } Also in the Model Family file which extends Model, should have the increment set to true otherwise the above $family-->family_id will return empty public $incrementing = true; A: After Saving $data->save(). all data is pushed inside $data. As this is an object and the current row is just saved recently inside $data. so last insertId will be found inside $data->id. Response code will be: return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200); A: Using Eloquent Model $user = new Report(); $user->email= 'johndoe@example.com'; $user->save(); $lastId = $user->id; Using Query Builder $lastId = DB::table('reports')->insertGetId(['email' => 'johndoe@example.com']); A: You can get last inserted id with same object you call save method; $data->save(); $inserted_id = $data->id; So you can simply write: if ($data->save()) { return Response::json(array('success' => true,'inserted_id'=>$data->id), 200); } A: To get the last inserted ID using Laravel Eloquent, you can use the ->id property on the model instance after calling the save() method. This property will return the ID of the last inserted record. Here's an example of how you can use this property to get the last inserted ID: // Create a new model instance $model = new Model(); // Set the model attributes $model->attribute1 = "value1"; $model->attribute2 = "value2"; // Save the model to the database $model->save(); // Get the last inserted ID $lastInsertedId = $model->id; Alternatively, you can use the insertGetId() method on the model's query builder to insert a new record and return the ID in one step. Here's an example of how you can use this method: // Insert a new record and get the ID $lastInsertedId = Model::insertGetId([ "attribute1" => "value1", "attribute2" => "value2", ]); Keep in mind that the insertGetId() method requires that the table you are inserting into has an auto-incrementing primary key. Additionally, this method is only available in Laravel versions 5.1 and higher. #gpt-chat
Get the Last Inserted Id Using Laravel Eloquent
I'm currently using the below code to insert data in a table: <?php public function saveDetailsCompany() { $post = Input::All(); $data = new Company; $data->nombre = $post['name']; $data->direccion = $post['address']; $data->telefono = $post['phone']; $data->email = $post['email']; $data->giro = $post['type']; $data->fecha_registro = date("Y-m-d H:i:s"); $data->fecha_modificacion = date("Y-m-d H:i:s"); if ($data->save()) { return Response::json(array('success' => true), 200); } } I want to return the last ID inserted but I don't know how to get it. Kind regards!
[ "After save, $data->id should be the last id inserted.\n$data->save();\n$data->id;\n\nCan be used like this. \nreturn Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);\n\nFor updated laravel version try this\nreturn response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);\n\n", "xdazz is right in this case, but for the benefit of future visitors who might be using DB::statement or DB::insert, there is another way:\nDB::getPdo()->lastInsertId();\n\n", "If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:\n$id = DB::table('users')->insertGetId([\n 'email' => 'john@example.com',\n 'votes' => 0\n]);\n\nRefer: https://laravel.com/docs/5.1/queries#inserts\n", "For anyone who also likes how Jeffrey Way uses Model::create() in his Laracasts 5 tutorials, where he just sends the Request straight into the database without explicitly setting each field in the controller, and using the model's $fillable for mass assignment (very important, for anyone new and using this way): I read a lot of people using insertGetId() but unfortunately this does not respect the $fillable whitelist so you'll get errors with it trying to insert _token and anything that isn't a field in the database, end up setting things you want to filter, etc. That bummed me out, because I want to use mass assignment and overall write less code when possible. Fortunately Eloquent's create method just wraps the save method (what @xdazz cited above), so you can still pull the last created ID...\npublic function store() {\n\n $input = Request::all();\n $id = Company::create($input)->id;\n\n return redirect('company/'.$id);\n}\n\n", "**** For Laravel ****\nFirstly create an object, Then set attributes value for that object, Then save the object record, and then get the last inserted id. such as\n$user = new User(); \n\n$user->name = 'John'; \n\n$user->save();\n\n// Now Getting The Last inserted id\n$insertedId = $user->id;\n\necho $insertedId ;\n\n", "There are several ways to get the last inserted id. All are based on what method do you used when inserting. In your case you can get last Id like the following:\n$data->save();\n$data->id;\n\nFor others who need to know how can they get last inserted id if they use other insert methods here is how:\n\nUsing create() method\n$book = Book::create(['name'=>'Laravel Warrior']);\n$lastId = $book->id;\n\nUsing insertGetId()\n$id = DB::table('books')->insertGetId( ['name' => 'Laravel warrior'] ); $lastId = $id;\n\nUsing lastInsertId() method\n$lastId = DB::getPdo()->lastInsertId();\n\n\nReference https://easycodesolution.com/2020/08/22/last-inserted-id-in-laravel/\n", "In laravel 5: you can do this: \nuse App\\Http\\Requests\\UserStoreRequest;\nclass UserController extends Controller {\n private $user;\n public function __construct( User $user )\n {\n $this->user = $user;\n }\n public function store( UserStoreRequest $request )\n {\n $user= $this->user->create([\n 'name' => $request['name'],\n 'email' => $request['email'],\n 'password' => Hash::make($request['password'])\n ]);\n $lastInsertedId= $user->id;\n }\n}\n\n", "This worked for me in laravel 4.2\n$id = User::insertGetId([\n 'username' => Input::get('username'),\n 'password' => Hash::make('password'),\n 'active' => 0\n]);\n\n", "Here's an example:\npublic static function saveTutorial(){\n\n $data = Input::all();\n\n $Tut = new Tutorial;\n $Tut->title = $data['title'];\n $Tut->tutorial = $data['tutorial']; \n $Tut->save();\n $LastInsertId = $Tut->id;\n\n return Response::json(array('success' => true,'last_id'=>$LastInsertId), 200);\n}\n\n", "Use insertGetId to insert and get inserted id at the same time \nFrom doc\n\nIf the table has an auto-incrementing id, use the insertGetId method\n to insert a record and then retrieve the ID:\n\nBy Model\n$id = Model::insertGetId([\"name\"=>\"Niklesh\",\"email\"=>\"myemail@gmail.com\"]);\n\nBy DB\n$id = DB::table('users')->insertGetId([\"name\"=>\"Niklesh\",\"email\"=>\"myemail@gmail.com\"]);\n\nFor more details : https://laravel.com/docs/5.5/queries#inserts\n", "For insert()\nExample:\n$data1 = array(\n 'company_id' => $company_id,\n 'branch_id' => $branch_id\n );\n\n$insert_id = CreditVoucher::insert($data1);\n$id = DB::getPdo()->lastInsertId();\ndd($id);\n\n", "Here is how we can get last inserted id in Laravel 4 \npublic function store()\n{\n $input = Input::all();\n\n $validation = Validator::make($input, user::$rules);\n\n if ($validation->passes())\n {\n\n $user= $this->user->create(array(\n 'name' => Input::get('name'),\n 'email' => Input::get('email'),\n 'password' => Hash::make(Input::get('password')),\n ));\n $lastInsertedId= $user->id; //get last inserted record's user id value\n $userId= array('user_id'=>$lastInsertedId); //put this value equal to datatable column name where it will be saved\n $user->update($userId); //update newly created record by storing the value of last inserted id\n return Redirect::route('users.index');\n }\n return Redirect::route('users.create')->withInput()->withErrors($validation)->with('message', 'There were validation errors.');\n }\n\n", "Although this question is a bit dated. My quick and dirty solution would look like this:\n$last_entry = Model::latest()->first();\n\nBut I guess it's vulnerable to race conditions on highly frequented databases.\n", "After saving model, the initialized instance has the id:\n$report = new Report();\n$report->user_id = $request->user_id;\n$report->patient_id = $request->patient_id;\n$report->diseases_id = $request->modality;\n$isReportCreated = $report->save();\nreturn $report->id; // this will return the saved report id\n\n", "You can easily fetch last inserted record Id \n$user = User::create($userData);\n$lastId = $user->value('id');\n\nIt's an awesome trick to fetch Id from the last inserted record in the DB.\n", "After\n$data->save()\n\n$data->id will give you the inserted id,\nNote: If your autoincrement column name is sno then you should use\n$data->sno and not $data->id\n", "After saving a record in database, you can access id by $data->id\nreturn Response::json(['success' => true, 'last_insert_id' => $data->id], 200)\n\n", "In Laravel 5.2 i would make it as clean as possible:\npublic function saveContact(Request $request, Contact $contact)\n{\n $create = $contact->create($request->all());\n return response()->json($create->id, 201);\n}\n\n", "For Laravel, If you insert a new record and call $data->save() this function executes an INSERT query and returns the primary key value (i.e. id by default).\nYou can use following code:\nif($data->save()) {\n return Response::json(array('status' => 1, 'primary_id'=>$data->id), 200);\n}\n\n", "You can do this:\n$result=app('db')->insert(\"INSERT INTO table...\");\n\n$lastInsertId=app('db')->getPdo()->lastInsertId();\n\n", "$objPost = new Post;\n$objPost->title = 'Title';\n$objPost->description = 'Description'; \n$objPost->save();\n$recId = $objPost->id; // If Id in table column name if other then id then user the other column name\n\nreturn Response::json(['success' => true,'id' => $recId], 200);\n\n", "For get last inserted id in database\nYou can use\n$data = new YourModelName;\n$data->name = 'Some Value';\n$data->email = 'abc@mail.com';\n$data->save();\n$lastInsertedId = $data->id;\n\nhere $lastInsertedId will gives you last inserted auto increment id.\n", "The shortest way is probably a call of the refresh() on the model:\npublic function create(array $data): MyModel\n{\n $myModel = new MyModel($dataArray);\n $myModel->saveOrFail();\n return $myModel->refresh();\n}\n\n", "You can also try like this:\npublic function storeAndLastInrestedId() {\n $data = new ModelName();\n $data->title = $request->title;\n $data->save();\n\n $last_insert_id = $data->id;\n return $last_insert_id;\n}\n\n", "Here it is how it worked for me, family_id is the primary key with auto increment I am using Laravel7\n public function store(Request $request){\n $family = new Family();\n $family->family_name = $request->get('FamilyName');\n $family->family_no = $request->get('FamilyNo');\n $family->save();\n //family_id is the primary key and auto increment\n return redirect('/family/detail/' . $family->family_id);\n }\n\nAlso in the Model Family file which extends Model, should have the increment set to true otherwise the above $family-->family_id will return empty\n public $incrementing = true;\n \n\n", "After Saving $data->save(). all data is pushed inside $data. As this is an object and the current row is just saved recently inside $data. so last insertId will be found inside $data->id. \nResponse code will be:\nreturn Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);\n\n", "Using Eloquent Model \n$user = new Report(); \n$user->email= 'johndoe@example.com'; \n$user->save();\n$lastId = $user->id;\n\nUsing Query Builder\n$lastId = DB::table('reports')->insertGetId(['email' => 'johndoe@example.com']);\n\n", "You can get last inserted id with same object you call save method; \n$data->save();\n$inserted_id = $data->id;\n\nSo you can simply write: \nif ($data->save()) {\n return Response::json(array('success' => true,'inserted_id'=>$data->id), 200);\n}\n\n", "To get the last inserted ID using Laravel Eloquent, you can use the ->id property on the model instance after calling the save() method. This property will return the ID of the last inserted record.\nHere's an example of how you can use this property to get the last inserted ID:\n// Create a new model instance\n$model = new Model();\n\n// Set the model attributes\n$model->attribute1 = \"value1\";\n$model->attribute2 = \"value2\";\n\n// Save the model to the database\n$model->save();\n\n// Get the last inserted ID\n$lastInsertedId = $model->id;\n\nAlternatively, you can use the insertGetId() method on the model's query builder to insert a new record and return the ID in one step. Here's an example of how you can use this method:\n// Insert a new record and get the ID\n$lastInsertedId = Model::insertGetId([\n \"attribute1\" => \"value1\",\n \"attribute2\" => \"value2\",\n]);\n\nKeep in mind that the insertGetId() method requires that the table you are inserting into has an auto-incrementing primary key. Additionally, this method is only available in Laravel versions 5.1 and higher.\n#gpt-chat\n" ]
[ 539, 168, 77, 71, 54, 24, 18, 18, 16, 13, 12, 11, 8, 7, 6, 4, 3, 3, 3, 3, 2, 1, 1, 1, 1, 0, 0, 0, 0 ]
[ "public function store( UserStoreRequest $request ) {\n $input = $request->all();\n $user = User::create($input);\n $userId=$user->id \n}\n\n", "Using Eloquent Model \nuse App\\Company;\n\npublic function saveDetailsCompany(Request $request)\n{\n\n$createcompany=Company::create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);\n\n// Last Inserted Row ID\n\necho $createcompany->id;\n\n}\n\nUsing Query Builder\n$createcompany=DB::table('company')->create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);\n\necho $createcompany->id;\n\nFor more methods to get Last Inserted Row id in Laravel : http://phpnotebook.com/95-laravel/127-3-methods-to-get-last-inserted-row-id-in-laravel\n", "You can use $this constructor variable to achieve \"Last Inserted Id Using Laravel Eloquent\" (without adding any extra column) in current function or controller.\npublic function store(Request $request){\n $request->validate([\n 'title' => 'required|max:255',\n 'desc' => 'required|max:5000'\n ]);\n\n $this->project = Project::create([\n 'name' => $request->title,\n 'description' => $request->desc,\n ]);\n\n dd($this->project->id); //This is your current/latest project id\n $request->session()->flash('project_added','Project added successfully.');\n return redirect()->back();\n\n}\n\n", "Optional method will be:\n$lastID = DB::table('EXAMPLE-TABLE')\n ->orderBy('id', 'desc')\n ->first();\n\n$lastId = $lastProduct->id;\n\n\nSource from Laravel 5.8 version\n" ]
[ -1, -1, -1, -2 ]
[ "database", "eloquent", "laravel", "php" ]
stackoverflow_0021084833_database_eloquent_laravel_php.txt
Q: Use data populated by useEffect in conditional useSWR I'm trying to resolve this issue, and I'm almost there. I'm getting the correct data from the API, and it's updating when it should, but on initial load useSWR is hitting the API with all null data. The data come from useContext, and are set in a useEffect hook in a parent of the component that calls useSWR. I guess what's happening is that the since useEffect isn't called until after initial hydration, the component with useSWR is being rendered before it has data. But if the context setter isn't wrapped in a useEffect, I get Warning: Cannot update a component (`ContestProvider`) while rendering a different component (`PageLandingPage`). To locate the bad setState() call inside `PageLandingPage`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render and it's stuck in an infinite loop. I could probably stop this by putting some checks in the fetcher, but that seems like a hack to me. The useSWR documentation addresses the case of fetching data server side and making it available to multiple components right in the Getting Started section, but what's the correct way to get data from the client that needs to be used in multiple components, including ones that want to fetch data from the server based on the client data? EDIT: Since originally asking the question, I've discovered conditional fetching, and the third option there seems nearly a perfect fit, but I'm using a complex key to a custom fetcher, and the data for the key aren't coming from another useSWR call, as in the example — they're coming from the useContext which has the unfortunate difference that, unlike the example, the data are null instead of undefined, so it won't throw. How can I use this conditionality with data coming in from the useContext? Here's the app hierarchy: <MyApp> <ContestEntryPage> <ContestProvider> // context provider <PageLandingPage> // sets the context <Section> <GridColumn> <DatoContent> <ContestPoints> // calls useSWR with data from the context Here's the useSWR call: // /components/ContestPoints.js const fetcher = async ({pageId, contestId, clientId}) => { const res = await fetch(`/api/getpoints?pageId=${pageId}&clientId=${clientId}&contestId=${contestId}`); if (!res.ok) { const error = new Error('A problem occured getting contest points'); error.info = await res.json(); error.status = res.status; throw error; } return res.json(); } const ContestPoints = () => { const { contestState } = useContest(); // XXX should be conditional on the `contestState` parameters const { data: points, error } = useSWR({ pageId: contestState.pageId, contestId: contestState.contestId, clientId: contestState.clientId }, fetcher); if (error) { logger.warn(error, `Problem getting contest points: ${error.status}: ${error.info}`); } return ( <p>{points?.points || 'Loading...'}</p> ) } export default ContestPoints It seems like finding a way to make that do the conditional fetching is likely best, but in case it's more elegant to leave the useSWR call as is, and address this farther up the chain, here are the other relevant pieces of code. The context is being set based on information in localStorage: // /components/PageLandingPage.js import { useContest } from '../utils/context/contest'; const PageLandingPage = ({ data }) => { const { dispatchContest } = useContest(); // wrapper around useContext which uses useReducer useEffect(() => { // Don't waste the time if we're not a contest page if (!data?.contestPage?.id) return; const storedCodes = getItem('myRefCodes', 'local'); //utility function to retrieve from local storage const refCodes = storedCodes ? JSON.parse(storedCodes)?.refCodes : []; const registration = refCodes .map((code) => { const [ contestId, clientId ] = hashids.decode(code); return { contestId: contestId, clientId: clientId } }) .find((reg) => reg.contestId && reg.clientId) dispatchContest({ payload: { pageId: data.contestPage.id, contestId: registration.contestId, clientId: registration.clientId, registrationUrl: landingPage?.registrationPage?.slug || '' }, type: 'update' }) }, [data, dispatchContest]) ... And the context wrapper is initialising with null state: const initialState = { contestId: null, clientId: null }; const ContestContext = createContext(initialState); function ContestProvider({ children }) { const [contestState, dispatchContest] = useReducer((contestState, action) => { return { ...contestState, ...action.payload } }, initialState); return ( <ContestContext.Provider value={{ contestState, dispatchContest }}> {children} </ContestContext.Provider> ); } function useContest() { const context = useContext(ContestContext); if (context === undefined) { throw new Error('useContest was used outside of its provider'); } return context; } export { ContestProvider, useContest } A: I'm not sure it's the best solution, but I ended up resolving this by using the first example in the documentation, using null and a new field in the context: const { data: points, error } = useSWR(contestState?.isSet ? { pageId: contestState.pageId, contestId: contestState.contestId, clientId: contestState.clientId } : null, fetcher); and the contestState.isSet gets set in the context: const initialState = { isSet: false, contestId: null, clientId: null }; and update it when all the other fields get set: dispatchContest({ payload: { isSet: true, pageId: data.contestPage.id, contestId: registration.contestId, clientId: registration.clientId, registrationUrl: landingPage?.registrationPage?.slug || '' }, type: 'update' })
Use data populated by useEffect in conditional useSWR
I'm trying to resolve this issue, and I'm almost there. I'm getting the correct data from the API, and it's updating when it should, but on initial load useSWR is hitting the API with all null data. The data come from useContext, and are set in a useEffect hook in a parent of the component that calls useSWR. I guess what's happening is that the since useEffect isn't called until after initial hydration, the component with useSWR is being rendered before it has data. But if the context setter isn't wrapped in a useEffect, I get Warning: Cannot update a component (`ContestProvider`) while rendering a different component (`PageLandingPage`). To locate the bad setState() call inside `PageLandingPage`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render and it's stuck in an infinite loop. I could probably stop this by putting some checks in the fetcher, but that seems like a hack to me. The useSWR documentation addresses the case of fetching data server side and making it available to multiple components right in the Getting Started section, but what's the correct way to get data from the client that needs to be used in multiple components, including ones that want to fetch data from the server based on the client data? EDIT: Since originally asking the question, I've discovered conditional fetching, and the third option there seems nearly a perfect fit, but I'm using a complex key to a custom fetcher, and the data for the key aren't coming from another useSWR call, as in the example — they're coming from the useContext which has the unfortunate difference that, unlike the example, the data are null instead of undefined, so it won't throw. How can I use this conditionality with data coming in from the useContext? Here's the app hierarchy: <MyApp> <ContestEntryPage> <ContestProvider> // context provider <PageLandingPage> // sets the context <Section> <GridColumn> <DatoContent> <ContestPoints> // calls useSWR with data from the context Here's the useSWR call: // /components/ContestPoints.js const fetcher = async ({pageId, contestId, clientId}) => { const res = await fetch(`/api/getpoints?pageId=${pageId}&clientId=${clientId}&contestId=${contestId}`); if (!res.ok) { const error = new Error('A problem occured getting contest points'); error.info = await res.json(); error.status = res.status; throw error; } return res.json(); } const ContestPoints = () => { const { contestState } = useContest(); // XXX should be conditional on the `contestState` parameters const { data: points, error } = useSWR({ pageId: contestState.pageId, contestId: contestState.contestId, clientId: contestState.clientId }, fetcher); if (error) { logger.warn(error, `Problem getting contest points: ${error.status}: ${error.info}`); } return ( <p>{points?.points || 'Loading...'}</p> ) } export default ContestPoints It seems like finding a way to make that do the conditional fetching is likely best, but in case it's more elegant to leave the useSWR call as is, and address this farther up the chain, here are the other relevant pieces of code. The context is being set based on information in localStorage: // /components/PageLandingPage.js import { useContest } from '../utils/context/contest'; const PageLandingPage = ({ data }) => { const { dispatchContest } = useContest(); // wrapper around useContext which uses useReducer useEffect(() => { // Don't waste the time if we're not a contest page if (!data?.contestPage?.id) return; const storedCodes = getItem('myRefCodes', 'local'); //utility function to retrieve from local storage const refCodes = storedCodes ? JSON.parse(storedCodes)?.refCodes : []; const registration = refCodes .map((code) => { const [ contestId, clientId ] = hashids.decode(code); return { contestId: contestId, clientId: clientId } }) .find((reg) => reg.contestId && reg.clientId) dispatchContest({ payload: { pageId: data.contestPage.id, contestId: registration.contestId, clientId: registration.clientId, registrationUrl: landingPage?.registrationPage?.slug || '' }, type: 'update' }) }, [data, dispatchContest]) ... And the context wrapper is initialising with null state: const initialState = { contestId: null, clientId: null }; const ContestContext = createContext(initialState); function ContestProvider({ children }) { const [contestState, dispatchContest] = useReducer((contestState, action) => { return { ...contestState, ...action.payload } }, initialState); return ( <ContestContext.Provider value={{ contestState, dispatchContest }}> {children} </ContestContext.Provider> ); } function useContest() { const context = useContext(ContestContext); if (context === undefined) { throw new Error('useContest was used outside of its provider'); } return context; } export { ContestProvider, useContest }
[ "I'm not sure it's the best solution, but I ended up resolving this by using the first example in the documentation, using null and a new field in the context:\nconst { data: points, error } = useSWR(contestState?.isSet ? {\n pageId: contestState.pageId,\n contestId: contestState.contestId,\n clientId: contestState.clientId\n } : null, fetcher);\n\nand the contestState.isSet gets set in the context:\nconst initialState = { \n isSet: false,\n contestId: null,\n clientId: null\n};\n\nand update it when all the other fields get set:\ndispatchContest({\n payload: {\n isSet: true,\n pageId: data.contestPage.id,\n contestId: registration.contestId,\n clientId: registration.clientId,\n registrationUrl: landingPage?.registrationPage?.slug || ''\n },\n type: 'update'\n })\n\n" ]
[ 0 ]
[]
[]
[ "next.js", "reactjs", "swr" ]
stackoverflow_0074665846_next.js_reactjs_swr.txt
Q: How to pass a reference to a function in RaisedButton.onpressed in FLUTTER, but with parameters? I already understood that we should call functions in FLUTTER without parentheses because you want to establish a reference to that function, not execute it. But what if you want to pass parameters to that function? How can I tell FLUTTER that I want to reference the function (not execute it), but pass arguments to it? The arguments are usually specified inside parentheses. I tried calling a function with parentheses when I have parameters to indicate, and it seems to work perfectly! It only executes the function when the button is pressed.... I'm a little confused. A: If the parameters line up you can pass a reference to the function and it will be called with those parameters. String validate(String? value) { if (value == null) { return 'Required'; } return null; } TextFormField( // Signature of validator and validate are the same validator: validate ) If the signatures don't overlap you have to use an anonymous function. TextFormField( validator: (value) => someOtherFunction(), )
How to pass a reference to a function in RaisedButton.onpressed in FLUTTER, but with parameters?
I already understood that we should call functions in FLUTTER without parentheses because you want to establish a reference to that function, not execute it. But what if you want to pass parameters to that function? How can I tell FLUTTER that I want to reference the function (not execute it), but pass arguments to it? The arguments are usually specified inside parentheses. I tried calling a function with parentheses when I have parameters to indicate, and it seems to work perfectly! It only executes the function when the button is pressed.... I'm a little confused.
[ "If the parameters line up you can pass a reference to the function and it will be called with those parameters.\nString validate(String? value) {\n if (value == null) {\n return 'Required';\n }\n return null;\n}\n\nTextFormField(\n // Signature of validator and validate are the same\n validator: validate\n)\n\nIf the signatures don't overlap you have to use an anonymous function.\nTextFormField(\n validator: (value) => someOtherFunction(),\n)\n\n" ]
[ 0 ]
[]
[]
[ "dart", "flutter" ]
stackoverflow_0074678155_dart_flutter.txt
Q: Prim's alogrithm using a 3 dimensional ArrayList in Java I am trying to implement prim's algorithm using 3 dimensional arraylist in java. The input graph is: Input: The function I have written for prim's algorithm is: class Solution { //Function to find sum of weights of edges of the Minimum Spanning Tree. static int spanningTree(int n, ArrayList<ArrayList<ArrayList<Integer>>> graph) { boolean mSet[]=new boolean[n]; int res=0; int key[]=new int[n]; Arrays.fill(key,Integer.MAX_VALUE); key[0]=0; for(int count=0;count<n;count++){ int u=-1; for(int i=0;i<n;i++){ if(!mSet[i]&&((u==-1)||(key[i]<key[u]))){ u=i; } } mSet[u]=true; res=res+key[u]; for(int v=0;v<n;v++){ if(!mSet[v]&&(graph.get(v).get(0).get(1)!=0)&&(graph.get(v).get(0).get(1)<key[v])){ key[v]=graph.get(v).get(0).get(1); } } } return res; } } From the above code I obtain 8 as the output when I should be getting a 4 and I am unable to figure out the error that I have made. The output is: Output: A: It looks like there is a mistake in your code when you are updating the values in the key array. In the line where you update the value of key[v], you are using the value of graph.get(v).get(0).get(1) instead of graph.get(u).get(v).get(1). This means that you are not using the correct edge weight to update the key array. Here is the updated code with the correct edge weight being used to update the key array: class Solution { //Function to find sum of weights of edges of the Minimum Spanning Tree. static int spanningTree(int n, ArrayList<ArrayList<ArrayList<Integer>>> graph) { boolean mSet[]=new boolean[n]; int res=0; int key[]=new int[n]; Arrays.fill(key,Integer.MAX_VALUE); key[0]=0; for(int count=0;count<n;count++){ int u=-1; for(int i=0;i<n;i++){ if(!mSet[i]&&((u==-1)||(key[i]<key[u]))){ u=i; } } mSet[u]=true; res=res+key[u]; for(int v=0;v<n;v++){ if(!mSet[v]&&(graph.get(u).get(v).get(1)!=0)&&(graph.get(u).get(v).get(1)<key[v])){ key[v]=graph.get(u).get(v).get(1); } } } return res; } } With this change, the output of the spanningTree function should be 4, which is the correct result for the given input graph.
Prim's alogrithm using a 3 dimensional ArrayList in Java
I am trying to implement prim's algorithm using 3 dimensional arraylist in java. The input graph is: Input: The function I have written for prim's algorithm is: class Solution { //Function to find sum of weights of edges of the Minimum Spanning Tree. static int spanningTree(int n, ArrayList<ArrayList<ArrayList<Integer>>> graph) { boolean mSet[]=new boolean[n]; int res=0; int key[]=new int[n]; Arrays.fill(key,Integer.MAX_VALUE); key[0]=0; for(int count=0;count<n;count++){ int u=-1; for(int i=0;i<n;i++){ if(!mSet[i]&&((u==-1)||(key[i]<key[u]))){ u=i; } } mSet[u]=true; res=res+key[u]; for(int v=0;v<n;v++){ if(!mSet[v]&&(graph.get(v).get(0).get(1)!=0)&&(graph.get(v).get(0).get(1)<key[v])){ key[v]=graph.get(v).get(0).get(1); } } } return res; } } From the above code I obtain 8 as the output when I should be getting a 4 and I am unable to figure out the error that I have made. The output is: Output:
[ "It looks like there is a mistake in your code when you are updating the values in the key array. In the line where you update the value of key[v], you are using the value of graph.get(v).get(0).get(1) instead of graph.get(u).get(v).get(1). This means that you are not using the correct edge weight to update the key array.\nHere is the updated code with the correct edge weight being used to update the key array:\nclass Solution\n{\n //Function to find sum of weights of edges of the Minimum Spanning Tree.\n static int spanningTree(int n, ArrayList<ArrayList<ArrayList<Integer>>> graph) \n {\n boolean mSet[]=new boolean[n];\n int res=0;\n int key[]=new int[n];\n Arrays.fill(key,Integer.MAX_VALUE);\n key[0]=0;\n for(int count=0;count<n;count++){\n int u=-1;\n for(int i=0;i<n;i++){\n if(!mSet[i]&&((u==-1)||(key[i]<key[u]))){\n u=i;\n }\n }\n mSet[u]=true;\n res=res+key[u];\n for(int v=0;v<n;v++){\n if(!mSet[v]&&(graph.get(u).get(v).get(1)!=0)&&(graph.get(u).get(v).get(1)<key[v])){\n key[v]=graph.get(u).get(v).get(1);\n }\n }\n }\n return res;\n }\n}\n\nWith this change, the output of the spanningTree function should be 4, which is the correct result for the given input graph.\n" ]
[ 0 ]
[]
[]
[ "java", "prims_algorithm" ]
stackoverflow_0074678269_java_prims_algorithm.txt
Q: Laravel Checking If a Record Exists I am new to Laravel. How do I find if a record exists? $user = User::where('email', '=', Input::get('email')); What can I do here to see if $user has a record? A: It depends if you want to work with the user afterwards or only check if one exists. If you want to use the user object if it exists: $user = User::where('email', '=', Input::get('email'))->first(); if ($user === null) { // user doesn't exist } And if you only want to check if (User::where('email', '=', Input::get('email'))->count() > 0) { // user found } Or even nicer if (User::where('email', '=', Input::get('email'))->exists()) { // user found } A: if (User::where('email', Input::get('email'))->exists()) { // exists } A: In laravel eloquent, has default exists() method, refer followed example. if (User::where('id', $user_id )->exists()) { // your code... } A: One of the best solution is to use the firstOrNew or firstOrCreate method. The documentation has more details on both. A: if($user->isEmpty()){ // has no records } Eloquent uses collections. See the following link: https://laravel.com/docs/5.4/eloquent-collections A: Laravel 5.6.26v to find the existing record through primary key ( email or id ) $user = DB::table('users')->where('email',$email)->first(); then if(!$user){ //user is not found } if($user){ // user found } include " use DB " and table name user become plural using the above query like user to users A: if (User::where('email', 'user@email.com')->first()) { // It exists } else { // It does not exist } Use first(), not count() if you only need to check for existence. first() is faster because it checks for a single match whereas count() counts all matches. A: This will check if requested email exist in the user table: if (User::where('email', $request->email)->exists()) { //email exists in user table } A: It is a bit late but it might help someone who is trying to use User::find()->exists() for record existence as Laravel shows different behavior for find() and where() methods. Considering email as your primary key let's examine the situation. $result = User::find($email)->exists(); If a user record with that email exists then it will return true. However the confusing thing is that if no user with that email exists then it will throw an error. i.e Call to a member function exists() on null. But the case is different for where() thing. $result = User::where("email", $email)->exists(); The above clause will give true if record exists and false if record doesn't exists. So always try to use where() for record existence and not find() to avoid NULL error. A: In your Controller $this->validate($request, [ 'email' => 'required|unique:user|email', ]); In your View - Display Already Exist Message @if (count($errors) > 0) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif A: Checking for null within if statement prevents Laravel from returning 404 immediately after the query is over. if ( User::find( $userId ) === null ) { return "user does not exist"; } else { $user = User::find( $userId ); return $user; } It seems like it runs double query if the user is found, but I can't seem to find any other reliable solution. A: if ($u = User::where('email', '=', $value)->first()) { // do something with $u return 'exists'; } else { return 'nope'; } would work with try/catch ->get() would still return an empty array A: $email = User::find($request->email); If($email->count()>0) <h1>Email exist, please make new email address</h1> endif A: Simple, comfortable and understandable with Validator class CustomerController extends Controller { public function register(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:customers', 'phone' => 'required|string|max:255|unique:customers', 'password' => 'required|string|min:6|confirmed', ]); if ($validator->fails()) { return response(['errors' => $validator->errors()->all()], 422); } A: I solved this, using empty() function: $user = User::where('email', Input::get('email'))->get()->first(); //for example: if (!empty($user)) User::destroy($user->id); A: you have seen plenty of solution, but magical checking syntax can be like, $model = App\Flight::findOrFail(1); $model = App\Flight::where('legs', '>', 100)->firstOrFail(); it will automatically raise an exception with response 404, when not found any related models Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The fingernail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, an Illuminate\Database\Eloquent\ModelNotFoundException will be thrown. Ref: https://laravel.com/docs/5.8/eloquent#retrieving-single-models A: $user = User::where('email', request('email'))->first(); return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist'); A: This will check if particular email address exist in the table: if (isset(User::where('email', Input::get('email'))->value('email'))) { // Input::get('email') exist in the table } A: Shortest working options: // if you need to do something with the user if ($user = User::whereEmail(Input::get('email'))->first()) { // ... } // otherwise $userExists = User::whereEmail(Input::get('email'))->exists(); A: $user = User::where('email', '=', Input::get('email'))->first(); if ($user === null) { // user doesn't exist } can be written as if (User::where('email', '=', Input::get('email'))->first() === null) { // user doesn't exist } This will return true or false without assigning a temporary variable if that is all you are using $user for in the original statement. A: You can use laravel validation if you want to insert a unique record: $validated = $request->validate([ 'title' => 'required|unique:usersTable,emailAddress|max:255', ]); But also you can use these ways: 1: if (User::where('email', $request->email)->exists()) { // object exists } else { // object not found } 2: $user = User::where('email', $request->email)->first(); if ($user) { // object exists } else { // object not found } 3: $user = User::where('email', $request->email)->first(); if ($user->isNotEmpty()) { // object exists } else { // object not found } 4: $user = User::where('email', $request->email)->firstOrCreate([ 'email' => 'email' ],$request->all()); A: I think below way is the simplest way to achieving same : $user = User::where('email', '=', $request->input('email'))->first(); if ($user) { // user doesn't exist! } A: Created below method (for myself) to check if the given record id exists on Db table or not. private function isModelRecordExist($model, $recordId) { if (!$recordId) return false; $count = $model->where(['id' => $recordId])->count(); return $count ? true : false; } // To Test $recordId = 5; $status = $this->isModelRecordExist( (new MyTestModel()), $recordId); Home It helps! A: The Easiest Way to do public function update(Request $request, $id) { $coupon = Coupon::where('name','=',$request->name)->first(); if($coupon->id != $id){ $validatedData = $request->validate([ 'discount' => 'required', 'name' => 'required|unique:coupons|max:255', ]); } $requestData = $request->all(); $coupon = Coupon::findOrFail($id); $coupon->update($requestData); return redirect('admin/coupons')->with('flash_message', 'Coupon updated!'); } A: Laravel 6 or on the top: Write the table name, then give where clause condition for instance where('id', $request->id) public function store(Request $request) { $target = DB:: table('categories') ->where('title', $request->name) ->get()->first(); if ($target === null) { // do what ever you need to do $cat = new Category(); $cat->title = $request->input('name'); $cat->parent_id = $request->input('parent_id'); $cat->user_id=auth()->user()->id; $cat->save(); return redirect(route('cats.app'))->with('success', 'App created successfully.'); }else{ // match found return redirect(route('cats.app'))->with('error', 'App already exists.'); } } A: If you want to insert a record in the database if a record with the same email not exists then you can do as follows: $user = User::updateOrCreate( ['email' => Input::get('email')], ['first_name' => 'Test', 'last_name' => 'Test'] ); The updateOrCreate method's first argument lists the column(s) that uniquely identify records within the associated table while the second argument consists of the values to insert or update. You can check out the docs here: Laravel upserts doc A: $userCnt = User::where("id",1)->count(); if( $userCnt ==0 ){ //////////record not exists }else{ //////////record exists } Note :: Where condition according your requirements. A: Simply use this one to get true or false $user = User::where('email', '=', Input::get('email'))->exists(); if you want $user with result you can use this one, $user = User::where('email', '=', Input::get('email'))->get(); and check result like this, if(count($user)>0){} Other wise you can use like this one, $user = User::where('email', '=', Input::get('email')); if($user->exists()){ $user = $user->get(); } A: To check if a record exists in Laravel, you can use the exists() method on the model's query builder. This method will return true if the record exists in the database, and false if it does not. Here's an example of how you can use the exists() method to check if a record exists: // Check if a record with the given ID exists $exists = Model::where('id', $id)->exists(); You can also use the whereExists() method on the query builder to check if a record exists that matches the given conditions. This method will return a boolean value indicating whether any records exist that match the given conditions. Here's an example of how you can use the whereExists() method to check if a record exists: // Check if a record with the given attribute exists $exists = Model::whereExists(function($query) use($value) { $query->where('attribute', $value); })->exists(); Keep in mind that these methods will only check if a record exists in the database, and will not return the actual record. To get the record itself, you can use the first() or find() methods on the query builder.
Laravel Checking If a Record Exists
I am new to Laravel. How do I find if a record exists? $user = User::where('email', '=', Input::get('email')); What can I do here to see if $user has a record?
[ "It depends if you want to work with the user afterwards or only check if one exists.\nIf you want to use the user object if it exists:\n$user = User::where('email', '=', Input::get('email'))->first();\nif ($user === null) {\n // user doesn't exist\n}\n\nAnd if you only want to check\nif (User::where('email', '=', Input::get('email'))->count() > 0) {\n // user found\n}\n\nOr even nicer\nif (User::where('email', '=', Input::get('email'))->exists()) {\n // user found\n}\n\n", "if (User::where('email', Input::get('email'))->exists()) {\n // exists\n}\n\n", "In laravel eloquent, has default exists() method, refer followed example.\nif (User::where('id', $user_id )->exists()) {\n // your code...\n}\n\n", "One of the best solution is to use the firstOrNew or firstOrCreate method. The documentation has more details on both.\n", "if($user->isEmpty()){\n // has no records\n}\n\nEloquent uses collections. \nSee the following link: https://laravel.com/docs/5.4/eloquent-collections\n", "Laravel 5.6.26v \nto find the existing record through primary key ( email or id ) \n $user = DB::table('users')->where('email',$email)->first();\n\nthen \n if(!$user){\n //user is not found \n }\n if($user){\n // user found \n }\n\ninclude \" use DB \" and table name user become plural using the above query like user to users\n", "if (User::where('email', 'user@email.com')->first()) {\n // It exists\n} else {\n // It does not exist\n}\n\nUse first(), not count() if you only need to check for existence.\nfirst() is faster because it checks for a single match whereas count() counts all matches.\n", "This will check if requested email exist in the user table:\nif (User::where('email', $request->email)->exists()) {\n //email exists in user table\n}\n\n", "It is a bit late but it might help someone who is trying to use User::find()->exists() for record existence as Laravel shows different behavior for find() and where() methods. Considering email as your primary key let's examine the situation.\n$result = User::find($email)->exists();\n\nIf a user record with that email exists then it will return true. However the confusing thing is that if no user with that email exists then it will throw an error. i.e\nCall to a member function exists() on null.\n\nBut the case is different for where() thing.\n$result = User::where(\"email\", $email)->exists();\n\nThe above clause will give true if record exists and false if record doesn't exists. So always try to use where() for record existence and not find() to avoid NULL error.\n", "In your Controller \n$this->validate($request, [\n 'email' => 'required|unique:user|email',\n ]); \n\nIn your View - Display Already Exist Message \n@if (count($errors) > 0)\n <div class=\"alert alert-danger\">\n <ul>\n @foreach ($errors->all() as $error)\n <li>{{ $error }}</li>\n @endforeach\n </ul>\n </div>\n@endif\n\n", "Checking for null within if statement prevents Laravel from returning 404 immediately after the query is over.\nif ( User::find( $userId ) === null ) {\n\n return \"user does not exist\";\n}\nelse {\n $user = User::find( $userId );\n\n return $user;\n}\n\nIt seems like it runs double query if the user is found, but I can't seem to find any other reliable solution.\n", "if ($u = User::where('email', '=', $value)->first())\n{\n // do something with $u\n return 'exists';\n} else {\n return 'nope';\n}\n\nwould work with try/catch \n->get() would still return an empty array\n", "$email = User::find($request->email);\nIf($email->count()>0)\n<h1>Email exist, please make new email address</h1>\nendif\n\n", "Simple, comfortable and understandable with Validator\nclass CustomerController extends Controller\n{\n public function register(Request $request)\n {\n\n $validator = Validator::make($request->all(), [\n 'name' => 'required|string|max:255',\n 'email' => 'required|string|email|max:255|unique:customers',\n 'phone' => 'required|string|max:255|unique:customers',\n 'password' => 'required|string|min:6|confirmed',\n ]);\n\n if ($validator->fails()) {\n return response(['errors' => $validator->errors()->all()], 422);\n }\n\n", "I solved this, using empty() function:\n$user = User::where('email', Input::get('email'))->get()->first();\n//for example:\nif (!empty($user))\n User::destroy($user->id);\n\n", "you have seen plenty of solution, but magical checking syntax can be like,\n$model = App\\Flight::findOrFail(1);\n\n$model = App\\Flight::where('legs', '>', 100)->firstOrFail();\n\nit will automatically raise an exception with response 404, when not found any related models Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The fingernail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, an Illuminate\\Database\\Eloquent\\ModelNotFoundException will be thrown.\nRef: https://laravel.com/docs/5.8/eloquent#retrieving-single-models\n", "$user = User::where('email', request('email'))->first();\nreturn (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');\n\n", "This will check if particular email address exist in the table:\nif (isset(User::where('email', Input::get('email'))->value('email')))\n{\n // Input::get('email') exist in the table \n}\n\n", "Shortest working options:\n// if you need to do something with the user \nif ($user = User::whereEmail(Input::get('email'))->first()) {\n\n // ...\n\n}\n\n// otherwise\n$userExists = User::whereEmail(Input::get('email'))->exists();\n\n", "$user = User::where('email', '=', Input::get('email'))->first();\nif ($user === null) {\n // user doesn't exist\n}\n\ncan be written as \nif (User::where('email', '=', Input::get('email'))->first() === null) {\n // user doesn't exist\n}\n\nThis will return true or false without assigning a temporary variable if that is all you are using $user for in the original statement.\n", "You can use laravel validation if you want to insert a unique record:\n$validated = $request->validate([\n 'title' => 'required|unique:usersTable,emailAddress|max:255',\n]);\n\nBut also you can use these ways:\n1:\nif (User::where('email', $request->email)->exists())\n{\n // object exists\n} else {\n // object not found\n}\n\n2:\n$user = User::where('email', $request->email)->first();\n\nif ($user)\n{\n // object exists\n} else {\n // object not found\n}\n\n3:\n$user = User::where('email', $request->email)->first();\n\nif ($user->isNotEmpty())\n{\n // object exists\n} else {\n // object not found\n}\n\n4:\n$user = User::where('email', $request->email)->firstOrCreate([\n 'email' => 'email'\n],$request->all());\n\n", "I think below way is the simplest way to achieving same :\n $user = User::where('email', '=', $request->input('email'))->first();\n if ($user) {\n // user doesn't exist!\n }\n\n", "Created below method (for myself) to check if the given record id exists on Db table or not.\nprivate function isModelRecordExist($model, $recordId)\n{\n if (!$recordId) return false;\n\n $count = $model->where(['id' => $recordId])->count();\n\n return $count ? true : false;\n}\n\n// To Test\n$recordId = 5;\n$status = $this->isModelRecordExist( (new MyTestModel()), $recordId);\n\nHome It helps!\n", "The Easiest Way to do \n public function update(Request $request, $id)\n{\n\n\n $coupon = Coupon::where('name','=',$request->name)->first(); \n\n if($coupon->id != $id){\n $validatedData = $request->validate([\n 'discount' => 'required', \n 'name' => 'required|unique:coupons|max:255', \n ]);\n }\n\n\n $requestData = $request->all();\n $coupon = Coupon::findOrFail($id);\n $coupon->update($requestData);\n return redirect('admin/coupons')->with('flash_message', 'Coupon updated!');\n}\n\n", "Laravel 6 or on the top: Write the table name, then give where clause condition for instance where('id', $request->id)\n public function store(Request $request)\n {\n\n $target = DB:: table('categories')\n ->where('title', $request->name)\n ->get()->first();\n if ($target === null) { // do what ever you need to do\n $cat = new Category();\n $cat->title = $request->input('name');\n $cat->parent_id = $request->input('parent_id');\n $cat->user_id=auth()->user()->id;\n $cat->save();\n return redirect(route('cats.app'))->with('success', 'App created successfully.');\n\n }else{ // match found \n return redirect(route('cats.app'))->with('error', 'App already exists.');\n }\n\n }\n\n", "If you want to insert a record in the database if a record with the same email not exists then you can do as follows:\n$user = User::updateOrCreate(\n ['email' => Input::get('email')],\n ['first_name' => 'Test', 'last_name' => 'Test']\n);\n\nThe updateOrCreate method's first argument lists the column(s) that uniquely identify records within the associated table while the second argument consists of the values to insert or update.\nYou can check out the docs here: Laravel upserts doc\n", "$userCnt = User::where(\"id\",1)->count();\nif( $userCnt ==0 ){\n //////////record not exists \n}else{\n //////////record exists \n}\n\nNote :: Where condition according your requirements.\n", "\nSimply use this one to get true or false\n$user = User::where('email', '=', Input::get('email'))->exists();\n\nif you want $user with result you can use this one,\n$user = User::where('email', '=', Input::get('email'))->get();\n\n\nand check result like this,\nif(count($user)>0){}\n\n\nOther wise you can use like this one,\n$user = User::where('email', '=', Input::get('email'));\nif($user->exists()){\n$user = $user->get();\n}\n\n\n", "To check if a record exists in Laravel, you can use the exists() method on the model's query builder. This method will return true if the record exists in the database, and false if it does not.\nHere's an example of how you can use the exists() method to check if a record exists:\n// Check if a record with the given ID exists\n$exists = Model::where('id', $id)->exists();\n\nYou can also use the whereExists() method on the query builder to check if a record exists that matches the given conditions. This method will return a boolean value indicating whether any records exist that match the given conditions.\nHere's an example of how you can use the whereExists() method to check if a record exists:\n// Check if a record with the given attribute exists\n$exists = Model::whereExists(function($query) use($value) {\n $query->where('attribute', $value);\n})->exists();\n\nKeep in mind that these methods will only check if a record exists in the database, and will not return the actual record. To get the record itself, you can use the first() or find() methods on the query builder.\n" ]
[ 809, 69, 43, 31, 20, 12, 9, 8, 7, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "The efficient way to check if the record exists you must use is_null method to check against the query.\nThe code below might be helpful:\n$user = User::where('email', '=', Input::get('email'));\nif(is_null($user)){\n //user does not exist...\n}else{\n //user exists...\n}\n\n", "It's simple to get to know if there are any records or not \n$user = User::where('email', '=', Input::get('email'))->get();\nif(count($user) > 0)\n{\necho \"There is data\";\n}\nelse\necho \"No data\";\n\n", "this is simple code to check email is exist or not in database\n\n\n $data = $request->all();\n $user = DB::table('User')->pluck('email')->toArray();\n if(in_array($user,$data['email']))\n {\n echo 'existed email';\n }\n\n\n" ]
[ -1, -4, -14 ]
[ "conditional_statements", "eloquent", "laravel", "laravel_5", "php" ]
stackoverflow_0027095090_conditional_statements_eloquent_laravel_laravel_5_php.txt
Q: Laravel Soft Delete Unique column name Suppose I have category table and I have used soft delete on it. Now first time I have added one category "Test" after that I have delete this category so it will update my deleted_at column from the database. Now when again I am trying to add category with name "Test" it is saying me that this name has been taken. I have tried with rules which are posted Here. But it is not working. I have used trait in my model. Below is my model code. <?php namespace App\Models; use Illuminate\Support\Facades\Validator as Validator; use Illuminate\Database\Eloquent\SoftDeletingTrait; class Category extends \Eloquent { use SoftDeletingTrait; protected $dates = ['deleted_at']; /** * Guarded fields which are not mass fillable * * @var array */ protected $guarded = array('id'); /** * Name of the table used * * @var string */ protected $table = 'travel_categories'; /** * Validating input. * * @param array $input * @return mixed (boolean | array) */ public static function validate($input, $id = null) { $rules = array( 'name' => array('required','min:2','max:100','regex:/[a-zA-z ]/','unique:travel_categories,name,NULL,id,deleted_at,NULL'), 'description' => 'Required|Min:2', 'image' => 'image' ); if ($id) { $rules['name'] = 'Required|Between:3,64|Unique:travel_categories,name,'.$id; } $validation = Validator::make($input,$rules); return ($validation->passes())?true : $validation->messages(); } } A: Did you understand the soft deleting purpose? It will only flag the data to be inactive. It will be there though. So, if you define the values of that column must be unique, it is right you could not create other one alike. If it needs to be unique, so you should restore and update the data. If it can have many ones, so you should remove the unique key applied on it (and call it by relationship for instance). Look at: Laravel Eloquent Soft Deleting A: First: I don't understand a couple of things. Are you trying to validate for create and update? Then why do you allow name to be of length 2 till 100 for creation, and only 3 till 64 for after updates? Second: I recommend dropping this: protected $dates = ['deleted_at']; I don't see the goal of that. Third, and I'm getting to the point here, what are you trying to do? I guess, what you are trying to do with this filter 'unique:travel_categories,name,NULL,id,deleted_at,NULL' is to check the uniqueness of the name among the active categories. In that case, that should work. A: As noted above, a unique index on [category, deleted_at] will not work because when deleted_at is null, many SQL RDBMS will allow multiple records to be inserted despite a unique index existing. In case anyone is interested I have now created a Laravel extension to handle the SQL unique-index constraints correctly: https://packagist.org/packages/tranzakt/laravel-softdeletesunique If anyone tries this, please give feedback on Github, thanks.
Laravel Soft Delete Unique column name
Suppose I have category table and I have used soft delete on it. Now first time I have added one category "Test" after that I have delete this category so it will update my deleted_at column from the database. Now when again I am trying to add category with name "Test" it is saying me that this name has been taken. I have tried with rules which are posted Here. But it is not working. I have used trait in my model. Below is my model code. <?php namespace App\Models; use Illuminate\Support\Facades\Validator as Validator; use Illuminate\Database\Eloquent\SoftDeletingTrait; class Category extends \Eloquent { use SoftDeletingTrait; protected $dates = ['deleted_at']; /** * Guarded fields which are not mass fillable * * @var array */ protected $guarded = array('id'); /** * Name of the table used * * @var string */ protected $table = 'travel_categories'; /** * Validating input. * * @param array $input * @return mixed (boolean | array) */ public static function validate($input, $id = null) { $rules = array( 'name' => array('required','min:2','max:100','regex:/[a-zA-z ]/','unique:travel_categories,name,NULL,id,deleted_at,NULL'), 'description' => 'Required|Min:2', 'image' => 'image' ); if ($id) { $rules['name'] = 'Required|Between:3,64|Unique:travel_categories,name,'.$id; } $validation = Validator::make($input,$rules); return ($validation->passes())?true : $validation->messages(); } }
[ "Did you understand the soft deleting purpose? It will only flag the data to be inactive. It will be there though.\nSo, if you define the values of that column must be unique, it is right you could not create other one alike.\n\nIf it needs to be unique, so you should restore and update the data.\nIf it can have many ones, so you should remove the unique key applied on it (and call it by relationship for instance).\n\nLook at: Laravel Eloquent Soft Deleting\n", "First: I don't understand a couple of things. Are you trying to validate for create and update? Then why do you allow name to be of length 2 till 100 for creation, and only 3 till 64 for after updates?\nSecond: I recommend dropping this:\nprotected $dates = ['deleted_at'];\n\nI don't see the goal of that.\nThird, and I'm getting to the point here, what are you trying to do? I guess, what you are trying to do with this filter 'unique:travel_categories,name,NULL,id,deleted_at,NULL' is to check the uniqueness of the name among the active categories. In that case, that should work.\n", "As noted above, a unique index on [category, deleted_at] will not work because when deleted_at is null, many SQL RDBMS will allow multiple records to be inserted despite a unique index existing.\nIn case anyone is interested I have now created a Laravel extension to handle the SQL unique-index constraints correctly: https://packagist.org/packages/tranzakt/laravel-softdeletesunique\nIf anyone tries this, please give feedback on Github, thanks.\n" ]
[ 3, 1, 0 ]
[ "I know this question is old, but I had a similar issue and I stumbled upon this. I wanted to mention how I fixed it for anyone, who is reading it in the future. The problem I had was that Laravel did not allow me to insert a value in a unique column when there was an old record with the same value, but was deleted using soft_delete.\nTo summarize, the goal is to ignore old soft deleted records for a unique column when inserting a new record. The solution I found is in the migration for the table. For example, let us assume we have these columns:\n\ncategory - unique\ndeleted_at - keeps tracks of the deleted rows\n\nBoth should be specified as unique in the migration like so:\n Schema::create('table_name', function (Blueprint $table) {\n $table->string(\"category\");\n $table->softDeletes();\n $table->unique([\"category\", \"deleted_at\"]);\n });\n\nSide note: If you already have the table like I did, you need to change the migration and create the table again (obviously the data will be lost):\n\nRemove the table\nChange the migration\nRemove the record about it from the migrations table\nrun \"php artisan migrate\" to create the table again\n\n" ]
[ -2 ]
[ "laravel", "php", "soft_delete", "unique" ]
stackoverflow_0026424294_laravel_php_soft_delete_unique.txt
Q: PHPStorm + PHPdoc - can I type hint individual array element? I have: $myarr['DB'] = new DB(); $myarr['config'] = new config(); Can I make somehow PHPStorm to know what exactly inside thouse keys? For now I see only hinting fo variables and class properties, but not array keys. A: Late answer, but things have changed. According to 2021.2 changelist it is possible now to define shape of a simple array with one line comment: /** * @return array{id: int, name: string, object: \Of\Some\Class} */ function getArray(): array {...} If there are object-like arrays in your code, you can now define their structure with this PHPDoc annotation: array{key: type, key: type, ...}. PhpStorm provides code completion for such annotated arrays, reducing the time you spend on routine typing and protecting you from mistakes. The support is limited to one-line array shape definitions. For larger structures, it is often better to use real objects and classes. Unfortunatelly I have not found a way to define structure of multi dimensional array, and it would be great to annotate a list of such "shaped" arrays... A: https://plugins.jetbrains.com/plugin/9927-deep-assoc-completion Image from the plugin's github repo. I use the plugin and can confirm it performs as described. A: You can define the array keys in advance, then PHPStorm will suggest them (CTRL+space) $my = array(); $my['qwe'] = ''; $my['asd'] = ''; $my['zxc'] = ''; $my['']// inside '' will be autosuggest You can also use phpdoc (CTRL+Q): /** * keys: * <pre> * some_array (array) * some_bool (boolean) * some_double (double) * some_nice_integer (integer) * </pre> * @return array */ public function toArray(){ // return some array } A: This functional is not realized yet in PhpStorm. Vote for support array access feature request. Also you can try silex idea plugin. A: According to https://youtrack.jetbrains.com/issue/WI-59083/recognize-use-of-list-with-array-shapes it is possible now to describe even item shape in the list: /** * @return array<int, array{id: int, name: string}> */ function getShapedArray(): array {...} Works nice with for loops, but no completion when: $array = getShapedArray(); $elementId = 2; // No completion for name property. $array[$elementId]['name'];
PHPStorm + PHPdoc - can I type hint individual array element?
I have: $myarr['DB'] = new DB(); $myarr['config'] = new config(); Can I make somehow PHPStorm to know what exactly inside thouse keys? For now I see only hinting fo variables and class properties, but not array keys.
[ "Late answer, but things have changed.\nAccording to 2021.2 changelist it is possible now to define shape of a simple array with one line comment:\n/**\n * @return array{id: int, name: string, object: \\Of\\Some\\Class}\n */\nfunction getArray(): array {...}\n\n\nIf there are object-like arrays in your code, you can now define their structure with this PHPDoc annotation: array{key: type, key: type, ...}.\nPhpStorm provides code completion for such annotated arrays, reducing the time you spend on routine typing and protecting you from mistakes.\nThe support is limited to one-line array shape definitions. For larger structures, it is often better to use real objects and classes.\n\nUnfortunatelly I have not found a way to define structure of multi dimensional array, and it would be great to annotate a list of such \"shaped\" arrays...\n", "https://plugins.jetbrains.com/plugin/9927-deep-assoc-completion\n\nImage from the plugin's github repo. I use the plugin and can confirm it performs as described.\n", "You can define the array keys in advance, then PHPStorm will suggest them (CTRL+space)\n$my = array();\n$my['qwe'] = '';\n$my['asd'] = '';\n$my['zxc'] = '';\n\n$my['']// inside '' will be autosuggest\n\nYou can also use phpdoc (CTRL+Q):\n/**\n * keys:\n * <pre>\n * some_array (array)\n * some_bool (boolean)\n * some_double (double)\n * some_nice_integer (integer)\n * </pre>\n * @return array\n */\npublic function toArray(){\n // return some array\n}\n\n", "This functional is not realized yet in PhpStorm. Vote for support array access feature request.\nAlso you can try silex idea plugin. \n", "According to https://youtrack.jetbrains.com/issue/WI-59083/recognize-use-of-list-with-array-shapes\nit is possible now to describe even item shape in the list:\n/**\n * @return array<int, array{id: int, name: string}>\n */\nfunction getShapedArray(): array {...}\n\nWorks nice with for loops, but no completion when:\n$array = getShapedArray();\n$elementId = 2;\n// No completion for name property.\n$array[$elementId]['name'];\n\n" ]
[ 17, 4, 3, 0, 0 ]
[ "For an arbitrary array, PHPStorm has no idea of the keys that are used in any array, and thus does not provide hints there. It is even possible to proof that it is impossible to reliably implement such a feature, so I think you are out of luck here.\nCollected From:\nStackoverflow Answer\n", "$obj = (object)[]; // Cast empty array to object\n\nadd properties:\n$obj->x = 'some'\n$obj->y = 'hints'\n\nNow, PHPStorm, when typing $obj-> ..... hints x and y \n" ]
[ -1, -3 ]
[ "php", "phpdoc", "phpstorm" ]
stackoverflow_0032611557_php_phpdoc_phpstorm.txt
Q: How to convert from C char buffer to String in Swift in XCode 14? There's a ton of references to this question but none of them seem to work. I'm using Xcode 14.1. What am I doing wrong? I have a C buffer in a struct: struct MY_C_STRUCT { char buff[256]; //Contains null-terminated C-string in UTF-8 encoding }; and I have a Swift struct where I'm trying to set its variable from MY_C_STRUCT::buff: class MyStruct : ObservableObject { @Published public var Buff : String = "" func from_MY_C_STRUCT(mi : MY_C_STRUCT) { Buff = String(cString: mi.buff) } } That gives me on the String(cString:) line: No exact matches in call to initializer A: As this blog explains, Swift imports fixed-sized C arrays as tuples! One way to treat the tuple as a buffer is to use withUnsafeBytes to get a pointer to the memory and then pass that pointer to String(cString:): Replace: Buff = String(cString: mi.buff) with: Buff = withUnsafeBytes(of: mi.buff) { (rawPtr) -> String in let ptr = rawPtr.baseAddress!.assumingMemoryBound(to: CChar.self) return String(cString: ptr) }
How to convert from C char buffer to String in Swift in XCode 14?
There's a ton of references to this question but none of them seem to work. I'm using Xcode 14.1. What am I doing wrong? I have a C buffer in a struct: struct MY_C_STRUCT { char buff[256]; //Contains null-terminated C-string in UTF-8 encoding }; and I have a Swift struct where I'm trying to set its variable from MY_C_STRUCT::buff: class MyStruct : ObservableObject { @Published public var Buff : String = "" func from_MY_C_STRUCT(mi : MY_C_STRUCT) { Buff = String(cString: mi.buff) } } That gives me on the String(cString:) line: No exact matches in call to initializer
[ "As this blog explains, Swift imports fixed-sized C arrays as tuples!\nOne way to treat the tuple as a buffer is to use withUnsafeBytes to get a pointer to the memory and then pass that pointer to String(cString:):\nReplace:\nBuff = String(cString: mi.buff)\n\nwith:\nBuff = withUnsafeBytes(of: mi.buff) { (rawPtr) -> String in\n let ptr = rawPtr.baseAddress!.assumingMemoryBound(to: CChar.self)\n return String(cString: ptr)\n}\n\n" ]
[ 0 ]
[]
[]
[ "c", "string", "swift", "xcode14" ]
stackoverflow_0074674319_c_string_swift_xcode14.txt
Q: Assemble COO matrix from a list of possibly repeated triplets in CUDA Given a std::vector<Eigen::Triplet<double>> its possible to create a Eigen::SparseMatrix<double> using setFromTriplets function. This function, by default, accumulates repeated triplets. I am trying to move my simulator code to CUDA and I have to build my sparse matrix. I have a kernel which computes the triplets and returns them in three device pointers (int*, int*, double*). However, I am not sure how to assemble the matrix from this pointers. cuSparse COO format says nothing about duplicated triplets and it actually says the rows should be sorted. Is there anyway to create a COO (or even better, a CSR directly) with CUDA/cuSparse given the i, j and value pointers with multiple (i,j) entries. A: The following code does the needed operations on the GPU using the Thrust library which is part of the CUDA Toolkit. If this operation is done often enough that you care about getting the best possible performance, you could directly use the CUB library which is used by Thrust as backend. That way you should be able to avoid multiple unnecessary copy operations. The APIs of interest for this would be cub::DeviceMergeSort (one might also be able to use cub::DeviceRadixSort with a type-punning tranform iterator) and cub::DeviceSegmentedReduce One way of avoiding the unnecessary initialization of the temporary vectors can be found in the uninitialized_vector.cu Thrust example. Another way of possibly improving performance without ditching Thrust would be to use the thrust::cuda::par_nosync execution policy. It is not yet implemented in the CUDA Toolkit 11.18 version of Thrust (1.15), so you will need to get a more recent version (1.16 or later) from Github. This can help hiding kernel launch overheads as it makes the Thrust algorithms asynchronous if possible (the segmented reduction has to be synchronous as it returns the new end iterators). You can also add explicit CUDA streams and pool memory resources to the API to take better care of the asynchronous behavior and avoid repeated allocation overhead respectively. See the cuda/explicit_cuda_stream.cu, cuda/custom_temporary_allocation.cu and mr_basic.cu Thrust examples for more information. #include <thrust/device_ptr.h> #include <thrust/device_vector.h> #include <thrust/distance.h> #include <thrust/iterator/zip_iterator.h> #include <thrust/reduce.h> #include <thrust/sort.h> #include <thrust/tuple.h> // Transforms triplets into COO sparse marix format in-place and // returns the number of non-zero entries (nnz). auto triplets2coo(int *d_rows, int *d_cols, float *d_vals, int num_triplets) { // thrust::device_ptr is a lightweight wrapper that lets Thrust algorithms // know which memory the pointer points to. thrust::device_pointer_cast is // the preferred way of creating them. While an API directly taking // wrapped pointers as arguments would be preferable, I chose it this way // to show how to wrap the pointers. auto const coord_iter = thrust::make_zip_iterator( thrust::make_tuple( thrust::device_pointer_cast(d_rows), thrust::device_pointer_cast(d_cols) )); auto const vals = thrust::device_pointer_cast(d_vals); // Sort in-place. thrust::sort_by_key(coord_iter, coord_iter + num_triplets, vals); // Segmented reduction can only be done out-of-place, // so allocate more memory. thrust::device_vector<int> tmp_rows(num_triplets); thrust::device_vector<int> tmp_cols(num_triplets); thrust::device_vector<float> tmp_vals(num_triplets); // Caution: These vectors are unnecessarily initialized to zero! auto const tmp_coord_iter = thrust::make_zip_iterator( thrust::make_tuple( tmp_rows.begin(), tmp_cols.begin() )); auto const new_ends = thrust::reduce_by_key(coord_iter, coord_iter + num_triplets, vals, tmp_coord_iter, tmp_vals.begin()); auto const nnz = thrust::distance(tmp_vals.begin(), new_ends.second); thrust::copy_n(tmp_coord_iter, nnz, coord_iter); thrust::copy_n(tmp_vals.cbegin(), nnz, vals); return nnz; }
Assemble COO matrix from a list of possibly repeated triplets in CUDA
Given a std::vector<Eigen::Triplet<double>> its possible to create a Eigen::SparseMatrix<double> using setFromTriplets function. This function, by default, accumulates repeated triplets. I am trying to move my simulator code to CUDA and I have to build my sparse matrix. I have a kernel which computes the triplets and returns them in three device pointers (int*, int*, double*). However, I am not sure how to assemble the matrix from this pointers. cuSparse COO format says nothing about duplicated triplets and it actually says the rows should be sorted. Is there anyway to create a COO (or even better, a CSR directly) with CUDA/cuSparse given the i, j and value pointers with multiple (i,j) entries.
[ "The following code does the needed operations on the GPU using the Thrust library which is part of the CUDA Toolkit. If this operation is done often enough that you care about getting the best possible performance, you could directly use the CUB library which is used by Thrust as backend. That way you should be able to avoid multiple unnecessary copy operations. The APIs of interest for this would be cub::DeviceMergeSort (one might also be able to use cub::DeviceRadixSort with a type-punning tranform iterator) and cub::DeviceSegmentedReduce\nOne way of avoiding the unnecessary initialization of the temporary vectors can be found in the uninitialized_vector.cu Thrust example.\nAnother way of possibly improving performance without ditching Thrust would be to use the thrust::cuda::par_nosync execution policy. It is not yet implemented in the CUDA Toolkit 11.18 version of Thrust (1.15), so you will need to get a more recent version (1.16 or later) from Github. This can help hiding kernel launch overheads as it makes the Thrust algorithms asynchronous if possible (the segmented reduction has to be synchronous as it returns the new end iterators). You can also add explicit CUDA streams and pool memory resources to the API to take better care of the asynchronous behavior and avoid repeated allocation overhead respectively. See the cuda/explicit_cuda_stream.cu, cuda/custom_temporary_allocation.cu and mr_basic.cu Thrust examples for more information.\n#include <thrust/device_ptr.h>\n#include <thrust/device_vector.h>\n#include <thrust/distance.h>\n#include <thrust/iterator/zip_iterator.h>\n#include <thrust/reduce.h>\n#include <thrust/sort.h>\n#include <thrust/tuple.h>\n\n// Transforms triplets into COO sparse marix format in-place and\n// returns the number of non-zero entries (nnz).\nauto triplets2coo(int *d_rows,\n int *d_cols,\n float *d_vals,\n int num_triplets) {\n // thrust::device_ptr is a lightweight wrapper that lets Thrust algorithms\n // know which memory the pointer points to. thrust::device_pointer_cast is\n // the preferred way of creating them. While an API directly taking\n // wrapped pointers as arguments would be preferable, I chose it this way \n // to show how to wrap the pointers.\n auto const coord_iter = thrust::make_zip_iterator(\n thrust::make_tuple(\n thrust::device_pointer_cast(d_rows),\n thrust::device_pointer_cast(d_cols)\n ));\n auto const vals = thrust::device_pointer_cast(d_vals);\n\n // Sort in-place.\n thrust::sort_by_key(coord_iter, coord_iter + num_triplets,\n vals);\n // Segmented reduction can only be done out-of-place,\n // so allocate more memory.\n thrust::device_vector<int> tmp_rows(num_triplets);\n thrust::device_vector<int> tmp_cols(num_triplets);\n thrust::device_vector<float> tmp_vals(num_triplets);\n // Caution: These vectors are unnecessarily initialized to zero!\n\n auto const tmp_coord_iter = thrust::make_zip_iterator(\n thrust::make_tuple(\n tmp_rows.begin(),\n tmp_cols.begin()\n ));\n\n auto const new_ends =\n thrust::reduce_by_key(coord_iter, coord_iter + num_triplets,\n vals,\n tmp_coord_iter,\n tmp_vals.begin());\n auto const nnz = thrust::distance(tmp_vals.begin(), new_ends.second);\n\n thrust::copy_n(tmp_coord_iter, nnz, coord_iter);\n thrust::copy_n(tmp_vals.cbegin(), nnz, vals);\n\n return nnz;\n}\n\n\n" ]
[ 0 ]
[]
[]
[ "c++", "cuda", "cusparse", "eigen" ]
stackoverflow_0074349633_c++_cuda_cusparse_eigen.txt
Q: Error with exporting excel file from database (vb.net) System.Runtime.InteropServices.COMException: 'Retrieving the COM class factory for component with CLSID {00020819-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).' I was just trying to export a database using vb.net to an excel file, I have tried to install and reinstall microsoft excel, adding and readding the imports of microsoft. can someone please helpppp code: Imports Excel = Microsoft.Office.Interop.Excel Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click Dim cnn As SqlConnection Dim cnnst As String Dim sql As String Dim i, j As Integer Dim xlapp As New Excel.Application Dim xlworkbook As New Excel.Workbook Dim xlworksheet As New Excel.Worksheet Dim misvalue As Object = Reflection.Missing.Value xlapp = New Excel.Application xlworkbook = xlapp.Workbooks.Add(misvalue) xlworksheet = xlworkbook.Sheets("sheet1") cnnst = "datasource=localhost;port=3306;username=root;password=;database=myconnector" cnn = New SqlConnection(cnnst) cnn.Open() sql = "select * from attendance" Dim cmd As New SqlDataAdapter(sql, cnn) Dim ds As New DataSet cmd.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 For j = 0 To ds.Tables(0).Columns.Count - 1 xlworksheet.Cells(i + 1, j + 1) = ds.Tables(0).Rows(i).Item(j) Next Next xlworksheet.SaveAs("D:\Report.xlsx") xlworkbook.Close() xlapp.Quit() Myobject(xlapp) Myobject(xlworkbook) Myobject(xlworksheet) cnn.Close() MsgBox("success", "Exported", MessageBoxButtons.OK) End Sub A: CLSID {00020819-0000-0000-C000-000000000046} is the WorkBook Class. Do not try to instantiate a Workbook by using the New keyword in the variable declaration statement. Dim xlworkbook As New Excel.Workbook should be Dim xlworkbook As Excel.Workbook The same also applies to the Worksheet variable declaration.
Error with exporting excel file from database (vb.net)
System.Runtime.InteropServices.COMException: 'Retrieving the COM class factory for component with CLSID {00020819-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).' I was just trying to export a database using vb.net to an excel file, I have tried to install and reinstall microsoft excel, adding and readding the imports of microsoft. can someone please helpppp code: Imports Excel = Microsoft.Office.Interop.Excel Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click Dim cnn As SqlConnection Dim cnnst As String Dim sql As String Dim i, j As Integer Dim xlapp As New Excel.Application Dim xlworkbook As New Excel.Workbook Dim xlworksheet As New Excel.Worksheet Dim misvalue As Object = Reflection.Missing.Value xlapp = New Excel.Application xlworkbook = xlapp.Workbooks.Add(misvalue) xlworksheet = xlworkbook.Sheets("sheet1") cnnst = "datasource=localhost;port=3306;username=root;password=;database=myconnector" cnn = New SqlConnection(cnnst) cnn.Open() sql = "select * from attendance" Dim cmd As New SqlDataAdapter(sql, cnn) Dim ds As New DataSet cmd.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 For j = 0 To ds.Tables(0).Columns.Count - 1 xlworksheet.Cells(i + 1, j + 1) = ds.Tables(0).Rows(i).Item(j) Next Next xlworksheet.SaveAs("D:\Report.xlsx") xlworkbook.Close() xlapp.Quit() Myobject(xlapp) Myobject(xlworkbook) Myobject(xlworksheet) cnn.Close() MsgBox("success", "Exported", MessageBoxButtons.OK) End Sub
[ "CLSID {00020819-0000-0000-C000-000000000046} is the WorkBook Class.\nDo not try to instantiate a Workbook by using the New keyword in the variable declaration statement.\nDim xlworkbook As New Excel.Workbook\n\nshould be\nDim xlworkbook As Excel.Workbook\n\nThe same also applies to the Worksheet variable declaration.\n" ]
[ 0 ]
[]
[]
[ "mysql", "vb.net" ]
stackoverflow_0074673313_mysql_vb.net.txt
Q: Using single ref for multiple input fields in react typescript I am trying to use the same ref for multiple input fields in for my form. But on logging it, the ref refers only to the first input field. Is there anyway I can use the same ref and use for different inputs? import React, {FC, useEffect, useRef, useState} from 'react'; import { IFormProps } from '../../utils/Interfaces'; import 'react-phone-number-input/style.css' const Form:FC<IFormProps> = ({formData, handleFormData, errors, handleValidate}) => { const inputField = React.useRef() as React.MutableRefObject<HTMLInputElement>; return ( <form className='user-form'> <label>First Name</label> <input type="text" ref = {inputField} value={formData.firstName} name="firstName" id="firstName" onChange={(e) => handleFormData(e)} placeholder="Enter your first name" onFocus={() => console.log('focus')} onBlur={() => handleValidate(inputField)} /> <label>Last Name</label> <input type="text" value={formData.lastName} name="lastName" id="lastName" onChange={(e) => handleFormData(e)} placeholder="Enter the last name" onBlur={() => handleValidate(inputField)} ref = {inputField} /> </form> ) } export default Form; I am passing this information to the parent to handle validation. I am not sure how I can pass the same ref(inputField) as different input elements with its attributes. I have tried doing this Use a single ref object across multiple input elements, but there is an error saying the following. I am aware its cause of typescript. But not sure how to handle it. ref = {(el) => (inputField.current["firstName"] = el)} Element implicitly has an 'any' type because expression of type '"firstName"' can't be used to index type 'HTMLInputElement'. Property 'firstName' does not exist on type 'HTMLInputElement'. A: Can define an array of ref and assign values by index const inputField = React.useRef<HTMLInputElement[]>([]) <input type="text" ref={el => inputField.current[0] = el} value={formData.firstName} name="firstName" id="firstName" onChange={(e) => handleFormData(e)} placeholder="Enter your first name" onFocus={() => console.log('focus')} onBlur={() => handleValidate(inputField)} /> <label>Last Name</label> <input type="text" value={formData.lastName} name="lastName" id="lastName" onChange={(e) => handleFormData(e)} placeholder="Enter the last name" onBlur={() => handleValidate(inputField)} ref={el => inputField.current[1] = el} /> A: In typescript, most hooks are generic. You declare their type using <>. If you want to assign to properties firstName and lastName then declare them in your type. You will also need to initialize the object. const inputField = React.useRef<{ firstName: HTMLInputElement; lastName: HTMLInputElement; }>({ firstName: null, lastName: null }); return ( <form className="user-form"> <label>First Name</label> <input ref={(ref) => (inputField.current.firstName = ref)} ... /> <label>Last Name</label> <input ref={(ref) => (inputField.current.lastName = ref)} ... /> </form> ); demo: https://stackblitz.com/edit/react-ts-zkc3nj?file=App.tsx
Using single ref for multiple input fields in react typescript
I am trying to use the same ref for multiple input fields in for my form. But on logging it, the ref refers only to the first input field. Is there anyway I can use the same ref and use for different inputs? import React, {FC, useEffect, useRef, useState} from 'react'; import { IFormProps } from '../../utils/Interfaces'; import 'react-phone-number-input/style.css' const Form:FC<IFormProps> = ({formData, handleFormData, errors, handleValidate}) => { const inputField = React.useRef() as React.MutableRefObject<HTMLInputElement>; return ( <form className='user-form'> <label>First Name</label> <input type="text" ref = {inputField} value={formData.firstName} name="firstName" id="firstName" onChange={(e) => handleFormData(e)} placeholder="Enter your first name" onFocus={() => console.log('focus')} onBlur={() => handleValidate(inputField)} /> <label>Last Name</label> <input type="text" value={formData.lastName} name="lastName" id="lastName" onChange={(e) => handleFormData(e)} placeholder="Enter the last name" onBlur={() => handleValidate(inputField)} ref = {inputField} /> </form> ) } export default Form; I am passing this information to the parent to handle validation. I am not sure how I can pass the same ref(inputField) as different input elements with its attributes. I have tried doing this Use a single ref object across multiple input elements, but there is an error saying the following. I am aware its cause of typescript. But not sure how to handle it. ref = {(el) => (inputField.current["firstName"] = el)} Element implicitly has an 'any' type because expression of type '"firstName"' can't be used to index type 'HTMLInputElement'. Property 'firstName' does not exist on type 'HTMLInputElement'.
[ "Can define an array of ref and assign values by index\n const inputField = React.useRef<HTMLInputElement[]>([])\n\n <input \n type=\"text\" \n ref={el => inputField.current[0] = el} \n value={formData.firstName} \n name=\"firstName\" id=\"firstName\" \n onChange={(e) => handleFormData(e)} placeholder=\"Enter your first name\"\n onFocus={() => console.log('focus')} \n onBlur={() => handleValidate(inputField)}\n />\n <label>Last Name</label>\n <input \n type=\"text\" \n value={formData.lastName} \n name=\"lastName\" id=\"lastName\" \n onChange={(e) => handleFormData(e)} \n placeholder=\"Enter the last name\"\n onBlur={() => handleValidate(inputField)}\n ref={el => inputField.current[1] = el} \n />\n\n", "In typescript, most hooks are generic. You declare their type using <>.\nIf you want to assign to properties firstName and lastName then declare them in your type. You will also need to initialize the object.\n const inputField = React.useRef<{\n firstName: HTMLInputElement;\n lastName: HTMLInputElement;\n }>({ firstName: null, lastName: null });\n\n return (\n <form className=\"user-form\">\n <label>First Name</label>\n <input\n ref={(ref) => (inputField.current.firstName = ref)}\n ...\n />\n <label>Last Name</label>\n <input\n ref={(ref) => (inputField.current.lastName = ref)}\n ...\n />\n </form>\n );\n\ndemo: https://stackblitz.com/edit/react-ts-zkc3nj?file=App.tsx\n" ]
[ 0, 0 ]
[]
[]
[ "reactjs", "ref", "typescript" ]
stackoverflow_0074678169_reactjs_ref_typescript.txt
Q: Have you ever get RuntimeError: await wasn't used with future? trying to extract data from a website by using asyncio and aiohttp, and AWAIT problem occur in for loop function. here my script : async def get_page(session,x): async with session.get(f'https://disclosure.bursamalaysia.com/FileAccess/viewHtml?e={x}') as r: return await r.text() async def get_all(session, urls): tasks =[] sem = asyncio.Semaphore(1) count = 0 for x in urls: count +=1 task = asyncio.create_task(get_page(session,x)) tasks.append(task) print(count,'-ID-',x,'|', end=' ') results = await asyncio.gather(*task) return results async def main(urls): async with aiohttp.ClientSession() as session: data = await get_all(session, urls) return if __name__ == '__main__': urls = titlelink results = asyncio.run(main(urls)) print(results) for the error, this is what it return when the scraper break : --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-3-5ac99108678c> in <module> 22 if __name__ == '__main__': 23 urls = titlelink ---> 24 results = asyncio.run(main(urls)) 25 print(results) ~\AppData\Local\Programs\Python\Python38\lib\site-packages\nest_asyncio.py in run(future, debug) 30 loop = asyncio.get_event_loop() 31 loop.set_debug(debug) ---> 32 return loop.run_until_complete(future) 33 34 if sys.version_info >= (3, 6, 0): ~\AppData\Local\Programs\Python\Python38\lib\site-packages\nest_asyncio.py in run_until_complete(self, future) 68 raise RuntimeError( 69 'Event loop stopped before Future completed.') ---> 70 return f.result() 71 72 def _run_once(self): ~\AppData\Local\Programs\Python\Python38\lib\asyncio\futures.py in result(self) 176 self.__log_traceback = False 177 if self._exception is not None: --> 178 raise self._exception 179 return self._result 180 ~\AppData\Local\Programs\Python\Python38\lib\asyncio\tasks.py in __step(***failed resolving arguments***) 278 # We use the `send` method directly, because coroutines 279 # don't have `__iter__` and `__next__` methods. --> 280 result = coro.send(None) 281 else: 282 result = coro.throw(exc) <ipython-input-3-5ac99108678c> in main(urls) 17 async def main(urls): 18 async with aiohttp.ClientSession() as session: ---> 19 data = await get_all(session, urls) 20 return 21 <ipython-input-3-5ac99108678c> in get_all(session, urls) 12 tasks.append(task) 13 print(count,'-ID-',x,'|', end=' ') ---> 14 results = await asyncio.gather(*task) 15 return results 16 ~\AppData\Local\Programs\Python\Python38\lib\asyncio\futures.py in __await__(self) 260 yield self # This tells Task to wait for completion. 261 if not self.done(): --> 262 raise RuntimeError("await wasn't used with future") 263 return self.result() # May raise too. 264 RuntimeError: await wasn't used with future is this error because of putting await inside the for loop function or it is because of the server problem? or maybe the way I wrote the script is wrong. Appreciate if any of you able to point me or guide me to the right direction A: You can use multiprocessing to scrape multiple link simultaneously(parallelly): from multiprocessing import Pool def scrape(url): #Scraper script p = Pool(10) # This “10” means that 10 URLs will be processed at the same time. p.map(scrape, list_of_all_urls) p.terminate() p.join() Here we map function scrape with list_of_all_urls and Pool p will take care of executing each of them concurrently.This is similar to looping over list_of_all_urls in simple.py but here it is done concurrently. If number of URLs is 100 and we specify Pool(20), then it will take 5 iterations (100/20) and 20 URLs will be processed in one go. Two things to note The links are not executed in order. You can see order is 2,1,3… This is because of multiprocessing and time is saved by one process by not waiting for previous one to finish. This is called parallel execution. This scrape very fast then normal. This difference grows very quickly when number of URLs increase which means that performance of multiprocessing script improves with large number of URLs. You may visit here for more/detail information. I believe this is same from previous question, I think you can use multiprocessing. I know this is not the right answer but you can use multiproces which is easy, and straightforward. A: await asyncio.gather(*task) Should be: await asyncio.gather(*tasks) The exception actually comes from the *task. Not sure what this syntax is meant for, but it's certainly not what you intended: >>> t = asyncio.Task(asyncio.sleep(10)) >>> (*t,) Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: await wasn't used with future
Have you ever get RuntimeError: await wasn't used with future?
trying to extract data from a website by using asyncio and aiohttp, and AWAIT problem occur in for loop function. here my script : async def get_page(session,x): async with session.get(f'https://disclosure.bursamalaysia.com/FileAccess/viewHtml?e={x}') as r: return await r.text() async def get_all(session, urls): tasks =[] sem = asyncio.Semaphore(1) count = 0 for x in urls: count +=1 task = asyncio.create_task(get_page(session,x)) tasks.append(task) print(count,'-ID-',x,'|', end=' ') results = await asyncio.gather(*task) return results async def main(urls): async with aiohttp.ClientSession() as session: data = await get_all(session, urls) return if __name__ == '__main__': urls = titlelink results = asyncio.run(main(urls)) print(results) for the error, this is what it return when the scraper break : --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-3-5ac99108678c> in <module> 22 if __name__ == '__main__': 23 urls = titlelink ---> 24 results = asyncio.run(main(urls)) 25 print(results) ~\AppData\Local\Programs\Python\Python38\lib\site-packages\nest_asyncio.py in run(future, debug) 30 loop = asyncio.get_event_loop() 31 loop.set_debug(debug) ---> 32 return loop.run_until_complete(future) 33 34 if sys.version_info >= (3, 6, 0): ~\AppData\Local\Programs\Python\Python38\lib\site-packages\nest_asyncio.py in run_until_complete(self, future) 68 raise RuntimeError( 69 'Event loop stopped before Future completed.') ---> 70 return f.result() 71 72 def _run_once(self): ~\AppData\Local\Programs\Python\Python38\lib\asyncio\futures.py in result(self) 176 self.__log_traceback = False 177 if self._exception is not None: --> 178 raise self._exception 179 return self._result 180 ~\AppData\Local\Programs\Python\Python38\lib\asyncio\tasks.py in __step(***failed resolving arguments***) 278 # We use the `send` method directly, because coroutines 279 # don't have `__iter__` and `__next__` methods. --> 280 result = coro.send(None) 281 else: 282 result = coro.throw(exc) <ipython-input-3-5ac99108678c> in main(urls) 17 async def main(urls): 18 async with aiohttp.ClientSession() as session: ---> 19 data = await get_all(session, urls) 20 return 21 <ipython-input-3-5ac99108678c> in get_all(session, urls) 12 tasks.append(task) 13 print(count,'-ID-',x,'|', end=' ') ---> 14 results = await asyncio.gather(*task) 15 return results 16 ~\AppData\Local\Programs\Python\Python38\lib\asyncio\futures.py in __await__(self) 260 yield self # This tells Task to wait for completion. 261 if not self.done(): --> 262 raise RuntimeError("await wasn't used with future") 263 return self.result() # May raise too. 264 RuntimeError: await wasn't used with future is this error because of putting await inside the for loop function or it is because of the server problem? or maybe the way I wrote the script is wrong. Appreciate if any of you able to point me or guide me to the right direction
[ "You can use multiprocessing to scrape multiple link simultaneously(parallelly):\nfrom multiprocessing import Pool\n \ndef scrape(url):\n #Scraper script\n\np = Pool(10)\n# This “10” means that 10 URLs will be processed at the same time.\np.map(scrape, list_of_all_urls)\np.terminate()\np.join()\n\n\nHere we map function scrape with list_of_all_urls and Pool p will take care of executing each of them concurrently.This is similar to looping over list_of_all_urls in simple.py but here it is done concurrently. If number of URLs is 100 and we specify Pool(20), then it will take 5 iterations (100/20) and 20 URLs will be processed in one go.\n\nTwo things to note\n\nThe links are not executed in order. You can see order is 2,1,3… This is because of multiprocessing and time is saved by one process by not waiting for previous one to finish. This is called parallel execution.\nThis scrape very fast then normal. This difference grows very quickly when number of URLs increase which means that performance of multiprocessing script improves with large number of URLs.\n\nYou may visit here for more/detail information.\nI believe this is same from previous question, I think you can use multiprocessing. I know this is not the right answer but you can use multiproces which is easy, and straightforward.\n", "await asyncio.gather(*task)\nShould be:\nawait asyncio.gather(*tasks)\nThe exception actually comes from the *task. Not sure what this syntax is meant for, but it's certainly not what you intended:\n>>> t = asyncio.Task(asyncio.sleep(10))\n>>> (*t,)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nRuntimeError: await wasn't used with future\n\n" ]
[ 0, 0 ]
[]
[]
[ "async_await", "asynchronous", "python" ]
stackoverflow_0068563801_async_await_asynchronous_python.txt
Q: How to use "new" on an abstract class I've tried to search for other questions like mine but I can't find any good result I'm trying to use a DLL that has a method that need to be called with a new class but that class is abstract. thanks. i tried to use new IClientHandler but it just errors A: You're trying to instantiate an abstract class in C# code. This is not possible, as an abstract class is a class that cannot be instantiated on its own. Instead, you would need to create a non-abstract class that extends the abstract class and then use that to create an object. Here's an example: abstract class AbstractClass { public abstract void AbstractMethod(); } class ConcreteClass : AbstractClass { public override void AbstractMethod() { Console.WriteLine("I'm a non-abstract method!"); } } // Now we can create an instance of ConcreteClass var instance = new ConcreteClass(); You can then call the AbstractMethod on the instance object, since it has been implemented in the ConcreteClass. Also my small mistake, as @ewerspej noticed: IClientHandler is an interface, not an abstract class. Neither can be instantiated. Interfaces require implementations that can be instantiated and abstract classes must be extended by non-abstract classes that can be instantiated.
How to use "new" on an abstract class
I've tried to search for other questions like mine but I can't find any good result I'm trying to use a DLL that has a method that need to be called with a new class but that class is abstract. thanks. i tried to use new IClientHandler but it just errors
[ "You're trying to instantiate an abstract class in C# code. This is not possible, as an abstract class is a class that cannot be instantiated on its own. Instead, you would need to create a non-abstract class that extends the abstract class and then use that to create an object.\nHere's an example:\nabstract class AbstractClass\n{\n public abstract void AbstractMethod();\n}\n\nclass ConcreteClass : AbstractClass\n{\n public override void AbstractMethod()\n {\n Console.WriteLine(\"I'm a non-abstract method!\");\n }\n}\n\n// Now we can create an instance of ConcreteClass\nvar instance = new ConcreteClass();\n\nYou can then call the AbstractMethod on the instance object, since it has been implemented in the ConcreteClass.\n\nAlso my small mistake, as @ewerspej noticed:\n\nIClientHandler is an interface, not an abstract class. Neither can be instantiated. Interfaces require implementations that can be instantiated and abstract classes must be extended by non-abstract classes that can be instantiated.\n\n" ]
[ 4 ]
[]
[]
[ "c#" ]
stackoverflow_0074678323_c#.txt
Q: Change color text on tab navbar I want to change the color the text of the navbar on click I have this code: $("a.tab").click(function() { $("a.tab").css("background-color", "#1F1F1F"); $(this).css("background-color", "#404040"); $("p.name_tab").css("color", "#939393"); $(this).css("color", "white"); }); It change well the background-color of my a balise by not the text inside. I try this but I need to click again on the text to color it. $("p.name_tab").click(function() { $("p.name_tab").css("color", "#939393"); $(this).css("color", "white"); }); A: change the p.name_tab elements that are inside the a.tab element that was clicked. $("a.tab").click(function() { // Change the background color of all a.tab elements $("a.tab").css("background-color", "#1F1F1F"); // Change the background color of the clicked a.tab element $(this).css("background-color", "#404040"); // Find the p.name_tab elements inside the clicked a.tab element $(this).find("p.name_tab").css("color", "white"); // Change the color of all other p.name_tab elements $("p.name_tab").not($(this).find("p.name_tab")).css("color", "#939393"); });
Change color text on tab navbar
I want to change the color the text of the navbar on click I have this code: $("a.tab").click(function() { $("a.tab").css("background-color", "#1F1F1F"); $(this).css("background-color", "#404040"); $("p.name_tab").css("color", "#939393"); $(this).css("color", "white"); }); It change well the background-color of my a balise by not the text inside. I try this but I need to click again on the text to color it. $("p.name_tab").click(function() { $("p.name_tab").css("color", "#939393"); $(this).css("color", "white"); });
[ "change the p.name_tab elements that are inside the a.tab element that was clicked.\n$(\"a.tab\").click(function() {\n // Change the background color of all a.tab elements\n $(\"a.tab\").css(\"background-color\", \"#1F1F1F\");\n\n // Change the background color of the clicked a.tab element\n $(this).css(\"background-color\", \"#404040\");\n\n // Find the p.name_tab elements inside the clicked a.tab element\n $(this).find(\"p.name_tab\").css(\"color\", \"white\");\n\n // Change the color of all other p.name_tab elements\n $(\"p.name_tab\").not($(this).find(\"p.name_tab\")).css(\"color\", \"#939393\");\n});\n\n" ]
[ -1 ]
[]
[]
[ "ajax", "css", "javascript", "jquery" ]
stackoverflow_0074678327_ajax_css_javascript_jquery.txt
Q: nodejs and Microsoft Graph API I would like to be able to send requests to the graph API from nodejs. For that I followed the tutorial https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-nodejs-console I manage to get a token that allows me to execute a request on the endpoint https://graph.microsoft.com/v1.0/users with insomnia. I have the list of users of the tenant in JSON. But in JS the response.data is unreadable (▼♦ ��KK♥...), I tried to change the encoding but without success. The tutorial uses the axios library and the get method to get the result, is it necessary to add something to get a json? A: You need to add Accept-Encoding with application/json in axios.get header. Using this option for axio get call at Add a method to call a web API section const options = { headers: { Authorization: `Bearer ${accessToken}`, 'Accept-Encoding': 'application/json' } }; It is known defect. The default of it is gzip in axios v1.2.0 File structure copy three files from tutorial And modify Axios option part package.json { "name": "answer89", "version": "1.0.0", "description": "", "main": "bin/index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@azure/msal-node": "^1.14.4", "axios": "^1.2.0", "dotenv": "^16.0.3", "yargs": "^17.6.2" } } .env # Credentials TENANT_ID={your tenant id} CLIENT_ID={your client id} CLIENT_SECRET={your secret} # Endpoints AAD_ENDPOINT=https://login.microsoftonline.com GRAPH_ENDPOINT=https://graph.microsoft.com CLIENT_ID - order is flipped in UI TENANT_ID CLIENT_SECRET Check permission in your app - User.Read Check owner is you Run it in Terminal npm install node . --op getUsers Finally run it got JWT(Access token) in Axios Header even if code ' ERR_BAD_REQUEST` A: I abandoned axios and use directly the fetch API with success. There is something not clear with Axios usage.
nodejs and Microsoft Graph API
I would like to be able to send requests to the graph API from nodejs. For that I followed the tutorial https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-nodejs-console I manage to get a token that allows me to execute a request on the endpoint https://graph.microsoft.com/v1.0/users with insomnia. I have the list of users of the tenant in JSON. But in JS the response.data is unreadable (▼♦ ��KK♥...), I tried to change the encoding but without success. The tutorial uses the axios library and the get method to get the result, is it necessary to add something to get a json?
[ "You need to add Accept-Encoding with application/json in axios.get header.\nUsing this option for axio get call\nat Add a method to call a web API section\n const options = {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Accept-Encoding': 'application/json'\n }\n };\n\nIt is known defect.\nThe default of it is gzip in axios v1.2.0\nFile structure\ncopy three files from tutorial\nAnd modify Axios option part\n\npackage.json\n{\n \"name\": \"answer89\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"bin/index.js\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"keywords\": [],\n \"author\": \"\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"@azure/msal-node\": \"^1.14.4\",\n \"axios\": \"^1.2.0\",\n \"dotenv\": \"^16.0.3\",\n \"yargs\": \"^17.6.2\"\n }\n}\n\n.env\n# Credentials\nTENANT_ID={your tenant id}\nCLIENT_ID={your client id}\nCLIENT_SECRET={your secret}\n\n# Endpoints\nAAD_ENDPOINT=https://login.microsoftonline.com\nGRAPH_ENDPOINT=https://graph.microsoft.com\n\nCLIENT_ID - order is flipped in UI\nTENANT_ID\n\nCLIENT_SECRET\n\nCheck permission in your app - User.Read\n\nCheck owner is you\n\nRun it in Terminal\nnpm install\nnode . --op getUsers\n\n\nFinally run it got JWT(Access token) in Axios Header even if code ' ERR_BAD_REQUEST`\n\n", "I abandoned axios and use directly the fetch API with success. There is something not clear with Axios usage.\n" ]
[ 0, 0 ]
[]
[]
[ "axios", "microsoft_graph_api", "node.js" ]
stackoverflow_0074654296_axios_microsoft_graph_api_node.js.txt
Q: Symfony error: Attribute "Symfony\Component\Routing\Annotation\Route" cannot target function (allowed targets: class, method) After upgrading from Symfony 6.1 to 6.2, I'm getting this error: Attribute "Symfony\Component\Routing\Annotation\Route" cannot target function (allowed targets: class, method) ...on this controller: final class HomepageController extends AbstractController { #[Route(path: '/', name: 'homepage')] public function __invoke(): Response { // ... } } A: Short Answer Doing one of the following will fix it: Update PHP to >= 8.1.10 Move the Route attribute from __invoke upwards to class Long Answer Symfony's Route attribute is allowed on classes and methods, see Route: #[\Attribute(\Attribute::IS_REPEATABLE | \Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD)] In Symfony 6.2 the way how attributes are read, has changed: https://github.com/symfony/symfony/pull/46001 Unfortunately, there was a bug introduced in PHP 8.1.6, so that the magic method __invoke() isn't covered by \Attribute::TARGET_METHOD anymore. This was fixed in PHP 8.1.10: https://github.com/php/php-src/pull/9173
Symfony error: Attribute "Symfony\Component\Routing\Annotation\Route" cannot target function (allowed targets: class, method)
After upgrading from Symfony 6.1 to 6.2, I'm getting this error: Attribute "Symfony\Component\Routing\Annotation\Route" cannot target function (allowed targets: class, method) ...on this controller: final class HomepageController extends AbstractController { #[Route(path: '/', name: 'homepage')] public function __invoke(): Response { // ... } }
[ "Short Answer\nDoing one of the following will fix it:\n\nUpdate PHP to >= 8.1.10\nMove the Route attribute from __invoke upwards to class\n\nLong Answer\nSymfony's Route attribute is allowed on classes and methods, see Route:\n#[\\Attribute(\\Attribute::IS_REPEATABLE | \\Attribute::TARGET_CLASS | \\Attribute::TARGET_METHOD)]\n\nIn Symfony 6.2 the way how attributes are read, has changed: https://github.com/symfony/symfony/pull/46001\nUnfortunately, there was a bug introduced in PHP 8.1.6, so that the magic method __invoke() isn't covered by \\Attribute::TARGET_METHOD anymore.\nThis was fixed in PHP 8.1.10: https://github.com/php/php-src/pull/9173\n" ]
[ 1 ]
[]
[]
[ "php", "symfony" ]
stackoverflow_0074678366_php_symfony.txt
Q: Load pdf on foreign url with pdf.js I am trying to load pdf from another server to the viewer of pdf.js in my server.I got error "PDF.js v1.4.20 (build: b15f335) Message: file origin does not match viewer's" I already checked many answer, many of them said that pass the pdf url through a proxy like:- link After searching a lot i found that they release a new patch in which they have lock down any CDR request, correct me if i am wrong:-Here is the link but in their user manual they specified that it is possible here is the link I tried all method but not able to enable CDR on my server and many methods didn't work. Please help me to resolve this issue. My Basic idea is to show pdf(which is hosted on 3rd party server) on my pdf reader(that i made it from pdf.js). A: I resolved this issue by comment this lines in viewer.js if (fileOrigin !== viewerOrigin) { throw new Error('file origin does not match viewer\'s'); } and use proxy like this. http://192.168.0.101/web/viewer.html?file=https://cors-anywhere.herokuapp.com/pathofpdf.pdf A: Add your domain/origin to HOSTED_VIEWER_ORIGINS array A: I resolved this issue by adding this line in viewer.js var LOCAL_AUTO_DETECT_ORIGIN = window.location.origin; var HOSTED_VIEWER_ORIGINS = ['null', 'http://mozilla.github.io', 'https://mozilla.github.io']; HOSTED_VIEWER_ORIGINS.push(LOCAL_AUTO_DETECT_ORIGIN); A: The problem in my case was the link wasnt in https while the site is secured A: pdfjs respect CORS settings. Do the following Go to viewer.js file and find the location of HOSTED_VIEWER_ORIGINS. Below that line add your domain to the array HOSTED_VIEWER_ORIGINS like this const LOCAL_AUTO_DETECT_ORIGIN = window.location.origin; HOSTED_VIEWER_ORIGINS.push(LOCAL_AUTO_DETECT_ORIGIN); if your file is hosted n AWS S3 bucket, then set CORS policy on the bucket to allow all your domains read files from that bucket That should solve your prblem
Load pdf on foreign url with pdf.js
I am trying to load pdf from another server to the viewer of pdf.js in my server.I got error "PDF.js v1.4.20 (build: b15f335) Message: file origin does not match viewer's" I already checked many answer, many of them said that pass the pdf url through a proxy like:- link After searching a lot i found that they release a new patch in which they have lock down any CDR request, correct me if i am wrong:-Here is the link but in their user manual they specified that it is possible here is the link I tried all method but not able to enable CDR on my server and many methods didn't work. Please help me to resolve this issue. My Basic idea is to show pdf(which is hosted on 3rd party server) on my pdf reader(that i made it from pdf.js).
[ "I resolved this issue by comment this lines in viewer.js\nif (fileOrigin !== viewerOrigin) {\nthrow new Error('file origin does not match viewer\\'s');\n}\n\nand use proxy like this.\nhttp://192.168.0.101/web/viewer.html?file=https://cors-anywhere.herokuapp.com/pathofpdf.pdf\n", "Add your domain/origin to HOSTED_VIEWER_ORIGINS array\n", "I resolved this issue by adding this line in viewer.js\n var LOCAL_AUTO_DETECT_ORIGIN = window.location.origin;\n\n var HOSTED_VIEWER_ORIGINS = ['null', 'http://mozilla.github.io', 'https://mozilla.github.io'];\n\n HOSTED_VIEWER_ORIGINS.push(LOCAL_AUTO_DETECT_ORIGIN);\n\n", "The problem in my case was the link wasnt in https while the site is secured\n", "pdfjs respect CORS settings. Do the following\n\nGo to viewer.js file and find the location of HOSTED_VIEWER_ORIGINS. Below that line add your domain to the array HOSTED_VIEWER_ORIGINS like this\n\n const LOCAL_AUTO_DETECT_ORIGIN = window.location.origin;\n HOSTED_VIEWER_ORIGINS.push(LOCAL_AUTO_DETECT_ORIGIN);\n\n\nif your file is hosted n AWS S3 bucket, then set CORS policy on the bucket to allow all your domains read files from that bucket\n\nThat should solve your prblem\n" ]
[ 22, 7, 0, 0, 0 ]
[]
[]
[ "javascript", "mozilla", "pdf.js", "reader" ]
stackoverflow_0037378251_javascript_mozilla_pdf.js_reader.txt
Q: Please let me know how to link this react to css file I'm a freshman in html/css. As I just have studied html/css these days, I have problem while I'm studying. I just want to link this React file to my css file, but I don't know how even if I search all the ways I can make it. (1) React file import styled, { keyframes } from "styled-components"; const Flow = () => { return ( <Container> <FlowBox> <FlowWrap> <Flow> <span>King of pirates</span> <span>King of pirates</span> <span>King of pirates</span> <span>King of pirates</span> </Flow> </FlowWrap> </FlowBox> </Container> ) } export default AboutFlow; const Container = styled.div` margin:100px 0 0 0; border-top:1px solid #000; border-bottom: 1px solid #000; ` const flowing = keyframes` 0% { transform: translate3d(0, 0, 0); } 100% { transform: translate3d(-50%, 0, 0); } ` const FlowBox = styled.div` position: relative; width: 100%; height: 250px; overflow: hidden; ` const FlowWrap = styled.div` display: flex; top: 0; left: 0; align-items: center; width: 100%; height: 100%; white-space: nowrap; ` const Flow = styled.div` font-size: clamp(15px, 10vw, 8rem); animation: ${flowing} 8s linear infinite; span{ display:inline-block; font-weight:600; padding:0 20px; } (2) My CSS file @import "./react.css"; .title{ background-image: url(../src/img/upper_blackbar_edit.png); min-width: 1000px; background-size:100% 50px; } .bg{ width:100%; min-width: 1000px; } .logo{ height:50px; vertical-align: top; } .map{ min-width: 100%; width: 80%; object-fit: cover; display: block; top:10%; margin:auto; } .body{ min-width: 1000px; background-image: url(../src/img/background.png); background-size:cover; overflow: scroll; } How can I see my css file linked with this react file? Please help me. I want some concrete ways to do so. A: import '(your css file path)'; const Flow = () => { return ( <Container className="(name your class)"> <FlowBox className="(name your class)"> <FlowWrap className="(name your class)"> <Flow> <span className="(name your class)">King of pirates</span> <span className="(name your class)">King of pirates</span> <span className="(name your class)">King of pirates</span> <span className="(name your class)">King of pirates</span> </Flow> </FlowWrap> </FlowBox> </Container> ) } Import the css file and then use className, It will work
Please let me know how to link this react to css file
I'm a freshman in html/css. As I just have studied html/css these days, I have problem while I'm studying. I just want to link this React file to my css file, but I don't know how even if I search all the ways I can make it. (1) React file import styled, { keyframes } from "styled-components"; const Flow = () => { return ( <Container> <FlowBox> <FlowWrap> <Flow> <span>King of pirates</span> <span>King of pirates</span> <span>King of pirates</span> <span>King of pirates</span> </Flow> </FlowWrap> </FlowBox> </Container> ) } export default AboutFlow; const Container = styled.div` margin:100px 0 0 0; border-top:1px solid #000; border-bottom: 1px solid #000; ` const flowing = keyframes` 0% { transform: translate3d(0, 0, 0); } 100% { transform: translate3d(-50%, 0, 0); } ` const FlowBox = styled.div` position: relative; width: 100%; height: 250px; overflow: hidden; ` const FlowWrap = styled.div` display: flex; top: 0; left: 0; align-items: center; width: 100%; height: 100%; white-space: nowrap; ` const Flow = styled.div` font-size: clamp(15px, 10vw, 8rem); animation: ${flowing} 8s linear infinite; span{ display:inline-block; font-weight:600; padding:0 20px; } (2) My CSS file @import "./react.css"; .title{ background-image: url(../src/img/upper_blackbar_edit.png); min-width: 1000px; background-size:100% 50px; } .bg{ width:100%; min-width: 1000px; } .logo{ height:50px; vertical-align: top; } .map{ min-width: 100%; width: 80%; object-fit: cover; display: block; top:10%; margin:auto; } .body{ min-width: 1000px; background-image: url(../src/img/background.png); background-size:cover; overflow: scroll; } How can I see my css file linked with this react file? Please help me. I want some concrete ways to do so.
[ "import '(your css file path)';\n\n const Flow = () => {\n return (\n <Container className=\"(name your class)\">\n <FlowBox className=\"(name your class)\">\n <FlowWrap className=\"(name your class)\">\n <Flow>\n <span className=\"(name your class)\">King of pirates</span>\n <span className=\"(name your class)\">King of pirates</span>\n <span className=\"(name your class)\">King of pirates</span>\n <span className=\"(name your class)\">King of pirates</span>\n </Flow>\n </FlowWrap>\n </FlowBox>\n </Container>\n )\n }\n\nImport the css file and then use className, It will work\n" ]
[ 0 ]
[]
[]
[ "css", "html", "react_native" ]
stackoverflow_0074665148_css_html_react_native.txt
Q: Setting up wireguard client I get wireguard working from my ubuntu laptop to my linode running ubuntu, but after the first couple of connections it stops connecting. Even my ssh to the server stops working. I have to run wp-quick down on the client to restore my connections, however, without wireguard. Here are my configs Server [Interface] Address = 10.0.0.1/24 SaveConfig = true PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE; ip6tables -A FORWARD -i wg0 -j ACCEPT; ip6tables -t nat -A POSTROUTING -o eth0 -j MASQUERADE PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE; ip6tables -D FORWARD -i wg0 -j ACCEPT; ip6tables -t nat -D POSTROUTING -o eth0 -j MASQUERADE ListenPort = 51820 PrivateKey = <Private Key> [Peer] PublicKey = <Public Key> AllowedIPs = 10.0.0.2/32 Endpoint = 98.122.111.39:51974 PersistentKeepAlive=30 Client [Interface] # IP Address and Private Key of the Client Address = 10.0.0.2/24 PrivateKey = <private key> [Peer] # Public key, IP Address and Port of the Server PublicKey = <public key> Endpoint = 50.116.60.189:51820 AllowedIPs = 0.0.0.0/0 I thought adding PersistentKeepAlive would help, but it doesn't seem to do anything. Can anyone help me understand what is going wrong? A: Ahhh, yes. Your resolveconf is updating your /etc/resolveconf file. This can happen most frequently when DHCP client does a DHCP-REBIND or worse, a DHCP-RENEW and your DHCP client is executing scripts to change it. A: You set the 51974 port when defining the Endpoint on the [Peer] from the "server" side. But you didn't specify ListenPort = 51974 on the client [Interface] configuration. A: u should setup the iptables to not forward port 22 into your vpn. according to this https://github.com/mochman/Bypass_CGNAT/wiki/Digital-Ocean-(Manual-Installation) u should add -i eth0 '!' --dport 22 to this aswell.
Setting up wireguard client
I get wireguard working from my ubuntu laptop to my linode running ubuntu, but after the first couple of connections it stops connecting. Even my ssh to the server stops working. I have to run wp-quick down on the client to restore my connections, however, without wireguard. Here are my configs Server [Interface] Address = 10.0.0.1/24 SaveConfig = true PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE; ip6tables -A FORWARD -i wg0 -j ACCEPT; ip6tables -t nat -A POSTROUTING -o eth0 -j MASQUERADE PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE; ip6tables -D FORWARD -i wg0 -j ACCEPT; ip6tables -t nat -D POSTROUTING -o eth0 -j MASQUERADE ListenPort = 51820 PrivateKey = <Private Key> [Peer] PublicKey = <Public Key> AllowedIPs = 10.0.0.2/32 Endpoint = 98.122.111.39:51974 PersistentKeepAlive=30 Client [Interface] # IP Address and Private Key of the Client Address = 10.0.0.2/24 PrivateKey = <private key> [Peer] # Public key, IP Address and Port of the Server PublicKey = <public key> Endpoint = 50.116.60.189:51820 AllowedIPs = 0.0.0.0/0 I thought adding PersistentKeepAlive would help, but it doesn't seem to do anything. Can anyone help me understand what is going wrong?
[ "Ahhh, yes.\nYour resolveconf is updating your /etc/resolveconf file.\nThis can happen most frequently when DHCP client does a DHCP-REBIND or worse, a DHCP-RENEW and your DHCP client is executing scripts to change it.\n", "You set the 51974 port when defining the Endpoint on the [Peer] from the \"server\" side. But you didn't specify ListenPort = 51974 on the client [Interface] configuration.\n", "u should setup the iptables to not forward port 22 into your vpn.\naccording to this\nhttps://github.com/mochman/Bypass_CGNAT/wiki/Digital-Ocean-(Manual-Installation)\nu should add\n-i eth0 '!' --dport 22\nto this aswell.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "wireguard" ]
stackoverflow_0067978912_wireguard.txt
Q: How do I rename all folders and files to lowercase on Linux? I have to rename a complete folder tree recursively so that no uppercase letter appears anywhere (it's C++ source code, but that shouldn't matter). Bonus points for ignoring CVS and Subversion version control files/folders. The preferred way would be a shell script, since a shell should be available on any Linux box. There were some valid arguments about details of the file renaming. I think files with the same lowercase names should be overwritten; it's the user's problem. When checked out on a case-ignoring file system, it would overwrite the first one with the latter, too. I would consider A-Z characters and transform them to a-z, everything else is just calling for problems (at least with source code). The script would be needed to run a build on a Linux system, so I think changes to CVS or Subversion version control files should be omitted. After all, it's just a scratch checkout. Maybe an "export" is more appropriate. A: Smaller still I quite like: rename 'y/A-Z/a-z/' * On case insensitive filesystems such as OS X's HFS+, you will want to add the -f flag: rename -f 'y/A-Z/a-z/' * A: A concise version using the "rename" command: find my_root_dir -depth -exec rename 's/(.*)\/([^\/]*)/$1\/\L$2/' {} \; This avoids problems with directories being renamed before files and trying to move files into non-existing directories (e.g. "A/A" into "a/a"). Or, a more verbose version without using "rename". for SRC in `find my_root_dir -depth` do DST=`dirname "${SRC}"`/`basename "${SRC}" | tr '[A-Z]' '[a-z]'` if [ "${SRC}" != "${DST}" ] then [ ! -e "${DST}" ] && mv -T "${SRC}" "${DST}" || echo "${SRC} was not renamed" fi done P.S. The latter allows more flexibility with the move command (for example, "svn mv"). A: for f in `find`; do mv -v "$f" "`echo $f | tr '[A-Z]' '[a-z]'`"; done A: Just simply try the following if you don't need to care about efficiency. zip -r foo.zip foo/* unzip -LL foo.zip A: One can simply use the following which is less complicated: rename 'y/A-Z/a-z/' * A: This works on CentOS/Red Hat Linux or other distributions without the rename Perl script: for i in $( ls | grep [A-Z] ); do mv -i "$i" "`echo $i | tr 'A-Z' 'a-z'`"; done Source: Rename all file names from uppercase to lowercase characters (In some distributions the default rename command comes from util-linux, and that is a different, incompatible tool.) A: This works if you already have or set up the rename command (e.g. through brew install in Mac): rename --lower-case --force somedir/* A: The simplest approach I found on Mac OS X was to use the rename package from http://plasmasturm.org/code/rename/: brew install rename rename --force --lower-case --nows * --force Rename even when a file with the destination name already exists. --lower-case Convert file names to all lower case. --nows Replace all sequences of whitespace in the filename with single underscore characters. A: Most of the answers above are dangerous, because they do not deal with names containing odd characters. Your safest bet for this kind of thing is to use find's -print0 option, which will terminate filenames with ASCII NUL instead of \n. Here is a script, which only alter files and not directory names so as not to confuse find: find . -type f -print0 | xargs -0n 1 bash -c \ 's=$(dirname "$0")/$(basename "$0"); d=$(dirname "$0")/$(basename "$0"|tr "[A-Z]" "[a-z]"); mv -f "$s" "$d"' I tested it, and it works with filenames containing spaces, all kinds of quotes, etc. This is important because if you run, as root, one of those other scripts on a tree that includes the file created by touch \;\ echo\ hacker::0:0:hacker:\$\'\057\'root:\$\'\057\'bin\$\'\057\'bash ... well guess what ... A: Here's my suboptimal solution, using a Bash shell script: #!/bin/bash # First, rename all folders for f in `find . -depth ! -name CVS -type d`; do g=`dirname "$f"`/`basename "$f" | tr '[A-Z]' '[a-z]'` if [ "xxx$f" != "xxx$g" ]; then echo "Renaming folder $f" mv -f "$f" "$g" fi done # Now, rename all files for f in `find . ! -type d`; do g=`dirname "$f"`/`basename "$f" | tr '[A-Z]' '[a-z]'` if [ "xxx$f" != "xxx$g" ]; then echo "Renaming file $f" mv -f "$f" "$g" fi done Folders are all renamed correctly, and mv isn't asking questions when permissions don't match, and CVS folders are not renamed (CVS control files inside that folder are still renamed, unfortunately). Since "find -depth" and "find | sort -r" both return the folder list in a usable order for renaming, I preferred using "-depth" for searching folders. A: One-liner: for F in K*; do NEWNAME=$(echo "$F" | tr '[:upper:]' '[:lower:]'); mv "$F" "$NEWNAME"; done Or even: for F in K*; do mv "$F" "${F,,}"; done Note that this will convert only files/directories starting with letter K, so adjust accordingly. A: Using Larry Wall's filename fixer: $op = shift or die $help; chomp(@ARGV = <STDIN>) unless @ARGV; for (@ARGV) { $was = $_; eval $op; die $@ if $@; rename($was,$_) unless $was eq $_; } It's as simple as find | fix 'tr/A-Z/a-z/' (where fix is of course the script above) A: The original question asked for ignoring SVN and CVS directories, which can be done by adding -prune to the find command. E.g to ignore CVS: find . -name CVS -prune -o -exec mv '{}' `echo {} | tr '[A-Z]' '[a-z]'` \; -print [edit] I tried this out, and embedding the lower-case translation inside the find didn't work for reasons I don't actually understand. So, amend this to: $> cat > tolower #!/bin/bash mv $1 `echo $1 | tr '[:upper:]' '[:lower:]'` ^D $> chmod u+x tolower $> find . -name CVS -prune -o -exec tolower '{}' \; Ian A: Not portable, Zsh only, but pretty concise. First, make sure zmv is loaded. autoload -U zmv Also, make sure extendedglob is on: setopt extendedglob Then use: zmv '(**/)(*)~CVS~**/CVS' '${1}${(L)2}' To recursively lowercase files and directories where the name is not CVS. A: This works nicely on macOS too: ruby -e "Dir['*'].each { |p| File.rename(p, p.downcase) }" A: This is a small shell script that does what you requested: root_directory="${1?-please specify parent directory}" do_it () { awk '{ lc= tolower($0); if (lc != $0) print "mv \"" $0 "\" \"" lc "\"" }' | sh } # first the folders find "$root_directory" -depth -type d | do_it find "$root_directory" ! -type d | do_it Note the -depth action in the first find. A: for f in `find -depth`; do mv ${f} ${f,,} ; done find -depth prints each file and directory, with a directory's contents printed before the directory itself. ${f,,} lowercases the file name. A: Use typeset: typeset -l new # Always lowercase find $topPoint | # Not using xargs to make this more readable while read old do new="$old" # $new is a lowercase version of $old mv "$old" "$new" # Quotes for those annoying embedded spaces done On Windows, emulations, like Git Bash, may fail because Windows isn't case-sensitive under the hood. For those, add a step that mv's the file to another name first, like "$old.tmp", and then to $new. A: In OS X, mv -f shows "same file" error, so I rename twice: for i in `find . -name "*" -type f |grep -e "[A-Z]"`; do j=`echo $i | tr '[A-Z]' '[a-z]' | sed s/\-1$//`; mv $i $i-1; mv $i-1 $j; done A: With MacOS, Install the rename package, brew install rename Use, find . -iname "*.py" -type f | xargs -I% rename -c -f "%" This command find all the files with a *.py extension and converts the filenames to lower case. `f` - forces a rename For example, $ find . -iname "*.py" -type f ./sample/Sample_File.py ./sample_file.py $ find . -iname "*.py" -type f | xargs -I% rename -c -f "%" $ find . -iname "*.py" -type f ./sample/sample_file.py ./sample_file.py A: Lengthy But "Works With No Surprises & No Installations" This script handles filenames with spaces, quotes, other unusual characters and Unicode, works on case insensitive filesystems and most Unix-y environments that have bash and awk installed (i.e. almost all). It also reports collisions if any (leaving the filename in uppercase) and of course renames both files & directories and works recursively. Finally it's highly adaptable: you can tweak the find command to target the files/dirs you wish and you can tweak awk to do other name manipulations. Note that by "handles Unicode" I mean that it will indeed convert their case (not ignore them like answers that use tr). # adapt the following command _IF_ you want to deal with specific files/dirs find . -depth -mindepth 1 -exec bash -c ' for file do # adapt the awk command if you wish to rename to something other than lowercase newname=$(dirname "$file")/$(basename "$file" | awk "{print tolower(\$0)}") if [ "$file" != "$newname" ] ; then # the extra step with the temp filename is for case-insensitive filesystems if [ ! -e "$newname" ] && [ ! -e "$newname.lcrnm.tmp" ] ; then mv -T "$file" "$newname.lcrnm.tmp" && mv -T "$newname.lcrnm.tmp" "$newname" else echo "ERROR: Name already exists: $newname" fi fi done ' sh {} + References My script is based on these excellent answers: https://unix.stackexchange.com/questions/9496/looping-through-files-with-spaces-in-the-names How to convert a string to lower case in Bash? A: I needed to do this on a Cygwin setup on Windows 7 and found that I got syntax errors with the suggestions from above that I tried (though I may have missed a working option). However, this solution straight from Ubuntu forums worked out of the can :-) ls | while read upName; do loName=`echo "${upName}" | tr '[:upper:]' '[:lower:]'`; mv "$upName" "$loName"; done (NB: I had previously replaced whitespace with underscores using: for f in *\ *; do mv "$f" "${f// /_}"; done ) A: Slugify Rename (regex) It is not exactly what the OP asked for, but what I was hoping to find on this page: A "slugify" version for renaming files so they are similar to URLs (i.e. only include alphanumeric, dots, and dashes): rename "s/[^a-zA-Z0-9\.]+/-/g" filename A: I would reach for Python in this situation, to avoid optimistically assuming paths without spaces or slashes. I've also found that python2 tends to be installed in more places than rename. #!/usr/bin/env python2 import sys, os def rename_dir(directory): print('DEBUG: rename('+directory+')') # Rename current directory if needed os.rename(directory, directory.lower()) directory = directory.lower() # Rename children for fn in os.listdir(directory): path = os.path.join(directory, fn) os.rename(path, path.lower()) path = path.lower() # Rename children within, if this child is a directory if os.path.isdir(path): rename_dir(path) # Run program, using the first argument passed to this Python script as the name of the folder rename_dir(sys.argv[1]) A: If you use Arch Linux, you can install rename) package from AUR that provides the renamexm command as /usr/bin/renamexm executable and a manual page along with it. It is a really powerful tool to quickly rename files and directories. Convert to lowercase rename -l Developers.mp3 # or --lowcase Convert to UPPER case rename -u developers.mp3 # or --upcase, long option Other options -R --recursive # directory and its children -t --test # Dry run, output but don't rename -o --owner # Change file owner as well to user specified -v --verbose # Output what file is renamed and its new name -s/str/str2 # Substitute string on pattern --yes # Confirm all actions You can fetch the sample Developers.mp3 file from here, if needed ;) A: None of the solutions here worked for me because I was on a system that didn't have access to the perl rename script, plus some of the files included spaces. However, I found a variant that works: find . -depth -exec sh -c ' t=${0%/*}/$(printf %s "${0##*/}" | tr "[:upper:]" "[:lower:]"); [ "$t" = "$0" ] || mv -i "$0" "$t" ' {} \; Credit goes to "Gilles 'SO- stop being evil'", see this answer on the similar question "change entire directory tree to lower-case names" on the Unix & Linux StackExchange. A: I believe the one-liners can be simplified: for f in **/*; do mv "$f" "${f:l}"; done A: ( find YOURDIR -type d | sort -r; find yourdir -type f ) | grep -v /CVS | grep -v /SVN | while read f; do mv -v $f `echo $f | tr '[A-Z]' '[a-z]'`; done First rename the directories bottom up sort -r (where -depth is not available), then the files. Then grep -v /CVS instead of find ...-prune because it's simpler. For large directories, for f in ... can overflow some shell buffers. Use find ... | while read to avoid that. And yes, this will clobber files which differ only in case... A: find . -depth -name '*[A-Z]*'|sed -n 's/\(.*\/\)\(.*\)/mv -n -v -T \1\2 \1\L\2/p'|sh I haven't tried the more elaborate scripts mentioned here, but none of the single commandline versions worked for me on my Synology NAS. rename is not available, and many of the variations of find fail because it seems to stick to the older name of the already renamed path (eg, if it finds ./FOO followed by ./FOO/BAR, renaming ./FOO to ./foo will still continue to list ./FOO/BAR even though that path is no longer valid). Above command worked for me without any issues. What follows is an explanation of each part of the command: find . -depth -name '*[A-Z]*' This will find any file from the current directory (change . to whatever directory you want to process), using a depth-first search (eg., it will list ./foo/bar before ./foo), but only for files that contain an uppercase character. The -name filter only applies to the base file name, not the full path. So this will list ./FOO/BAR but not ./FOO/bar. This is ok, as we don't want to rename ./FOO/bar. We want to rename ./FOO though, but that one is listed later on (this is why -depth is important). This comand in itself is particularly useful to finding the files that you want to rename in the first place. Use this after the complete rename command to search for files that still haven't been replaced because of file name collisions or errors. sed -n 's/\(.*\/\)\(.*\)/mv -n -v -T \1\2 \1\L\2/p' This part reads the files outputted by find and formats them in a mv command using a regular expression. The -n option stops sed from printing the input, and the p command in the search-and-replace regex outputs the replaced text. The regex itself consists of two captures: the part up until the last / (which is the directory of the file), and the filename itself. The directory is left intact, but the filename is transformed to lowercase. So, if find outputs ./FOO/BAR, it will become mv -n -v -T ./FOO/BAR ./FOO/bar. The -n option of mv makes sure existing lowercase files are not overwritten. The -v option makes mv output every change that it makes (or doesn't make - if ./FOO/bar already exists, it outputs something like ./FOO/BAR -> ./FOO/BAR, noting that no change has been made). The -T is very important here - it treats the target file as a directory. This will make sure that ./FOO/BAR isn't moved into ./FOO/bar if that directory happens to exist. Use this together with find to generate a list of commands that will be executed (handy to verify what will be done without actually doing it) sh This pretty self-explanatory. It routes all the generated mv commands to the shell interpreter. You can replace it with bash or any shell of your liking. A: Using bash, without rename: find . -exec bash -c 'mv $0 ${0,,}' {} \;
How do I rename all folders and files to lowercase on Linux?
I have to rename a complete folder tree recursively so that no uppercase letter appears anywhere (it's C++ source code, but that shouldn't matter). Bonus points for ignoring CVS and Subversion version control files/folders. The preferred way would be a shell script, since a shell should be available on any Linux box. There were some valid arguments about details of the file renaming. I think files with the same lowercase names should be overwritten; it's the user's problem. When checked out on a case-ignoring file system, it would overwrite the first one with the latter, too. I would consider A-Z characters and transform them to a-z, everything else is just calling for problems (at least with source code). The script would be needed to run a build on a Linux system, so I think changes to CVS or Subversion version control files should be omitted. After all, it's just a scratch checkout. Maybe an "export" is more appropriate.
[ "Smaller still I quite like:\nrename 'y/A-Z/a-z/' *\n\nOn case insensitive filesystems such as OS X's HFS+, you will want to add the -f flag:\nrename -f 'y/A-Z/a-z/' *\n\n", "A concise version using the \"rename\" command:\nfind my_root_dir -depth -exec rename 's/(.*)\\/([^\\/]*)/$1\\/\\L$2/' {} \\;\n\nThis avoids problems with directories being renamed before files and trying to move files into non-existing directories (e.g. \"A/A\" into \"a/a\").\nOr, a more verbose version without using \"rename\".\nfor SRC in `find my_root_dir -depth`\ndo\n DST=`dirname \"${SRC}\"`/`basename \"${SRC}\" | tr '[A-Z]' '[a-z]'`\n if [ \"${SRC}\" != \"${DST}\" ]\n then\n [ ! -e \"${DST}\" ] && mv -T \"${SRC}\" \"${DST}\" || echo \"${SRC} was not renamed\"\n fi\ndone\n\nP.S.\nThe latter allows more flexibility with the move command (for example, \"svn mv\").\n", "for f in `find`; do mv -v \"$f\" \"`echo $f | tr '[A-Z]' '[a-z]'`\"; done\n\n", "Just simply try the following if you don't need to care about efficiency.\nzip -r foo.zip foo/*\nunzip -LL foo.zip\n\n", "One can simply use the following which is less complicated:\nrename 'y/A-Z/a-z/' *\n\n", "This works on CentOS/Red Hat Linux or other distributions without the rename Perl script:\nfor i in $( ls | grep [A-Z] ); do mv -i \"$i\" \"`echo $i | tr 'A-Z' 'a-z'`\"; done\n\nSource: Rename all file names from uppercase to lowercase characters\n(In some distributions the default rename command comes from util-linux, and that is a different, incompatible tool.)\n", "This works if you already have or set up the rename command (e.g. through brew install in Mac):\nrename --lower-case --force somedir/*\n\n", "The simplest approach I found on Mac OS X was to use the rename package from http://plasmasturm.org/code/rename/:\nbrew install rename\nrename --force --lower-case --nows *\n\n\n--force Rename even when a file with the destination name already exists.\n--lower-case Convert file names to all lower case.\n--nows Replace all sequences of whitespace in the filename with single underscore characters.\n\n", "Most of the answers above are dangerous, because they do not deal with names containing odd characters. Your safest bet for this kind of thing is to use find's -print0 option, which will terminate filenames with ASCII NUL instead of \\n.\nHere is a script, which only alter files and not directory names so as not to confuse find:\nfind . -type f -print0 | xargs -0n 1 bash -c \\\n's=$(dirname \"$0\")/$(basename \"$0\");\nd=$(dirname \"$0\")/$(basename \"$0\"|tr \"[A-Z]\" \"[a-z]\"); mv -f \"$s\" \"$d\"'\n\nI tested it, and it works with filenames containing spaces, all kinds of quotes, etc. This is important because if you run, as root, one of those other scripts on a tree that includes the file created by\ntouch \\;\\ echo\\ hacker::0:0:hacker:\\$\\'\\057\\'root:\\$\\'\\057\\'bin\\$\\'\\057\\'bash\n\n... well guess what ...\n", "Here's my suboptimal solution, using a Bash shell script:\n#!/bin/bash\n# First, rename all folders\nfor f in `find . -depth ! -name CVS -type d`; do\n g=`dirname \"$f\"`/`basename \"$f\" | tr '[A-Z]' '[a-z]'`\n if [ \"xxx$f\" != \"xxx$g\" ]; then\n echo \"Renaming folder $f\"\n mv -f \"$f\" \"$g\"\n fi\ndone\n\n# Now, rename all files\nfor f in `find . ! -type d`; do\n g=`dirname \"$f\"`/`basename \"$f\" | tr '[A-Z]' '[a-z]'`\n if [ \"xxx$f\" != \"xxx$g\" ]; then\n echo \"Renaming file $f\"\n mv -f \"$f\" \"$g\"\n fi\ndone\n\nFolders are all renamed correctly, and mv isn't asking questions when permissions don't match, and CVS folders are not renamed (CVS control files inside that folder are still renamed, unfortunately).\nSince \"find -depth\" and \"find | sort -r\" both return the folder list in a usable order for renaming, I preferred using \"-depth\" for searching folders.\n", "One-liner:\nfor F in K*; do NEWNAME=$(echo \"$F\" | tr '[:upper:]' '[:lower:]'); mv \"$F\" \"$NEWNAME\"; done\n\nOr even:\nfor F in K*; do mv \"$F\" \"${F,,}\"; done\n\nNote that this will convert only files/directories starting with letter K, so adjust accordingly.\n", "Using Larry Wall's filename fixer:\n$op = shift or die $help;\nchomp(@ARGV = <STDIN>) unless @ARGV;\nfor (@ARGV) {\n $was = $_;\n eval $op;\n die $@ if $@;\n rename($was,$_) unless $was eq $_;\n}\n\nIt's as simple as\nfind | fix 'tr/A-Z/a-z/'\n\n(where fix is of course the script above)\n", "The original question asked for ignoring SVN and CVS directories, which can be done by adding -prune to the find command. E.g to ignore CVS:\nfind . -name CVS -prune -o -exec mv '{}' `echo {} | tr '[A-Z]' '[a-z]'` \\; -print\n\n[edit] I tried this out, and embedding the lower-case translation inside the find didn't work for reasons I don't actually understand. So, amend this to:\n$> cat > tolower\n#!/bin/bash\nmv $1 `echo $1 | tr '[:upper:]' '[:lower:]'`\n^D\n$> chmod u+x tolower \n$> find . -name CVS -prune -o -exec tolower '{}' \\;\n\nIan\n", "Not portable, Zsh only, but pretty concise.\nFirst, make sure zmv is loaded.\nautoload -U zmv\n\nAlso, make sure extendedglob is on:\nsetopt extendedglob\n\nThen use:\nzmv '(**/)(*)~CVS~**/CVS' '${1}${(L)2}'\n\nTo recursively lowercase files and directories where the name is not CVS.\n", "This works nicely on macOS too:\nruby -e \"Dir['*'].each { |p| File.rename(p, p.downcase) }\"\n\n", "This is a small shell script that does what you requested:\nroot_directory=\"${1?-please specify parent directory}\"\ndo_it () {\n awk '{ lc= tolower($0); if (lc != $0) print \"mv \\\"\" $0 \"\\\" \\\"\" lc \"\\\"\" }' | sh\n}\n# first the folders\nfind \"$root_directory\" -depth -type d | do_it\nfind \"$root_directory\" ! -type d | do_it\n\nNote the -depth action in the first find.\n", "for f in `find -depth`; do mv ${f} ${f,,} ; done\n\nfind -depth prints each file and directory, with a directory's contents printed before the directory itself. ${f,,} lowercases the file name.\n", "Use typeset:\ntypeset -l new # Always lowercase\nfind $topPoint | # Not using xargs to make this more readable\n while read old\n do new=\"$old\" # $new is a lowercase version of $old\n mv \"$old\" \"$new\" # Quotes for those annoying embedded spaces\n done\n\nOn Windows, emulations, like Git Bash, may fail because Windows isn't case-sensitive under the hood. For those, add a step that mv's the file to another name first, like \"$old.tmp\", and then to $new.\n", "In OS X, mv -f shows \"same file\" error, so I rename twice:\nfor i in `find . -name \"*\" -type f |grep -e \"[A-Z]\"`; do j=`echo $i | tr '[A-Z]' '[a-z]' | sed s/\\-1$//`; mv $i $i-1; mv $i-1 $j; done\n\n", "With MacOS,\nInstall the rename package,\nbrew install rename\n\nUse,\nfind . -iname \"*.py\" -type f | xargs -I% rename -c -f \"%\" \n\nThis command find all the files with a *.py extension and converts the filenames to lower case.\n`f` - forces a rename\n\nFor example,\n$ find . -iname \"*.py\" -type f\n./sample/Sample_File.py\n./sample_file.py\n$ find . -iname \"*.py\" -type f | xargs -I% rename -c -f \"%\"\n$ find . -iname \"*.py\" -type f\n./sample/sample_file.py\n./sample_file.py\n\n", "Lengthy But \"Works With No Surprises & No Installations\"\nThis script handles filenames with spaces, quotes, other unusual characters and Unicode, works on case insensitive filesystems and most Unix-y environments that have bash and awk installed (i.e. almost all). It also reports collisions if any (leaving the filename in uppercase) and of course renames both files & directories and works recursively. Finally it's highly adaptable: you can tweak the find command to target the files/dirs you wish and you can tweak awk to do other name manipulations. Note that by \"handles Unicode\" I mean that it will indeed convert their case (not ignore them like answers that use tr).\n# adapt the following command _IF_ you want to deal with specific files/dirs\nfind . -depth -mindepth 1 -exec bash -c '\n for file do\n # adapt the awk command if you wish to rename to something other than lowercase\n newname=$(dirname \"$file\")/$(basename \"$file\" | awk \"{print tolower(\\$0)}\")\n if [ \"$file\" != \"$newname\" ] ; then\n # the extra step with the temp filename is for case-insensitive filesystems\n if [ ! -e \"$newname\" ] && [ ! -e \"$newname.lcrnm.tmp\" ] ; then\n mv -T \"$file\" \"$newname.lcrnm.tmp\" && mv -T \"$newname.lcrnm.tmp\" \"$newname\" \n else\n echo \"ERROR: Name already exists: $newname\"\n fi\n fi \n done\n' sh {} +\n\n\nReferences\nMy script is based on these excellent answers:\nhttps://unix.stackexchange.com/questions/9496/looping-through-files-with-spaces-in-the-names\nHow to convert a string to lower case in Bash?\n", "I needed to do this on a Cygwin setup on Windows 7 and found that I got syntax errors with the suggestions from above that I tried (though I may have missed a working option). However, this solution straight from Ubuntu forums worked out of the can :-)\nls | while read upName; do loName=`echo \"${upName}\" | tr '[:upper:]' '[:lower:]'`; mv \"$upName\" \"$loName\"; done\n\n(NB: I had previously replaced whitespace with underscores using:\nfor f in *\\ *; do mv \"$f\" \"${f// /_}\"; done\n\n)\n", "Slugify Rename (regex)\nIt is not exactly what the OP asked for, but what I was hoping to find on this page:\nA \"slugify\" version for renaming files so they are similar to URLs (i.e. only include alphanumeric, dots, and dashes):\nrename \"s/[^a-zA-Z0-9\\.]+/-/g\" filename\n\n", "I would reach for Python in this situation, to avoid optimistically assuming paths without spaces or slashes. I've also found that python2 tends to be installed in more places than rename.\n#!/usr/bin/env python2\nimport sys, os\n\ndef rename_dir(directory):\n print('DEBUG: rename('+directory+')')\n\n # Rename current directory if needed\n os.rename(directory, directory.lower())\n directory = directory.lower()\n\n # Rename children\n for fn in os.listdir(directory):\n path = os.path.join(directory, fn)\n os.rename(path, path.lower())\n path = path.lower()\n\n # Rename children within, if this child is a directory\n if os.path.isdir(path):\n rename_dir(path)\n\n# Run program, using the first argument passed to this Python script as the name of the folder\nrename_dir(sys.argv[1])\n\n", "If you use Arch Linux, you can install rename) package from AUR that provides the renamexm command as /usr/bin/renamexm executable and a manual page along with it.\nIt is a really powerful tool to quickly rename files and directories.\nConvert to lowercase\nrename -l Developers.mp3 # or --lowcase\n\nConvert to UPPER case\nrename -u developers.mp3 # or --upcase, long option\n\nOther options\n-R --recursive # directory and its children\n\n-t --test # Dry run, output but don't rename\n\n-o --owner # Change file owner as well to user specified\n\n-v --verbose # Output what file is renamed and its new name\n\n-s/str/str2 # Substitute string on pattern\n\n--yes # Confirm all actions\n\nYou can fetch the sample Developers.mp3 file from here, if needed ;)\n", "None of the solutions here worked for me because I was on a system that didn't have access to the perl rename script, plus some of the files included spaces. However, I found a variant that works:\nfind . -depth -exec sh -c '\n t=${0%/*}/$(printf %s \"${0##*/}\" | tr \"[:upper:]\" \"[:lower:]\");\n [ \"$t\" = \"$0\" ] || mv -i \"$0\" \"$t\"\n' {} \\;\n\nCredit goes to \"Gilles 'SO- stop being evil'\", see this answer on the similar question \"change entire directory tree to lower-case names\" on the Unix & Linux StackExchange.\n", "I believe the one-liners can be simplified:\nfor f in **/*; do mv \"$f\" \"${f:l}\"; done\n", "( find YOURDIR -type d | sort -r;\n find yourdir -type f ) |\ngrep -v /CVS | grep -v /SVN |\nwhile read f; do mv -v $f `echo $f | tr '[A-Z]' '[a-z]'`; done\n\nFirst rename the directories bottom up sort -r (where -depth is not available), then the files.\nThen grep -v /CVS instead of find ...-prune because it's simpler.\nFor large directories, for f in ... can overflow some shell buffers.\nUse find ... | while read to avoid that.\nAnd yes, this will clobber files which differ only in case...\n", "find . -depth -name '*[A-Z]*'|sed -n 's/\\(.*\\/\\)\\(.*\\)/mv -n -v -T \\1\\2 \\1\\L\\2/p'|sh\n\nI haven't tried the more elaborate scripts mentioned here, but none of the single commandline versions worked for me on my Synology NAS. rename is not available, and many of the variations of find fail because it seems to stick to the older name of the already renamed path (eg, if it finds ./FOO followed by ./FOO/BAR, renaming ./FOO to ./foo will still continue to list ./FOO/BAR even though that path is no longer valid). Above command worked for me without any issues.\nWhat follows is an explanation of each part of the command:\n\nfind . -depth -name '*[A-Z]*'\n\nThis will find any file from the current directory (change . to whatever directory you want to process), using a depth-first search (eg., it will list ./foo/bar before ./foo), but only for files that contain an uppercase character. The -name filter only applies to the base file name, not the full path. So this will list ./FOO/BAR but not ./FOO/bar. This is ok, as we don't want to rename ./FOO/bar. We want to rename ./FOO though, but that one is listed later on (this is why -depth is important).\nThis comand in itself is particularly useful to finding the files that you want to rename in the first place. Use this after the complete rename command to search for files that still haven't been replaced because of file name collisions or errors.\n\nsed -n 's/\\(.*\\/\\)\\(.*\\)/mv -n -v -T \\1\\2 \\1\\L\\2/p'\n\nThis part reads the files outputted by find and formats them in a mv command using a regular expression. The -n option stops sed from printing the input, and the p command in the search-and-replace regex outputs the replaced text.\nThe regex itself consists of two captures: the part up until the last / (which is the directory of the file), and the filename itself. The directory is left intact, but the filename is transformed to lowercase. So, if find outputs ./FOO/BAR, it will become mv -n -v -T ./FOO/BAR ./FOO/bar. The -n option of mv makes sure existing lowercase files are not overwritten. The -v option makes mv output every change that it makes (or doesn't make - if ./FOO/bar already exists, it outputs something like ./FOO/BAR -> ./FOO/BAR, noting that no change has been made). The -T is very important here - it treats the target file as a directory. This will make sure that ./FOO/BAR isn't moved into ./FOO/bar if that directory happens to exist.\nUse this together with find to generate a list of commands that will be executed (handy to verify what will be done without actually doing it)\n\nsh\n\nThis pretty self-explanatory. It routes all the generated mv commands to the shell interpreter. You can replace it with bash or any shell of your liking.\n", "Using bash, without rename:\nfind . -exec bash -c 'mv $0 ${0,,}' {} \\;\n\n" ]
[ 311, 197, 109, 108, 26, 19, 18, 18, 16, 6, 6, 5, 5, 5, 4, 3, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "linux", "lowercase", "rename" ]
stackoverflow_0000152514_linux_lowercase_rename.txt
Q: ListTile Heading, Trailing are not Centered So this seems basic but I can't figure it out. I have a ListTile that has a leading checkbox, a title, and a trailing icon. With the last Flutter update, the checkbox and icon are no longer centered for some reason. I want them centered vertically. I tried adding Center(), Align(), Expanded(), and Flexible() in various ways to the checkbox but it just pushes the title off the screen or does nothing. Any tips? Any help is appreciated. ListTile( leading: Checkbox( value: item.checked, onChanged: (bool newValue) { setState(() { item.checked = newValue; }); firestoreUtil.updateList(user, taskList); }, activeColor: Theme.of(context).primaryColor, ), title: InkWell( onTap: () { editTask(item); }, child: Text( item.task, style: TextStyle(fontSize: 18), )), trailing: ReorderableListener( child: Container( padding: EdgeInsets.only(right: 16), child: Icon(Icons.drag_handle)), ), contentPadding: EdgeInsets.all(8), ), Debug mode: A: Use Column inside the leading, and set the MainAxisAlignment to center leading: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Icon(leadingnIcon, color: Colors.blueGrey,), ], ), A: Just add Icon inside Container with double.infinity height. leading: Container( height: double.infinity, child: Icon(Icons.star), ), A: I solved this by just making my own ListTile. It's basically just a row with padding. Works great and is more customizable than ListTile. A: This below trick work for me, leading: Container( constraints: const BoxConstraints(minWidth: 70.0, maxWidth: 80), height: double.infinity, child: Align( alignment: Alignment.centerLeft, child: Text( .... A: In case you choose to go the DIY route, here's an example implementation of a simple ListTile: class CustomListTile extends StatelessWidget { const CustomListTile( {Key? key, required this.title, this.content, this.leading, this.trailing, this.onTap}) : super(key: key); final Widget title; final Widget? content; final Widget? leading; final Widget? trailing; final VoidCallback? onTap; @override Widget build(BuildContext context) { return InkWell( onTap: onTap, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ leading ?? const SizedBox(), const SizedBox(width: 20), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ title, const SizedBox(height: 4), content ?? const SizedBox(), ], ), ), trailing ?? const SizedBox(), ], ), ), ); } } A: You can do it like this, there is no better solution ListTile( minLeadingWidth: 0.0, minVerticalPadding: 0.0, contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), title: Text('Bla bla'), leading: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(Icons.close) ], ), ) A: This worked for me! ListTile( leading: const SizedBox( height: double.infinity, child: Icon(Icons.location_on_rounded)), tileColor: DesignColor.grey, title: "Title 1".textMediumRegular(), subtitle: "Title 2".textSmall(), trailing: const SizedBox( height: double.infinity, child: Icon(Icons.edit_rounded)), ) Output:
ListTile Heading, Trailing are not Centered
So this seems basic but I can't figure it out. I have a ListTile that has a leading checkbox, a title, and a trailing icon. With the last Flutter update, the checkbox and icon are no longer centered for some reason. I want them centered vertically. I tried adding Center(), Align(), Expanded(), and Flexible() in various ways to the checkbox but it just pushes the title off the screen or does nothing. Any tips? Any help is appreciated. ListTile( leading: Checkbox( value: item.checked, onChanged: (bool newValue) { setState(() { item.checked = newValue; }); firestoreUtil.updateList(user, taskList); }, activeColor: Theme.of(context).primaryColor, ), title: InkWell( onTap: () { editTask(item); }, child: Text( item.task, style: TextStyle(fontSize: 18), )), trailing: ReorderableListener( child: Container( padding: EdgeInsets.only(right: 16), child: Icon(Icons.drag_handle)), ), contentPadding: EdgeInsets.all(8), ), Debug mode:
[ "Use Column inside the leading, and set the MainAxisAlignment to center\n leading: Column(\n mainAxisAlignment: MainAxisAlignment.center,\n children: <Widget>[\n Icon(leadingnIcon, color: Colors.blueGrey,),\n ],\n ),\n\n", "Just add Icon inside Container with double.infinity height.\nleading: Container(\n height: double.infinity,\n child: Icon(Icons.star),\n ),\n\n", "I solved this by just making my own ListTile. It's basically just a row with padding. Works great and is more customizable than ListTile.\n", "This below trick work for me,\nleading: Container(\n constraints: const BoxConstraints(minWidth: 70.0, maxWidth: 80),\n height: double.infinity,\n child: Align(\n alignment: Alignment.centerLeft,\n child: Text( \n ....\n\n", "In case you choose to go the DIY route, here's an example implementation of a simple ListTile:\nclass CustomListTile extends StatelessWidget {\n const CustomListTile(\n {Key? key,\n required this.title,\n this.content,\n this.leading,\n this.trailing,\n this.onTap})\n : super(key: key);\n final Widget title;\n final Widget? content;\n final Widget? leading;\n final Widget? trailing;\n final VoidCallback? onTap;\n\n @override\n Widget build(BuildContext context) {\n return InkWell(\n onTap: onTap,\n child: Padding(\n padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),\n child: Row(\n crossAxisAlignment: CrossAxisAlignment.start,\n children: [\n leading ?? const SizedBox(),\n const SizedBox(width: 20),\n Expanded(\n child: Column(\n crossAxisAlignment: CrossAxisAlignment.start,\n children: [\n title,\n const SizedBox(height: 4),\n content ?? const SizedBox(),\n ],\n ),\n ),\n trailing ?? const SizedBox(),\n ],\n ),\n ),\n );\n }\n}\n\n", "You can do it like this, there is no better solution\nListTile(\n minLeadingWidth: 0.0,\n minVerticalPadding: 0.0,\n contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),\n title: Text('Bla bla'),\n leading: Column(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Icon(Icons.close)\n ],\n ),\n)\n\n", "This worked for me!\nListTile(\n leading: const SizedBox(\n height: double.infinity,\n child: Icon(Icons.location_on_rounded)),\n tileColor: DesignColor.grey,\n title: \"Title 1\".textMediumRegular(),\n subtitle: \"Title 2\".textSmall(),\n trailing: const SizedBox(\n height: double.infinity,\n child: Icon(Icons.edit_rounded)),\n)\n\nOutput:\n\n" ]
[ 59, 44, 3, 1, 0, 0, 0 ]
[]
[]
[ "dart", "flutter" ]
stackoverflow_0055168962_dart_flutter.txt
Q: How to run two processes with dockerfile? I need to run uvicorn server process and my python script (which is another process). Since uvicorn start a process that doesn't end, the second command will not start. So i ask you if you know some workaround to overcome this problem. I tried to do this command: CMD cd Manager ; uvicorn ManagerBot:app --host 0.0.0.0 --port 8000 && python ManagerBot.py also this: CMD cd Manager ; uvicorn ManagerBot:app --host 0.0.0.0 --port 8000 ; python ManagerBot.py But the script doesn't start (only the uvicorn server start) I remind you that, the script, is another process that doesn't end so the "viceversa" will not work. A: Create a wrapper script, e.g. run.sh: #!/bin/bash # Start the first process uvicorn ManagerBot:app --host 0.0.0.0 --port 8000 & # Start the second process python ManagerBot.py & # Wait for any process to exit wait -n # Exit with status of process that exited first exit $? Then, in Dockerfile: ... COPY run.sh /run.sh RUN chmod +x /run.sh ENTRYPOINT ["/run.sh"]
How to run two processes with dockerfile?
I need to run uvicorn server process and my python script (which is another process). Since uvicorn start a process that doesn't end, the second command will not start. So i ask you if you know some workaround to overcome this problem. I tried to do this command: CMD cd Manager ; uvicorn ManagerBot:app --host 0.0.0.0 --port 8000 && python ManagerBot.py also this: CMD cd Manager ; uvicorn ManagerBot:app --host 0.0.0.0 --port 8000 ; python ManagerBot.py But the script doesn't start (only the uvicorn server start) I remind you that, the script, is another process that doesn't end so the "viceversa" will not work.
[ "Create a wrapper script, e.g. run.sh:\n#!/bin/bash\n\n# Start the first process\nuvicorn ManagerBot:app --host 0.0.0.0 --port 8000 &\n \n# Start the second process\npython ManagerBot.py &\n \n# Wait for any process to exit\nwait -n\n \n# Exit with status of process that exited first\nexit $?\n\nThen, in Dockerfile:\n... \nCOPY run.sh /run.sh\nRUN chmod +x /run.sh\nENTRYPOINT [\"/run.sh\"]\n\n" ]
[ 1 ]
[]
[]
[ "command", "docker", "dockerfile", "python", "server" ]
stackoverflow_0074678353_command_docker_dockerfile_python_server.txt
Q: How to Load More Posts In CollectionView? i am making app with Xcode using Swift , i fetch posts from my WordPress Website, i am very new to Xcode and Swift , i have fetched posts from my Website Successfully , now the problem is that when is try to load more posts (More than 10 posts) , i mean pagination, i see some problems, like when i do pagination after 10th post, it show the next 11-20 posts but it not starts from post 11th but it goes directly to post 20 and because of that , all next posts loaded automatically untill the end of posts, and one more thing when next posts are loading than i can't see the old posts like when 11-20 posts loaded then 1-10 posts are not shown and CollectionView starts from number 11. this is my code to fetch posts.. func fetchPostData(completionHandler: @escaping ([Post]) -> Void ) { self.page += 1 let url = URL(string: "https://www.sikhnama.com/wp-json/wp/v2/posts/?categories=6&page=\(page)")! let task = URLSession.shared.dataTask(with: url) { (data, response, error) in guard let data = data else {return} do { let postsData = try JSONDecoder().decode([Post].self, from: data) completionHandler(postsData) DispatchQueue.main.async { self.collectionView.reloadData() } } catch { let error = error print(String(describing: error)) } }.resume() } in ViewDid Load self.fetchPostData { (posts) in self.newsData = posts } and this is how i do pagination func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if indexPath.row == self.newsData.count - 1 { //numberofitem count updateNextSet() } } func updateNextSet(){ self.fetchPostData { (posts) in self.newsData = posts } } CollectionView Code extension ViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return self.newsData.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MovieCollectionViewCell", for: indexPath) as! MovieCollectionViewCell cell.setup(with: newsData[indexPath.row]) return cell } please help . thanks A: When the next batch of posts come back, you are overwriting the existing posts rather than appending them: self.fetchPostData { (posts) in self.newsData = posts } Instead, you need to append the new posts instead such as by using the += operator. In addition, you should call reloadData() within the fetchPostData completion handler rather than inside the response of the HTTP request to give your code better separation of concerns. So the above code would become: self.fetchPostData { (posts) in self.newsData += posts self.collectionView.reloadData() }
How to Load More Posts In CollectionView?
i am making app with Xcode using Swift , i fetch posts from my WordPress Website, i am very new to Xcode and Swift , i have fetched posts from my Website Successfully , now the problem is that when is try to load more posts (More than 10 posts) , i mean pagination, i see some problems, like when i do pagination after 10th post, it show the next 11-20 posts but it not starts from post 11th but it goes directly to post 20 and because of that , all next posts loaded automatically untill the end of posts, and one more thing when next posts are loading than i can't see the old posts like when 11-20 posts loaded then 1-10 posts are not shown and CollectionView starts from number 11. this is my code to fetch posts.. func fetchPostData(completionHandler: @escaping ([Post]) -> Void ) { self.page += 1 let url = URL(string: "https://www.sikhnama.com/wp-json/wp/v2/posts/?categories=6&page=\(page)")! let task = URLSession.shared.dataTask(with: url) { (data, response, error) in guard let data = data else {return} do { let postsData = try JSONDecoder().decode([Post].self, from: data) completionHandler(postsData) DispatchQueue.main.async { self.collectionView.reloadData() } } catch { let error = error print(String(describing: error)) } }.resume() } in ViewDid Load self.fetchPostData { (posts) in self.newsData = posts } and this is how i do pagination func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if indexPath.row == self.newsData.count - 1 { //numberofitem count updateNextSet() } } func updateNextSet(){ self.fetchPostData { (posts) in self.newsData = posts } } CollectionView Code extension ViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return self.newsData.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MovieCollectionViewCell", for: indexPath) as! MovieCollectionViewCell cell.setup(with: newsData[indexPath.row]) return cell } please help . thanks
[ "When the next batch of posts come back, you are overwriting the existing posts rather than appending them:\nself.fetchPostData { (posts) in\n self.newsData = posts \n}\n\nInstead, you need to append the new posts instead such as by using the += operator.\nIn addition, you should call reloadData() within the fetchPostData completion handler rather than inside the response of the HTTP request to give your code better separation of concerns.\nSo the above code would become:\nself.fetchPostData { (posts) in\n self.newsData += posts \n self.collectionView.reloadData()\n}\n\n" ]
[ 1 ]
[]
[]
[ "ios", "pagination", "swift", "swiftui", "uicollectionview" ]
stackoverflow_0074678241_ios_pagination_swift_swiftui_uicollectionview.txt
Q: Haskel how can I turn this list of string into a list of lists? The string looks like this: ",w84,w41,w56,w170,w56,w41,w84,/,,w24,w40,w17,w40,w48,,/ ,,,w16,w16,w16,,,/,,,,,,,,/,,,,,,,,/,,,,,,,,/,,,b1,b1,b1,,,/ ,,b3,b130,b17,b130,b129,,/,b69,b146,b131,b170,b131,b146,b69," But it should look like this [[Empty,Piece White 84,Piece White 41,Piece White 56,Piece White 170,Piece White 56,Piece White 41,Piece White 84,Empty],[Empty,Empty,Piece White 24,Piece White 40,Piece White 17,Piece White 40,Piece White 48,Empty,Empty],[Empty,Empty,Empty,Piece White 16,Piece White 16,Piece White 16,Empty,Empty,Empty],[Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty],[Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty],[Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty],[Empty,Empty,Empty,Piece Black 1,Piece Black 1,Piece Black 1,Empty,Empty,Empty],[Empty,Empty,Piece Black 3,Piece Black 130,Piece Black 17,Piece Black 130,Piece Black 129,Empty,Empty],[Empty,Piece Black 69,Piece Black 146,Piece Black 131,Piece Black 170,Piece Black 131,Piece Black 146,Piece Black 69,Empty]] The list my code creates looks like this: [["Empty,Piece White 84,Piece White 41,Piece White 56,Piece White 170,Piece White 56,Piece White 41,Piece White 84,Empty"], ["Empty,Empty,Piece White 24,Piece White 40,Piece White 17,Piece White 40,Piece White 48,Empty,Empty"], ["Empty,Empty,Empty,Piece White 16,Piece White 16,Piece White 16,Empty,Empty,Empty"], ["Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty"] data Player = Black | White deriving Show data Cell = Piece Player Int | Empty deriving Show data Pos = Pos { col :: Char, row :: Int } deriving Show type Board = [[Cell]] I have these data types. I am almost done with this task all I need is to get rid of the quotation marks. This is my code so far: buildBoard x = rec(help3(wop(helper (replaceO x)))) wop (x:xs) = splitOn "/" (x:xs) help3 (x:xs) = map (\x -> [x])(x:xs) rec (x:xs) = map(\x -> [recH(x)])(x:xs) recH (x:xs) = checkComma(x) helper (x:y:xs) |x == ',' && y == ',' = x:'E':'m':'p':'t':'y':helper(y:xs) |otherwise = x:helper (y:xs) helper [] = [] helper [x] = [x] checkComma (x:xs) = if head (x:xs) == ',' then checkComma('E':'m':'p':'t':'y':',':xs) else if last (x:xs) == ',' then reverse(turnAr(reverse(x:xs))) else (x:xs) turnAr (x:xs) = 'y':'t':'p':'m':'E':',':xs replaceO [] = [] replaceO (x:xs) = if x == 'w' then 'P':'i':'e':'c':'e':' ':'W':'h':'i':'t':'e':' ': replaceO xs else if x == 'b' then 'P':'i':'e':'c':'e':' ':'B':'l':'a':'c':'k':' ': replaceO xs else if x == 'E' then 'E':'m':'p':'t':'y':' ': replaceO xs else x : replaceO xs A: Just getting rid of the quotation marks is not something you can easily do. I think you'll have to make some significant changes to your code. I'd recommend doing the splitOn "/" first and then further splitOn "," which yields a list of lists of strings where each of the strings represents a cell. Then you can pretty easily write a function parseCell :: String -> Cell to parse those inner cells. This function will be a bit like your replaceO function but it should also handle all empty cells and actually parsing the integers (you can use the read function for that).
Haskel how can I turn this list of string into a list of lists?
The string looks like this: ",w84,w41,w56,w170,w56,w41,w84,/,,w24,w40,w17,w40,w48,,/ ,,,w16,w16,w16,,,/,,,,,,,,/,,,,,,,,/,,,,,,,,/,,,b1,b1,b1,,,/ ,,b3,b130,b17,b130,b129,,/,b69,b146,b131,b170,b131,b146,b69," But it should look like this [[Empty,Piece White 84,Piece White 41,Piece White 56,Piece White 170,Piece White 56,Piece White 41,Piece White 84,Empty],[Empty,Empty,Piece White 24,Piece White 40,Piece White 17,Piece White 40,Piece White 48,Empty,Empty],[Empty,Empty,Empty,Piece White 16,Piece White 16,Piece White 16,Empty,Empty,Empty],[Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty],[Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty],[Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty],[Empty,Empty,Empty,Piece Black 1,Piece Black 1,Piece Black 1,Empty,Empty,Empty],[Empty,Empty,Piece Black 3,Piece Black 130,Piece Black 17,Piece Black 130,Piece Black 129,Empty,Empty],[Empty,Piece Black 69,Piece Black 146,Piece Black 131,Piece Black 170,Piece Black 131,Piece Black 146,Piece Black 69,Empty]] The list my code creates looks like this: [["Empty,Piece White 84,Piece White 41,Piece White 56,Piece White 170,Piece White 56,Piece White 41,Piece White 84,Empty"], ["Empty,Empty,Piece White 24,Piece White 40,Piece White 17,Piece White 40,Piece White 48,Empty,Empty"], ["Empty,Empty,Empty,Piece White 16,Piece White 16,Piece White 16,Empty,Empty,Empty"], ["Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty"] data Player = Black | White deriving Show data Cell = Piece Player Int | Empty deriving Show data Pos = Pos { col :: Char, row :: Int } deriving Show type Board = [[Cell]] I have these data types. I am almost done with this task all I need is to get rid of the quotation marks. This is my code so far: buildBoard x = rec(help3(wop(helper (replaceO x)))) wop (x:xs) = splitOn "/" (x:xs) help3 (x:xs) = map (\x -> [x])(x:xs) rec (x:xs) = map(\x -> [recH(x)])(x:xs) recH (x:xs) = checkComma(x) helper (x:y:xs) |x == ',' && y == ',' = x:'E':'m':'p':'t':'y':helper(y:xs) |otherwise = x:helper (y:xs) helper [] = [] helper [x] = [x] checkComma (x:xs) = if head (x:xs) == ',' then checkComma('E':'m':'p':'t':'y':',':xs) else if last (x:xs) == ',' then reverse(turnAr(reverse(x:xs))) else (x:xs) turnAr (x:xs) = 'y':'t':'p':'m':'E':',':xs replaceO [] = [] replaceO (x:xs) = if x == 'w' then 'P':'i':'e':'c':'e':' ':'W':'h':'i':'t':'e':' ': replaceO xs else if x == 'b' then 'P':'i':'e':'c':'e':' ':'B':'l':'a':'c':'k':' ': replaceO xs else if x == 'E' then 'E':'m':'p':'t':'y':' ': replaceO xs else x : replaceO xs
[ "Just getting rid of the quotation marks is not something you can easily do.\nI think you'll have to make some significant changes to your code. I'd recommend doing the splitOn \"/\" first and then further splitOn \",\" which yields a list of lists of strings where each of the strings represents a cell.\nThen you can pretty easily write a function parseCell :: String -> Cell to parse those inner cells. This function will be a bit like your replaceO function but it should also handle all empty cells and actually parsing the integers (you can use the read function for that).\n" ]
[ 1 ]
[]
[]
[ "haskell", "string" ]
stackoverflow_0074677284_haskell_string.txt
Q: Django admin site user password change Django admin site used to have a form to change the password for a user that wasn't the logged in user. You would look at the user's update page, and by the password field, there was a change password link. You would click it, and it would take you to a different page for changing the password. I used to take advantage of that page to allow changing of a user's password, without having to open the admin. In Django 4, it seems to now be missing. In fact, I can't figure out how one would change a user's password other than their own, without writing my own view. I have 2 questions: Is there a way in the admin site now to change a different user's password? If this view is gone, what is now the best way for a superuser to have a view that can change passwords for a user? Edit: This is what I see. There is no link to change the password where there used to be. A: Are you sure you have checked it right? When you select an user it appears by default in the upper part, just after some semi-blinded parameters of the password. A: The problem was when I am using AbstractBaseUser, and the admin site registration I was using admin.ModelAdmin instead of UserAdmin. from django.contrib.auth import get_user_model from django.contrib import admin from django.contrib.auth.admin import UserAdmin class EmployeeAdmin(UserAdmin): ordering = ['email', ] list_display = ['email', ] fieldsets = ( (None, {'fields': ('email', 'password')}), ('Info', {'fields': ('first_name', 'last_name', 'phone',)}), ('Address', {'fields': ('address', 'city', 'state', 'zip_code')}), ('Schedule', {'fields': ('time_off',)}), ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ('Important dates', {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( ("User Details", {'fields': ('email', 'password1', 'password2')}), ("Permission", {'fields': ('is_active', 'is_staff', 'is_admin')}), ) admin.site.register(get_user_model(), EmployeeAdmin)
Django admin site user password change
Django admin site used to have a form to change the password for a user that wasn't the logged in user. You would look at the user's update page, and by the password field, there was a change password link. You would click it, and it would take you to a different page for changing the password. I used to take advantage of that page to allow changing of a user's password, without having to open the admin. In Django 4, it seems to now be missing. In fact, I can't figure out how one would change a user's password other than their own, without writing my own view. I have 2 questions: Is there a way in the admin site now to change a different user's password? If this view is gone, what is now the best way for a superuser to have a view that can change passwords for a user? Edit: This is what I see. There is no link to change the password where there used to be.
[ "Are you sure you have checked it right? When you select an user it appears by default in the upper part, just after some semi-blinded parameters of the password.\n\n", "The problem was when I am using AbstractBaseUser, and the admin site registration I was using admin.ModelAdmin instead of UserAdmin.\nfrom django.contrib.auth import get_user_model\nfrom django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin\n\n\nclass EmployeeAdmin(UserAdmin):\n ordering = ['email', ]\n list_display = ['email', ]\n fieldsets = (\n (None, {'fields': ('email', 'password')}),\n ('Info', {'fields': ('first_name', 'last_name', 'phone',)}),\n ('Address', {'fields': ('address', 'city', 'state', 'zip_code')}),\n ('Schedule', {'fields': ('time_off',)}),\n ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser',\n 'groups', 'user_permissions')}),\n ('Important dates', {'fields': ('last_login', 'date_joined')}),\n )\n add_fieldsets = (\n (\"User Details\", {'fields': ('email', 'password1', 'password2')}),\n (\"Permission\", {'fields': ('is_active', 'is_staff', 'is_admin')}),\n )\n\n\nadmin.site.register(get_user_model(), EmployeeAdmin)\n\n" ]
[ 0, 0 ]
[]
[]
[ "django", "django_views" ]
stackoverflow_0074669595_django_django_views.txt
Q: PMD Ignore Spring Field Injections in gradle config Currently I have several Controllers that inject dependencies through a field marked with @Autowired. When I try to run gradle build the following violations come up. These all correspond to the instances of where a spring component has been injected. I am aware of the ignoreAnnotations property that seems to exist for PMD, however, I am not sure if one can actually specify this in a gradle configuration? Any help would be appreciated. A: The root cause is: field injection is code smell and bad design practice. When @Autowired is used on a non-transient field it can cause issues with serialization. This is because the field will not be properly initialized when the object is deserialized, leading to a NullPointerException when the object is used. To fix this issue either make the fields transient or -- much better -- use constructor injection. To use constructor injection add a constructor to your class that takes all of the required dependencies as arguments, and annotate the constructor with @Autowired (the annotation is optional in modern Spring versions). @Component class MyClass { private final Dependency1 dependency1; private final Dependency2 dependency2; @Autowired public MyClass(Dependency1 dependency1, Dependency2 dependency2) { this.dependency1 = dependency1; this.dependency2 = dependency2; } }
PMD Ignore Spring Field Injections in gradle config
Currently I have several Controllers that inject dependencies through a field marked with @Autowired. When I try to run gradle build the following violations come up. These all correspond to the instances of where a spring component has been injected. I am aware of the ignoreAnnotations property that seems to exist for PMD, however, I am not sure if one can actually specify this in a gradle configuration? Any help would be appreciated.
[ "The root cause is: field injection is code smell and bad design practice.\nWhen @Autowired is used on a non-transient field it can cause issues with serialization. This is because the field will not be properly initialized when the object is deserialized, leading to a NullPointerException when the object is used.\nTo fix this issue either make the fields transient or -- much better -- use constructor injection. To use constructor injection add a constructor to your class that takes all of the required dependencies as arguments, and annotate the constructor with @Autowired (the annotation is optional in modern Spring versions).\n@Component\nclass MyClass {\n private final Dependency1 dependency1;\n private final Dependency2 dependency2;\n\n @Autowired\n public MyClass(Dependency1 dependency1, Dependency2 dependency2) {\n this.dependency1 = dependency1;\n this.dependency2 = dependency2;\n }\n}\n\n" ]
[ 0 ]
[]
[]
[ "gradle", "java", "pmd", "spring" ]
stackoverflow_0074678285_gradle_java_pmd_spring.txt
Q: Converting list of dictionary and dictionay data to a dataframe in python I am trying to send a SOAP request and iteratively and the response captured for each iteration is as follows. df = {'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '0BQU22', 'NVIC_MODEL': '0BQU', 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'} {'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '0BQT22', 'NVIC_MODEL': '0BQT', 'ModelName': 'FDIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'} [{'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '09GE22', 'NVIC_MODEL': '09GE', 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'}, {'@diffgr:id': 'Table2', '@msdata:rowOrder': '1', 'NVIC_CUR': '0BR222', 'NVIC_MODEL': '0BR2', 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'}] [{'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '09HR22', 'NVIC_MODEL': '09HR', 'ModelName': 'DIESEL TURBO 5 3198 cc DTFI 6 SP AUTOMATIC'}, {'@diffgr:id': 'Table2', '@msdata:rowOrder': '1', 'NVIC_CUR': '09HS22', 'NVIC_MODEL': '09HS', 'ModelName': 'DIESEL TURBO 5 3198 cc DTFI 6 SP MANUAL'}] The SOAP API sometimes return dictionary data, and sometime list of dictionary. My idea was to create a Dataframe of selected columns (NVIC_CUR, NVIC_MODEL, ModelName) output dataframe A: You can do it by this three-step- You can append each SOAP API response to either its dictionary or a list to a new python list, let's say its called - list_of_dict, and Then iterate it and append it to a new list let's call it final_list_of_dict if it's a dictionary else iterate it again if a listlike below. Finally, make a dataframe from the list of dictionaries. Fullcode: import pandas as pd list_of_dict = [{'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '0BQU22', 'NVIC_MODEL': '0BQU', 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'}, {'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '0BQT22', 'NVIC_MODEL': '0BQT', 'ModelName': 'FDIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'}, [{'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '09GE22', 'NVIC_MODEL': '09GE', 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'}, {'@diffgr:id': 'Table2', '@msdata:rowOrder': '1', 'NVIC_CUR': '0BR222', 'NVIC_MODEL': '0BR2', 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'}], [{'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '09HR22', 'NVIC_MODEL': '09HR', 'ModelName': 'DIESEL TURBO 5 3198 cc DTFI 6 SP AUTOMATIC'}, {'@diffgr:id': 'Table2', '@msdata:rowOrder': '1', 'NVIC_CUR': '09HS22', 'NVIC_MODEL': '09HS', 'ModelName': 'DIESEL TURBO 5 3198 cc DTFI 6 SP MANUAL'}] ] final_list_of_dict = [] for item in list_of_dict: if isinstance(item, list): for item in item: final_list_of_dict.append(item) final_list_of_dict.append(item) df = pd.DataFrame(final_list_of_dict, columns=['NVIC_CUR', 'NVIC_MODEL','ModelName']) print(df) Output: NVIC_CUR NVIC_MODEL ModelName 0 0BQU22 0BQU DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC 1 0BQT22 0BQT FDIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOM... 2 09GE22 09GE DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC 3 0BR222 0BR2 DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC 4 0BR222 0BR2 DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC 5 09HR22 09HR DIESEL TURBO 5 3198 cc DTFI 6 SP AUTOMATIC 6 09HS22 09HS DIESEL TURBO 5 3198 cc DTFI 6 SP MANUAL 7 09HS22 09HS DIESEL TURBO 5 3198 cc DTFI 6 SP MANUAL A: Try using pandas library, it makes it quite easy: import pandas as pd df = { '@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '0BQU22', 'NVIC_MODEL': '0BQU', 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC' } if isinstance(df, list): result = pd.DataFrame(df) else: result = pd.DataFrame.from_dict(df, orient='index', columns=['NVIC_CUR', 'NVIC_MODEL', 'ModelName'] )
Converting list of dictionary and dictionay data to a dataframe in python
I am trying to send a SOAP request and iteratively and the response captured for each iteration is as follows. df = {'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '0BQU22', 'NVIC_MODEL': '0BQU', 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'} {'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '0BQT22', 'NVIC_MODEL': '0BQT', 'ModelName': 'FDIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'} [{'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '09GE22', 'NVIC_MODEL': '09GE', 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'}, {'@diffgr:id': 'Table2', '@msdata:rowOrder': '1', 'NVIC_CUR': '0BR222', 'NVIC_MODEL': '0BR2', 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'}] [{'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '09HR22', 'NVIC_MODEL': '09HR', 'ModelName': 'DIESEL TURBO 5 3198 cc DTFI 6 SP AUTOMATIC'}, {'@diffgr:id': 'Table2', '@msdata:rowOrder': '1', 'NVIC_CUR': '09HS22', 'NVIC_MODEL': '09HS', 'ModelName': 'DIESEL TURBO 5 3198 cc DTFI 6 SP MANUAL'}] The SOAP API sometimes return dictionary data, and sometime list of dictionary. My idea was to create a Dataframe of selected columns (NVIC_CUR, NVIC_MODEL, ModelName) output dataframe
[ "You can do it by this three-step-\n\nYou can append each SOAP API response to either its dictionary or a list to a new python list, let's say its called - list_of_dict, and\n\nThen iterate it and append it to a new list let's call it final_list_of_dict if it's a dictionary else iterate it again if a listlike below.\n\nFinally, make a dataframe from the list of dictionaries.\n\n\nFullcode:\nimport pandas as pd\n\nlist_of_dict = [{'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '0BQU22', 'NVIC_MODEL': '0BQU', 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'},\n{'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '0BQT22', 'NVIC_MODEL': '0BQT', 'ModelName': 'FDIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'},\n[{'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '09GE22', 'NVIC_MODEL': '09GE', 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'}, {'@diffgr:id': 'Table2', '@msdata:rowOrder': '1', 'NVIC_CUR': '0BR222', 'NVIC_MODEL': '0BR2', 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'}],\n[{'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '09HR22', 'NVIC_MODEL': '09HR', 'ModelName': 'DIESEL TURBO 5 3198 cc DTFI 6 SP AUTOMATIC'}, {'@diffgr:id': 'Table2', '@msdata:rowOrder': '1', 'NVIC_CUR': '09HS22', 'NVIC_MODEL': '09HS', 'ModelName': 'DIESEL TURBO 5 3198 cc DTFI 6 SP MANUAL'}]\n]\n\nfinal_list_of_dict = []\nfor item in list_of_dict:\n if isinstance(item, list):\n for item in item:\n final_list_of_dict.append(item)\n final_list_of_dict.append(item) \ndf = pd.DataFrame(final_list_of_dict, columns=['NVIC_CUR', 'NVIC_MODEL','ModelName'])\nprint(df)\n\nOutput:\n NVIC_CUR NVIC_MODEL ModelName\n0 0BQU22 0BQU DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC\n1 0BQT22 0BQT FDIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOM...\n2 09GE22 09GE DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC\n3 0BR222 0BR2 DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC\n4 0BR222 0BR2 DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC\n5 09HR22 09HR DIESEL TURBO 5 3198 cc DTFI 6 SP AUTOMATIC\n6 09HS22 09HS DIESEL TURBO 5 3198 cc DTFI 6 SP MANUAL\n7 09HS22 09HS DIESEL TURBO 5 3198 cc DTFI 6 SP MANUAL\n\n", "Try using pandas library, it makes it quite easy:\nimport pandas as pd\n\n\ndf = {\n '@diffgr:id': 'Table1', \n '@msdata:rowOrder': '0', \n 'NVIC_CUR': '0BQU22', \n 'NVIC_MODEL': '0BQU', \n 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'\n}\n\nif isinstance(df, list):\n result = pd.DataFrame(df)\nelse:\n result = pd.DataFrame.from_dict(df, \n orient='index',\n columns=['NVIC_CUR', 'NVIC_MODEL', 'ModelName']\n )\n\n" ]
[ 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074678229_dictionary_list_python.txt
Q: How to insert data from a form into a table in php without using databsaes? I need to create a table of 17 rows where each row contains information such as row number, name, surname, email and birthday. The data is provided by this form: <form action="index.php" method="post"> <input type="text" name="name" placeholder="name" /> <input type="text" name="surname" placeholder="surname" /> <input type="text" name="emailbirthday" placeholder="emailbirthday" /> <input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" /> <button type="reset">Reset Form</button> <button type="submit">Submit Form</button> </form> After clicking submit the data should be displayed in the nth row of the table(row number one if it is the first "pack" of data submitted, number two if its the second and so on). This problem could easely be solved using databases but i cannot use them(by professors order). I tried to create an array than push values into it like this: $array_name = array(); $name = $_POST["name"]; array_push($array_name, $name); This approach doesn't work(the index of the array stays 0 alla of the time so it keeps replacing the first value again and again) and manually incrementing the index counter of the array doesn't work either. A: Normally one should use a database approach but your professor explicitly forbids it. There are many other ways to do it. (store as TEXT/JSON/CSV file or localstorage / cookies), etc. For me I would use session to do the job declare a session variable which is an array if user submits the form, store the POST data into another array (subarray) containing name, surname, birthday, email add the subarray into the main session variable array print it out at the end as a table So the PHP will be: <?php session_start(); ?> <form action="#" method="post"> <input type="text" name="name" placeholder="name" /> <input type="text" name="surname" placeholder="surname" /> <input type="text" name="email" placeholder="email" /> <input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" /> <button type="reset">Reset Form</button> <button type="submit">Submit Form</button> </form> <?php if (!isset($_SESSION["arr"])){ $_SESSION["arr"]=array(); } if ($_POST) { $subarray=array( "name"=>$_POST["name"], "surname"=>$_POST["surname"], "birthday"=>$_POST["birthday"], "email"=>$_POST["email"] ); $_SESSION["arr"][]=$subarray; } echo "<table border=1><tr><td>Name<td>Surname<td>Email<td>Birthday"; foreach($_SESSION["arr"] as $suba){ echo "<tr><td>" . $suba["name"] ; echo "<td>" . $suba["surname"] ; echo "<td>" . $suba["email"] ; echo "<td>" . $suba["birthday"] ; } echo "</table>"; ?> However, if you need the data to be persistent (even after the user closes the browser), then you need to store the data say in file format or cookies, etc. A: If you need to save data persistent and using file to save data is acceptable, i'd use something like that: <?php $file = 'path/to/file.txt'; $data = json_decode(file_get_contents($file), true); if ($_POST) { $data[] = [ "name" => $_POST['name'], "surname" => $_POST['surname'], "emailbirthday" => $_POST['emailbirthday'], "birthday" => $_POST['birthday'] ]; } file_put_contents($file, json_encode($data)); ?> <form action="index.php" method="post"> <input type="text" name="name" placeholder="name" /> <input type="text" name="surname" placeholder="surname" /> <input type="text" name="emailbirthday" placeholder="emailbirthday" /> <input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" /> <button type="reset">Reset Form</button> <button type="submit">Submit Form</button> </form> <table> <tr> <th>Name</th> <th>Surname</th> <th>Emailbirthday</th> <th>Birthday</th> </tr> <?php foreach ($data as $row) { print '<tr> <td>'.$row['name'].'</td> <td>'.$row['surname'].'</td> <td>'.$row['emailbirthday'].'</td> <td>'.$row['birthday'].'</td> </tr>'; } ?> </table> A: You can use the post values of hidden fields: <form action="" method="post"> <input type="text" name="name" placeholder="name" /> <input type="text" name="surname" placeholder="surname" /> <input type="text" name="emailbirthday" placeholder="emailbirthday" /> <input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" /> <button type="reset">Reset Form</button> <button type="submit">Submit Form</button> <?php if($_POST["names"] == "") { $value = $_POST["name"]; } else { $value = $_POST["names"]."-".$_POST["name"]; } ?> <input type="text" name="names" style='display:none;' value="<?php echo $value ?>"> </form>
How to insert data from a form into a table in php without using databsaes?
I need to create a table of 17 rows where each row contains information such as row number, name, surname, email and birthday. The data is provided by this form: <form action="index.php" method="post"> <input type="text" name="name" placeholder="name" /> <input type="text" name="surname" placeholder="surname" /> <input type="text" name="emailbirthday" placeholder="emailbirthday" /> <input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" /> <button type="reset">Reset Form</button> <button type="submit">Submit Form</button> </form> After clicking submit the data should be displayed in the nth row of the table(row number one if it is the first "pack" of data submitted, number two if its the second and so on). This problem could easely be solved using databases but i cannot use them(by professors order). I tried to create an array than push values into it like this: $array_name = array(); $name = $_POST["name"]; array_push($array_name, $name); This approach doesn't work(the index of the array stays 0 alla of the time so it keeps replacing the first value again and again) and manually incrementing the index counter of the array doesn't work either.
[ "Normally one should use a database approach but your professor explicitly forbids it.\nThere are many other ways to do it. (store as TEXT/JSON/CSV file or localstorage / cookies), etc. For me I would use session to do the job\n\ndeclare a session variable which is an array\nif user submits the form, store the POST data into another array (subarray) containing name, surname, birthday, email\nadd the subarray into the main session variable array\nprint it out at the end as a table\n\nSo the PHP will be:\n<?php\nsession_start();\n?>\n<form action=\"#\" method=\"post\">\n <input type=\"text\" name=\"name\" placeholder=\"name\" />\n <input type=\"text\" name=\"surname\" placeholder=\"surname\" />\n <input type=\"text\" name=\"email\" placeholder=\"email\" />\n <input type=\"text\" name=\"birthday\" placeholder=\"birthday(dd/mm/aaa)\" />\n <button type=\"reset\">Reset Form</button>\n <button type=\"submit\">Submit Form</button>\n</form>\n\n<?php\n\nif (!isset($_SESSION[\"arr\"])){\n $_SESSION[\"arr\"]=array();\n}\n\nif ($_POST) {\n $subarray=array(\n \"name\"=>$_POST[\"name\"], \n \"surname\"=>$_POST[\"surname\"],\n \"birthday\"=>$_POST[\"birthday\"], \n \"email\"=>$_POST[\"email\"]\n );\n $_SESSION[\"arr\"][]=$subarray;\n}\n\necho \"<table border=1><tr><td>Name<td>Surname<td>Email<td>Birthday\";\n\nforeach($_SESSION[\"arr\"] as $suba){\n echo \"<tr><td>\" . $suba[\"name\"] ;\n echo \"<td>\" . $suba[\"surname\"] ;\n echo \"<td>\" . $suba[\"email\"] ;\n echo \"<td>\" . $suba[\"birthday\"] ;\n}\necho \"</table>\";\n?>\n\nHowever, if you need the data to be persistent (even after the user closes the browser), then you need to store the data say in file format or cookies, etc.\n", "If you need to save data persistent and using file to save data is acceptable, i'd use something like that:\n<?php\n$file = 'path/to/file.txt';\n$data = json_decode(file_get_contents($file), true);\n\nif ($_POST) {\n $data[] = [\n \"name\" => $_POST['name'],\n \"surname\" => $_POST['surname'],\n \"emailbirthday\" => $_POST['emailbirthday'],\n \"birthday\" => $_POST['birthday']\n ];\n}\n\nfile_put_contents($file, json_encode($data));\n?>\n\n<form action=\"index.php\" method=\"post\">\n <input type=\"text\" name=\"name\" placeholder=\"name\" />\n <input type=\"text\" name=\"surname\" placeholder=\"surname\" />\n <input type=\"text\" name=\"emailbirthday\" placeholder=\"emailbirthday\" />\n <input type=\"text\" name=\"birthday\" placeholder=\"birthday(dd/mm/aaa)\" />\n <button type=\"reset\">Reset Form</button>\n <button type=\"submit\">Submit Form</button>\n</form>\n\n<table>\n <tr>\n <th>Name</th>\n <th>Surname</th>\n <th>Emailbirthday</th>\n <th>Birthday</th>\n </tr>\n<?php\n foreach ($data as $row) {\n print '<tr>\n <td>'.$row['name'].'</td>\n <td>'.$row['surname'].'</td>\n <td>'.$row['emailbirthday'].'</td>\n <td>'.$row['birthday'].'</td>\n </tr>';\n }\n?>\n</table>\n\n", "You can use the post values of hidden fields:\n <form action=\"\" method=\"post\">\n <input type=\"text\" name=\"name\" placeholder=\"name\" />\n <input type=\"text\" name=\"surname\" placeholder=\"surname\" />\n <input type=\"text\" name=\"emailbirthday\" placeholder=\"emailbirthday\" />\n <input type=\"text\" name=\"birthday\" placeholder=\"birthday(dd/mm/aaa)\" />\n <button type=\"reset\">Reset Form</button>\n <button type=\"submit\">Submit Form</button>\n \n<?php\nif($_POST[\"names\"] == \"\")\n{\n$value = $_POST[\"name\"];\n}\nelse\n{\n$value = $_POST[\"names\"].\"-\".$_POST[\"name\"];\n}\n?>\n<input type=\"text\" name=\"names\" style='display:none;' value=\"<?php echo $value ?>\">\n</form>\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "html", "php", "web" ]
stackoverflow_0074677017_html_php_web.txt
Q: Error When Trying to Calculate FLOPS for Complex TF2 Keras Models I want to calculate the FLOPS in the ML models used. I get an error when I tried to calculate for much complex models. I get this Error for Efficientnet Models: ValueError: Unknown layer: FixedDropout. Please ensure this object is passed to the `custom_objects` argument. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details. ​ The function to calculate the FLOPS: 1) def get_flops(model, batch_size=None): if batch_size is None: batch_size = 1 real_model = tf.function(model).get_concrete_function(tf.TensorSpec([batch_size] + model.inputs[0].shape[1:], model.inputs[0].dtype)) frozen_func, graph_def = convert_variables_to_constants_v2_as_graph(real_model) run_meta = tf.compat.v1.RunMetadata() opts = tf.compat.v1.profiler.ProfileOptionBuilder.float_operation() flops = tf.compat.v1.profiler.profile(graph=frozen_func.graph, run_meta=run_meta, cmd='op', options=opts) return flops.total_float_ops or 2) def get_flops(model_h5_path): session = tf.compat.v1.Session() graph = tf.compat.v1.get_default_graph() with graph.as_default(): with session.as_default(): model = tf.keras.models.load_model(model_h5_path) run_meta = tf.compat.v1.RunMetadata() opts = tf.compat.v1.profiler.ProfileOptionBuilder.float_operation() # We use the Keras session graph in the call to the profiler. flops = tf.compat.v1.profiler.profile(graph=graph, run_meta=run_meta, cmd='op', options=opts) return flops.total_float_ops On the contrary, I am able to calculate the FLOPS for models like Resnets, just that it is not possible for bit complex models. How can I mitigate the issue? A: In the first function, you are using the convert_variables_to_constants_v2_as_graph function from TensorFlow to convert the model to a graph. This function has a custom_objects parameter that you can use to pass the custom layers that the model uses. You can add the FixedDropout layer to this parameter to fix the error you are seeing. Here is an example of how you could use the custom_objects parameter to fix the error: import tensorflow as tf from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2_as_graph # Define the custom layer class class FixedDropout(tf.keras.layers.Dropout): def call(self, inputs, training=None): return inputs def get_flops(model, batch_size=None): if batch_size is None: batch_size = 1 real_model = tf.function(model).get_concrete_function(tf.TensorSpec([batch_size] + model.inputs[0].shape[1:], model.inputs[0].dtype)) # Pass the custom layer class to the custom_objects parameter frozen_func, graph_def = convert_variables_to_constants_v2_as_graph(real_model, custom_objects={'FixedDropout': FixedDropout}) run_meta = tf.compat.v1.RunMetadata() opts = tf.compat.v1.profiler.ProfileOptionBuilder.float_operation() flops = tf.compat.v1.profiler.profile(graph=frozen_func.graph, run_meta=run_meta, cmd='op', options=opts) return flops.total_float_ops
Error When Trying to Calculate FLOPS for Complex TF2 Keras Models
I want to calculate the FLOPS in the ML models used. I get an error when I tried to calculate for much complex models. I get this Error for Efficientnet Models: ValueError: Unknown layer: FixedDropout. Please ensure this object is passed to the `custom_objects` argument. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details. ​ The function to calculate the FLOPS: 1) def get_flops(model, batch_size=None): if batch_size is None: batch_size = 1 real_model = tf.function(model).get_concrete_function(tf.TensorSpec([batch_size] + model.inputs[0].shape[1:], model.inputs[0].dtype)) frozen_func, graph_def = convert_variables_to_constants_v2_as_graph(real_model) run_meta = tf.compat.v1.RunMetadata() opts = tf.compat.v1.profiler.ProfileOptionBuilder.float_operation() flops = tf.compat.v1.profiler.profile(graph=frozen_func.graph, run_meta=run_meta, cmd='op', options=opts) return flops.total_float_ops or 2) def get_flops(model_h5_path): session = tf.compat.v1.Session() graph = tf.compat.v1.get_default_graph() with graph.as_default(): with session.as_default(): model = tf.keras.models.load_model(model_h5_path) run_meta = tf.compat.v1.RunMetadata() opts = tf.compat.v1.profiler.ProfileOptionBuilder.float_operation() # We use the Keras session graph in the call to the profiler. flops = tf.compat.v1.profiler.profile(graph=graph, run_meta=run_meta, cmd='op', options=opts) return flops.total_float_ops On the contrary, I am able to calculate the FLOPS for models like Resnets, just that it is not possible for bit complex models. How can I mitigate the issue?
[ "In the first function, you are using the convert_variables_to_constants_v2_as_graph function from TensorFlow to convert the model to a graph. This function has a custom_objects parameter that you can use to pass the custom layers that the model uses. You can add the FixedDropout layer to this parameter to fix the error you are seeing.\nHere is an example of how you could use the custom_objects parameter to fix the error:\nimport tensorflow as tf\nfrom tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2_as_graph\n\n# Define the custom layer class\nclass FixedDropout(tf.keras.layers.Dropout):\n def call(self, inputs, training=None):\n return inputs\n\ndef get_flops(model, batch_size=None):\n if batch_size is None:\n batch_size = 1\n\n real_model = tf.function(model).get_concrete_function(tf.TensorSpec([batch_size] + model.inputs[0].shape[1:], model.inputs[0].dtype))\n\n # Pass the custom layer class to the custom_objects parameter\n frozen_func, graph_def = convert_variables_to_constants_v2_as_graph(real_model, custom_objects={'FixedDropout': FixedDropout})\n\n run_meta = tf.compat.v1.RunMetadata()\n opts = tf.compat.v1.profiler.ProfileOptionBuilder.float_operation()\n flops = tf.compat.v1.profiler.profile(graph=frozen_func.graph,\n run_meta=run_meta, cmd='op', options=opts)\n return flops.total_float_ops\n\n" ]
[ 0 ]
[]
[]
[ "computer_vision", "keras", "machine_learning", "python", "tensorflow" ]
stackoverflow_0074675233_computer_vision_keras_machine_learning_python_tensorflow.txt
Q: Empty object being sent to exel file c# I am trying to write a c# program to make a Bank system with users creating bank accounts. And I want to be able to save these accounts given through the console to an excel file so it can retrieve them later if needed. I followed a tutorial on how to do that and made minor adjustments to the code but when I try to run the program with some test accounts it writes them as blank accounts with no data and I can't see why it would do this. public class Account { protected static int count = 1; protected int accountNum; protected string fName; protected string lName; protected int idNumber; protected string address; protected DateOnly birthday = new(); protected bool flag; Savings.SpendingRef = Spendings(accountNum); public Account(string fn, string ln, int idnum, string add, DateOnly bd) { //System.Threading.Interlocked.Increment(ref count); this.accountNum = count++; fName = fn; lName = ln; idNumber = idnum; address = add; birthday = bd; flag = false; } public int AccountNum{get;} public string FName{get; set;} public string LName{get; set;} public int IdNumber{get; set;} public string Address{get; set;} public DateOnly Birthday{get;} public bool Flag{get; set;} public string GetAccount(){ string s = "--------------------------------\n"; s += "Account Number :" + accountNum + "\nAccount belonging to :" + fName + " " + LName + "\nID Number :" + IdNumber + "\nAddress :" + address + "\nBirthday : " + birthday + "\nAccount blocked? :" + flag; s += "\n--------------------------------\n"; Console.WriteLine(s); return s; } } Here is how the account class is implemented static async Task Main(string[] args) { ExcelPackage.LicenseContext = LicenseContext.NonCommercial; var file = new FileInfo(@"..\..\..\SavedAccounts.XLSX"); //Other code not important var Accounts = GetSetupData(); await SaveExcelFile(Accounts, file); } private static List<Account> GetSetupData() { List<Account> output = new() { new Account("Jerome", "Dupret", 42069, "68 rue des ecoles", new DateOnly(1999, 08, 10)), new Account("Deborah", "Pierre", 69420, "68 rue des ecoles", new DateOnly(2000, 02, 18)), }; return output; } Here are the test accounts I want to be inserted. private static async Task SaveExcelFile(List<Account> accounts, FileInfo file) { DeleteIfExists(file); using var package = new ExcelPackage(file);//basically a Dispose method to get rid of any useless data var ws = package.Workbook.Worksheets.Add("AccountData"); var range = ws.Cells["A1"].LoadFromCollection(accounts, true); range.AutoFitColumns(); await package.SaveAsync(); } And this is where the call and the write function itself happen. I used console Writes at every step to check if the accounts lose info at any time but they never do, I'm confused as to why it isn't sent properly. A: It looks like you never set your public properties such as Fname, either you need to set them in the constructor or make the getter get the protected field. for example protected string fName; public string FName { get { return fName; } set { fName = value; } } This needs to be done on all the public fields so they all get the field that gets set in the constructor. The set is not required but if you dont use it FName and fName can become diffrent values since fName is only set in the constructor.
Empty object being sent to exel file c#
I am trying to write a c# program to make a Bank system with users creating bank accounts. And I want to be able to save these accounts given through the console to an excel file so it can retrieve them later if needed. I followed a tutorial on how to do that and made minor adjustments to the code but when I try to run the program with some test accounts it writes them as blank accounts with no data and I can't see why it would do this. public class Account { protected static int count = 1; protected int accountNum; protected string fName; protected string lName; protected int idNumber; protected string address; protected DateOnly birthday = new(); protected bool flag; Savings.SpendingRef = Spendings(accountNum); public Account(string fn, string ln, int idnum, string add, DateOnly bd) { //System.Threading.Interlocked.Increment(ref count); this.accountNum = count++; fName = fn; lName = ln; idNumber = idnum; address = add; birthday = bd; flag = false; } public int AccountNum{get;} public string FName{get; set;} public string LName{get; set;} public int IdNumber{get; set;} public string Address{get; set;} public DateOnly Birthday{get;} public bool Flag{get; set;} public string GetAccount(){ string s = "--------------------------------\n"; s += "Account Number :" + accountNum + "\nAccount belonging to :" + fName + " " + LName + "\nID Number :" + IdNumber + "\nAddress :" + address + "\nBirthday : " + birthday + "\nAccount blocked? :" + flag; s += "\n--------------------------------\n"; Console.WriteLine(s); return s; } } Here is how the account class is implemented static async Task Main(string[] args) { ExcelPackage.LicenseContext = LicenseContext.NonCommercial; var file = new FileInfo(@"..\..\..\SavedAccounts.XLSX"); //Other code not important var Accounts = GetSetupData(); await SaveExcelFile(Accounts, file); } private static List<Account> GetSetupData() { List<Account> output = new() { new Account("Jerome", "Dupret", 42069, "68 rue des ecoles", new DateOnly(1999, 08, 10)), new Account("Deborah", "Pierre", 69420, "68 rue des ecoles", new DateOnly(2000, 02, 18)), }; return output; } Here are the test accounts I want to be inserted. private static async Task SaveExcelFile(List<Account> accounts, FileInfo file) { DeleteIfExists(file); using var package = new ExcelPackage(file);//basically a Dispose method to get rid of any useless data var ws = package.Workbook.Worksheets.Add("AccountData"); var range = ws.Cells["A1"].LoadFromCollection(accounts, true); range.AutoFitColumns(); await package.SaveAsync(); } And this is where the call and the write function itself happen. I used console Writes at every step to check if the accounts lose info at any time but they never do, I'm confused as to why it isn't sent properly.
[ "It looks like you never set your public properties such as Fname, either you need to set them in the constructor or make the getter get the protected field.\nfor example\nprotected string fName;\n\npublic string FName\n {\n get\n {\n return fName;\n }\n set\n {\n fName = value;\n }\n }\n\nThis needs to be done on all the public fields so they all get the field that gets set in the constructor.\nThe set is not required but if you dont use it FName and fName can become diffrent values since fName is only set in the constructor.\n" ]
[ 1 ]
[]
[]
[ "c#", "excel" ]
stackoverflow_0074677669_c#_excel.txt
Q: Java JTableModel to display horizontally I have a resultset from a query (date and room) some kind of matrix. 9 room and date between (jan/01/2022 to jan/31/2022). try { String query="select a.Tarikh AS 'TARIKH',a.Room AS 'ROOM',b.Room as 'BOOKED'" + "from (Select * from Tarikh Cross Join Room) as a\n" + "left join Booking as b\n" + "on a.Tarikh = b.Tarikh\n" + "and (a.Room = b.Room)\n" + "WHERE (a.Tarikh BETWEEN '2022-01-01' AND '2022-03-01');"; PreparedStatement pst=connection.prepareStatement(query); ResultSet rs = pst.executeQuery(); // this line below implement the usage of net.proteanit.sql.DbUtils (import library) table_1.setModel(DbUtils.resultSetToTableModel(rs)); // --- pst.execute(); rs.close(); } catch (Exception e) { e.printStackT } The problem is, how do I make a JtableModel to display from this Room Date Booked 101 2022-01-01 2022-01-01 102 2022-01-01 2022-01-01 103 2022-01-01 2022-01-01 104 2022-01-01 2022-01-01 105 2022-01-01 null 106 2022-01-01 null 107 2022-01-01 null 108 2022-01-01 null 109 2022-01-01 null 101 2022-01-02 null 102 2022-01-02 2022-01-02 103 2022-01-02 null 104 2022-01-02 null 105 2022-01-02 null 106 2022-01-02 null 107 2022-01-02 null 108 2022-01-02 null 109 2022-01-02 null and so on.... I am expecting the records to be : 0101 0201 0301 0401 0501 and so on.... 101 X 102 X X 103 X 104 X 105 106 107 108 109 Does anyone know, please help.TQ A: You need to parse the ResultSet data to create your TableModel manually. I might start by creating a TreeMap from the ResultSet data. The room number is the key and an ArrayList can be use each non-null booked date. Once this is done you can then create a DefaultTableModel with "x" rows and 32 columns. The number of rows will be based on the number of entries in the TreeMap. The first column will be the room number. The next 31 columns will be the days of the month. Now you need to read each key from the TreeMap. Each key will represent a row in the TableModel. As you read each key: set the room number in the first column: setValueAt(roomNumber, currentRow, 0) loop thru each booked date in the ArrayList and parse out the day. So "2022-01-01" will become column 1. Now you can update the value in your model using setValueAt("X", currentRow, column) increment the currentRow Repeat the above steps for all keys in the TreeMap.
Java JTableModel to display horizontally
I have a resultset from a query (date and room) some kind of matrix. 9 room and date between (jan/01/2022 to jan/31/2022). try { String query="select a.Tarikh AS 'TARIKH',a.Room AS 'ROOM',b.Room as 'BOOKED'" + "from (Select * from Tarikh Cross Join Room) as a\n" + "left join Booking as b\n" + "on a.Tarikh = b.Tarikh\n" + "and (a.Room = b.Room)\n" + "WHERE (a.Tarikh BETWEEN '2022-01-01' AND '2022-03-01');"; PreparedStatement pst=connection.prepareStatement(query); ResultSet rs = pst.executeQuery(); // this line below implement the usage of net.proteanit.sql.DbUtils (import library) table_1.setModel(DbUtils.resultSetToTableModel(rs)); // --- pst.execute(); rs.close(); } catch (Exception e) { e.printStackT } The problem is, how do I make a JtableModel to display from this Room Date Booked 101 2022-01-01 2022-01-01 102 2022-01-01 2022-01-01 103 2022-01-01 2022-01-01 104 2022-01-01 2022-01-01 105 2022-01-01 null 106 2022-01-01 null 107 2022-01-01 null 108 2022-01-01 null 109 2022-01-01 null 101 2022-01-02 null 102 2022-01-02 2022-01-02 103 2022-01-02 null 104 2022-01-02 null 105 2022-01-02 null 106 2022-01-02 null 107 2022-01-02 null 108 2022-01-02 null 109 2022-01-02 null and so on.... I am expecting the records to be : 0101 0201 0301 0401 0501 and so on.... 101 X 102 X X 103 X 104 X 105 106 107 108 109 Does anyone know, please help.TQ
[ "You need to parse the ResultSet data to create your TableModel manually.\nI might start by creating a TreeMap from the ResultSet data. The room number is the key and an ArrayList can be use each non-null booked date.\nOnce this is done you can then create a DefaultTableModel with \"x\" rows and 32 columns. The number of rows will be based on the number of entries in the TreeMap. The first column will be the room number. The next 31 columns will be the days of the month.\nNow you need to read each key from the TreeMap. Each key will represent a row in the TableModel. As you read each key:\n\nset the room number in the first column: setValueAt(roomNumber, currentRow, 0)\nloop thru each booked date in the ArrayList and parse out the day. So \"2022-01-01\" will become column 1. Now you can update the value in your model using setValueAt(\"X\", currentRow, column)\nincrement the currentRow\n\nRepeat the above steps for all keys in the TreeMap.\n" ]
[ 1 ]
[]
[]
[ "abstracttablemodel", "java", "jtable", "sqlite", "swing" ]
stackoverflow_0074677753_abstracttablemodel_java_jtable_sqlite_swing.txt
Q: Transition property not working in this senario , here i am given max-height 0 to main-div and dropdown max-height 150px some transition this is a css part here i am applying the transition to main-div class but it's not working properly ul { list-style: none; } .main-div { max-height: 0; overflow-y: hidden; background-color: skyblue; transition: height 0.1s linear; box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px; } .dropdown-open { max-height: 150px; border: 1px solid red; } import { useState } from "react"; import "./styles.css"; export default function App() { const [show, setShow] = useState(false); return ( <div className="App"> <button onClick={() => setshow(!show)}>dropdown</button> {show ? ( <div className={`main-div ${show && "dropdown-open"}`}> <div>static data</div> <ul> <li>list 1</li> <li>list 2</li> <li>list 3</li> <li>list 4</li> <li>list 5</li> </ul> </div> ) : ( "" )} </div> ); } Here i am trying to apply transition to the main-div whenever use click on the button main-div takes max height so in my case transition not taking A: .main-div { max-height: 0; overflow-y: hidden; background-color: skyblue; transition: max-height 0.1s linear; box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px; }
Transition property not working in this senario , here i am given max-height 0 to main-div and dropdown max-height 150px some transition
this is a css part here i am applying the transition to main-div class but it's not working properly ul { list-style: none; } .main-div { max-height: 0; overflow-y: hidden; background-color: skyblue; transition: height 0.1s linear; box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px; } .dropdown-open { max-height: 150px; border: 1px solid red; } import { useState } from "react"; import "./styles.css"; export default function App() { const [show, setShow] = useState(false); return ( <div className="App"> <button onClick={() => setshow(!show)}>dropdown</button> {show ? ( <div className={`main-div ${show && "dropdown-open"}`}> <div>static data</div> <ul> <li>list 1</li> <li>list 2</li> <li>list 3</li> <li>list 4</li> <li>list 5</li> </ul> </div> ) : ( "" )} </div> ); } Here i am trying to apply transition to the main-div whenever use click on the button main-div takes max height so in my case transition not taking
[ ".main-div {\n max-height: 0;\n overflow-y: hidden;\n background-color: skyblue;\n transition: max-height 0.1s linear;\n box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;\n}\n\n" ]
[ 0 ]
[]
[]
[ "css", "javascript", "reactjs", "transition" ]
stackoverflow_0074678243_css_javascript_reactjs_transition.txt
Q: Unable to install discord py with pip i have python 3.11 downloaded, and i installed pip with it. however, i can't install discord py with py -3 -m pip install -U discord.py i've tried a few other ways, still didn't work. in the end it says: note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for yarl Failed to build multidict yarl ERROR: Could not build wheels for multidict, yarl, which is required to install pyproject.toml-based projects there are a few other errors throughout the process. A: Hmmm, it seems it might be a problem due to dependencies to yarl and multidict (happens). I've had the same problem with itertools, and even opencv taking extremely long to build with a non-upgraded pip version! Have you tried upgrading pip? Same problem with those libraries' dependencies. pip3 install --upgrade pip A: If pip direct installation doesn't work, try cloning the git repo: $ pip install git+https://github.com/Rapptz/discord.py A: You can try pip install discord.py A: You could also try pip install discord
Unable to install discord py with pip
i have python 3.11 downloaded, and i installed pip with it. however, i can't install discord py with py -3 -m pip install -U discord.py i've tried a few other ways, still didn't work. in the end it says: note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for yarl Failed to build multidict yarl ERROR: Could not build wheels for multidict, yarl, which is required to install pyproject.toml-based projects there are a few other errors throughout the process.
[ "Hmmm, it seems it might be a problem due to dependencies to yarl and multidict (happens). I've had the same problem with itertools, and even opencv taking extremely long to build with a non-upgraded pip version!\nHave you tried upgrading pip? Same problem with those libraries' dependencies.\npip3 install --upgrade pip\n\n", "If pip direct installation doesn't work, try cloning the git repo:\n$ pip install git+https://github.com/Rapptz/discord.py\n\n", "You can try pip install discord.py\n", "You could also try pip install discord\n" ]
[ 1, 1, 0, 0 ]
[]
[]
[ "cmd", "discord", "discord.py", "installation", "python" ]
stackoverflow_0074617360_cmd_discord_discord.py_installation_python.txt
Q: Using Typekit / Adobe Fonts with @next/font The current Next.js Font Optimization docs and the @next/font API Reference describe how to bring in Google Fonts as well as local font files, but the best practice for bringing in Typekit / Adobe Fonts is not described. What is the best way to use Typekit / Adobe Fonts so that Next.js optimizations are applied? A: @next/font has no support for Typekit yet and there isn't any related issue open on their GitHub repo (probably due to legal restrictions imposed by Typekit itself). However, this doesn't mean that you cannot use Typekit fonts with Next.js. Prior to Next.js 13, it had a feature called automatic font optimization which still exists, and supports Typekit (added in vercel/next.js#24834). It will basically inline your font CSS. So, if you have: // pages/_document.tsx import { Html, Head, Main, NextScript } from 'next/document' const Document = () => { return ( <Html> <Head> <link rel="stylesheet" href="https://use.typekit.net/plm1izr.css" /> </Head> <body> <Main /> <NextScript /> </body> </Html> ) } export default Document Then Next.js will generate your documents having some content like this in head (saves a request to Typekit): <link rel="preconnect" href="https://use.typekit.net" crossorigin /> <!-- ... --> <style data-href="https://use.typekit.net/plm1izr.css"> @import url('https://p.typekit.net/p.css?s=1&k=plm1izr&ht=tk&f=32266&a=23152309&app=typekit&e=css'); @font-face { font-family: 'birra-2'; src: url('https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3') format('woff2'), url('https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3') format('woff'), url('https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3') format('opentype'); font-display: auto; font-style: normal; font-weight: 700; font-stretch: normal; } .tk-birra-2 { font-family: 'birra-2', serif; } </style> Here is the integration suite, you can check it out for different ways to add that stylesheet link: https://github.com/vercel/next.js/tree/canary/test/integration/font-optimization/fixtures/with-typekit (some of those methods are deprecated and will give you warnings).
Using Typekit / Adobe Fonts with @next/font
The current Next.js Font Optimization docs and the @next/font API Reference describe how to bring in Google Fonts as well as local font files, but the best practice for bringing in Typekit / Adobe Fonts is not described. What is the best way to use Typekit / Adobe Fonts so that Next.js optimizations are applied?
[ "@next/font has no support for Typekit yet and there isn't any related issue open on their GitHub repo (probably due to legal restrictions imposed by Typekit itself).\nHowever, this doesn't mean that you cannot use Typekit fonts with Next.js. Prior to Next.js 13, it had a feature called automatic font optimization which still exists, and supports Typekit (added in vercel/next.js#24834).\nIt will basically inline your font CSS. So, if you have:\n// pages/_document.tsx\n\nimport { Html, Head, Main, NextScript } from 'next/document'\n\nconst Document = () => {\n return (\n <Html>\n <Head>\n <link rel=\"stylesheet\" href=\"https://use.typekit.net/plm1izr.css\" />\n </Head>\n <body>\n <Main />\n <NextScript />\n </body>\n </Html>\n )\n}\n\nexport default Document\n\nThen Next.js will generate your documents having some content like this in head (saves a request to Typekit):\n<link rel=\"preconnect\" href=\"https://use.typekit.net\" crossorigin />\n<!-- ... -->\n<style data-href=\"https://use.typekit.net/plm1izr.css\">\n @import url('https://p.typekit.net/p.css?s=1&k=plm1izr&ht=tk&f=32266&a=23152309&app=typekit&e=css');\n @font-face {\n font-family: 'birra-2';\n src: url('https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3')\n format('woff2'),\n url('https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3')\n format('woff'),\n url('https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3')\n format('opentype');\n font-display: auto;\n font-style: normal;\n font-weight: 700;\n font-stretch: normal;\n }\n .tk-birra-2 {\n font-family: 'birra-2', serif;\n }\n</style>\n\nHere is the integration suite, you can check it out for different ways to add that stylesheet link: https://github.com/vercel/next.js/tree/canary/test/integration/font-optimization/fixtures/with-typekit (some of those methods are deprecated and will give you warnings).\n" ]
[ 1 ]
[]
[]
[ "next.js", "typekit" ]
stackoverflow_0074598024_next.js_typekit.txt
Q: Can you use setReduxObject and selectReduxObject in the same .jsx page? I am learning Redux and I have deviated from the instructor's code. I am trying to convert my code from context & state into Redux. Is it advisable to use setReduxObject (setCategoriesMap in my code) and selectReduxObject (selectCategoriesMap in my code) in the same .jsx page? Are there any concerns around this? Thanks! My code: import { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { getCategoriesAndDocuments } from "../../utils/firebase/firebase.utils"; import { setCategoriesMap } from "../../store/categories/categories.action"; import { selectCategoriesMap } from "../../store/categories/categories.selector"; import Category from "../../components/category/category.component"; const Shop = () => { const dispatch = useDispatch(); useEffect(() => { const getCategoriesMap = async () => { const categories = await getCategoriesAndDocuments(); dispatch(setCategoriesMap(categories)); }; getCategoriesMap(); }, []); const categoriesMap = useSelector(selectCategoriesMap); return ( <div> {Object.keys(categoriesMap).map((key) => { const products = categoriesMap[key]; return <Category key={key} title={key} products={products} />; })} </div> ); }; export default Shop; A: This is just the default approach, nothing to be concerned about. As soon as you're using getCategoriesAndDocuments the same way in another component though, it's better to move this to an async action creator. Could even do it for this component already to improve separation of concerns. The component does not necessarily need to be involved with firebase, its job is display logic. Wether the data comes from firebase or localStorage or some graphQL server should not matter.
Can you use setReduxObject and selectReduxObject in the same .jsx page?
I am learning Redux and I have deviated from the instructor's code. I am trying to convert my code from context & state into Redux. Is it advisable to use setReduxObject (setCategoriesMap in my code) and selectReduxObject (selectCategoriesMap in my code) in the same .jsx page? Are there any concerns around this? Thanks! My code: import { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { getCategoriesAndDocuments } from "../../utils/firebase/firebase.utils"; import { setCategoriesMap } from "../../store/categories/categories.action"; import { selectCategoriesMap } from "../../store/categories/categories.selector"; import Category from "../../components/category/category.component"; const Shop = () => { const dispatch = useDispatch(); useEffect(() => { const getCategoriesMap = async () => { const categories = await getCategoriesAndDocuments(); dispatch(setCategoriesMap(categories)); }; getCategoriesMap(); }, []); const categoriesMap = useSelector(selectCategoriesMap); return ( <div> {Object.keys(categoriesMap).map((key) => { const products = categoriesMap[key]; return <Category key={key} title={key} products={products} />; })} </div> ); }; export default Shop;
[ "This is just the default approach, nothing to be concerned about.\nAs soon as you're using getCategoriesAndDocuments the same way in another component though, it's better to move this to an async action creator.\nCould even do it for this component already to improve separation of concerns. The component does not necessarily need to be involved with firebase, its job is display logic. Wether the data comes from firebase or localStorage or some graphQL server should not matter.\n" ]
[ 0 ]
[]
[]
[ "asynchronous", "react_redux", "reactjs", "redux" ]
stackoverflow_0074665901_asynchronous_react_redux_reactjs_redux.txt
Q: useNavigate() breaks the hook I made a simple react hook. import React from "react"; import { useNavigate } from "react-router-dom"; export default function SearchReq(searchTerm: string) { if (searchTerm === "") return; const navigate = useNavigate(); console.log(searchTerm); // window.location.href = "/search?searchTerm=" + searchTerm; navigate("/search?searchTerm=" + searchTerm, { replace: true }); } But for some reason it is giving me an error I had figured out that the line that is causing an error is const navigate = useNavigate() but I don't understand why can any one explain it to me? Here is the error: A: to use the useNavigate hook, you need to make sure that your React component is rendered inside a Router component from the react-router library. import React from "react"; import { useNavigate } from "react-router-dom"; import { Router } from "react-router"; function MyComponent() { const navigate = useNavigate(); const handleClick = () => { navigate("/some/other/route"); }; return ( <button onClick={handleClick}> Go to some other route </button> ); } function App() { return ( <Router> <MyComponent /> </Router> ); } Requested Edit : import React from "react"; import { useNavigate } from "react-router-dom"; function MyComponent() { const navigate = useNavigate(); // Navigate to a different route when the button is clicked const handleClick = () => { navigate("/some/other/route"); }; return ( <button onClick={handleClick}> Go to some other route </button> ); } A: Define the hooks in root level of the component. before return statement export default function SearchReq(searchTerm: string) { const navigate = useNavigate(); // window.location.href = "/search?searchTerm=" + searchTerm; useEffect(() => { if(searchTerm) navigate("/search?searchTerm=" + searchTerm, { replace: true }); }, [searchTerm]) return null }
useNavigate() breaks the hook
I made a simple react hook. import React from "react"; import { useNavigate } from "react-router-dom"; export default function SearchReq(searchTerm: string) { if (searchTerm === "") return; const navigate = useNavigate(); console.log(searchTerm); // window.location.href = "/search?searchTerm=" + searchTerm; navigate("/search?searchTerm=" + searchTerm, { replace: true }); } But for some reason it is giving me an error I had figured out that the line that is causing an error is const navigate = useNavigate() but I don't understand why can any one explain it to me? Here is the error:
[ "to use the useNavigate hook, you need to make sure that your React component is rendered inside a Router component from the react-router library.\nimport React from \"react\";\nimport { useNavigate } from \"react-router-dom\";\nimport { Router } from \"react-router\"; \n\nfunction MyComponent() {\n const navigate = useNavigate();\n\n const handleClick = () => {\n navigate(\"/some/other/route\");\n };\n\n return (\n <button onClick={handleClick}>\n Go to some other route\n </button>\n );\n}\n\nfunction App() {\n return (\n <Router>\n <MyComponent />\n </Router>\n );\n}\n\nRequested Edit :\nimport React from \"react\";\nimport { useNavigate } from \"react-router-dom\";\n\nfunction MyComponent() {\n const navigate = useNavigate();\n\n // Navigate to a different route when the button is clicked\n const handleClick = () => {\n navigate(\"/some/other/route\");\n };\n\n return (\n <button onClick={handleClick}>\n Go to some other route\n </button>\n );\n}\n\n", "Define the hooks in root level of the component. before return statement\nexport default function SearchReq(searchTerm: string) {\n\n const navigate = useNavigate(); \n\n // window.location.href = \"/search?searchTerm=\" + searchTerm;\n\n useEffect(() => {\n if(searchTerm) navigate(\"/search?searchTerm=\" + searchTerm, { replace: true });\n\n }, [searchTerm])\n\n return null\n}\n\n" ]
[ 1, 0 ]
[]
[]
[ "reactjs", "typescript" ]
stackoverflow_0074678383_reactjs_typescript.txt
Q: Usage exceeded flood-stage watermark index has read-only-allow-delete when trying to delete document I have issue with deleting document from elasticsearch with command: DELETE /indexName/_doc/1 When trying to fire above http request I am getting too_many_requests/12/disk usage exceeded flood-stage watermark index has read-only-allow-delete. And I understand that I need to increase disc size for my node to make it work or disable flood-stage watermark. But when I saw read-only-allow-delete I thought that I can READ from given index and DELETE documents to free some space. But in realty I can only READ, why is that? Does ...-allow-delete means something different or is it not related to rest call and I need to clean my node by 'hand'? A: If you are unable to delete the index, it is possible that the index is in regular read-only mode rather than read-only-allow-delete mode. In regular read-only mode, you will not be able to delete documents from the index, and you may not be able to delete the index itself. To check the current mode of the index, you can use the Elasticsearch GET command to retrieve the index's settings. For example: GET /indexName/_settings This will return a JSON object containing the index's settings, including its read-only mode. If the index is in read-only mode, the "settings" object will contain a "blocks" object with a "read_only" property set to true.
Usage exceeded flood-stage watermark index has read-only-allow-delete when trying to delete document
I have issue with deleting document from elasticsearch with command: DELETE /indexName/_doc/1 When trying to fire above http request I am getting too_many_requests/12/disk usage exceeded flood-stage watermark index has read-only-allow-delete. And I understand that I need to increase disc size for my node to make it work or disable flood-stage watermark. But when I saw read-only-allow-delete I thought that I can READ from given index and DELETE documents to free some space. But in realty I can only READ, why is that? Does ...-allow-delete means something different or is it not related to rest call and I need to clean my node by 'hand'?
[ "If you are unable to delete the index, it is possible that the index is in regular read-only mode rather than read-only-allow-delete mode. In regular read-only mode, you will not be able to delete documents from the index, and you may not be able to delete the index itself.\nTo check the current mode of the index, you can use the Elasticsearch GET command to retrieve the index's settings. For example:\nGET /indexName/_settings\nThis will return a JSON object containing the index's settings, including its read-only mode. If the index is in read-only mode, the \"settings\" object will contain a \"blocks\" object with a \"read_only\" property set to true.\n" ]
[ 1 ]
[]
[]
[ "elasticsearch" ]
stackoverflow_0074678289_elasticsearch.txt
Q: How to create several components in Livewire at once i have this kinda problem im creating SPA with Laravel and Livewire and i need to create more than 200 components, so how can i do that except writing php artisan make:livewire ComponentName1, php artisan make:livewire ComponentName2 and so on. Naming of my components is pretty simple - Modal1, Modal2, Modal3.... Modal250. A: One way to generate multiple Livewire components quickly is to use a script to automate the process. For example, you could create a simple Bash script that uses a loop to run the php artisan make:livewire command multiple times, appending a number to the end of the component name each time. Here's an example of what that script might look like: #!/bin/bash for i in {1..250} do php artisan make:livewire "Modal$i" done Save the script to a file, make it executable (using the chmod command), and then run it to generate all of your Livewire components at once. Another option is to use the Laravel factories feature to generate dummy data for your components. This would allow you to quickly create a large number of dummy components without having to run the make:livewire command manually. You can find more information about using factories in the Laravel documentation.
How to create several components in Livewire at once
i have this kinda problem im creating SPA with Laravel and Livewire and i need to create more than 200 components, so how can i do that except writing php artisan make:livewire ComponentName1, php artisan make:livewire ComponentName2 and so on. Naming of my components is pretty simple - Modal1, Modal2, Modal3.... Modal250.
[ "One way to generate multiple Livewire components quickly is to use a script to automate the process. For example, you could create a simple Bash script that uses a loop to run the php artisan make:livewire command multiple times, appending a number to the end of the component name each time.\nHere's an example of what that script might look like:\n#!/bin/bash\n\nfor i in {1..250}\ndo\n php artisan make:livewire \"Modal$i\"\ndone\n\nSave the script to a file, make it executable (using the chmod command), and then run it to generate all of your Livewire components at once.\nAnother option is to use the Laravel factories feature to generate dummy data for your components. This would allow you to quickly create a large number of dummy components without having to run the make:livewire command manually. You can find more information about using factories in the Laravel documentation.\n" ]
[ 0 ]
[]
[]
[ "laravel", "laravel_livewire" ]
stackoverflow_0074678343_laravel_laravel_livewire.txt
Q: extracting data elements from a HTML string in Pandas I gave up on initial attempts to scrape the data that I need for manually creating a CSV file. 0 The Kingsley School https://www.isc.co.uk/schools/england/warwicks... warwickshire 1 Abberley Hall https://www.isc.co.uk/schools/england/worceste... worcestershire 2 Buttercup Primary School https://www.isc.co.uk/schools/england/london-a... london-area 3 Moorfield School https://www.isc.co.uk/schools/england/yorkshir... yorkshire-area-west 4 Avalon School https://www.isc.co.uk/schools/england/merseysi... merseyside 5 Haberdashers' Monmouth Schools https://www.isc.co.uk/schools/wales/monmouthsh... monmouthshire 6 Wells Cathedral School https://www.isc.co.uk/schools/england/somerset... somerset 7 Marlborough House School https://www.isc.co.uk/schools/england/kent/cra... ken Then thought I'd pull in the data from the web pages using requests thus: def grab_data(s): results = requests.get(s).content return results df['data'] = df['URL'].map(lambda x: grab_data(x)) But the results are a pigging mess. Is there a better way to parse the data that doesn't involve lots of str.replace? b'\r\n\r\n<!DOCTYPE html>\r\n<html lang="en">\r\n\t<head>\r\n\t\t<meta charset="UTF-8" />\r\n\r\n\t<title>\r\n\t\tThe Kingsley School, Royal Leamington Spa - ISC\r\n\t</title>\r\n\t\t<meta name="robots" content="index, follow" />\r\n\t\t<link rel="canonical" href="/schools/england/warwickshire/royal-leamington-spa/the-kingsley-school/" />\r\n\t<meta name="description" content="Information about Royal Leamington Spa, The Kingsley School" />\r\n\r\n\r\n\t\t\n\t<meta name="viewport" content="width=device-width, initial-scale=1.0">\n\t<meta name="format-detection" content="telephone-no" />\n\t<!-- Google Tag Manager -->\n\t<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({\'gtm.start\':\n\t\tnew Date().getTime(),event:\'gtm.js\'});var f=d.getElementsByTagName(s)[0],\n\t\tj=d.createElement(s),dl=l!=\'dataLayer\'?\'&l=\'+l:\'\';j.async=true;j.src=\n\t\t\'https://www.googletagmanager.com/gtm.js?id=\'+i+dl;f.parentNode.insertBefore(j,f);\n\t})(window,document,\'script\',\'dataLayer\',\'GTM-TCCJT7P\');</script>\n\t<!-- End Google Tag Manager -->\n\t<script src="/bundles/upper?v=C-4SuuHJ23ObmSV6TVgJvlUZTwUHbE9Mit8bUEVmwIo1"></script>\r\n \n\t<link href="/bundles/site?v=_nmQ8YRQiebaCD8eMIdpKjF42e4TM9br-6hkul2424o1" rel="stylesheet"/>\r\n \n\t<link rel="apple-touch-icon" sizes="180x180" href="/favicon/isc/apple-touch-icon.png">\r\n<link rel="icon" type="image/png" sizes="32x32" href="/favicon/isc/favicon-32x32.png">\r\n<link rel="icon" type="image/png" sizes="16x16" href="/favicon/isc/favicon-16x16.png">\r\n<link rel="manifest" href="/favicon/isc/site.webmanifest">\r\n<link rel="mask-icon" href="/favicon/isc/safari-pinned-tab.svg" color="#5bbad5">\r\n<meta name="msapplication-TileColor" content="#ffc40d">\r\n<meta name="msapplication-config" content="/favicon/isc/browserconfig.xml">\r\n<meta name="theme-color" content="#ffffff">\n\t\n\t<script>\n\t\tvar aId = 0; // mz values\n\t\tvar sId = 0;\n\t\tvar mID = 0;\n\n\n\t</script>\n\t<script src=\'https://www.google.com/recaptcha/api.js\'></script>\n\t<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">\n\t\r\n\r\n\t\t<script type="application/ld+json">\r\n\t\t\t{\r\n "@context": "https://schema.org",\r\n "@type": "School",\r\n "name": "The Kingsley School",\r\n "url": "https://www.thekingsleyschool.co.uk/",\r\n "description": "Kingsley provides a friendly, supportive family environment where individuals are encouraged to enjoy learning, and to aim for and achieve excellence. Our principal aim is to enable all our pupils to fulfil their potential wherever it may lie, through our wide range of subjects, lively extra-curricular activities, small classes and highly effective pastoral care.\\r\\n",\r\n "address": {\r\n "@type": "PostalAddress",\r\n "addressCountry": "England",\r\n "addressLocality": "Royal Leamington Spa",\r\n "streetAddress": "Beauchamp Avenue",\r\n "postalCode": "CV32 5RD",\r\n "telephone": "+44 (0)1926 425127"\r\n },\r\n "geo": {\r\n "@type": "GeoCoordinates",\r\n "latitude": 52.2942769,\r\n "longitude": -1.5379113\r\n },\r\n "email": "schooloffice@kingsleyschool.co.uk"\r\n}\r\n\t\t</script>\r\n\t\n\r\n\t</head>\r\n\t<body>\r\n\t<!-- Google Tag Manager (noscript) -->\r\n\t<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-TCCJT7P"\r\n\t height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>\r\n\t<!-- End Google Tag Manager (noscript) -->\r\n\t\n<script>\n\t(function (i, s, o, g, r, a, m) {\n\t\ti[\'GoogleAnalyticsObject\'] = r; i[r] = i[r] || function () {\n\t\t\t(i[r].q = i[r].q || []).push(arguments)\n\t\t}, i[r].l = 1 * new Date(); a = s.createElement(o),\n\t\t\tm = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)\n\t})(window, document, \'script\', \'https://www.google-analytics.com/analytics.js\', \'ga\');\n\tga(\'create\', \'UA-30159752-1\', \'auto\');\n\tga(\'send\', \'pageview\');\n</script>\n\n<script type="text/javascript" I want to try a method in lxml in python and wanted to pull out values from HTML. For instance, a lot of the HTML is messy. How do I search for a particular phrase in a document when all I've got is the HTML and no real structure that I can find? A: This example will give you a start how to select tags from the page and extract the required text: import requests from bs4 import BeautifulSoup url = "https://www.isc.co.uk/schools/wales/monmouthshire/monmouth/haberdashers-monmouth-schools/" soup = BeautifulSoup(requests.get(url).content, "html.parser") aff = ( soup.select_one('strong:-soup-contains("Religious affiliation")') .find_next_sibling(text=True) .strip() ) boys = soup.select(".boys-range p:has(strong)")[1:] boys = [p.get_text(strip=True).split(":") for p in boys] girls = soup.select(".girls-range p:has(strong)")[1:] girls = [p.get_text(strip=True).split(":") for p in girls] print(aff) print(boys) print(girls) Prints: Church in Wales [['Day', '3 to 18 (522)'], ['Boarding', '7 to 18 (150)'], ['Sixth form', ' (156)']] [['Day', '3 to 18 (456)'], ['Boarding', '7 to 18 (108)'], ['Sixth form', ' (104)']]
extracting data elements from a HTML string in Pandas
I gave up on initial attempts to scrape the data that I need for manually creating a CSV file. 0 The Kingsley School https://www.isc.co.uk/schools/england/warwicks... warwickshire 1 Abberley Hall https://www.isc.co.uk/schools/england/worceste... worcestershire 2 Buttercup Primary School https://www.isc.co.uk/schools/england/london-a... london-area 3 Moorfield School https://www.isc.co.uk/schools/england/yorkshir... yorkshire-area-west 4 Avalon School https://www.isc.co.uk/schools/england/merseysi... merseyside 5 Haberdashers' Monmouth Schools https://www.isc.co.uk/schools/wales/monmouthsh... monmouthshire 6 Wells Cathedral School https://www.isc.co.uk/schools/england/somerset... somerset 7 Marlborough House School https://www.isc.co.uk/schools/england/kent/cra... ken Then thought I'd pull in the data from the web pages using requests thus: def grab_data(s): results = requests.get(s).content return results df['data'] = df['URL'].map(lambda x: grab_data(x)) But the results are a pigging mess. Is there a better way to parse the data that doesn't involve lots of str.replace? b'\r\n\r\n<!DOCTYPE html>\r\n<html lang="en">\r\n\t<head>\r\n\t\t<meta charset="UTF-8" />\r\n\r\n\t<title>\r\n\t\tThe Kingsley School, Royal Leamington Spa - ISC\r\n\t</title>\r\n\t\t<meta name="robots" content="index, follow" />\r\n\t\t<link rel="canonical" href="/schools/england/warwickshire/royal-leamington-spa/the-kingsley-school/" />\r\n\t<meta name="description" content="Information about Royal Leamington Spa, The Kingsley School" />\r\n\r\n\r\n\t\t\n\t<meta name="viewport" content="width=device-width, initial-scale=1.0">\n\t<meta name="format-detection" content="telephone-no" />\n\t<!-- Google Tag Manager -->\n\t<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({\'gtm.start\':\n\t\tnew Date().getTime(),event:\'gtm.js\'});var f=d.getElementsByTagName(s)[0],\n\t\tj=d.createElement(s),dl=l!=\'dataLayer\'?\'&l=\'+l:\'\';j.async=true;j.src=\n\t\t\'https://www.googletagmanager.com/gtm.js?id=\'+i+dl;f.parentNode.insertBefore(j,f);\n\t})(window,document,\'script\',\'dataLayer\',\'GTM-TCCJT7P\');</script>\n\t<!-- End Google Tag Manager -->\n\t<script src="/bundles/upper?v=C-4SuuHJ23ObmSV6TVgJvlUZTwUHbE9Mit8bUEVmwIo1"></script>\r\n \n\t<link href="/bundles/site?v=_nmQ8YRQiebaCD8eMIdpKjF42e4TM9br-6hkul2424o1" rel="stylesheet"/>\r\n \n\t<link rel="apple-touch-icon" sizes="180x180" href="/favicon/isc/apple-touch-icon.png">\r\n<link rel="icon" type="image/png" sizes="32x32" href="/favicon/isc/favicon-32x32.png">\r\n<link rel="icon" type="image/png" sizes="16x16" href="/favicon/isc/favicon-16x16.png">\r\n<link rel="manifest" href="/favicon/isc/site.webmanifest">\r\n<link rel="mask-icon" href="/favicon/isc/safari-pinned-tab.svg" color="#5bbad5">\r\n<meta name="msapplication-TileColor" content="#ffc40d">\r\n<meta name="msapplication-config" content="/favicon/isc/browserconfig.xml">\r\n<meta name="theme-color" content="#ffffff">\n\t\n\t<script>\n\t\tvar aId = 0; // mz values\n\t\tvar sId = 0;\n\t\tvar mID = 0;\n\n\n\t</script>\n\t<script src=\'https://www.google.com/recaptcha/api.js\'></script>\n\t<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">\n\t\r\n\r\n\t\t<script type="application/ld+json">\r\n\t\t\t{\r\n "@context": "https://schema.org",\r\n "@type": "School",\r\n "name": "The Kingsley School",\r\n "url": "https://www.thekingsleyschool.co.uk/",\r\n "description": "Kingsley provides a friendly, supportive family environment where individuals are encouraged to enjoy learning, and to aim for and achieve excellence. Our principal aim is to enable all our pupils to fulfil their potential wherever it may lie, through our wide range of subjects, lively extra-curricular activities, small classes and highly effective pastoral care.\\r\\n",\r\n "address": {\r\n "@type": "PostalAddress",\r\n "addressCountry": "England",\r\n "addressLocality": "Royal Leamington Spa",\r\n "streetAddress": "Beauchamp Avenue",\r\n "postalCode": "CV32 5RD",\r\n "telephone": "+44 (0)1926 425127"\r\n },\r\n "geo": {\r\n "@type": "GeoCoordinates",\r\n "latitude": 52.2942769,\r\n "longitude": -1.5379113\r\n },\r\n "email": "schooloffice@kingsleyschool.co.uk"\r\n}\r\n\t\t</script>\r\n\t\n\r\n\t</head>\r\n\t<body>\r\n\t<!-- Google Tag Manager (noscript) -->\r\n\t<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-TCCJT7P"\r\n\t height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>\r\n\t<!-- End Google Tag Manager (noscript) -->\r\n\t\n<script>\n\t(function (i, s, o, g, r, a, m) {\n\t\ti[\'GoogleAnalyticsObject\'] = r; i[r] = i[r] || function () {\n\t\t\t(i[r].q = i[r].q || []).push(arguments)\n\t\t}, i[r].l = 1 * new Date(); a = s.createElement(o),\n\t\t\tm = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)\n\t})(window, document, \'script\', \'https://www.google-analytics.com/analytics.js\', \'ga\');\n\tga(\'create\', \'UA-30159752-1\', \'auto\');\n\tga(\'send\', \'pageview\');\n</script>\n\n<script type="text/javascript" I want to try a method in lxml in python and wanted to pull out values from HTML. For instance, a lot of the HTML is messy. How do I search for a particular phrase in a document when all I've got is the HTML and no real structure that I can find?
[ "This example will give you a start how to select tags from the page and extract the required text:\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nurl = \"https://www.isc.co.uk/schools/wales/monmouthshire/monmouth/haberdashers-monmouth-schools/\"\nsoup = BeautifulSoup(requests.get(url).content, \"html.parser\")\n\naff = (\n soup.select_one('strong:-soup-contains(\"Religious affiliation\")')\n .find_next_sibling(text=True)\n .strip()\n)\n\nboys = soup.select(\".boys-range p:has(strong)\")[1:]\nboys = [p.get_text(strip=True).split(\":\") for p in boys]\n\ngirls = soup.select(\".girls-range p:has(strong)\")[1:]\ngirls = [p.get_text(strip=True).split(\":\") for p in girls]\n\nprint(aff)\nprint(boys)\nprint(girls)\n\nPrints:\nChurch in Wales\n[['Day', '3 to 18 (522)'], ['Boarding', '7 to 18 (150)'], ['Sixth form', ' (156)']]\n[['Day', '3 to 18 (456)'], ['Boarding', '7 to 18 (108)'], ['Sixth form', ' (104)']]\n\n" ]
[ 0 ]
[]
[]
[ "html", "lxml", "pandas", "parsing" ]
stackoverflow_0074673178_html_lxml_pandas_parsing.txt
Q: Imported module not found in PyInstaller I'm working in Windows, using PyInstaller to package a python file. But some error is occuring: Traceback (most recent call last): File "<string>", line 2, in <module> File "D:\Useful Apps\pyinstaller-2.0\PyInstaller\loader\iu.py", line 386, in importHook mod = _self_doimport(nm, ctx, fqname) File "D:\Useful Apps\pyinstaller-2.0\PyInstaller\loader\iu.py", line 480, in doimport exec co in mod.__dict__ File "D:\Useful Apps\pyinstaller-2.0\server\build\pyi.win32\server\out00-PYZ.pyz\SocketServer", line 132, in <module> File "D:\Useful Apps\pyinstaller-2.0\PyInstaller\loader\iu.py", line 386, in importHook mod = _self_doimport(nm, ctx, fqname) File "D:\Useful Apps\pyinstaller-2.0\PyInstaller\loader\iu.py", line 480, in doimport exec co in mod.__dict__ File "D:\Useful Apps\pyinstaller-2.0\server\build\pyi.win32\server\out00-PYZ.pyz\socket", line 47, in <module> File "D:\Useful Apps\pyinstaller-2.0\PyInstaller\loader\iu.py", line 409, in importHook raise ImportError("No module named %s" % fqname) ImportError: No module named _socket I know that _socket is in path C:\Python27\libs\_socket.lib, but how can let the generated EXE find that file? A: If you are using virtualenv you should use the "-p" or "--path='D:...'" option. Like this: pyinstaller.exe --onefile --paths=D:\env\Lib\site-packages .\foo.py What this does is generates foo.spec file with this pathex path A: This sounds like a job for hidden imports (only available in the latest builds). From the docs a = Analysis(['myscript.py'], hiddenimports = ['_socket'], <and everything else>) A: In my case, I had to delete all folders and files related to pyinstaller in my directory, i.e. __pycache__, build, dist, and *.spec. I re-ran the build and the exe worked. A: In my case I was trying to import a folder that I created, and ended up here. I solved that problem by removing __init__.py from the main folder, keeping the __init__.py in the subfolders that I was importing. A: You can add the path to your application spec file. In the Analysis object you can specify pathex=['C:\Python27\libs\', 'C:\Python27\Lib\site-packages'], and any other path ... Note that if the path is not found there is no problem ... I have paths from linux as well in there. A: If you are using an virtual environment, then problem is because of environment. SOLUTION Just activate the environment and run the pyinstaller command. For example, If you are using environment of pipenv then run commands in following order. pipenv shell # To activate environment pyintaller --onefile youscript.py # Command to generate executable A: just delete the '__pycache__' directory then run your exe file again. It worked out for me A: None of the above answers worked for me, but I did get it to work. I was using openpyxl and it required jdcal in the datetime.py module. None of the hidden imports or any of those methods helped, running the exe would still say jdcal not found. The work-around that I used was to just copy the few functions from jdcal directly into the datetime.py in the openpyxl code. Then ran pyinstaller -F program.py and it worked! A: Had similar issues. Here's my fix for PyQt5, cffi, python 3.4.3: This fixes the 'sip' not found error and the '_cffi_backend' one if that comes up: # -*- mode: python -*- block_cipher = None a = Analysis(['LightShowApp.py'], pathex=['c:\\MyProjects\\light-show-editor-36', 'c:\\Python34\\libs\\', 'c:\\Python34\\Lib\\site-packages'], binaries=None, datas=None, hiddenimports=['sip', 'cffi'], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name='LightShowApp', debug=False, strip=False, upx=True, console=True ) Look at 'pathex' and 'hiddenimports' above. Those are the only changes from default generated. Build exe with: pyinstaller LightShowApp.spec -F I ran that outside of venv or pip-win - whateverTF that crap is for! A: The executor does not know the location of the library, "C:\Python27\Lib\site-packages" etc. Thus, pyinstaller binds the module locations when creating the executable. Therefore, you need to import all the modules, you have used into your program. Import the "_socket" module in your main file and recompile using pyinstaller. I would probably work. Note: But the versions of the modules installed in your system and used in the program must be compatible. A: Another "In my case" post. pypdfium2 (an import in my file that I want to convert to an .exe) has a .dll that it calls called pdfium. pyinstaller doesn't import that .dll when you go to build the .exe by default. Fix: I think you can do the option --collect-all pypdfium2 ,but at least for me --add-data "C:\Program Files\Python39\Lib\site-packages\pypdfium2\pdfium.dll";. (The "." at the end is intentional and needed!) got the job done. A: I found out that if you make the setup.py for your code and run python setup.py install and then python setup.py build the pyinstaller will be able to find your packages. you can use the find_packages function from setuptools in your setup.py file so it automatically includes everything.
Imported module not found in PyInstaller
I'm working in Windows, using PyInstaller to package a python file. But some error is occuring: Traceback (most recent call last): File "<string>", line 2, in <module> File "D:\Useful Apps\pyinstaller-2.0\PyInstaller\loader\iu.py", line 386, in importHook mod = _self_doimport(nm, ctx, fqname) File "D:\Useful Apps\pyinstaller-2.0\PyInstaller\loader\iu.py", line 480, in doimport exec co in mod.__dict__ File "D:\Useful Apps\pyinstaller-2.0\server\build\pyi.win32\server\out00-PYZ.pyz\SocketServer", line 132, in <module> File "D:\Useful Apps\pyinstaller-2.0\PyInstaller\loader\iu.py", line 386, in importHook mod = _self_doimport(nm, ctx, fqname) File "D:\Useful Apps\pyinstaller-2.0\PyInstaller\loader\iu.py", line 480, in doimport exec co in mod.__dict__ File "D:\Useful Apps\pyinstaller-2.0\server\build\pyi.win32\server\out00-PYZ.pyz\socket", line 47, in <module> File "D:\Useful Apps\pyinstaller-2.0\PyInstaller\loader\iu.py", line 409, in importHook raise ImportError("No module named %s" % fqname) ImportError: No module named _socket I know that _socket is in path C:\Python27\libs\_socket.lib, but how can let the generated EXE find that file?
[ "If you are using virtualenv you should use the \"-p\" or \"--path='D:...'\" option. Like this:\npyinstaller.exe --onefile --paths=D:\\env\\Lib\\site-packages .\\foo.py\n\nWhat this does is generates foo.spec file with this pathex path\n", "This sounds like a job for hidden imports (only available in the latest builds). \nFrom the docs\na = Analysis(['myscript.py'], \n hiddenimports = ['_socket'], \n <and everything else>)\n\n", "In my case, I had to delete all folders and files related to pyinstaller in my directory, i.e. __pycache__, build, dist, and *.spec. I re-ran the build and the exe worked.\n", "In my case I was trying to import a folder that I created, and ended up here. I solved that problem by removing __init__.py from the main folder, keeping the __init__.py in the subfolders that I was importing.\n", "You can add the path to your application spec file.\nIn the Analysis object you can specify pathex=['C:\\Python27\\libs\\', 'C:\\Python27\\Lib\\site-packages'], and any other path ...\nNote that if the path is not found there is no problem ... I have paths from linux as well in there.\n", "If you are using an virtual environment, then problem is because of environment.\nSOLUTION\nJust activate the environment and run the pyinstaller command. For example, If you are using environment of pipenv then run commands in following order.\npipenv shell # To activate environment\n\npyintaller --onefile youscript.py # Command to generate executable \n\n", "just delete the '__pycache__' directory then run your exe file again. It worked out for me\n", "None of the above answers worked for me, but I did get it to work. I was using openpyxl and it required jdcal in the datetime.py module. None of the hidden imports or any of those methods helped, running the exe would still say jdcal not found. The work-around that I used was to just copy the few functions from jdcal directly into the datetime.py in the openpyxl code. Then ran \npyinstaller -F program.py\nand it worked!\n", "Had similar issues. Here's my fix for PyQt5, cffi, python 3.4.3:\nThis fixes the 'sip' not found error and the '_cffi_backend' one if that comes up:\n# -*- mode: python -*-\n\nblock_cipher = None\n\n\na = Analysis(['LightShowApp.py'],\n pathex=['c:\\\\MyProjects\\\\light-show-editor-36',\n 'c:\\\\Python34\\\\libs\\\\', 'c:\\\\Python34\\\\Lib\\\\site-packages'],\n binaries=None,\n datas=None,\n hiddenimports=['sip', 'cffi'],\n hookspath=[],\n runtime_hooks=[],\n excludes=[],\n win_no_prefer_redirects=False,\n win_private_assemblies=False,\n cipher=block_cipher)\npyz = PYZ(a.pure, a.zipped_data,\n cipher=block_cipher)\nexe = EXE(pyz,\n a.scripts,\n a.binaries,\n a.zipfiles,\n a.datas,\n name='LightShowApp',\n debug=False,\n strip=False,\n upx=True,\n console=True )\n\nLook at 'pathex' and 'hiddenimports' above. Those are the only changes from default generated. Build exe with:\npyinstaller LightShowApp.spec -F\nI ran that outside of venv or pip-win - whateverTF that crap is for!\n", "The executor does not know the location of the library, \"C:\\Python27\\Lib\\site-packages\" etc. Thus, pyinstaller binds the module locations when creating the executable. Therefore, you need to import all the modules, you have used into your program.\nImport the \"_socket\" module in your main file and recompile using pyinstaller.\nI would probably work.\nNote: But the versions of the modules installed in your system and used in the program must be compatible.\n", "Another \"In my case\" post.\npypdfium2 (an import in my file that I want to convert to an .exe) has a .dll that it calls called pdfium. pyinstaller doesn't import that .dll when you go to build the .exe by default.\nFix:\nI think you can do the option --collect-all pypdfium2 ,but at least for me --add-data \"C:\\Program Files\\Python39\\Lib\\site-packages\\pypdfium2\\pdfium.dll\";. (The \".\" at the end is intentional and needed!) got the job done.\n", "I found out that if you make the setup.py for your code and run python setup.py install and then python setup.py build the pyinstaller will be able to find your packages. you can use the find_packages function from setuptools in your setup.py file so it automatically includes everything.\n" ]
[ 19, 4, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "exe", "pyinstaller", "python", "sockets", "windows" ]
stackoverflow_0015114695_exe_pyinstaller_python_sockets_windows.txt
Q: check if a register value is even/odd in MIPS I tried to do the following: # with $s6 holding i+j andi $s7, $s6, 0x1 # (i + j) & 1 (to check if it's even) if: bneq $s7, $zero, else however it generates an error... am I doing something wrong? A: Perhaps your assembler doesn't like 0x1 integers? andi $s7, $s6, 1 bnez $s7, odd # branch if not-equal to Zero. Or if your assembler doesn't like ABI names for registers, use register numbers? andi $23, $22, 1 # $22=$s6 and $23=$s7 If you use MARS or SPIM Simulator, or clang or other normal MIPS assemblers, andi $s7, $s6, 0x1 assembles just fine. Note andi doesn't add anything, so the i+j comment doesn't match andi Rdest, Rsrc1, Imm Put the logical AND of the integers from register Rsrc1 And Imm into register Rdest. A: bneq does not exist. Use bne $s7,$zero,else Post edit: Heres a working example #include<mips/regdef> ... andi t1,t1,0x1 Please add any error msg! A: Following your question title, I thought this answer could be as useful to someone else as it was for me: Since, for a binary value, if it ends with 0, it's even, if it ends with 1, it's odd. So, you basically need to get the first bit of a number with shift logical instructions like bellow. sll $t0, $s0, 0x1F srl $s1, $t0, 0x1F s0 contains the value to be validated t0 intermediates the shift operations s1 has the final result (0 for even, 1 for odd) Since each register has a value of 32 bits and we need just the first one, we shift the others 31 (0x1F) bits
check if a register value is even/odd in MIPS
I tried to do the following: # with $s6 holding i+j andi $s7, $s6, 0x1 # (i + j) & 1 (to check if it's even) if: bneq $s7, $zero, else however it generates an error... am I doing something wrong?
[ "Perhaps your assembler doesn't like 0x1 integers?\nandi $s7, $s6, 1\nbnez $s7, odd # branch if not-equal to Zero.\n\nOr if your assembler doesn't like ABI names for registers, use register numbers?\nandi $23, $22, 1 # $22=$s6 and $23=$s7\n\nIf you use MARS or SPIM Simulator, or clang or other normal MIPS assemblers,\nandi $s7, $s6, 0x1 assembles just fine.\n\nNote andi doesn't add anything, so the i+j comment doesn't match\n\nandi Rdest, Rsrc1, Imm Put the logical\nAND of the integers from register\nRsrc1 And Imm into register Rdest.\n\n", "bneq does not exist.\nUse\nbne $s7,$zero,else\n\nPost edit:\nHeres a working example\n #include<mips/regdef>\n ...\n andi t1,t1,0x1\n\nPlease add any error msg!\n", "Following your question title, I thought this answer could be as useful to someone else as it was for me:\nSince, for a binary value, if it ends with 0, it's even, if it ends with 1, it's odd. So, you basically need to get the first bit of a number with shift logical instructions like bellow.\nsll $t0, $s0, 0x1F \nsrl $s1, $t0, 0x1F \n\n\ns0 contains the value to be validated\nt0 intermediates the shift operations\ns1 has the final result (0 for even, 1 for odd)\nSince each register has a value of 32 bits and we need just the first one, we shift the others 31 (0x1F) bits\n\n" ]
[ 5, 1, 0 ]
[]
[]
[ "assembly", "mips" ]
stackoverflow_0002300138_assembly_mips.txt
Q: Sequelize error with MariaDB I am trying to setup sequelize as ORM for my MariaDB. Here is my setup: var sequelize = require('sequelize'); var db= new sequelize('dbname', 'user', 'pass', { dialect: 'mariadb' }); When I run my app I get the following error : /my/path/to/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:23 throw new Error('Please install mysql package manually'); ^ Error: Please install mysql package manually Why is sequelize trying to connect to mysql rather than mariadb as I specified in the dialect directive? Am I missing something? A: Sequelize now has the dialect mariadb, do not use mysql npm install --save mariadb npm install --save sequelize Sequelize connection code... var sequelize = new Sequelize('database', 'username', 'password', { dialect: 'mariadb' }) A: Sequelize internally uses the same library to connect with MariaDB or MySQL , take a look to the documentation http://docs.sequelizejs.com/en/latest/docs/getting-started/ specifically in the section Installation. To make it works you just need to install mysql package so: $ npm install --save mysql2 A: What the previous answer fails to mention is you must also set the dialect to MySQL...dialect: mysql because dialect: mariadb does not exist. A: You must install mysql or any dialect using -g. npm i -g mysql A: If you are using yarn: yarn add mariadb
Sequelize error with MariaDB
I am trying to setup sequelize as ORM for my MariaDB. Here is my setup: var sequelize = require('sequelize'); var db= new sequelize('dbname', 'user', 'pass', { dialect: 'mariadb' }); When I run my app I get the following error : /my/path/to/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:23 throw new Error('Please install mysql package manually'); ^ Error: Please install mysql package manually Why is sequelize trying to connect to mysql rather than mariadb as I specified in the dialect directive? Am I missing something?
[ "Sequelize now has the dialect mariadb, do not use mysql\nnpm install --save mariadb\nnpm install --save sequelize\n\nSequelize connection code...\nvar sequelize = new Sequelize('database', 'username', 'password', {\n dialect: 'mariadb'\n})\n\n", "Sequelize internally uses the same library to connect with MariaDB or MySQL , take a look to the documentation \nhttp://docs.sequelizejs.com/en/latest/docs/getting-started/ specifically in the section Installation.\nTo make it works you just need to install mysql package so:\n$ npm install --save mysql2\n\n", "What the previous answer fails to mention is you must also set the dialect to MySQL...dialect: mysql because dialect: mariadb does not exist.\n", "You must install mysql or any dialect using -g.\nnpm i -g mysql\n\n", "If you are using yarn:\nyarn add mariadb\n\n" ]
[ 8, 5, 3, 0, 0 ]
[]
[]
[ "mariadb", "mariasql", "node.js", "sequelize.js" ]
stackoverflow_0035796963_mariadb_mariasql_node.js_sequelize.js.txt
Q: Why factorial function return not 1? I can't understand why the function returned a result and not a unit, how does it work? function factorial(n) { return (n != 1) ? n * factorial(n - 1) : 1; } console.log(factorial(5)); // result is 120 why not 1 ? A: This is a recursive function. You start by passing in 5. It then calls itself with 4, and so on. The math for each call looks like this: factorial(5): 5 * factorial(4) factorial(4): 4 * factorial(3) factorial(3): 3 * factorial(2) factorial(2): 2 * factorial(1) factorial(1): 1 Once you get to the "base case", 1, execution goes back up the stack in reverse order and uses the result of each previous step: factorial(1): 1 factorial(2): 2 * 1 = 2 factorial(3): 3 * 2 = 6 factorial(4): 4 * 6 = 24 factorial(5): 5 * 24 = 120 And so factorial(5) returns 120.
Why factorial function return not 1?
I can't understand why the function returned a result and not a unit, how does it work? function factorial(n) { return (n != 1) ? n * factorial(n - 1) : 1; } console.log(factorial(5)); // result is 120 why not 1 ?
[ "This is a recursive function. You start by passing in 5. It then calls itself with 4, and so on. The math for each call looks like this:\nfactorial(5): 5 * factorial(4)\nfactorial(4): 4 * factorial(3)\nfactorial(3): 3 * factorial(2)\nfactorial(2): 2 * factorial(1)\nfactorial(1): 1\n\nOnce you get to the \"base case\", 1, execution goes back up the stack in reverse order and uses the result of each previous step:\nfactorial(1): 1\nfactorial(2): 2 * 1 = 2\nfactorial(3): 3 * 2 = 6\nfactorial(4): 4 * 6 = 24\nfactorial(5): 5 * 24 = 120\n\nAnd so factorial(5) returns 120.\n" ]
[ 1 ]
[]
[]
[ "javascript" ]
stackoverflow_0074678389_javascript.txt
Q: How to extract certain letters from a string using Python I have a string 'A1T1730' From this I need to extract the second letter and the last four letters. For example, from 'A1T1730' I need to extract '1' and '1730'. I'm not sure how to do this in Python. I have the following right now which extracts every character from the string separately so can someone please help me update it as per the above need. list = ['A1T1730'] for letter in list[0]: print letter Which gives me the result of A, 1, T, 1, 7, 3, 0 A: my_string = "A1T1730" my_string = my_string[1] + my_string[-4:] print my_string Output 11730 If you want to extract them to different variables, you can just do first, last = my_string[1], my_string[-4:] print first, last Output 1 1730 A: Using filter with str.isdigit (as unbound method form): >>> filter(str.isdigit, 'A1T1730') '11730' >>> ''.join(filter(str.isdigit, 'A1T1730')) # In Python 3.x '11730' If you want to get numbers separated, use regular expression (See re.findall): >>> import re >>> re.findall(r'\d+', 'A1T1730') ['1', '1730'] Use thefourtheye's solution if the positions of digits are fixed. BTW, don't use list as a variable name. It shadows builtin list function. A: You can use the function isdigit(). If that character is a digit it returns true and otherwise returns false: list = ['A1T1730'] for letter in list[0]: if letter.isdigit() == True: print letter, #The coma is used for print in the same line I hope this useful. A: Well you could do like this _2nd = lsit[0][1] # last 4 characters numbers = list[0][-4:]
How to extract certain letters from a string using Python
I have a string 'A1T1730' From this I need to extract the second letter and the last four letters. For example, from 'A1T1730' I need to extract '1' and '1730'. I'm not sure how to do this in Python. I have the following right now which extracts every character from the string separately so can someone please help me update it as per the above need. list = ['A1T1730'] for letter in list[0]: print letter Which gives me the result of A, 1, T, 1, 7, 3, 0
[ "my_string = \"A1T1730\"\nmy_string = my_string[1] + my_string[-4:]\nprint my_string\n\nOutput\n11730\n\nIf you want to extract them to different variables, you can just do\nfirst, last = my_string[1], my_string[-4:]\nprint first, last\n\nOutput\n1 1730\n\n", "Using filter with str.isdigit (as unbound method form):\n>>> filter(str.isdigit, 'A1T1730')\n'11730'\n>>> ''.join(filter(str.isdigit, 'A1T1730')) # In Python 3.x\n'11730'\n\nIf you want to get numbers separated, use regular expression (See re.findall):\n>>> import re\n>>> re.findall(r'\\d+', 'A1T1730')\n['1', '1730']\n\nUse thefourtheye's solution if the positions of digits are fixed.\n\nBTW, don't use list as a variable name. It shadows builtin list function.\n", "You can use the function isdigit(). If that character is a digit it returns true and otherwise returns false:\nlist = ['A1T1730'] \nfor letter in list[0]:\n if letter.isdigit() == True:\n print letter, #The coma is used for print in the same line \n\nI hope this useful.\n", "Well you could do like this\n_2nd = lsit[0][1]\n\n# last 4 characters\nnumbers = list[0][-4:]\n\n\n" ]
[ 5, 4, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0021187124_list_python.txt
Q: Pandas: sort_index - help understanding 'key' argument I am trying to sort a complex index (weird strings, with a custom order). I originally tried to do this, but its messing up the index (because its overwriting, not actually sorting) df.index = list(sorted(df.index, key=Delta_Sorter.sort)) # <--Delta_Sorter.sort is a classmethod Instead, I should probably be using Pandas.DataFrame.sort_index(), and pass key = Delta_Sorter.sort. I was hoping someone could please help me understand the key argument though. From the docs: key: callable, optional If not None, apply the key function to the index values before sorting. This is similar to the key argument in the builtin sorted() function, with the notable difference that this key function should be vectorized. It should expect an Index and return an Index of the same shape. For MultiIndex inputs, the key is applied per level. In particular, I dont know what it means that it should be vectorized. The docs don't have an example... EDIT I tried using numpy.vectorize(Delta_Sorter.sort), but it raises: ValueError: User-provided key function must not change the shape of the array. class Delta_Sorter(): @classmethod def sort(cls, x): # x = index value from the DataFrame level_1 = cls._underlying_sort(x) #<- returns int level_2 = cls._string_tenor_sorter(x) #<- returns int return (level_1, level_2) # <-- uses a tuple to create sort 'levels' Passing the df.index directly into the np.vectorize(Delta_Sorter.sort)(df.index) returns: (array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), array([ 10, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 20, 200, 30, 40, 50, 60, 70, 80, 90, 2, 5, 10, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 20, 200, 30, 40, 50, 60, 70, 80, 90, 400, 480, 600, 800, 1000, 1200, 240, 280, 320, 360]))
Pandas: sort_index - help understanding 'key' argument
I am trying to sort a complex index (weird strings, with a custom order). I originally tried to do this, but its messing up the index (because its overwriting, not actually sorting) df.index = list(sorted(df.index, key=Delta_Sorter.sort)) # <--Delta_Sorter.sort is a classmethod Instead, I should probably be using Pandas.DataFrame.sort_index(), and pass key = Delta_Sorter.sort. I was hoping someone could please help me understand the key argument though. From the docs: key: callable, optional If not None, apply the key function to the index values before sorting. This is similar to the key argument in the builtin sorted() function, with the notable difference that this key function should be vectorized. It should expect an Index and return an Index of the same shape. For MultiIndex inputs, the key is applied per level. In particular, I dont know what it means that it should be vectorized. The docs don't have an example... EDIT I tried using numpy.vectorize(Delta_Sorter.sort), but it raises: ValueError: User-provided key function must not change the shape of the array. class Delta_Sorter(): @classmethod def sort(cls, x): # x = index value from the DataFrame level_1 = cls._underlying_sort(x) #<- returns int level_2 = cls._string_tenor_sorter(x) #<- returns int return (level_1, level_2) # <-- uses a tuple to create sort 'levels' Passing the df.index directly into the np.vectorize(Delta_Sorter.sort)(df.index) returns: (array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), array([ 10, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 20, 200, 30, 40, 50, 60, 70, 80, 90, 2, 5, 10, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 20, 200, 30, 40, 50, 60, 70, 80, 90, 400, 480, 600, 800, 1000, 1200, 240, 280, 320, 360]))
[]
[]
[ "Syntax: DataFrame.sort_index(axis=0, level=None, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’, sort_remaining=True, by=None)\nParameters :\naxis : index, columns to direct sorting\nlevel : if not None, sort on values in specified index level(s)\nascending : Sort ascending vs. descending\ninplace : if True, perform operation in-place\nkind : {‘quicksort’, ‘mergesort’, ‘heapsort’}, default ‘quicksort’. Choice of sorting algorithm. See also ndarray.np.sort for more information. mergesort is the only stable algorithm. For DataFrames, this option is only applied when sorting on a single column or label.\nna_position : [{‘first’, ‘last’}, default ‘last’] First puts NaNs at the beginning, last puts NaNs at the end. Not implemented for MultiIndex.\nsort_remaining : If true and sorting by level and index is multilevel, sort by other levels too (in order) after sorting by specified level\nReturn : sorted_obj : DataFrame\n" ]
[ -2 ]
[ "pandas", "python" ]
stackoverflow_0074678401_pandas_python.txt
Q: Printing Even and Odd using two Threads in Java I tried the code below. I took this piece of code from some other post which is correct as per the author. But when I try running, it doesn't give me the exact result. This is mainly to print even and odd values in sequence. public class PrintEvenOddTester { public static void main(String ... args){ Printer print = new Printer(false); Thread t1 = new Thread(new TaskEvenOdd(print)); Thread t2 = new Thread(new TaskEvenOdd(print)); t1.start(); t2.start(); } } class TaskEvenOdd implements Runnable { int number=1; Printer print; TaskEvenOdd(Printer print){ this.print = print; } @Override public void run() { System.out.println("Run method"); while(number<10){ if(number%2 == 0){ System.out.println("Number is :"+ number); print.printEven(number); number+=2; } else { System.out.println("Number is :"+ number); print.printOdd(number); number+=2; } } } } class Printer { boolean isOdd; Printer(boolean isOdd){ this.isOdd = isOdd; } synchronized void printEven(int number) { while(isOdd){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Even:"+number); isOdd = true; notifyAll(); } synchronized void printOdd(int number) { while(!isOdd){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Odd:"+number); isOdd = false; notifyAll(); } } Can someone help me in fixing this? EDIT Expected result: Odd:1 Even:2 Odd:3 Even:4 Odd:5 Even:6 Odd:7 Even:8 Odd:9 A: Found the solution. Someone looking for solution to this problem can refer :-) public class PrintEvenOddTester { public static void main(String... args) { Printer print = new Printer(); Thread t1 = new Thread(new TaskEvenOdd(print, 10, false)); Thread t2 = new Thread(new TaskEvenOdd(print, 10, true)); t1.start(); t2.start(); } } class TaskEvenOdd implements Runnable { private int max; private Printer print; private boolean isEvenNumber; TaskEvenOdd(Printer print, int max, boolean isEvenNumber) { this.print = print; this.max = max; this.isEvenNumber = isEvenNumber; } @Override public void run() { //System.out.println("Run method"); int number = isEvenNumber == true ? 2 : 1; while (number <= max) { if (isEvenNumber) { //System.out.println("Even :"+ Thread.currentThread().getName()); print.printEven(number); //number+=2; } else { //System.out.println("Odd :"+ Thread.currentThread().getName()); print.printOdd(number); // number+=2; } number += 2; } } } class Printer { boolean isOdd = false; synchronized void printEven(int number) { while (isOdd == false) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Even:" + number); isOdd = false; notifyAll(); } synchronized void printOdd(int number) { while (isOdd == true) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Odd:" + number); isOdd = true; notifyAll(); } } This gives output like: Odd:1 Even:2 Odd:3 Even:4 Odd:5 Even:6 Odd:7 Even:8 Odd:9 Even:10 A: Use this following very simple JAVA 8 Runnable Class feature public class MultiThreadExample { static AtomicInteger atomicNumber = new AtomicInteger(1); public static void main(String[] args) { Runnable print = () -> { while (atomicNumber.get() < 10) { synchronized (atomicNumber) { if ((atomicNumber.get() % 2 == 0) && "Even".equals(Thread.currentThread().getName())) { System.out.println("Even" + ":" + atomicNumber.getAndIncrement()); } //else if ((atomicNumber.get() % 2 != 0) && "Odd".equals(Thread.currentThread().getName())) else {System.out.println("Odd" + ":" + atomicNumber.getAndIncrement()); } } } }; Thread t1 = new Thread(print); t1.setName("Even"); t1.start(); Thread t2 = new Thread(print); t2.setName("Odd"); t2.start(); } } A: Here is the code which I made it work through a single class package com.learn.thread; public class PrintNumbers extends Thread { volatile static int i = 1; Object lock; PrintNumbers(Object lock) { this.lock = lock; } public static void main(String ar[]) { Object obj = new Object(); // This constructor is required for the identification of wait/notify // communication PrintNumbers odd = new PrintNumbers(obj); PrintNumbers even = new PrintNumbers(obj); odd.setName("Odd"); even.setName("Even"); odd.start(); even.start(); } @Override public void run() { while (i <= 10) { if (i % 2 == 0 && Thread.currentThread().getName().equals("Even")) { synchronized (lock) { System.out.println(Thread.currentThread().getName() + " - " + i); i++; try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } if (i % 2 == 1 && Thread.currentThread().getName().equals("Odd")) { synchronized (lock) { System.out.println(Thread.currentThread().getName() + " - " + i); i++; lock.notify(); } } } } } Output: Odd - 1 Even - 2 Odd - 3 Even - 4 Odd - 5 Even - 6 Odd - 7 Even - 8 Odd - 9 Even - 10 Odd - 11 A: private Object lock = new Object(); private volatile boolean isOdd = false; public void generateEvenNumbers(int number) throws InterruptedException { synchronized (lock) { while (isOdd == false) { lock.wait(); } System.out.println(number); isOdd = false; lock.notifyAll(); } } public void generateOddNumbers(int number) throws InterruptedException { synchronized (lock) { while (isOdd == true) { lock.wait(); } System.out.println(number); isOdd = true; lock.notifyAll(); } } A: This is easiest solution for this problem. public class OddEven implements Runnable { @Override public void run() { // TODO Auto-generated method stub for (int i = 1; i <= 10; i++) { synchronized (this) { if (i % 2 == 0 && Thread.currentThread().getName().equals("t2")) { try { notifyAll(); System.out.println("Even Thread : " + i); wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (i % 2 != 0 && Thread.currentThread().getName().equals("t1")) { try { notifyAll(); System.out.println("Odd Thread : " + i); wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } public static void main(String[] args) { OddEven obj = new OddEven(); Thread t1 = new Thread(obj, "t1"); Thread t2 = new Thread(obj, "t2"); t1.start(); t2.start(); } } A: Simplest Solution!! public class OddEvenWithThread { public static void main(String a[]) { Thread t1 = new Thread(new OddEvenRunnable(0), "Even Thread"); Thread t2 = new Thread(new OddEvenRunnable(1), "Odd Thread"); t1.start(); t2.start(); } } class OddEvenRunnable implements Runnable { Integer evenflag; static Integer number = 1; static Object lock = new Object(); OddEvenRunnable(Integer evenFlag) { this.evenflag = evenFlag; } @Override public void run() { while (number < 10) { synchronized (lock) { try { while (number % 2 != evenflag) { lock.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " " + number); number++; lock.notifyAll(); } } } } A: The same can be done with Lock interface: import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class NumberPrinter implements Runnable { private Lock lock; private Condition condition; private String type; private static boolean oddTurn = true; public NumberPrinter(String type, Lock lock, Condition condition) { this.type = type; this.lock = lock; this.condition = condition; } public void run() { int i = type.equals("odd") ? 1 : 2; while (i <= 10) { if (type.equals("odd")) printOdd(i); if (type.equals("even")) printEven(i); i = i + 2; } } private void printOdd(int i) { // synchronized (lock) { lock.lock(); while (!oddTurn) { try { // lock.wait(); condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(type + " " + i); oddTurn = false; // lock.notifyAll(); condition.signalAll(); lock.unlock(); } // } private void printEven(int i) { // synchronized (lock) { lock.lock(); while (oddTurn) { try { // lock.wait(); condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(type + " " + i); oddTurn = true; // lock.notifyAll(); condition.signalAll(); lock.unlock(); } // } public static void main(String[] args) { Lock lock = new ReentrantLock(); Condition condition = lock.newCondition(); Thread odd = new Thread(new NumberPrinter("odd", lock, condition)); Thread even = new Thread(new NumberPrinter("even", lock, condition)); odd.start(); even.start(); } } A: This code will also work fine. class Thread1 implements Runnable { private static boolean evenFlag = true; public synchronized void run() { if (evenFlag == true) { printEven(); } else { printOdd(); } } public void printEven() { for (int i = 0; i <= 10; i += 2) { System.out.println(i+""+Thread.currentThread()); } evenFlag = false; } public void printOdd() { for (int i = 1; i <= 11; i += 2) { System.out.println(i+""+Thread.currentThread()); } evenFlag = true; } } public class OddEvenDemo { public static void main(String[] args) { Thread1 t1 = new Thread1(); Thread td1 = new Thread(t1); Thread td2 = new Thread(t1); td1.start(); td2.start(); } } A: import java.util.concurrent.atomic.AtomicInteger; public class PrintEvenOddTester { public static void main(String ... args){ Printer print = new Printer(false); Thread t1 = new Thread(new TaskEvenOdd(print, "Thread1", new AtomicInteger(1))); Thread t2 = new Thread(new TaskEvenOdd(print,"Thread2" , new AtomicInteger(2))); t1.start(); t2.start(); } } class TaskEvenOdd implements Runnable { Printer print; String name; AtomicInteger number; TaskEvenOdd(Printer print, String name, AtomicInteger number){ this.print = print; this.name = name; this.number = number; } @Override public void run() { System.out.println("Run method"); while(number.get()<10){ if(number.get()%2 == 0){ print.printEven(number.get(),name); } else { print.printOdd(number.get(),name); } number.addAndGet(2); } } } class Printer { boolean isEven; public Printer() { } public Printer(boolean isEven) { this.isEven = isEven; } synchronized void printEven(int number, String name) { while (!isEven) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(name+": Even:" + number); isEven = false; notifyAll(); } synchronized void printOdd(int number, String name) { while (isEven) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(name+": Odd:" + number); isEven = true; notifyAll(); } } A: The other question was closed as a duplicate of this one. I think we can safely get rid of "even or odd" problem and use the wait/notify construct as follows: public class WaitNotifyDemoEvenOddThreads { /** * A transfer object, only use with proper client side locking! */ static final class LastNumber { int num; final int limit; LastNumber(int num, int limit) { this.num = num; this.limit = limit; } } static final class NumberPrinter implements Runnable { private final LastNumber last; private final int init; NumberPrinter(LastNumber last, int init) { this.last = last; this.init = init; } @Override public void run() { int i = init; synchronized (last) { while (i <= last.limit) { while (last.num != i) { try { last.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + " prints: " + i); last.num = i + 1; i += 2; last.notify(); } } } } public static void main(String[] args) { LastNumber last = new LastNumber(0, 10); // or 0, 1000 NumberPrinter odd = new NumberPrinter(last, 1); NumberPrinter even = new NumberPrinter(last, 0); new Thread(odd, "o").start(); new Thread(even, "e").start(); } } A: Simpler Version in Java 8: public class EvenOddPrinter { static boolean flag = true; public static void main(String[] args) { Runnable odd = () -> { for (int i = 1; i <= 10;) { if(EvenOddPrinter.flag) { System.out.println(i); i+=2; EvenOddPrinter.flag = !EvenOddPrinter.flag; } } }; Runnable even = () -> { for (int i = 2; i <= 10;) { if(!EvenOddPrinter.flag) { System.out.println(i); i+=2; EvenOddPrinter.flag = !EvenOddPrinter.flag; } } }; Thread t1 = new Thread(odd, "Odd"); Thread t2 = new Thread(even, "Even"); t1.start(); t2.start(); } } A: package pkgscjp; public class OddPrint implements Runnable { public static boolean flag = true; public void run() { for (int i = 1; i <= 99;) { if (flag) { System.out.println(i); flag = false; i = i + 2; } } } } package pkgscjp; public class EvenPrint implements Runnable { public void run() { for (int i = 2; i <= 100;) { if (!OddPrint.flag) { System.out.println(i); OddPrint.flag = true; i = i + 2; } } } } package pkgscjp; public class NaturalNumberThreadMain { public static void main(String args[]) { EvenPrint ep = new EvenPrint(); OddPrint op = new OddPrint(); Thread te = new Thread(ep); Thread to = new Thread(op); to.start(); te.start(); } } A: I have done it this way, while printing using two threads we cannot predict the sequence which thread would get executed first so to overcome this situation we have to synchronize the shared resource,in my case the print function which two threads are trying to access. class Printoddeven{ public synchronized void print(String msg) { try { if(msg.equals("Even")) { for(int i=0;i<=10;i+=2) { System.out.println(msg+" "+i); Thread.sleep(2000); notify(); wait(); } } else { for(int i=1;i<=10;i+=2) { System.out.println(msg+" "+i); Thread.sleep(2000); notify(); wait(); } } } catch (Exception e) { e.printStackTrace(); } } } class PrintOdd extends Thread{ Printoddeven oddeven; public PrintOdd(Printoddeven oddeven){ this.oddeven=oddeven; } public void run(){ oddeven.print("ODD"); } } class PrintEven extends Thread{ Printoddeven oddeven; public PrintEven(Printoddeven oddeven){ this.oddeven=oddeven; } public void run(){ oddeven.print("Even"); } } public class mainclass { public static void main(String[] args) { Printoddeven obj = new Printoddeven();//only one object PrintEven t1=new PrintEven(obj); PrintOdd t2=new PrintOdd(obj); t1.start(); t2.start(); } } A: This is my solution to the problem. I have two classes implementing Runnable, one prints odd sequence and the other prints even. I have an instance of Object, that I use for lock. I initialize the two classes with the same object. There is a synchronized block inside the run method of the two classes, where, inside a loop, each method prints one of the numbers, notifies the other thread, waiting for lock on the same object and then itself waits for the same lock again. The classes : public class PrintEven implements Runnable{ private Object lock; public PrintEven(Object lock) { this.lock = lock; } @Override public void run() { synchronized (lock) { for (int i = 2; i <= 10; i+=2) { System.out.println("EVEN:="+i); lock.notify(); try { //if(i!=10) lock.wait(); lock.wait(500); } catch (InterruptedException e) { e.printStackTrace(); } } } } } public class PrintOdd implements Runnable { private Object lock; public PrintOdd(Object lock) { this.lock = lock; } @Override public void run() { synchronized (lock) { for (int i = 1; i <= 10; i+=2) { System.out.println("ODD:="+i); lock.notify(); try { //if(i!=9) lock.wait(); lock.wait(500); } catch (InterruptedException e) { e.printStackTrace(); } } } } } public class PrintEvenOdd { public static void main(String[] args){ Object lock = new Object(); Thread thread1 = new Thread(new PrintOdd(lock)); Thread thread2 = new Thread(new PrintEven(lock)); thread1.start(); thread2.start(); } } The upper limit in my example is 10. Once the odd thread prints 9 or the even thread prints 10, then we don't need any of the threads to wait any more. So, we can handle that using one if-block. Or, we can use the overloaded wait(long timeout) method for the wait to be timed out. One flaw here though. With this code, we cannot guarantee which thread will start execution first. Another example, using Lock and Condition import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class LockConditionOddEven { public static void main(String[] args) { Lock lock = new ReentrantLock(); Condition evenCondition = lock.newCondition(); Condition oddCondition = lock.newCondition(); Thread evenThread = new Thread(new EvenPrinter(10, lock, evenCondition, oddCondition)); Thread oddThread = new Thread(new OddPrinter(10, lock, evenCondition, oddCondition)); oddThread.start(); evenThread.start(); } static class OddPrinter implements Runnable{ int i = 1; int limit; Lock lock; Condition evenCondition; Condition oddCondition; public OddPrinter(int limit) { super(); this.limit = limit; } public OddPrinter(int limit, Lock lock, Condition evenCondition, Condition oddCondition) { super(); this.limit = limit; this.lock = lock; this.evenCondition = evenCondition; this.oddCondition = oddCondition; } @Override public void run() { while( i <=limit) { lock.lock(); System.out.println("Odd:"+i); evenCondition.signal(); i+=2; try { oddCondition.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { lock.unlock(); } } } } static class EvenPrinter implements Runnable{ int i = 2; int limit; Lock lock; Condition evenCondition; Condition oddCondition; public EvenPrinter(int limit) { super(); this.limit = limit; } public EvenPrinter(int limit, Lock lock, Condition evenCondition, Condition oddCondition) { super(); this.limit = limit; this.lock = lock; this.evenCondition = evenCondition; this.oddCondition = oddCondition; } @Override public void run() { while( i <=limit) { lock.lock(); System.out.println("Even:"+i); i+=2; oddCondition.signal(); try { evenCondition.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { lock.unlock(); } } } } } A: Here is the working code to print odd even no alternatively using wait and notify mechanism. I have restrict the limit of numbers to print 1 to 50. public class NotifyTest { Object ob=new Object(); public static void main(String[] args) { // TODO Auto-generated method stub NotifyTest nt=new NotifyTest(); even e=new even(nt.ob); odd o=new odd(nt.ob); Thread t1=new Thread(e); Thread t2=new Thread(o); t1.start(); t2.start(); } } class even implements Runnable { Object lock; int i=2; public even(Object ob) { this.lock=ob; } @Override public void run() { // TODO Auto-generated method stub while(i<=50) { synchronized (lock) { try { lock.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Even Thread Name-->>" + Thread.currentThread().getName() + "Value-->>" + i); i=i+2; } } } class odd implements Runnable { Object lock; int i=1; public odd(Object ob) { this.lock=ob; } @Override public void run() { // TODO Auto-generated method stub while(i<=49) { synchronized (lock) { System.out.println("Odd Thread Name-->>" + Thread.currentThread().getName() + "Value-->>" + i); i=i+2; lock.notify(); } try { Thread.sleep(1000); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } A: Following is my implementation using 2 Semaphores. Odd Semaphore with permit 1. Even Semaphore with permit 0. Pass the two Semaphores to both threads as following signature (my, other):- To Odd thread pass in the order (odd, even) To Even thread pass in this order (even, odd) run() method logic is my.acquireUninterruptibly() -> Print -> other.release() In Even thread as even Sema is 0 it will block. In Odd thread as odd Sema is available (init to 1) this will print 1 and then release even Sema allowing Even thread to run. Even thread runs prints 2 and release odd Sema allowing Odd thread to run. import java.util.concurrent.Semaphore; public class EvenOdd { private final static String ODD = "ODD"; private final static String EVEN = "EVEN"; private final static int MAX_ITERATIONS = 10; public static class EvenOddThread implements Runnable { private String mType; private int mNum; private Semaphore mMySema; private Semaphore mOtherSema; public EvenOddThread(String str, Semaphore mine, Semaphore other) { mType = str; mMySema = mine;//new Semaphore(1); // start out as unlocked mOtherSema = other;//new Semaphore(0); if(str.equals(ODD)) { mNum = 1; } else { mNum = 2; } } @Override public void run() { for (int i = 0; i < MAX_ITERATIONS; i++) { mMySema.acquireUninterruptibly(); if (mType.equals(ODD)) { System.out.println("Odd Thread - " + mNum); } else { System.out.println("Even Thread - " + mNum); } mNum += 2; mOtherSema.release(); } } } public static void main(String[] args) throws InterruptedException { Semaphore odd = new Semaphore(1); Semaphore even = new Semaphore(0); System.out.println("Start!!!"); System.out.println(); Thread tOdd = new Thread(new EvenOddThread(ODD, odd, even)); Thread tEven = new Thread(new EvenOddThread(EVEN, even, odd)); tOdd.start(); tEven.start(); tOdd.join(); tEven.join(); System.out.println(); System.out.println("Done!!!"); } } Following is the output:- Start!!! Odd Thread - 1 Even Thread - 2 Odd Thread - 3 Even Thread - 4 Odd Thread - 5 Even Thread - 6 Odd Thread - 7 Even Thread - 8 Odd Thread - 9 Even Thread - 10 Odd Thread - 11 Even Thread - 12 Odd Thread - 13 Even Thread - 14 Odd Thread - 15 Even Thread - 16 Odd Thread - 17 Even Thread - 18 Odd Thread - 19 Even Thread - 20 Done!!! A: I think the solutions being provided have unnecessarily added stuff and does not use semaphores to its full potential. Here's what my solution is. package com.test.threads; import java.util.concurrent.Semaphore; public class EvenOddThreadTest { public static int MAX = 100; public static Integer number = new Integer(0); //Unlocked state public Semaphore semaphore = new Semaphore(1); class PrinterThread extends Thread { int start = 0; String name; PrinterThread(String name ,int start) { this.start = start; this.name = name; } @Override public void run() { try{ while(start < MAX){ // try to acquire the number of semaphore equal to your value // and if you do not get it then wait for it. semaphore.acquire(start); System.out.println(name + " : " + start); // prepare for the next iteration. start+=2; // release one less than what you need to print in the next iteration. // This will release the other thread which is waiting to print the next number. semaphore.release(start-1); } } catch(InterruptedException e){ } } } public static void main(String args[]) { EvenOddThreadTest test = new EvenOddThreadTest(); PrinterThread a = test.new PrinterThread("Even",1); PrinterThread b = test.new PrinterThread("Odd", 2); try { a.start(); b.start(); } catch (Exception e) { } } } A: package com.example; public class MyClass { static int mycount=0; static Thread t; static Thread t2; public static void main(String[] arg) { t2=new Thread(new Runnable() { @Override public void run() { System.out.print(mycount++ + " even \n"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } if(mycount>25) System.exit(0); run(); } }); t=new Thread(new Runnable() { @Override public void run() { System.out.print(mycount++ + " odd \n"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } if(mycount>26) System.exit(0); run(); } }); t.start(); t2.start(); } } A: Working solution using single class package com.fursa.threads; public class PrintNumbers extends Thread { Object lock; PrintNumbers(Object lock) { this.lock = lock; } public static void main(String ar[]) { Object obj = new Object(); // This constructor is required for the identification of wait/notify // communication PrintNumbers odd = new PrintNumbers(obj); PrintNumbers even = new PrintNumbers(obj); odd.setName("Odd"); even.setName("Even"); even.start(); odd.start(); } @Override public void run() { for(int i=0;i<=100;i++) { synchronized (lock) { if (Thread.currentThread().getName().equals("Even")) { if(i % 2 == 0 ){ System.out.println(Thread.currentThread().getName() + " - "+ i); try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } else if (i % 2 != 0 ) { lock.notify(); } } if (Thread.currentThread().getName().equals("Odd")) { if(i % 2 == 1 ){ System.out.println(Thread.currentThread().getName() + " - "+ i); try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } else if (i % 2 != 1 ) { lock.notify(); } } } } } } A: You can use the following code to get the output with creating two anonymous thread classes. package practice; class Display { boolean isEven = false; synchronized public void printEven(int number) throws InterruptedException { while (isEven) wait(); System.out.println("Even : " + number); isEven = true; notify(); } synchronized public void printOdd(int number) throws InterruptedException { while (!isEven) wait(); System.out.println("Odd : " + number); isEven = false; notify(); } } public class OddEven { public static void main(String[] args) { // TODO Auto-generated method stub final Display disp = new Display(); new Thread() { public void run() { int num = 0; for (int i = num; i <= 10; i += 2) { try { disp.printEven(i); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }.start(); new Thread() { public void run() { int num = 1; for (int i = num; i <= 10; i += 2) { try { disp.printOdd(i); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }.start(); } } A: This can be acheived using Lock and Condition : import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class EvenOddThreads { public static void main(String[] args) throws InterruptedException { Printer p = new Printer(); Thread oddThread = new Thread(new PrintThread(p,false),"Odd :"); Thread evenThread = new Thread(new PrintThread(p,true),"Even :"); oddThread.start(); evenThread.start(); } } class PrintThread implements Runnable{ Printer p; boolean isEven = false; PrintThread(Printer p, boolean isEven){ this.p = p; this.isEven = isEven; } @Override public void run() { int i = (isEven==true) ? 2 : 1; while(i < 10 ){ if(isEven){ p.printEven(i); }else{ p.printOdd(i); } i=i+2; } } } class Printer{ boolean isEven = true; Lock lock = new ReentrantLock(); Condition condEven = lock.newCondition(); Condition condOdd = lock.newCondition(); public void printEven(int no){ lock.lock(); while(isEven==true){ try { condEven.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() +no); isEven = true; condOdd.signalAll(); lock.unlock(); } public void printOdd(int no){ lock.lock(); while(isEven==false){ try { condOdd.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() +no); isEven = false; condEven.signalAll(); lock.unlock(); } } A: Class to print odd Even number public class PrintOddEven implements Runnable { private int max; private int number; public PrintOddEven(int max_number,int number) { max = max_number; this.number = number; } @Override public void run() { while(number<=max) { if(Thread.currentThread().getName().equalsIgnoreCase("odd")) { try { printOdd(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { printEven(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public synchronized void printOdd() throws InterruptedException { if(number%2==0) { wait(); } System.out.println(number+Thread.currentThread().getName()); number++; notifyAll(); } public synchronized void printEven() throws InterruptedException { if(number%2!=0) { wait(); } System.out.println(number+Thread.currentThread().getName()); number++; notifyAll(); } } Driver Program public class OddEvenThread { public static void main(String[] args) { PrintOddEven printer = new PrintOddEven(10,1); Thread thread1 = new Thread(printer,"odd"); Thread thread2 = new Thread (printer,"even"); thread1.start(); thread2.start(); } } A: public class ThreadEvenOdd { static int cnt=0; public static void main(String[] args) { Thread t1 = new Thread(new Runnable() { @Override public void run() { synchronized(this) { while(cnt<101) { if(cnt%2==0) { System.out.print(cnt+" "); cnt++; } notifyAll(); } } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { synchronized(this) { while(cnt<101) { if(cnt%2==1) { System.out.print(cnt+" "); cnt++; } notifyAll(); } } } }); t1.start(); t2.start(); } } A: public class OddAndEvenThreadProblems { private static Integer i = 0; public static void main(String[] args) { new EvenClass().start(); new OddClass().start(); } public static class EvenClass extends Thread { public void run() { while (i < 10) { synchronized (i) { if (i % 2 == 0 ) { try { Thread.sleep(1000); System.out.println(" EvenClass " + i); i = i + 1; } catch (Exception e) { e.printStackTrace(); } } } } } } public static class OddClass extends Thread { @Override public void run() { while (i < 10) { synchronized (i) { if (i % 2 == 1) { try { Thread.sleep(1000); System.out.println(" OddClass " + i); i = i + 1; } catch (Exception e) { e.printStackTrace(); } } } } } } } OUTPUT will be :- EvenClass 0 OddClass 1 EvenClass 2 OddClass 3 EvenClass 4 OddClass 5 EvenClass 6 OddClass 7 EvenClass 8 OddClass 9 A: package example; public class PrintSeqTwoThreads { public static void main(String[] args) { final Object mutex = new Object(); Thread t1 = new Thread() { @Override public void run() { for (int j = 0; j < 10;) { synchronized (mutex) { System.out.println(Thread.currentThread().getName() + " " + j); j = j + 2; mutex.notify(); try { mutex.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }; Thread t2 = new Thread() { @Override public void run() { for (int j = 1; j < 10;) { synchronized (mutex) { System.out.println(Thread.currentThread().getName() + " " + j); j = j + 2; mutex.notify(); try { mutex.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }; t1.start(); t2.start(); } } A: Please use the following code to print odd and even number in a proper order along with desired messages. package practice; class Test { private static boolean oddFlag = true; int count = 1; private void oddPrinter() { synchronized (this) { while(true) { try { if(count < 10) { if(oddFlag) { Thread.sleep(500); System.out.println(Thread.currentThread().getName() + ": " + count++); oddFlag = !oddFlag; notifyAll(); } else { wait(); } } else { System.out.println("Odd Thread finished"); notify(); break; } } catch (InterruptedException e) { e.printStackTrace(); } } } } private void evenPrinter() { synchronized (this) { while (true) { try { if(count < 10) { if(!oddFlag) { Thread.sleep(500); System.out.println(Thread.currentThread().getName() + ": " + count++); oddFlag = !oddFlag; notify(); } else { wait(); } } else { System.out.println("Even Thread finished"); notify(); break; } } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) throws InterruptedException{ final Test test = new Test(); Thread t1 = new Thread(new Runnable() { public void run() { test.oddPrinter(); } }, "Thread 1"); Thread t2 = new Thread(new Runnable() { public void run() { test.evenPrinter(); } }, "Thread 2"); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Main thread finished"); } } A: I could not understand most of the codes that were here so I wrote myself one, maybe it helps someone like me: NOTE: This does not use separate print even and odd method. One method print() does it all. public class test { private static int START_INT = 1; private static int STOP_INT = 10; private static String THREAD_1 = "Thread A"; private static String THREAD_2 = "Thread B"; public static void main(String[] args) { SynchronizedRepository syncRep = new SynchronizedRepository(START_INT,STOP_INT); Runnable r1 = new EvenOddWorker(THREAD_1,syncRep); Runnable r2 = new EvenOddWorker(THREAD_2,syncRep); Thread t1 = new Thread(r1, THREAD_1); Thread t2 = new Thread(r2, THREAD_2); t1.start(); t2.start(); } } public class SynchronizedRepository { private volatile int number; private volatile boolean isSlotEven; private int startNumber; private int stopNumber; public SynchronizedRepository(int startNumber, int stopNumber) { super(); this.number = startNumber; this.isSlotEven = startNumber%2==0; this.startNumber = startNumber; this.stopNumber = stopNumber; } public synchronized void print(String threadName) { try { for(int i=startNumber; i<=stopNumber/2; i++){ if ((isSlotEven && number % 2 == 0)|| (!isSlotEven && number % 2 != 0)){ System.out.println(threadName + " "+ number); isSlotEven = !isSlotEven; number++; } notifyAll(); wait(); } notifyAll(); } catch (InterruptedException e) { e.printStackTrace(); } } } public class EvenOddWorker implements Runnable { private String threadName; private SynchronizedRepository syncRep; public EvenOddWorker(String threadName, SynchronizedRepository syncRep) { super(); this.threadName = threadName; this.syncRep = syncRep; } @Override public void run() { syncRep.print(threadName); } } A: Simple solution :) package com.code.threads; public class PrintOddEven extends Thread { private Object lock; static volatile int count = 1; PrintOddEven(Object lock) { this.lock = lock; } @Override public void run () { while(count <= 10) { if (count % 2 == 0) { synchronized(lock){ System.out.println("Even - " + count); ++count; try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } else { synchronized(lock){ System.out.println("Odd - " + count); ++count; lock.notify(); } } } } public static void main(String[] args) { Object obj = new Object(); PrintOddEven even = new PrintOddEven(obj); PrintOddEven odd = new PrintOddEven(obj); even.start(); odd.start(); } } A: public class Main { public static void main(String[] args) throws Exception{ int N = 100; PrintingThread oddNumberThread = new PrintingThread(N - 1); PrintingThread evenNumberThread = new PrintingThread(N); oddNumberThread.start(); // make sure that even thread only start after odd thread while (!evenNumberThread.isAlive()) { if(oddNumberThread.isAlive()) { evenNumberThread.start(); } else { Thread.sleep(100); } } } } class PrintingThread extends Thread { private static final Object object = new Object(); // lock for both threads final int N; // N determines whether given thread is even or odd PrintingThread(int N) { this.N = N; } @Override public void run() { synchronized (object) { int start = N % 2 == 0 ? 2 : 1; // if N is odd start from 1 else start from 0 for (int i = start; i <= N; i = i + 2) { System.out.println(i); try { object.notify(); // will notify waiting thread object.wait(); // will make current thread wait } catch (InterruptedException e) { e.printStackTrace(); } } } } } A: class PrintNumberTask implements Runnable { Integer count; Object lock; PrintNumberTask(int i, Object object) { this.count = i; this.lock = object; } @Override public void run() { while (count <= 10) { synchronized (lock) { if (count % 2 == 0) { System.out.println(count); count++; lock.notify(); try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } else { System.out.println(count); count++; lock.notify(); try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } A: This solution works for me (Java 8 and above used Lamda expression) public class EvenOddUsingThread { static int number = 100; static int counter = 1; public static void main(String[] args) { EvenOddUsingThread eod = new EvenOddUsingThread(); Thread t1 = new Thread(() -> eod.printOdd()); Thread t2 = new Thread(() -> eod.printEven()); t1.start(); t2.start(); } public void printOdd() { synchronized (this) { while (counter < number) { if (counter % 2 == 0) { try { wait(); } catch (InterruptedException e) { } } // Print the number System.out.println(counter + " Thread Name: " + Thread.currentThread().getName()); // Increment counter counter++; // Notify to second thread notify(); } } } public void printEven() { synchronized (this) { while (counter < number) { if (counter % 2 == 1) { try { wait(); } catch (InterruptedException ignored) { } } // Print the number System.out.println(counter + " Thread Name: " + Thread.currentThread().getName()); // Increment counter counter++; // Notify to second thread notify(); } } } } A: The solution below is using java 8 completable future and executor service to print even and odd numbers using two threads. ExecutorService firstExecutorService = Executors.newSingleThreadExecutor(r -> { Thread t = new Thread(r); t.setName("first"); return t; }); ExecutorService secondExecutorService = Executors.newSingleThreadExecutor(r -> { Thread t = new Thread(r); t.setName("second"); return t; }); IntStream.range(1, 101).forEach(num -> { CompletableFuture<Integer> thenApplyAsync = CompletableFuture.completedFuture(num).thenApplyAsync(x -> { if (x % 2 == 1) { System.out.println(x + " " + Thread.currentThread().getName()); } return num; }, firstExecutorService); thenApplyAsync.join(); CompletableFuture<Integer> thenApplyAsync2 = CompletableFuture.completedFuture(num).thenApplyAsync(x -> { if (x % 2 == 0) { System.out.println(x + " " + Thread.currentThread().getName()); } return num; }, secondExecutorService); thenApplyAsync2.join(); }); firstExecutorService.shutdown(); secondExecutorService.shutdown(); The below is the console log of it. A: We can print odd and even using two separate threads using CompletableFuture as well: import java.util.concurrent.CompletableFuture; import java.util.function.IntPredicate; import java.util.stream.IntStream; public class OddEvenBy2Thread { private static Object object = new Object(); private static IntPredicate evenCondition = e -> e % 2 == 0; private static IntPredicate oddCondition = e -> e % 2 != 0; public static void main(String[] args) throws InterruptedException { // Odd number printer CompletableFuture.runAsync(() -> OddEvenBy2Thread.printNumber(oddCondition)); // Even number printer CompletableFuture.runAsync(() -> OddEvenBy2Thread.printNumber(evenCondition)); Thread.sleep(1000); } public static void printNumber(IntPredicate condition){ IntStream.rangeClosed(1, 10).filter(condition).forEach(OddEvenBy2Thread::execute); } public static void execute(int num){ synchronized (object){ try{ System.out.println(Thread.currentThread().getName()+" : "+num); object.notify(); object.wait(); }catch (InterruptedException e){ e.printStackTrace(); } } } }
Printing Even and Odd using two Threads in Java
I tried the code below. I took this piece of code from some other post which is correct as per the author. But when I try running, it doesn't give me the exact result. This is mainly to print even and odd values in sequence. public class PrintEvenOddTester { public static void main(String ... args){ Printer print = new Printer(false); Thread t1 = new Thread(new TaskEvenOdd(print)); Thread t2 = new Thread(new TaskEvenOdd(print)); t1.start(); t2.start(); } } class TaskEvenOdd implements Runnable { int number=1; Printer print; TaskEvenOdd(Printer print){ this.print = print; } @Override public void run() { System.out.println("Run method"); while(number<10){ if(number%2 == 0){ System.out.println("Number is :"+ number); print.printEven(number); number+=2; } else { System.out.println("Number is :"+ number); print.printOdd(number); number+=2; } } } } class Printer { boolean isOdd; Printer(boolean isOdd){ this.isOdd = isOdd; } synchronized void printEven(int number) { while(isOdd){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Even:"+number); isOdd = true; notifyAll(); } synchronized void printOdd(int number) { while(!isOdd){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Odd:"+number); isOdd = false; notifyAll(); } } Can someone help me in fixing this? EDIT Expected result: Odd:1 Even:2 Odd:3 Even:4 Odd:5 Even:6 Odd:7 Even:8 Odd:9
[ "Found the solution. Someone looking for solution to this problem can refer :-)\npublic class PrintEvenOddTester {\n\n public static void main(String... args) {\n Printer print = new Printer();\n Thread t1 = new Thread(new TaskEvenOdd(print, 10, false));\n Thread t2 = new Thread(new TaskEvenOdd(print, 10, true));\n t1.start();\n t2.start();\n }\n\n}\n\nclass TaskEvenOdd implements Runnable {\n\n private int max;\n private Printer print;\n private boolean isEvenNumber;\n\n TaskEvenOdd(Printer print, int max, boolean isEvenNumber) {\n this.print = print;\n this.max = max;\n this.isEvenNumber = isEvenNumber;\n }\n\n @Override\n public void run() {\n\n //System.out.println(\"Run method\");\n int number = isEvenNumber == true ? 2 : 1;\n while (number <= max) {\n\n if (isEvenNumber) {\n //System.out.println(\"Even :\"+ Thread.currentThread().getName());\n print.printEven(number);\n //number+=2;\n } else {\n //System.out.println(\"Odd :\"+ Thread.currentThread().getName());\n print.printOdd(number);\n // number+=2;\n }\n number += 2;\n }\n\n }\n\n}\n\nclass Printer {\n\n boolean isOdd = false;\n\n synchronized void printEven(int number) {\n\n while (isOdd == false) {\n try {\n wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n System.out.println(\"Even:\" + number);\n isOdd = false;\n notifyAll();\n }\n\n synchronized void printOdd(int number) {\n while (isOdd == true) {\n try {\n wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n System.out.println(\"Odd:\" + number);\n isOdd = true;\n notifyAll();\n }\n\n}\n\nThis gives output like:\nOdd:1\nEven:2\nOdd:3\nEven:4\nOdd:5\nEven:6\nOdd:7\nEven:8\nOdd:9\nEven:10\n\n", "Use this following very simple JAVA 8 Runnable Class feature\npublic class MultiThreadExample {\n\nstatic AtomicInteger atomicNumber = new AtomicInteger(1);\n\npublic static void main(String[] args) {\n Runnable print = () -> {\n while (atomicNumber.get() < 10) {\n synchronized (atomicNumber) {\n if ((atomicNumber.get() % 2 == 0) && \"Even\".equals(Thread.currentThread().getName())) {\n System.out.println(\"Even\" + \":\" + atomicNumber.getAndIncrement());\n } //else if ((atomicNumber.get() % 2 != 0) && \"Odd\".equals(Thread.currentThread().getName()))\n else {System.out.println(\"Odd\" + \":\" + atomicNumber.getAndIncrement());\n }\n }\n }\n };\n\n Thread t1 = new Thread(print);\n t1.setName(\"Even\");\n t1.start();\n Thread t2 = new Thread(print);\n t2.setName(\"Odd\");\n t2.start();\n\n}\n}\n\n", "Here is the code which I made it work through a single class\npackage com.learn.thread;\n\npublic class PrintNumbers extends Thread {\nvolatile static int i = 1;\nObject lock;\n\nPrintNumbers(Object lock) {\n this.lock = lock;\n}\n\npublic static void main(String ar[]) {\n Object obj = new Object();\n // This constructor is required for the identification of wait/notify\n // communication\n PrintNumbers odd = new PrintNumbers(obj);\n PrintNumbers even = new PrintNumbers(obj);\n odd.setName(\"Odd\");\n even.setName(\"Even\");\n odd.start();\n even.start();\n}\n\n@Override\npublic void run() {\n while (i <= 10) {\n if (i % 2 == 0 && Thread.currentThread().getName().equals(\"Even\")) {\n synchronized (lock) {\n System.out.println(Thread.currentThread().getName() + \" - \"\n + i);\n i++;\n try {\n lock.wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n if (i % 2 == 1 && Thread.currentThread().getName().equals(\"Odd\")) {\n synchronized (lock) {\n System.out.println(Thread.currentThread().getName() + \" - \"\n + i);\n i++;\n lock.notify();\n }\n }\n }\n }\n}\n\nOutput:\nOdd - 1\nEven - 2\nOdd - 3\nEven - 4\nOdd - 5\nEven - 6\nOdd - 7\nEven - 8\nOdd - 9\nEven - 10\nOdd - 11\n\n", " private Object lock = new Object();\n private volatile boolean isOdd = false;\n\n\n public void generateEvenNumbers(int number) throws InterruptedException {\n\n synchronized (lock) {\n while (isOdd == false) \n {\n lock.wait();\n }\n System.out.println(number);\n isOdd = false;\n lock.notifyAll();\n }\n }\n\n public void generateOddNumbers(int number) throws InterruptedException {\n\n synchronized (lock) {\n while (isOdd == true) {\n lock.wait();\n }\n System.out.println(number);\n isOdd = true;\n lock.notifyAll();\n }\n }\n\n", "This is easiest solution for this problem. \npublic class OddEven implements Runnable {\n @Override\n public void run() {\n // TODO Auto-generated method stub\n\n for (int i = 1; i <= 10; i++) {\n synchronized (this) {\n if (i % 2 == 0 && Thread.currentThread().getName().equals(\"t2\")) {\n try {\n notifyAll();\n System.out.println(\"Even Thread : \" + i);\n wait();\n } catch (InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n } else if (i % 2 != 0\n && Thread.currentThread().getName().equals(\"t1\")) {\n try {\n notifyAll();\n System.out.println(\"Odd Thread : \" + i);\n wait();\n } catch (InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n }\n }\n\n }\n\n public static void main(String[] args) {\n\n OddEven obj = new OddEven();\n Thread t1 = new Thread(obj, \"t1\");\n Thread t2 = new Thread(obj, \"t2\");\n t1.start();\n t2.start();\n\n }\n}\n\n", "Simplest Solution!! \npublic class OddEvenWithThread {\n public static void main(String a[]) {\n Thread t1 = new Thread(new OddEvenRunnable(0), \"Even Thread\");\n Thread t2 = new Thread(new OddEvenRunnable(1), \"Odd Thread\");\n\n t1.start();\n t2.start();\n }\n}\n\nclass OddEvenRunnable implements Runnable {\n Integer evenflag;\n static Integer number = 1;\n static Object lock = new Object();\n\n OddEvenRunnable(Integer evenFlag) {\n this.evenflag = evenFlag;\n }\n\n @Override\n public void run() {\n while (number < 10) {\n synchronized (lock) {\n try {\n while (number % 2 != evenflag) {\n lock.wait();\n }\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n\n System.out.println(Thread.currentThread().getName() + \" \" + number);\n number++;\n lock.notifyAll();\n }\n }\n }\n}\n\n", "The same can be done with Lock interface:\nimport java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\n\npublic class NumberPrinter implements Runnable {\n private Lock lock;\n private Condition condition;\n private String type;\n private static boolean oddTurn = true;\n\n public NumberPrinter(String type, Lock lock, Condition condition) {\n this.type = type;\n this.lock = lock;\n this.condition = condition;\n }\n\n public void run() {\n int i = type.equals(\"odd\") ? 1 : 2;\n while (i <= 10) {\n if (type.equals(\"odd\"))\n printOdd(i);\n if (type.equals(\"even\"))\n printEven(i);\n i = i + 2;\n }\n }\n\n private void printOdd(int i) {\n // synchronized (lock) {\n lock.lock();\n while (!oddTurn) {\n try {\n // lock.wait();\n condition.await();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n System.out.println(type + \" \" + i);\n oddTurn = false;\n // lock.notifyAll();\n condition.signalAll();\n lock.unlock();\n }\n\n // }\n\n private void printEven(int i) {\n // synchronized (lock) {\n lock.lock();\n while (oddTurn) {\n try {\n // lock.wait();\n condition.await();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n System.out.println(type + \" \" + i);\n oddTurn = true;\n // lock.notifyAll();\n condition.signalAll();\n lock.unlock();\n }\n\n // }\n\n public static void main(String[] args) {\n Lock lock = new ReentrantLock();\n Condition condition = lock.newCondition();\n Thread odd = new Thread(new NumberPrinter(\"odd\", lock, condition));\n Thread even = new Thread(new NumberPrinter(\"even\", lock, condition));\n odd.start();\n even.start();\n }\n}\n\n", "This code will also work fine.\nclass Thread1 implements Runnable {\n\n private static boolean evenFlag = true;\n\n public synchronized void run() {\n if (evenFlag == true) {\n printEven();\n } else {\n printOdd();\n }\n }\n\n public void printEven() {\n for (int i = 0; i <= 10; i += 2) {\n System.out.println(i+\"\"+Thread.currentThread());\n }\n evenFlag = false;\n }\n\n public void printOdd() {\n for (int i = 1; i <= 11; i += 2) {\n System.out.println(i+\"\"+Thread.currentThread());\n }\n evenFlag = true;\n }\n}\n\npublic class OddEvenDemo {\n\n public static void main(String[] args) {\n\n Thread1 t1 = new Thread1();\n Thread td1 = new Thread(t1);\n Thread td2 = new Thread(t1);\n td1.start();\n td2.start();\n\n }\n}\n\n", "import java.util.concurrent.atomic.AtomicInteger;\n\n\npublic class PrintEvenOddTester {\n public static void main(String ... args){\n Printer print = new Printer(false);\n Thread t1 = new Thread(new TaskEvenOdd(print, \"Thread1\", new AtomicInteger(1)));\n Thread t2 = new Thread(new TaskEvenOdd(print,\"Thread2\" , new AtomicInteger(2)));\n t1.start();\n t2.start();\n }\n}\n\nclass TaskEvenOdd implements Runnable {\n Printer print;\n String name;\n AtomicInteger number;\n TaskEvenOdd(Printer print, String name, AtomicInteger number){\n this.print = print;\n this.name = name;\n this.number = number;\n }\n\n @Override\n public void run() {\n\n System.out.println(\"Run method\");\n while(number.get()<10){\n\n if(number.get()%2 == 0){\n print.printEven(number.get(),name);\n }\n else {\n print.printOdd(number.get(),name);\n }\n number.addAndGet(2);\n }\n\n }\n\n }\n\n\n\nclass Printer {\n boolean isEven;\n\n public Printer() { }\n\n public Printer(boolean isEven) {\n this.isEven = isEven;\n }\n\n synchronized void printEven(int number, String name) {\n\n while (!isEven) {\n try {\n wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n System.out.println(name+\": Even:\" + number);\n isEven = false;\n notifyAll();\n }\n\n synchronized void printOdd(int number, String name) {\n while (isEven) {\n try {\n wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n System.out.println(name+\": Odd:\" + number);\n isEven = true;\n notifyAll();\n }\n}\n\n", "The other question was closed as a duplicate of this one. I think we can safely get rid of \"even or odd\" problem and use the wait/notify construct as follows:\npublic class WaitNotifyDemoEvenOddThreads {\n /**\n * A transfer object, only use with proper client side locking!\n */\n static final class LastNumber {\n int num;\n final int limit;\n\n LastNumber(int num, int limit) {\n this.num = num;\n this.limit = limit;\n }\n }\n\n static final class NumberPrinter implements Runnable {\n private final LastNumber last;\n private final int init;\n\n NumberPrinter(LastNumber last, int init) {\n this.last = last;\n this.init = init;\n }\n\n @Override\n public void run() {\n int i = init;\n synchronized (last) {\n while (i <= last.limit) {\n while (last.num != i) {\n try {\n last.wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n System.out.println(Thread.currentThread().getName() + \" prints: \" + i);\n last.num = i + 1;\n i += 2;\n last.notify();\n }\n }\n }\n }\n\n public static void main(String[] args) {\n LastNumber last = new LastNumber(0, 10); // or 0, 1000\n NumberPrinter odd = new NumberPrinter(last, 1);\n NumberPrinter even = new NumberPrinter(last, 0);\n new Thread(odd, \"o\").start();\n new Thread(even, \"e\").start();\n }\n}\n\n", "Simpler Version in Java 8:\n\npublic class EvenOddPrinter {\n static boolean flag = true;\n public static void main(String[] args) {\n Runnable odd = () -> {\n for (int i = 1; i <= 10;) {\n if(EvenOddPrinter.flag) {\n System.out.println(i);\n i+=2;\n EvenOddPrinter.flag = !EvenOddPrinter.flag;\n }\n }\n };\n\n Runnable even = () -> {\n for (int i = 2; i <= 10;) {\n if(!EvenOddPrinter.flag) {\n System.out.println(i);\n i+=2;\n EvenOddPrinter.flag = !EvenOddPrinter.flag;\n }\n }\n };\n\n Thread t1 = new Thread(odd, \"Odd\");\n Thread t2 = new Thread(even, \"Even\");\n t1.start();\n t2.start();\n }\n}\n\n", "package pkgscjp;\n\npublic class OddPrint implements Runnable {\n\n public static boolean flag = true;\n\n public void run() {\n for (int i = 1; i <= 99;) {\n if (flag) {\n System.out.println(i);\n flag = false;\n i = i + 2;\n }\n }\n }\n\n}\n\n\npackage pkgscjp;\n\npublic class EvenPrint implements Runnable {\n public void run() {\n for (int i = 2; i <= 100;) {\n if (!OddPrint.flag) {\n System.out.println(i);\n OddPrint.flag = true;\n i = i + 2;\n }\n }\n\n }\n}\n\n\npackage pkgscjp;\n\npublic class NaturalNumberThreadMain {\n public static void main(String args[]) {\n EvenPrint ep = new EvenPrint();\n OddPrint op = new OddPrint();\n Thread te = new Thread(ep);\n Thread to = new Thread(op);\n to.start();\n te.start();\n\n }\n\n}\n\n", "I have done it this way, while printing using two threads we cannot predict the sequence which thread\n would get executed first so to overcome this situation we have to synchronize the shared resource,in\n my case the print function which two threads are trying to access.\nclass Printoddeven{\n\n public synchronized void print(String msg) {\n try {\n if(msg.equals(\"Even\")) {\n for(int i=0;i<=10;i+=2) {\n System.out.println(msg+\" \"+i);\n Thread.sleep(2000);\n notify();\n wait();\n }\n } else {\n for(int i=1;i<=10;i+=2) {\n System.out.println(msg+\" \"+i);\n Thread.sleep(2000);\n notify();\n wait();\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n}\n\nclass PrintOdd extends Thread{\n Printoddeven oddeven;\n public PrintOdd(Printoddeven oddeven){\n this.oddeven=oddeven;\n }\n\n public void run(){\n oddeven.print(\"ODD\");\n }\n}\n\nclass PrintEven extends Thread{\n Printoddeven oddeven;\n public PrintEven(Printoddeven oddeven){\n this.oddeven=oddeven;\n }\n\n public void run(){\n oddeven.print(\"Even\");\n }\n}\n\n\n\npublic class mainclass \n{\n public static void main(String[] args) {\n Printoddeven obj = new Printoddeven();//only one object \n PrintEven t1=new PrintEven(obj); \n PrintOdd t2=new PrintOdd(obj); \n t1.start(); \n t2.start(); \n }\n}\n\n", "This is my solution to the problem. I have two classes implementing Runnable, one prints odd sequence and the other prints even. I have an instance of Object, that I use for lock. I initialize the two classes with the same object. There is a synchronized block inside the run method of the two classes, where, inside a loop, each method prints one of the numbers, notifies the other thread, waiting for lock on the same object and then itself waits for the same lock again.\nThe classes : \npublic class PrintEven implements Runnable{\nprivate Object lock;\npublic PrintEven(Object lock) {\n this.lock = lock;\n}\n@Override\npublic void run() {\n synchronized (lock) {\n for (int i = 2; i <= 10; i+=2) {\n System.out.println(\"EVEN:=\"+i);\n lock.notify();\n try {\n //if(i!=10) lock.wait();\n lock.wait(500);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n\n }\n}\n\n\npublic class PrintOdd implements Runnable {\nprivate Object lock;\npublic PrintOdd(Object lock) {\n this.lock = lock;\n}\n@Override\npublic void run() {\n synchronized (lock) {\n for (int i = 1; i <= 10; i+=2) {\n System.out.println(\"ODD:=\"+i);\n lock.notify();\n try {\n //if(i!=9) lock.wait();\n lock.wait(500);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n}\n}\n\npublic class PrintEvenOdd {\npublic static void main(String[] args){\n Object lock = new Object(); \n Thread thread1 = new Thread(new PrintOdd(lock));\n Thread thread2 = new Thread(new PrintEven(lock));\n thread1.start();\n thread2.start();\n}\n}\n\nThe upper limit in my example is 10. Once the odd thread prints 9 or the even thread prints 10, then we don't need any of the threads to wait any more. So, we can handle that using one if-block. Or, we can use the overloaded wait(long timeout) method for the wait to be timed out.\nOne flaw here though. With this code, we cannot guarantee which thread will start execution first.\nAnother example, using Lock and Condition\nimport java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\n\npublic class LockConditionOddEven {\n public static void main(String[] args) {\n Lock lock = new ReentrantLock();\n Condition evenCondition = lock.newCondition();\n Condition oddCondition = lock.newCondition();\n Thread evenThread = new Thread(new EvenPrinter(10, lock, evenCondition, oddCondition));\n Thread oddThread = new Thread(new OddPrinter(10, lock, evenCondition, oddCondition));\n oddThread.start();\n evenThread.start();\n}\n\nstatic class OddPrinter implements Runnable{\n int i = 1;\n int limit;\n Lock lock;\n Condition evenCondition;\n Condition oddCondition;\n\n public OddPrinter(int limit) {\n super();\n this.limit = limit;\n }\n\n public OddPrinter(int limit, Lock lock, Condition evenCondition, Condition oddCondition) {\n super();\n this.limit = limit;\n this.lock = lock;\n this.evenCondition = evenCondition;\n this.oddCondition = oddCondition;\n }\n\n @Override\n public void run() {\n while( i <=limit) {\n lock.lock();\n System.out.println(\"Odd:\"+i);\n evenCondition.signal();\n i+=2;\n try {\n oddCondition.await();\n } catch (InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }finally {\n lock.unlock();\n }\n }\n }\n}\n\nstatic class EvenPrinter implements Runnable{\n int i = 2;\n int limit;\n Lock lock;\n Condition evenCondition;\n Condition oddCondition;\n\n public EvenPrinter(int limit) {\n super();\n this.limit = limit;\n }\n\n\n public EvenPrinter(int limit, Lock lock, Condition evenCondition, Condition oddCondition) {\n super();\n this.limit = limit;\n this.lock = lock;\n this.evenCondition = evenCondition;\n this.oddCondition = oddCondition;\n }\n\n\n @Override\n public void run() {\n while( i <=limit) {\n lock.lock();\n System.out.println(\"Even:\"+i);\n i+=2;\n oddCondition.signal();\n try {\n evenCondition.await();\n } catch (InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }finally {\n lock.unlock();\n }\n }\n }\n}\n\n}\n", "Here is the working code to print odd even no alternatively using wait and notify mechanism. I have restrict the limit of numbers to print 1 to 50.\npublic class NotifyTest {\n Object ob=new Object(); \n\n public static void main(String[] args) {\n // TODO Auto-generated method stub\n NotifyTest nt=new NotifyTest();\n\n even e=new even(nt.ob); \n odd o=new odd(nt.ob);\n\n Thread t1=new Thread(e);\n Thread t2=new Thread(o);\n\n t1.start(); \n t2.start();\n }\n} \n\nclass even implements Runnable\n{\n Object lock; \n int i=2;\n\n public even(Object ob)\n {\n this.lock=ob; \n }\n\n @Override\n public void run() {\n // TODO Auto-generated method stub \n while(i<=50)\n {\n synchronized (lock) { \n try {\n lock.wait();\n } catch (InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n\n System.out.println(\"Even Thread Name-->>\" + Thread.currentThread().getName() + \"Value-->>\" + i);\n i=i+2; \n } \n } \n} \n\nclass odd implements Runnable\n{\n\n Object lock;\n int i=1; \n\n public odd(Object ob)\n {\n this.lock=ob;\n }\n\n @Override\n public void run() {\n // TODO Auto-generated method stub\n while(i<=49)\n {\n synchronized (lock) { \n System.out.println(\"Odd Thread Name-->>\" + Thread.currentThread().getName() + \"Value-->>\" + i);\n i=i+2; \n lock.notify();\n }\n try {\n Thread.sleep(1000);\n } catch (Exception e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n } \n}\n\n", "Following is my implementation using 2 Semaphores. \n\nOdd Semaphore with permit 1.\nEven Semaphore with permit 0.\nPass the two Semaphores to both threads as following signature (my, other):-\nTo Odd thread pass in the order (odd, even)\nTo Even thread pass in this order (even, odd)\nrun() method logic is my.acquireUninterruptibly() -> Print -> other.release()\nIn Even thread as even Sema is 0 it will block. \nIn Odd thread as odd Sema is available (init to 1) this will print 1 and then release even Sema allowing Even thread to run.\nEven thread runs prints 2 and release odd Sema allowing Odd thread to run.\nimport java.util.concurrent.Semaphore;\n\n\npublic class EvenOdd {\nprivate final static String ODD = \"ODD\";\nprivate final static String EVEN = \"EVEN\";\nprivate final static int MAX_ITERATIONS = 10;\n\npublic static class EvenOddThread implements Runnable { \n private String mType;\n private int mNum;\n private Semaphore mMySema;\n private Semaphore mOtherSema;\n\n public EvenOddThread(String str, Semaphore mine, Semaphore other) {\n mType = str;\n mMySema = mine;//new Semaphore(1); // start out as unlocked\n mOtherSema = other;//new Semaphore(0);\n if(str.equals(ODD)) {\n mNum = 1;\n }\n else {\n mNum = 2;\n }\n }\n\n @Override\n public void run() { \n\n for (int i = 0; i < MAX_ITERATIONS; i++) {\n mMySema.acquireUninterruptibly();\n if (mType.equals(ODD)) {\n System.out.println(\"Odd Thread - \" + mNum);\n } else {\n System.out.println(\"Even Thread - \" + mNum);\n }\n mNum += 2;\n mOtherSema.release();\n } \n }\n\n}\n\n public static void main(String[] args) throws InterruptedException {\n Semaphore odd = new Semaphore(1);\n Semaphore even = new Semaphore(0);\n\n System.out.println(\"Start!!!\");\n System.out.println();\n\n Thread tOdd = new Thread(new EvenOddThread(ODD, \n odd, \n even));\n Thread tEven = new Thread(new EvenOddThread(EVEN, \n even, \n odd));\n\n tOdd.start();\n tEven.start();\n\n tOdd.join();\n tEven.join();\n\n System.out.println();\n System.out.println(\"Done!!!\");\n } \n\n}\n\n\nFollowing is the output:-\nStart!!!\n\nOdd Thread - 1\nEven Thread - 2\nOdd Thread - 3\nEven Thread - 4\nOdd Thread - 5\nEven Thread - 6\nOdd Thread - 7\nEven Thread - 8\nOdd Thread - 9\nEven Thread - 10\nOdd Thread - 11\nEven Thread - 12\nOdd Thread - 13\nEven Thread - 14\nOdd Thread - 15\nEven Thread - 16\nOdd Thread - 17\nEven Thread - 18\nOdd Thread - 19\nEven Thread - 20\n\nDone!!!\n\n", "I think the solutions being provided have unnecessarily added stuff and does not use semaphores to its full potential. Here's what my solution is.\npackage com.test.threads;\n\nimport java.util.concurrent.Semaphore;\n\npublic class EvenOddThreadTest {\n\n public static int MAX = 100;\n public static Integer number = new Integer(0);\n\n //Unlocked state\n public Semaphore semaphore = new Semaphore(1);\n class PrinterThread extends Thread {\n\n int start = 0;\n String name;\n\n PrinterThread(String name ,int start) {\n this.start = start;\n this.name = name;\n }\n\n @Override\n public void run() {\n try{\n while(start < MAX){\n // try to acquire the number of semaphore equal to your value\n // and if you do not get it then wait for it.\n semaphore.acquire(start);\n System.out.println(name + \" : \" + start);\n // prepare for the next iteration.\n start+=2;\n // release one less than what you need to print in the next iteration.\n // This will release the other thread which is waiting to print the next number.\n semaphore.release(start-1);\n }\n } catch(InterruptedException e){\n\n }\n }\n }\n\n public static void main(String args[]) {\n EvenOddThreadTest test = new EvenOddThreadTest();\n PrinterThread a = test.new PrinterThread(\"Even\",1);\n PrinterThread b = test.new PrinterThread(\"Odd\", 2);\n try {\n a.start();\n b.start();\n } catch (Exception e) {\n\n }\n }\n}\n\n", "package com.example;\n\npublic class MyClass {\n static int mycount=0;\n static Thread t;\n static Thread t2;\n public static void main(String[] arg)\n {\n t2=new Thread(new Runnable() {\n @Override\n public void run() {\n System.out.print(mycount++ + \" even \\n\");\n try {\n Thread.sleep(500);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n if(mycount>25)\n System.exit(0);\n run();\n }\n });\n t=new Thread(new Runnable() {\n @Override\n public void run() {\n System.out.print(mycount++ + \" odd \\n\");\n try {\n Thread.sleep(500);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n if(mycount>26)\n System.exit(0);\n run();\n }\n });\n t.start();\n t2.start();\n }\n}\n\n", "Working solution using single class\npackage com.fursa.threads;\n\n public class PrintNumbers extends Thread {\n\n Object lock;\n\n PrintNumbers(Object lock) {\n this.lock = lock;\n }\n\n public static void main(String ar[]) {\n Object obj = new Object();\n // This constructor is required for the identification of wait/notify\n // communication\n PrintNumbers odd = new PrintNumbers(obj);\n PrintNumbers even = new PrintNumbers(obj);\n odd.setName(\"Odd\");\n even.setName(\"Even\");\n even.start();\n odd.start();\n\n }\n\n @Override\n public void run() {\n for(int i=0;i<=100;i++) {\n\n synchronized (lock) {\n\n if (Thread.currentThread().getName().equals(\"Even\")) {\n\n if(i % 2 == 0 ){\n System.out.println(Thread.currentThread().getName() + \" - \"+ i);\n try {\n lock.wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n } \n else if (i % 2 != 0 ) {\n lock.notify();\n }\n }\n\n if (Thread.currentThread().getName().equals(\"Odd\")) {\n\n if(i % 2 == 1 ){\n System.out.println(Thread.currentThread().getName() + \" - \"+ i);\n try {\n lock.wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n } \n else if (i % 2 != 1 ) {\n lock.notify();\n }\n }\n\n }\n }\n }\n}\n\n", "You can use the following code to get the output with creating two anonymous thread classes.\npackage practice;\n\nclass Display {\n boolean isEven = false;\n\n synchronized public void printEven(int number) throws InterruptedException {\n while (isEven)\n wait();\n System.out.println(\"Even : \" + number);\n isEven = true;\n notify();\n }\n\n synchronized public void printOdd(int number) throws InterruptedException {\n while (!isEven)\n wait();\n System.out.println(\"Odd : \" + number);\n isEven = false;\n notify();\n }\n}\n\npublic class OddEven {\n\n public static void main(String[] args) {\n // TODO Auto-generated method stub\n final Display disp = new Display();\n\n\n new Thread() {\n public void run() {\n int num = 0;\n for (int i = num; i <= 10; i += 2) {\n try {\n disp.printEven(i);\n } catch (InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n }\n }.start();\n\n new Thread() {\n public void run() {\n int num = 1;\n for (int i = num; i <= 10; i += 2) {\n try {\n disp.printOdd(i);\n } catch (InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n }\n }.start();\n }\n\n}\n\n", "This can be acheived using Lock and Condition :\nimport java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\n\npublic class EvenOddThreads {\n\n public static void main(String[] args) throws InterruptedException {\n Printer p = new Printer();\n Thread oddThread = new Thread(new PrintThread(p,false),\"Odd :\");\n Thread evenThread = new Thread(new PrintThread(p,true),\"Even :\");\n oddThread.start();\n evenThread.start();\n }\n\n}\n\nclass PrintThread implements Runnable{\n Printer p;\n boolean isEven = false;\n\n PrintThread(Printer p, boolean isEven){\n this.p = p;\n this.isEven = isEven;\n }\n\n @Override\n public void run() {\n int i = (isEven==true) ? 2 : 1;\n while(i < 10 ){\n if(isEven){\n p.printEven(i);\n }else{\n p.printOdd(i);\n }\n i=i+2;\n }\n }\n}\n\nclass Printer{\n\n boolean isEven = true;\n Lock lock = new ReentrantLock();\n Condition condEven = lock.newCondition();\n Condition condOdd = lock.newCondition();\n\n public void printEven(int no){\n lock.lock();\n while(isEven==true){\n try {\n condEven.await();\n } catch (InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n System.out.println(Thread.currentThread().getName() +no);\n isEven = true;\n condOdd.signalAll();\n lock.unlock();\n }\n\n public void printOdd(int no){\n lock.lock();\n while(isEven==false){\n try {\n condOdd.await();\n } catch (InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n System.out.println(Thread.currentThread().getName() +no);\n isEven = false;\n condEven.signalAll();\n lock.unlock();\n }\n}\n\n", "Class to print odd Even number\npublic class PrintOddEven implements Runnable {\n\n private int max;\n private int number;\n\n public PrintOddEven(int max_number,int number) {\n max = max_number;\n this.number = number;\n }\n\n @Override\n public void run() {\n\n\n while(number<=max)\n {\n if(Thread.currentThread().getName().equalsIgnoreCase(\"odd\"))\n {\n try {\n printOdd();\n } catch (InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n else\n {\n try {\n printEven();\n } catch (InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n\n }\n\n\n }\n\n public synchronized void printOdd() throws InterruptedException\n {\n\n if(number%2==0)\n {\n wait();\n }\n\n System.out.println(number+Thread.currentThread().getName());\n number++;\n notifyAll();\n }\n\n public synchronized void printEven() throws InterruptedException\n {\n\n if(number%2!=0)\n {\n wait();\n }\n\n System.out.println(number+Thread.currentThread().getName());\n number++;\n notifyAll();\n }\n\n}\n\nDriver Program\npublic class OddEvenThread {\n\n public static void main(String[] args) {\n\n PrintOddEven printer = new PrintOddEven(10,1); \n Thread thread1 = new Thread(printer,\"odd\");\n Thread thread2 = new Thread (printer,\"even\");\n\n thread1.start();\n thread2.start();\n\n }\n\n}\n\n", "public class ThreadEvenOdd {\n static int cnt=0;\n public static void main(String[] args) {\n\n Thread t1 = new Thread(new Runnable() {\n\n @Override\n public void run() {\n synchronized(this) {\n while(cnt<101) {\n if(cnt%2==0) {\n System.out.print(cnt+\" \");\n cnt++;\n }\n notifyAll();\n }\n }\n }\n\n });\n Thread t2 = new Thread(new Runnable() {\n\n @Override\n public void run() {\n synchronized(this) {\n while(cnt<101) {\n if(cnt%2==1) {\n System.out.print(cnt+\" \");\n cnt++;\n }\n notifyAll();\n }\n }\n }\n });\n\n t1.start();\n t2.start();\n }\n}\n\n", " public class OddAndEvenThreadProblems {\n private static Integer i = 0;\n\n public static void main(String[] args) {\n new EvenClass().start();\n new OddClass().start();\n\n }\n\n public static class EvenClass extends Thread {\n\n public void run() {\n while (i < 10) {\n synchronized (i) {\n if (i % 2 == 0 ) {\n try {\n Thread.sleep(1000);\n System.out.println(\" EvenClass \" + i);\n i = i + 1;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n }\n }\n }\n }\n }\n\n public static class OddClass extends Thread {\n\n @Override\n public void run() {\n while (i < 10) {\n synchronized (i) {\n if (i % 2 == 1) {\n try {\n Thread.sleep(1000);\n System.out.println(\" OddClass \" + i);\n i = i + 1;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n }\n }\n }\n }\n }\n }\n\n\n\n\n\nOUTPUT will be :- \n\n EvenClass 0\n OddClass 1\n EvenClass 2\n OddClass 3\n EvenClass 4\n OddClass 5\n EvenClass 6\n OddClass 7\n EvenClass 8\n OddClass 9\n\n", "package example;\n\npublic class PrintSeqTwoThreads {\n\n public static void main(String[] args) {\n final Object mutex = new Object();\n Thread t1 = new Thread() {\n @Override\n public void run() {\n for (int j = 0; j < 10;) {\n synchronized (mutex) {\n System.out.println(Thread.currentThread().getName() + \" \" + j);\n j = j + 2;\n mutex.notify();\n try {\n mutex.wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n }\n };\n Thread t2 = new Thread() {\n @Override\n public void run() {\n for (int j = 1; j < 10;) {\n synchronized (mutex) {\n System.out.println(Thread.currentThread().getName() + \" \" + j);\n j = j + 2;\n mutex.notify();\n try {\n mutex.wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n }\n };\n t1.start();\n t2.start();\n }\n}\n\n", "Please use the following code to print odd and even number in a proper order along with desired messages.\npackage practice;\n\n\nclass Test {\n\n private static boolean oddFlag = true;\n int count = 1;\n\n private void oddPrinter() {\n synchronized (this) {\n while(true) {\n try {\n if(count < 10) {\n if(oddFlag) {\n Thread.sleep(500);\n System.out.println(Thread.currentThread().getName() + \": \" + count++);\n oddFlag = !oddFlag;\n notifyAll();\n }\n else {\n wait();\n }\n }\n else {\n System.out.println(\"Odd Thread finished\");\n notify();\n break;\n }\n }\n catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n }\n\n private void evenPrinter() {\n synchronized (this) {\n while (true) {\n try {\n if(count < 10) {\n if(!oddFlag) {\n Thread.sleep(500);\n System.out.println(Thread.currentThread().getName() + \": \" + count++);\n oddFlag = !oddFlag;\n notify();\n }\n else {\n wait();\n }\n }\n else {\n System.out.println(\"Even Thread finished\");\n notify();\n break;\n }\n }\n catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n }\n\n\n public static void main(String[] args) throws InterruptedException{\n final Test test = new Test();\n\n Thread t1 = new Thread(new Runnable() {\n public void run() {\n test.oddPrinter();\n }\n }, \"Thread 1\");\n\n Thread t2 = new Thread(new Runnable() {\n public void run() {\n test.evenPrinter();\n }\n }, \"Thread 2\");\n\n t1.start();\n t2.start();\n\n t1.join();\n t2.join();\n\n System.out.println(\"Main thread finished\");\n }\n}\n\n", "I could not understand most of the codes that were here so I wrote myself one, maybe it helps someone like me:\nNOTE: This does not use separate print even and odd method. One method print() does it all.\npublic class test {\n\n private static int START_INT = 1;\n private static int STOP_INT = 10;\n private static String THREAD_1 = \"Thread A\";\n private static String THREAD_2 = \"Thread B\";\n\n public static void main(String[] args) {\n SynchronizedRepository syncRep = new SynchronizedRepository(START_INT,STOP_INT);\n Runnable r1 = new EvenOddWorker(THREAD_1,syncRep);\n Runnable r2 = new EvenOddWorker(THREAD_2,syncRep);\n Thread t1 = new Thread(r1, THREAD_1);\n Thread t2 = new Thread(r2, THREAD_2);\n t1.start();\n t2.start();\n }\n\n}\n\n\n\n\npublic class SynchronizedRepository {\n private volatile int number;\n private volatile boolean isSlotEven;\n private int startNumber;\n private int stopNumber;\n\n public SynchronizedRepository(int startNumber, int stopNumber) {\n super();\n this.number = startNumber;\n this.isSlotEven = startNumber%2==0;\n this.startNumber = startNumber;\n this.stopNumber = stopNumber;\n }\n\n\n public synchronized void print(String threadName) {\n try {\n for(int i=startNumber; i<=stopNumber/2; i++){\n if ((isSlotEven && number % 2 == 0)||\n (!isSlotEven && number % 2 != 0)){\n System.out.println(threadName + \" \"+ number);\n isSlotEven = !isSlotEven;\n number++;\n }\n notifyAll();\n wait();\n }\n notifyAll();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n\n }\n\n}\n\n\n\npublic class EvenOddWorker implements Runnable {\n\n private String threadName;\n private SynchronizedRepository syncRep;\n\n public EvenOddWorker(String threadName, SynchronizedRepository syncRep) {\n super();\n this.threadName = threadName;\n this.syncRep = syncRep;\n }\n\n @Override\n public void run() {\n syncRep.print(threadName);\n }\n\n}\n\n", "Simple solution :)\npackage com.code.threads;\n\npublic class PrintOddEven extends Thread {\n\n private Object lock;\n static volatile int count = 1;\n\n PrintOddEven(Object lock) {\n this.lock = lock;\n }\n\n @Override\n public void run () {\n while(count <= 10) {\n if (count % 2 == 0) {\n synchronized(lock){\n System.out.println(\"Even - \" + count);\n ++count;\n try {\n lock.wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n } else {\n synchronized(lock){\n System.out.println(\"Odd - \" + count);\n ++count;\n lock.notify();\n }\n }\n }\n }\n\n public static void main(String[] args) {\n Object obj = new Object();\n PrintOddEven even = new PrintOddEven(obj);\n PrintOddEven odd = new PrintOddEven(obj);\n\n even.start();\n odd.start();\n }\n}\n\n", "public class Main {\n public static void main(String[] args) throws Exception{\n int N = 100;\n PrintingThread oddNumberThread = new PrintingThread(N - 1);\n PrintingThread evenNumberThread = new PrintingThread(N);\n oddNumberThread.start();\n // make sure that even thread only start after odd thread\n while (!evenNumberThread.isAlive()) {\n if(oddNumberThread.isAlive()) {\n evenNumberThread.start();\n } else {\n Thread.sleep(100);\n }\n }\n\n }\n}\n\nclass PrintingThread extends Thread {\n private static final Object object = new Object(); // lock for both threads\n final int N;\n // N determines whether given thread is even or odd\n PrintingThread(int N) {\n this.N = N;\n }\n\n @Override\n public void run() {\n synchronized (object) {\n int start = N % 2 == 0 ? 2 : 1; // if N is odd start from 1 else start from 0\n for (int i = start; i <= N; i = i + 2) {\n System.out.println(i);\n try {\n object.notify(); // will notify waiting thread\n object.wait(); // will make current thread wait\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n }\n}\n\n", "class PrintNumberTask implements Runnable {\nInteger count;\nObject lock;\n\nPrintNumberTask(int i, Object object) {\n this.count = i;\n this.lock = object;\n}\n\n@Override\npublic void run() {\n while (count <= 10) {\n synchronized (lock) {\n if (count % 2 == 0) {\n System.out.println(count);\n count++;\n lock.notify();\n try {\n lock.wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n } else {\n System.out.println(count);\n count++;\n lock.notify();\n try {\n lock.wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n }\n}\n\n}\n", "This solution works for me (Java 8 and above used Lamda expression)\npublic class EvenOddUsingThread {\n\n static int number = 100;\n static int counter = 1;\n\n public static void main(String[] args) {\n EvenOddUsingThread eod = new EvenOddUsingThread();\n Thread t1 = new Thread(() -> eod.printOdd());\n Thread t2 = new Thread(() -> eod.printEven());\n t1.start();\n t2.start();\n }\n\n public void printOdd() {\n synchronized (this) {\n while (counter < number) {\n if (counter % 2 == 0) {\n try {\n wait();\n } catch (InterruptedException e) {\n }\n }\n // Print the number\n System.out.println(counter + \" Thread Name: \" + Thread.currentThread().getName());\n // Increment counter\n counter++;\n // Notify to second thread\n notify();\n }\n }\n }\n\n public void printEven() {\n synchronized (this) {\n while (counter < number) {\n if (counter % 2 == 1) {\n try {\n wait();\n } catch (InterruptedException ignored) {\n }\n }\n // Print the number\n System.out.println(counter + \" Thread Name: \" + Thread.currentThread().getName());\n // Increment counter\n counter++;\n // Notify to second thread\n notify();\n }\n }\n }\n\n}\n\n", "The solution below is using java 8 completable future and executor service to print even and odd numbers using two threads.\nExecutorService firstExecutorService = Executors.newSingleThreadExecutor(r -> {\n Thread t = new Thread(r);\n t.setName(\"first\");\n return t;\n });\n\n ExecutorService secondExecutorService = Executors.newSingleThreadExecutor(r -> {\n Thread t = new Thread(r);\n t.setName(\"second\");\n return t;\n });\n\n IntStream.range(1, 101).forEach(num -> {\n\n CompletableFuture<Integer> thenApplyAsync = CompletableFuture.completedFuture(num).thenApplyAsync(x -> {\n\n if (x % 2 == 1) {\n System.out.println(x + \" \" + Thread.currentThread().getName());\n }\n return num;\n }, firstExecutorService);\n\n thenApplyAsync.join();\n\n CompletableFuture<Integer> thenApplyAsync2 = CompletableFuture.completedFuture(num).thenApplyAsync(x -> {\n if (x % 2 == 0) {\n System.out.println(x + \" \" + Thread.currentThread().getName());\n }\n return num;\n }, secondExecutorService);\n\n thenApplyAsync2.join();\n });\n\n firstExecutorService.shutdown();\n secondExecutorService.shutdown();\n\nThe below is the console log of it.\n\n", "We can print odd and even using two separate threads using CompletableFuture as well:\nimport java.util.concurrent.CompletableFuture;\nimport java.util.function.IntPredicate;\nimport java.util.stream.IntStream;\n\npublic class OddEvenBy2Thread {\n\n private static Object object = new Object();\n\n private static IntPredicate evenCondition = e -> e % 2 == 0;\n private static IntPredicate oddCondition = e -> e % 2 != 0;\n\n public static void main(String[] args) throws InterruptedException {\n\n // Odd number printer\n CompletableFuture.runAsync(() -> OddEvenBy2Thread.printNumber(oddCondition));\n\n // Even number printer\n CompletableFuture.runAsync(() -> OddEvenBy2Thread.printNumber(evenCondition));\n\n Thread.sleep(1000);\n }\n\n public static void printNumber(IntPredicate condition){\n IntStream.rangeClosed(1, 10).filter(condition).forEach(OddEvenBy2Thread::execute);\n }\n\n public static void execute(int num){\n synchronized (object){\n try{\n System.out.println(Thread.currentThread().getName()+\" : \"+num);\n object.notify();\n object.wait();\n }catch (InterruptedException e){\n e.printStackTrace();\n }\n }\n\n }\n}\n\n\n" ]
[ 54, 22, 13, 5, 3, 3, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "public class EvenOddex {\npublic static class print {\n\n int n;\n boolean isOdd = false;\n\n synchronized public void printEven(int n) {\n\n while (isOdd) {\n try {\n wait();\n } catch (InterruptedException ex) {\n Logger.getLogger(EvenOddex.class.getName()).log(Level.SEVERE, null, ex);\n }\n\n }\n\n System.out.print(Thread.currentThread().getName() + n + \"\\n\");\n\n isOdd = true;\n notify();\n }\n\n synchronized public void printOdd(int n) {\n while (!isOdd) {\n try {\n wait();\n } catch (InterruptedException ex) {\n Logger.getLogger(EvenOddex.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n\n\n System.out.print(Thread.currentThread().getName() + n + \"\\n\");\n isOdd = false;\n notify();\n\n\n\n }\n}\n\npublic static class even extends Thread {\n\n print po;\n\n even(print po) {\n\n this.po = po;\n\n new Thread(this, \"Even\").start();\n\n }\n\n @Override\n public void run() {\n\n\n for (int j = 0; j < 10; j++) {\n if ((j % 2) == 0) {\n po.printEven(j);\n }\n }\n\n }\n}\n\npublic static class odd extends Thread {\n\n print po;\n\n odd(print po) {\n\n this.po = po;\n new Thread(this, \"Odd\").start();\n }\n\n @Override\n public void run() {\n\n for (int i = 0; i < 10; i++) {\n\n if ((i % 2) != 0) {\n po.printOdd(i);\n }\n }\n\n }\n}\n\npublic static void main(String args[]) {\n print po = new print();\n new even(po);\n new odd(po);\n\n}\n\n}\n", "public class Multi extends Thread{ \n public static int a;\n static{a=1;}\n public void run(){ \n for(int i=1;i<5;i++){ \n System.out.println(\"Thread Id \"+this.getId()+\" Value \"+a++);\n try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);} \n\n } \n } \npublic static void main(String args[]){ \n Multi t1=new Multi(); \n Multi t2=new Multi(); \n\n t1.start(); \n t2.start(); \n } \n} \n\n", "public class PrintOddEven {\nprivate static class PrinterThread extends Thread {\n\n private static int current = 0;\n private static final Object LOCK = new Object();\n\n private PrinterThread(String name, int number) {\n this.name = name;\n this.number = number;\n }\n\n @Override\n public void run() {\n while (true) {\n synchronized (LOCK) {\n try {\n LOCK.wait(1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n\n if (current < number) {\n System.out.println(name + ++current);\n } else {\n break;\n }\n\n LOCK.notifyAll();\n }\n }\n }\n\n int number;\n String name;\n}\n\npublic static void main(String[] args) {\n new PrinterThread(\"thread1 : \", 20).start();\n new PrinterThread(\"thread2 : \", 20).start();\n}\n}\n\n", "public class Solution {\n static class NumberGenerator{\n\n private static volatile boolean printEvenNumber = false;\n\n\n public void printEvenNumber(int i) {\n synchronized (this) {\n if(!printEvenNumber) {\n try {\n wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n System.out.println(i);\n printEvenNumber = !printEvenNumber;\n notify();\n }\n }\n\n public void printOddNumber(int i ) {\n synchronized (this) {\n if(printEvenNumber) {\n try {\n wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n\n System.out.println(i);\n printEvenNumber = !printEvenNumber;\n notify();\n }\n }\n\n}\n\nstatic class OddNumberGenerator implements Runnable{\n private NumberGenerator numberGenerator;\n\n public OddNumberGenerator(NumberGenerator numberGenerator) {\n this.numberGenerator = numberGenerator;\n }\n\n @Override\n public void run() {\n for(int i = 1; i <100; i = i + 2) {\n numberGenerator.printOddNumber(i);\n }\n }\n}\n\nstatic class EvenNumberGenerator implements Runnable {\n private NumberGenerator numberGenerator;\n\n public EvenNumberGenerator(NumberGenerator numberGenerator) {\n this.numberGenerator = numberGenerator;\n }\n\n @Override\n public void run() {\n for (int i = 2; i <= 100; i = i + 2) {\n numberGenerator.printEvenNumber(i);\n }\n }\n}\n\n\npublic static void main(String[] args) {\n NumberGenerator ng = new NumberGenerator();\n OddNumberGenerator oddNumberGenerator = new OddNumberGenerator(ng);\n EvenNumberGenerator evenNumberGenerator = new EvenNumberGenerator(ng);\n new Thread(oddNumberGenerator).start();\n new Thread(evenNumberGenerator).start();\n\n}\n\n}\n", "package programs.multithreading;\n\npublic class PrintOddEvenNoInSequence {\n\nfinal int upto;\nfinal PrintOddEvenNoInSequence obj;\nvolatile boolean oddFlag,evenFlag;\npublic PrintOddEvenNoInSequence(int upto){\n this.upto = upto;\n obj = this;\n oddFlag = true;\n evenFlag = false;\n}\nvoid printInSequence(){\n\n Thread odd = new Thread(new Runnable() {\n @Override\n public void run() {\n for(int i = 1; i <= upto; i = i + 2){\n synchronized (obj) {\n while(!oddFlag){\n try {\n obj.wait();\n } catch (InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n System.out.println(\"Odd:\"+i);\n oddFlag = false;\n evenFlag = true;\n obj.notify();\n }\n }\n }\n });\n\n Thread even = new Thread(new Runnable() {\n @Override\n public void run() {\n for(int i = 2; i <= upto; i = i + 2){\n synchronized (obj) {\n while(!evenFlag){\n try {\n obj.wait();\n } catch (InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n System.out.println(\"Even:\"+i);\n oddFlag = true;\n evenFlag = false;\n obj.notify();\n }\n }\n }\n });\n\n odd.start();\n even.start();\n\n}\npublic static void main(String[] args) {\n new PrintOddEvenNoInSequence(100).printInSequence();\n}\n}\n\n", "See the Clean implementation\npublic class PrintOddEvenByTwoThreads {\n static int number = 1;\n static Thread odd;\n static Thread even;\n static int max = 10;\n\n static class OddThread extends Thread {\n @Override\n public void run() {\n while (number <= max) {\n if (number % 2 == 1) {\n System.out.println(Thread.currentThread() + \"\" + number++);\n } else {\n\n synchronized (odd) {\n synchronized (even) {\n even.notify();\n }\n try {\n wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n }\n }\n }\n\n static class EvenThread extends Thread {\n @Override\n public void run() {\n while (number <= max) {\n if (number % 2 == 0) {\n System.out.println(Thread.currentThread() + \"\" + number++);\n } else {\n\n synchronized (even) {\n synchronized (odd) {\n odd.notify();\n }\n try {\n wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n }\n }\n }\n\n public static void main(String[] args) throws InterruptedException {\n odd = new OddThread();\n even = new EvenThread();\n odd.start();\n even.start();\n }\n}\n\n", "1- The number is initialized with 1 and isOdd flag is set to false. set isOdd to true\n2- Increment should be by 1 (not by 2) i.e number+=1;\n", "import java.util.concurrent.Semaphore;\n\n\npublic class PrintOddAndEven {\n\nprivate static class OddThread extends Thread {\n private Semaphore semaphore;\n private Semaphore otherSemaphore;\n private int value = 1;\n\n public OddThread(Semaphore semaphore, Semaphore otherSemaphore) {\n this.semaphore = semaphore;\n this.otherSemaphore = otherSemaphore;\n }\n\n public void run() {\n while (value <= 100) {\n try {\n // Acquire odd semaphore\n semaphore.acquire();\n System.out.println(\" Odd Thread \" + value + \" \" + Thread.currentThread().getName());\n\n } catch (InterruptedException excetion) {\n excetion.printStackTrace();\n }\n value = value + 2;\n // Release odd semaphore\n otherSemaphore.release();\n }\n }\n}\n\n\nprivate static class EvenThread extends Thread {\n private Semaphore semaphore;\n private Semaphore otherSemaphore;\n\n private int value = 2;\n\n public EvenThread(Semaphore semaphore, Semaphore otherSemaphore) {\n this.semaphore = semaphore;\n this.otherSemaphore = otherSemaphore;\n }\n\n public void run() {\n while (value <= 100) {\n try {\n // Acquire even semaphore\n semaphore.acquire();\n System.out.println(\" Even Thread \" + value + \" \" + Thread.currentThread().getName());\n\n } catch (InterruptedException excetion) {\n excetion.printStackTrace();\n }\n value = value + 2;\n // Release odd semaphore\n otherSemaphore.release();\n }\n }\n}\n\n\npublic static void main(String[] args) {\n //Initialize oddSemaphore with permit 1\n Semaphore oddSemaphore = new Semaphore(1);\n //Initialize evenSempahore with permit 0\n Semaphore evenSempahore = new Semaphore(0);\n OddThread oddThread = new OddThread(oddSemaphore, evenSempahore);\n EvenThread evenThread = new EvenThread(evenSempahore, oddSemaphore);\n oddThread.start();\n evenThread.start();\n }\n}\n\n", "Simple Solution below:-\npackage com.test;\n\nclass MyThread implements Runnable{\n\n @Override\n public void run() {\n int i=1;\n while(true) {\n String name=Thread.currentThread().getName();\n if(name.equals(\"task1\") && i%2!=0) {\n System.out.println(name+\"::::\"+i);\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }else if(name.equals(\"task2\") && i%2==0){\n System.out.println(name+\"::::\"+i);\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n i++;\n }\n\n }\n\n public static void main(String[] args) {\n\n MyThread task1=new MyThread();\n MyThread task2=new MyThread();\n\n Thread t1=new Thread(task1,\"task1\");\n Thread t2=new Thread(task2,\"task2\");\n\n t1.start();\n t2.start();\n\n }\n\n}\n\n" ]
[ -1, -1, -1, -1, -1, -1, -1, -2, -2 ]
[ "java", "multithreading", "synchronization" ]
stackoverflow_0016689449_java_multithreading_synchronization.txt
Q: Is there a way to have semi-transparent elements (divs) overlap, and have the overlapped area NOT add up the 2 alpha values? So if div 1 and div 2 have 0.5 alpha, the area where they overlap would still have 0.5 alpha, and NOT 0.75 alpha. I couldn't really think of any possible ways I could do this A: mix-blend-mode property accepts a number of different blend modes, each of which determines how the colors and alpha values of overlapping elements are combined. // This CSS rule sets the mix-blend-mode of all elements with the class "semi-transparent" to "screen" .semi-transparent { mix-blend-mode: screen; } the mix-blend-mode property is set to screen for all elements with the class semi-transparent. This causes the colors and alpha values of overlapping elements to be blended together using the screen blend mode, which prevents the alpha values from adding up.
Is there a way to have semi-transparent elements (divs) overlap, and have the overlapped area NOT add up the 2 alpha values?
So if div 1 and div 2 have 0.5 alpha, the area where they overlap would still have 0.5 alpha, and NOT 0.75 alpha. I couldn't really think of any possible ways I could do this
[ "mix-blend-mode property accepts a number of different blend modes, each of which determines how the colors and alpha values of overlapping elements are combined.\n// This CSS rule sets the mix-blend-mode of all elements with the class \"semi-transparent\" to \"screen\"\n.semi-transparent {\n mix-blend-mode: screen;\n}\n\nthe mix-blend-mode property is set to screen for all elements with the class semi-transparent. This causes the colors and alpha values of overlapping elements to be blended together using the screen blend mode, which prevents the alpha values from adding up.\n" ]
[ 0 ]
[]
[]
[ "css", "html", "javascript" ]
stackoverflow_0074678405_css_html_javascript.txt
Q: How do you get owlapi projects to compile and run on MacOS 12 (which runs Java 19 by default) with Maven? Since upgrading to MacOS 12, when I run owlapi-dependent projects that are compiled with Maven, the Guice library which owlapi depends on, throws several different types of exceptions at start time. What can I do to resolve this? For example: Exception in thread "main" java.lang.NoSuchMethodError: com.google.inject.internal.BytecodeGen.getClassLoader(Ljava/lang/Class;)Ljava/lang/ClassLoader; com.google.inject.internal.MessageProcessor visit INFO: An exception was caught and reported. Message: java.lang.NoSuchMethodException: uk.ac.manchester.cs.owl.owlapi.OWLOntologyFactoryImpl.<init>() com.google.inject.CreationException: Unable to create injector, see the following errors: 1) An exception was caught and reported. Message: Injection failed for interface OWLOntologyFactory at [unknown source] 1 error ====================== Full classname legend: ====================== OWLOntologyFactory: "org.semanticweb.owlapi.model.OWLOntologyFactory" ======================== End of classname legend: ======================== at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:576) at com.google.inject.internal.InternalInjectorCreator.initializeStatically(InternalInjectorCreator.java:163) at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:110) at com.google.inject.Guice.createInjector(Guice.java:87) at com.google.inject.Guice.createInjector(Guice.java:69) at com.google.inject.Guice.createInjector(Guice.java:59) at org.semanticweb.owlapi.apibinding.OWLManager.<clinit>(OWLManager.java:42) ... 2 more Here are the dependencies in the pom file I'm using: <dependencies> <dependency> <groupId>net.sourceforge.owlapi</groupId> <artifactId>jfact</artifactId> <version>5.0.0</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.6.1</version> <scope>test</scope> </dependency> <dependency> <groupId>net.sourceforge.owlapi</groupId> <artifactId>owlapi-rio</artifactId> <version>5.1.0</version> </dependency> <dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> <version>5.1.0</version> </dependency> <dependency> <groupId>net.sourceforge.owlapi</groupId> <artifactId>owlapi-distribution</artifactId> <version>5.1.0</version> </dependency> <dependency> <groupId>ch.securityvision</groupId> <artifactId>xattrj</artifactId> <version>1.3</version> </dependency> </dependencies> A: Thr guice dependency was removed from the 5.x branch of owlapi a few years ago. Try updating owlapi to 5.1.20 and removing the explicit guice dependency in your pom. This should exclude all guice references. If necessary, exclude it from the jfact dependency as well (I have not tried jfact with any java version past 8 but i would expect it to work, it doesn't have any features that are known to be incompatible with newer jdks.
How do you get owlapi projects to compile and run on MacOS 12 (which runs Java 19 by default) with Maven?
Since upgrading to MacOS 12, when I run owlapi-dependent projects that are compiled with Maven, the Guice library which owlapi depends on, throws several different types of exceptions at start time. What can I do to resolve this? For example: Exception in thread "main" java.lang.NoSuchMethodError: com.google.inject.internal.BytecodeGen.getClassLoader(Ljava/lang/Class;)Ljava/lang/ClassLoader; com.google.inject.internal.MessageProcessor visit INFO: An exception was caught and reported. Message: java.lang.NoSuchMethodException: uk.ac.manchester.cs.owl.owlapi.OWLOntologyFactoryImpl.<init>() com.google.inject.CreationException: Unable to create injector, see the following errors: 1) An exception was caught and reported. Message: Injection failed for interface OWLOntologyFactory at [unknown source] 1 error ====================== Full classname legend: ====================== OWLOntologyFactory: "org.semanticweb.owlapi.model.OWLOntologyFactory" ======================== End of classname legend: ======================== at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:576) at com.google.inject.internal.InternalInjectorCreator.initializeStatically(InternalInjectorCreator.java:163) at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:110) at com.google.inject.Guice.createInjector(Guice.java:87) at com.google.inject.Guice.createInjector(Guice.java:69) at com.google.inject.Guice.createInjector(Guice.java:59) at org.semanticweb.owlapi.apibinding.OWLManager.<clinit>(OWLManager.java:42) ... 2 more Here are the dependencies in the pom file I'm using: <dependencies> <dependency> <groupId>net.sourceforge.owlapi</groupId> <artifactId>jfact</artifactId> <version>5.0.0</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.6.1</version> <scope>test</scope> </dependency> <dependency> <groupId>net.sourceforge.owlapi</groupId> <artifactId>owlapi-rio</artifactId> <version>5.1.0</version> </dependency> <dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> <version>5.1.0</version> </dependency> <dependency> <groupId>net.sourceforge.owlapi</groupId> <artifactId>owlapi-distribution</artifactId> <version>5.1.0</version> </dependency> <dependency> <groupId>ch.securityvision</groupId> <artifactId>xattrj</artifactId> <version>1.3</version> </dependency> </dependencies>
[ "Thr guice dependency was removed from the 5.x branch of owlapi a few years ago. Try updating owlapi to 5.1.20 and removing the explicit guice dependency in your pom. This should exclude all guice references. If necessary, exclude it from the jfact dependency as well (I have not tried jfact with any java version past 8 but i would expect it to work, it doesn't have any features that are known to be incompatible with newer jdks.\n" ]
[ 0 ]
[]
[]
[ "guice", "java", "maven", "ontology", "owl" ]
stackoverflow_0074672282_guice_java_maven_ontology_owl.txt
Q: Print statement is not working in view controller method when run the UI Test case in Xcode 14.0 I have created a custom framework and inside that all the logs are recorded when we initialise the framework. Now I have integrate that framework inside a demo project and write UI test case for the same. When I add the breakpoint inside the method then only logs are getting printed in the console while running the UI test case .Otherwise it don't print the logs in the console when break point is not added. I don't know why thing is happening. I need logs for analysis purpose. Could you please help me . Print statement is only working when adding break point in the view controller class. A: Your UI test code runs in a separate process outside of your app process. The default state shows the debugger for the UI test process, and not your app process, and will only show print statements written in the UI test code. The print statement you wrote seems like it’s a part of your app code. If you hit a breakpoint in your app code, the Xcode console switches to show the debugger for your app, as opposed to the debugger for your UI test, which is why you see the print statement there.
Print statement is not working in view controller method when run the UI Test case in Xcode 14.0
I have created a custom framework and inside that all the logs are recorded when we initialise the framework. Now I have integrate that framework inside a demo project and write UI test case for the same. When I add the breakpoint inside the method then only logs are getting printed in the console while running the UI test case .Otherwise it don't print the logs in the console when break point is not added. I don't know why thing is happening. I need logs for analysis purpose. Could you please help me . Print statement is only working when adding break point in the view controller class.
[ "Your UI test code runs in a separate process outside of your app process. The default state shows the debugger for the UI test process, and not your app process, and will only show print statements written in the UI test code. The print statement you wrote seems like it’s a part of your app code.\nIf you hit a breakpoint in your app code, the Xcode console switches to show the debugger for your app, as opposed to the debugger for your UI test, which is why you see the print statement there.\n" ]
[ 0 ]
[]
[]
[ "ios", "swift", "xctest" ]
stackoverflow_0074625938_ios_swift_xctest.txt
Q: Application built by jarbundler fails to launch I am building a Java 9 application for MacOS using Jarbundler, via ant. The build process succeeds without complaint, but the resulting application does not launch. However, when I run the executable within the generated application bundle, it does work. The problem, therefore, seems to be that launchd cannot find or launch that executable. When I open the executable, I see: The application cannot be opened for an unexpected reason, error=Error Domain=NSOSStatusErrorDomain Code=-10810 "kLSUnknownErr: Unexpected internal error" UserInfo={_LSFunction=_LSLaunchWithRunningboard, _LSLine=2732, NSUnderlyingError=0x600003f40630 {Error Domain=RBSRequestErrorDomain Code=5 "Launch failed." UserInfo={NSLocalizedFailureReason=Launch failed., NSUnderlyingError=0x600003f404b0 {Error Domain=NSPOSIXErrorDomain Code=21 "Is a directory" UserInfo={NSLocalizedDescription=Launchd job spawn failed}}}}} The fx:deploy task looks like this: <fx:deploy width="300" height="250" nativeBundles="image" outdir="Platforms/Macintosh/dist" mainClass="<classname>" outfile="<applicationname>"> <fx:application refId="<appid>"/> <fx:resources refid="<resources>"/> <fx:info title="<appname>" vendor="<myname>"/> </fx:deploy> where the <parameters> are specified, of course. Here is the equivalent (at least in the sense that it produces the same error) javapackager command line: javapackager -deploy -native image -outdir Platforms/Macintosh/dist -outfile appname -srcdir Platforms/Java/dist -srcfiles jarfilename -appclass classname -name "appname" -title "appname demo" -nosign jarfilename and classname are set correctly. And again, the executable in the generated application bundle runs with the expected outcome. I am missing something, but I am unsure of what. Any advice? Thanks in advance. A: The error you are having is because you are trying to create a file, in this case it is either appname or jarfilename but that path has been already created as a folder, probably by a previous command. Maybe you can try to list files and folders in the folder where this command is running and check if this is correct
Application built by jarbundler fails to launch
I am building a Java 9 application for MacOS using Jarbundler, via ant. The build process succeeds without complaint, but the resulting application does not launch. However, when I run the executable within the generated application bundle, it does work. The problem, therefore, seems to be that launchd cannot find or launch that executable. When I open the executable, I see: The application cannot be opened for an unexpected reason, error=Error Domain=NSOSStatusErrorDomain Code=-10810 "kLSUnknownErr: Unexpected internal error" UserInfo={_LSFunction=_LSLaunchWithRunningboard, _LSLine=2732, NSUnderlyingError=0x600003f40630 {Error Domain=RBSRequestErrorDomain Code=5 "Launch failed." UserInfo={NSLocalizedFailureReason=Launch failed., NSUnderlyingError=0x600003f404b0 {Error Domain=NSPOSIXErrorDomain Code=21 "Is a directory" UserInfo={NSLocalizedDescription=Launchd job spawn failed}}}}} The fx:deploy task looks like this: <fx:deploy width="300" height="250" nativeBundles="image" outdir="Platforms/Macintosh/dist" mainClass="<classname>" outfile="<applicationname>"> <fx:application refId="<appid>"/> <fx:resources refid="<resources>"/> <fx:info title="<appname>" vendor="<myname>"/> </fx:deploy> where the <parameters> are specified, of course. Here is the equivalent (at least in the sense that it produces the same error) javapackager command line: javapackager -deploy -native image -outdir Platforms/Macintosh/dist -outfile appname -srcdir Platforms/Java/dist -srcfiles jarfilename -appclass classname -name "appname" -title "appname demo" -nosign jarfilename and classname are set correctly. And again, the executable in the generated application bundle runs with the expected outcome. I am missing something, but I am unsure of what. Any advice? Thanks in advance.
[ "The error you are having is because you are trying to create a file, in this case it is either appname or jarfilename but that path has been already created as a folder, probably by a previous command.\nMaybe you can try to list files and folders in the folder where this command is running and check if this is correct\n" ]
[ 0 ]
[]
[]
[ "ant", "java", "javapackager", "macos" ]
stackoverflow_0074607648_ant_java_javapackager_macos.txt
Q: Looking for an example of using ElasticSearch with ASP.NET How do you implement the search DATABASE table capabilities of Elasticsearch in asp.net? Could anyone share some code examples or article links if posssible? Went through official documentation https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/introduction.html A: To implement Elasticsearch search capabilities in ASP.NET, you can use the Elasticsearch.NET and NEST client libraries. These libraries provide a simple and easy-to-use API for working with Elasticsearch from ASP.NET. Here is an example of how you can use the Elasticsearch.NET client library to search a database table in Elasticsearch: // create a new Elasticsearch client var elasticClient = new ElasticClient(); // search for documents with a specific field value var searchResponse = elasticClient.Search<YourDocumentType>(s => s .Index("your-index-name") .Type("your-type-name") .Query(q => q .Match(m => m .Field("field-name") .Query("field-value") ) ) ); // process the search results foreach (var hit in searchResponse.Hits) { Console.WriteLine(hit.Source); } In this example, we search for documents in the "your-index-name" index and "your-type-name" type with a "field-name" field that has a value of "field-value". The search results are returned as a list of IHit objects, where YourDocumentType is the type of the documents being searched. For more information on using Elasticsearch.NET and NEST in ASP.NET, please see the Elasticsearch.NET and NEST documentation: Elasticsearch.NET: https://www.elastic.co/guide/en/elasticsearch-net/current/index.html NEST: https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/index.html
Looking for an example of using ElasticSearch with ASP.NET
How do you implement the search DATABASE table capabilities of Elasticsearch in asp.net? Could anyone share some code examples or article links if posssible? Went through official documentation https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/introduction.html
[ "To implement Elasticsearch search capabilities in ASP.NET, you can use the Elasticsearch.NET and NEST client libraries. These libraries provide a simple and easy-to-use API for working with Elasticsearch from ASP.NET. Here is an example of how you can use the Elasticsearch.NET client library to search a database table in Elasticsearch:\n// create a new Elasticsearch client\nvar elasticClient = new ElasticClient();\n\n// search for documents with a specific field value\nvar searchResponse = elasticClient.Search<YourDocumentType>(s => s\n .Index(\"your-index-name\")\n .Type(\"your-type-name\")\n .Query(q => q\n .Match(m => m\n .Field(\"field-name\")\n .Query(\"field-value\")\n )\n )\n);\n\n// process the search results\nforeach (var hit in searchResponse.Hits)\n{\n Console.WriteLine(hit.Source);\n}\n\nIn this example, we search for documents in the \"your-index-name\" index and \"your-type-name\" type with a \"field-name\" field that has a value of \"field-value\". The search results are returned as a list of IHit objects, where YourDocumentType is the type of the documents being searched.\nFor more information on using Elasticsearch.NET and NEST in ASP.NET, please see the Elasticsearch.NET and NEST documentation:\nElasticsearch.NET:\nhttps://www.elastic.co/guide/en/elasticsearch-net/current/index.html\nNEST:\nhttps://www.elastic.co/guide/en/elasticsearch/client/net-api/current/index.html\n" ]
[ 0 ]
[]
[]
[ "asp.net", "asp.net_core", "elasticsearch", "lucene.net", "solrnet" ]
stackoverflow_0074674759_asp.net_asp.net_core_elasticsearch_lucene.net_solrnet.txt
Q: Is there Any performance optimization on spring boot 3.0 Hi is there Any comparison about performance between spring boot 2.x and 3.0. A: In terms of performance, it is difficult to compare the two versions directly, as there are many factors that can affect the performance of a Spring Boot application, such as the specific features and dependencies used, the hardware and software environment, and the workload. I haven't found any relevant performance comparisons. However, in general, Spring Boot 3.0 may be better due to several improvements that have been made in the new version. Some of the performance improvements in Spring Boot 3.0 include: The use of the Eclipse JDT compiler for annotation processing, which can improve build time and memory usage. The use of the Reactor 3.4.0 library for reactive programming, which can improve the performance of reactive applications. The use of the Java 15+ List.of and Map.of methods for creating immutable collections, which can improve the performance of applications that use these collections. Overall, it is recommended to test the performance of your specific application and compare the results between the two versions to determine which one performs better for your use case. It is possible that the same application will perform better on the older version of Spring Boot.
Is there Any performance optimization on spring boot 3.0
Hi is there Any comparison about performance between spring boot 2.x and 3.0.
[ "In terms of performance, it is difficult to compare the two versions directly, as there are many factors that can affect the performance of a Spring Boot application, such as the specific features and dependencies used, the hardware and software environment, and the workload. I haven't found any relevant performance comparisons. However, in general, Spring Boot 3.0 may be better due to several improvements that have been made in the new version.\nSome of the performance improvements in Spring Boot 3.0 include:\n\nThe use of the Eclipse JDT compiler for annotation processing, which\ncan improve build time and memory usage.\nThe use of the Reactor 3.4.0\nlibrary for reactive programming, which can improve the performance\nof reactive applications.\nThe use of the Java 15+ List.of and Map.of\nmethods for creating immutable collections, which can improve the\nperformance of applications that use these collections.\n\nOverall, it is recommended to test the performance of your specific application and compare the results between the two versions to determine which one performs better for your use case. It is possible that the same application will perform better on the older version of Spring Boot.\n" ]
[ 0 ]
[]
[]
[ "spring", "spring_boot", "spring_boot_3" ]
stackoverflow_0074674327_spring_spring_boot_spring_boot_3.txt
Q: Can _Generic match on string of type? Example use-case, do a thing for all types that contain the string "int". More precise, have a struct Point in different versions as Point__alloca or Point__boehm, and then a macro new that switches on that name. Hm, maybe macro stringification could do that? A: Standard C supports only very limited introspection (examination of the program by itself) and nothing that would discern whether a type name contained particular characters or any ability to enumerate “all types” at all, let alone all types matching a criterion. In short, there is no support for the feature you request.
Can _Generic match on string of type?
Example use-case, do a thing for all types that contain the string "int". More precise, have a struct Point in different versions as Point__alloca or Point__boehm, and then a macro new that switches on that name. Hm, maybe macro stringification could do that?
[ "Standard C supports only very limited introspection (examination of the program by itself) and nothing that would discern whether a type name contained particular characters or any ability to enumerate “all types” at all, let alone all types matching a criterion. In short, there is no support for the feature you request.\n" ]
[ 0 ]
[]
[]
[ "c", "generics" ]
stackoverflow_0074678006_c_generics.txt
Q: grep or sed do not recognise GPS corrdinate string with degree the string looks like (37°35'11.2" N 85°30'40.3"W) grep does not work grep -a "(37\°35\'11\.2\" N 85\°30\'40\.3\"W)" file.txt grep "(37\°35\'11\.2\" N 85\°30\'40\.3\"W)" file.txt grep -a "(37°35'11.2\" N 85°30'40.3\"W)" file.txt A: One more generic way (you can change \d by numbers): $ grep -P '\d+.\d+.\d+.\d+" N \d+.\d+.\d+.\d+..' l 37°35'11.2" N 85°30'40.3"W A: This is actually a shell quoting problem rather than a grep or sed. Do not escape the ° and ' characters enclosed in double-quotes with backslashes since they are not special between double-quotes (When those characters are "escaped" with backslashes, these backslashes are passed literally to the command, that is, they are not removed). Call the grep like this: grep "(37°35'11.2\" N 85°30'40.3\"W)" file.txt In shell, the characters that need to be escaped by a backslash when enclosed in double-quotes are ", $, `, and the \ itself. Also, the use of -F option of grep could be a good idea for this case because the regex argument of grep is treated as a fixed string.
grep or sed do not recognise GPS corrdinate string with degree
the string looks like (37°35'11.2" N 85°30'40.3"W) grep does not work grep -a "(37\°35\'11\.2\" N 85\°30\'40\.3\"W)" file.txt grep "(37\°35\'11\.2\" N 85\°30\'40\.3\"W)" file.txt grep -a "(37°35'11.2\" N 85°30'40.3\"W)" file.txt
[ "One more generic way (you can change \\d by numbers):\n$ grep -P '\\d+.\\d+.\\d+.\\d+\" N \\d+.\\d+.\\d+.\\d+..' l\n37°35'11.2\" N 85°30'40.3\"W\n\n", "This is actually a shell quoting problem rather than a grep or sed. Do not escape the ° and ' characters enclosed in double-quotes with backslashes since they are not special between double-quotes (When those characters are \"escaped\" with backslashes, these backslashes are passed literally to the command, that is, they are not removed). Call the grep like this:\ngrep \"(37°35'11.2\\\" N 85°30'40.3\\\"W)\" file.txt\n\nIn shell, the characters that need to be escaped by a backslash when enclosed in double-quotes are \", $, `, and the \\ itself. Also, the use of -F option of grep could be a good idea for this case because the regex argument of grep is treated as a fixed string.\n" ]
[ 0, 0 ]
[]
[]
[ "gps", "grep", "sed", "string" ]
stackoverflow_0074672034_gps_grep_sed_string.txt
Q: writting query script on grafana that uses elasticsearch as the data source i want to write an aggregation query that use an script for computing the size of an specific field in elasticsearch. then i want visualize this query in grafana. but i cant convert this query on grafana dashboard. the DSL query in elasticsearch is: GET index_name/_search { "query": { "term": { "content_type": { "value": "voice" } } }, "aggs": { "voice_type": { "terms": { "field": "voice_type", }, "aggs": { "number_of_voice": { "filter": { "script": { "script": { "lang": "painless", "source": "doc['like_list'].size() >= params.value", "params": { "value" : 3 } } } } } } } } } i can't convert this query in grafana dashboard. Has anyone encountered this problem? or has anyone had experienced to write script query on grafana? A: To convert the Elasticsearch query shown in your example to a Grafana query, you will need to use the Elasticsearch query language (DSL) syntax supported by Grafana. The Grafana query editor uses a specific syntax for Elasticsearch queries, which is similar but not identical to the Elasticsearch DSL syntax. Here is an example of how you could convert the Elasticsearch query in your example to a Grafana query: { "query": { "bool": { "filter": [ { "term": { "content_type": "voice" } } ] } }, "aggs": { "voice_type": { "terms": { "field": "voice_type" }, "aggs": { "number_of_voice": { "bucket_script": { "buckets_path": { "count": "voice_type>_count" }, "script": { "inline": "params.count >= 3", "lang": "painless" } } } } } } } In this example, we use the bool query to filter for documents with a content_type field that has a value of "voice". We then use a terms aggregation to group the documents by their voice_type field, and a bucket_script aggregation to compute the number of voices based on the like_list field. For more information on using Elasticsearch queries in Grafana, please see the Grafana documentation: https://grafana.com/docs/grafana/latest/features/datasources/elasticsearch/.
writting query script on grafana that uses elasticsearch as the data source
i want to write an aggregation query that use an script for computing the size of an specific field in elasticsearch. then i want visualize this query in grafana. but i cant convert this query on grafana dashboard. the DSL query in elasticsearch is: GET index_name/_search { "query": { "term": { "content_type": { "value": "voice" } } }, "aggs": { "voice_type": { "terms": { "field": "voice_type", }, "aggs": { "number_of_voice": { "filter": { "script": { "script": { "lang": "painless", "source": "doc['like_list'].size() >= params.value", "params": { "value" : 3 } } } } } } } } } i can't convert this query in grafana dashboard. Has anyone encountered this problem? or has anyone had experienced to write script query on grafana?
[ "To convert the Elasticsearch query shown in your example to a Grafana query, you will need to use the Elasticsearch query language (DSL) syntax supported by Grafana. The Grafana query editor uses a specific syntax for Elasticsearch queries, which is similar but not identical to the Elasticsearch DSL syntax.\nHere is an example of how you could convert the Elasticsearch query in your example to a Grafana query:\n{\n \"query\": {\n \"bool\": {\n \"filter\": [\n {\n \"term\": {\n \"content_type\": \"voice\"\n }\n }\n ]\n }\n },\n \"aggs\": {\n \"voice_type\": {\n \"terms\": {\n \"field\": \"voice_type\"\n },\n \"aggs\": {\n \"number_of_voice\": {\n \"bucket_script\": {\n \"buckets_path\": {\n \"count\": \"voice_type>_count\"\n },\n \"script\": {\n \"inline\": \"params.count >= 3\",\n \"lang\": \"painless\"\n }\n }\n }\n }\n }\n }\n}\n\nIn this example, we use the bool query to filter for documents with a content_type field that has a value of \"voice\". We then use a terms aggregation to group the documents by their voice_type field, and a bucket_script aggregation to compute the number of voices based on the like_list field.\nFor more information on using Elasticsearch queries in Grafana, please see the Grafana documentation: https://grafana.com/docs/grafana/latest/features/datasources/elasticsearch/.\n" ]
[ 0 ]
[]
[]
[ "elasticsearch", "grafana" ]
stackoverflow_0074673611_elasticsearch_grafana.txt
Q: I have issues in reverse relation in nodejs using moongose one to one relationship So bassically I have three roles for users admin seller buyer This is my User Scheme const userSchema = mongoose.Schema({ email: { type: String, required: true, unique: true }, password: { type: String, required: true, select: false }, role: { type: String, enum: ['seller', 'buyer'], required: true }, admin: { type: mongoose.Schema.Types.ObjectId, ref: 'Admin' }, seller: { type: mongoose.Schema.Types.ObjectId, red: 'Seller'}, buyer: { type: mongoose.Schema.Types.ObjectId, ref: 'Buyer' }, }) userSchema.plugin(uniqueValidator) module.exports = mongoose.model('User', userSchema) This is my User Roles Schemas Seller Schema const sellerUserSchema = mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, firstName: { type: String, required: true }, lastName: { type: String }, email: { type: String, required: true, unique: true }, dob: { type: Date, min: '1950-01-01', max: new Date() }, }) Buyer Schema const buyerUserSchema = mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, firstName: { type: String, required: true }, lastName: { type: String }, email: { type: String, required: true, unique: true }, dob: { type: Date, min: '1950-01-01', max: new Date() }, }) Now when I do const usersQuery = Seller.find().populate('user').then(d=>{ console.log('details',d) }) I get the correct result like I get seller data and then object of user including all details you can check the result below in screenshot But When I do like const usersQuery = User.find().populate('seller','buyer') I am not getting any sort of seller or buyer data here is the result attached So my expected result is like i get user data and inside seller or buyer object Below is my database structure of MongoDB Users Sellers And buyers collections is same like seller Any help will be appriciated A: Since you have no reference of "seller" or "buyer" in User Schema , so you should try Aggregate Instead User.aggregate([ { $lookup: { from: "sellers", localField: "_id", foreignField: "user", as: "sellerSchemaUser" } }, { $lookup: { from: "buyers", localField: "_id", foreignField: "user", as: "buyerSchemaUser" } } ]) As I can see from your screenshot , your "seller" Collection not yet has any document in it , so you will get an empty array in "sellerSchemaUser" for now. Note: Lookup will return matched Documents from other collection in form of array of objects.
I have issues in reverse relation in nodejs using moongose one to one relationship
So bassically I have three roles for users admin seller buyer This is my User Scheme const userSchema = mongoose.Schema({ email: { type: String, required: true, unique: true }, password: { type: String, required: true, select: false }, role: { type: String, enum: ['seller', 'buyer'], required: true }, admin: { type: mongoose.Schema.Types.ObjectId, ref: 'Admin' }, seller: { type: mongoose.Schema.Types.ObjectId, red: 'Seller'}, buyer: { type: mongoose.Schema.Types.ObjectId, ref: 'Buyer' }, }) userSchema.plugin(uniqueValidator) module.exports = mongoose.model('User', userSchema) This is my User Roles Schemas Seller Schema const sellerUserSchema = mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, firstName: { type: String, required: true }, lastName: { type: String }, email: { type: String, required: true, unique: true }, dob: { type: Date, min: '1950-01-01', max: new Date() }, }) Buyer Schema const buyerUserSchema = mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, firstName: { type: String, required: true }, lastName: { type: String }, email: { type: String, required: true, unique: true }, dob: { type: Date, min: '1950-01-01', max: new Date() }, }) Now when I do const usersQuery = Seller.find().populate('user').then(d=>{ console.log('details',d) }) I get the correct result like I get seller data and then object of user including all details you can check the result below in screenshot But When I do like const usersQuery = User.find().populate('seller','buyer') I am not getting any sort of seller or buyer data here is the result attached So my expected result is like i get user data and inside seller or buyer object Below is my database structure of MongoDB Users Sellers And buyers collections is same like seller Any help will be appriciated
[ "Since you have no reference of \"seller\" or \"buyer\" in User Schema , so you should try Aggregate Instead\nUser.aggregate([\n {\n $lookup: {\n from: \"sellers\",\n localField: \"_id\",\n foreignField: \"user\",\n as: \"sellerSchemaUser\"\n }\n },\n {\n $lookup: {\n from: \"buyers\",\n localField: \"_id\",\n foreignField: \"user\",\n as: \"buyerSchemaUser\"\n }\n }\n])\n\nAs I can see from your screenshot , your \"seller\" Collection not yet has any document in it , so you will get an empty array in \"sellerSchemaUser\" for now.\nNote: Lookup will return matched Documents from other collection in form of array of objects.\n" ]
[ 1 ]
[]
[]
[ "express", "mongoose", "mongoose_populate", "mongoose_schema", "node.js" ]
stackoverflow_0074675565_express_mongoose_mongoose_populate_mongoose_schema_node.js.txt
Q: TypeError:run() missing 1 required positional argument: 'self' I wrote a simple program in pycharm on Windows, then it ran. In order to get the apk file, I installed ubuntu on a virtual machine. Then I installed pip, paycharm, kivy. Qivy installed through the terminal according to the instructions with their site. I typed the code and got an error:run() missing 1 required positional argument: 'self'. I tried to google but I couldn’t find anything really. from kivy.app import App from kivy.uix.floatlayout import FloatLayout class Container(FloatLayout): pass class MyApp(App): def build(self): return Container() if __name__=='__main__': MyApp().run() in .kv file <Container>: Button: background_normal: '' background_color: 0.5, 0, 1, .5 size_hint: 0.3, 0.3 pos_hint: {'center_x' : 0.5 , 'center_y':0.5} text:'Push' color: 0,1,0.5,1 on_release: self.text = 'on release' full error traceback A: the .kv file does not support multi-line entries so far as I know. The method on_release needs to reference a function and you would normally put that in the widget (root.your_function) or app (app.your_function). I changed the answer to use build_string only for convenience; it is a good idea to use a separate .kv file in your application as you did. from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.lang import Builder Builder.load_string(''' <Container>: Button: background_normal: '' background_color: 0.5, 0, 1, .5 size_hint: 0.3, 0.3 pos_hint: {'center_x' : 0.5 , 'center_y':0.5} text:'Push' color: 0,1,0.5,1 # self argument here will be the button object on_release: app.button_callback(self) ''') class Container(FloatLayout): pass class MyApp(App): def button_callback(self, my_button): print(my_button.text) self.count += 1 my_button.text = f"on_release {self.count}" def build(self): self.count = 0 return Container() if __name__=='__main__': MyApp().run()
TypeError:run() missing 1 required positional argument: 'self'
I wrote a simple program in pycharm on Windows, then it ran. In order to get the apk file, I installed ubuntu on a virtual machine. Then I installed pip, paycharm, kivy. Qivy installed through the terminal according to the instructions with their site. I typed the code and got an error:run() missing 1 required positional argument: 'self'. I tried to google but I couldn’t find anything really. from kivy.app import App from kivy.uix.floatlayout import FloatLayout class Container(FloatLayout): pass class MyApp(App): def build(self): return Container() if __name__=='__main__': MyApp().run() in .kv file <Container>: Button: background_normal: '' background_color: 0.5, 0, 1, .5 size_hint: 0.3, 0.3 pos_hint: {'center_x' : 0.5 , 'center_y':0.5} text:'Push' color: 0,1,0.5,1 on_release: self.text = 'on release' full error traceback
[ "the .kv file does not support multi-line entries so far as I know. The method on_release needs to reference a function and you would normally put that in the widget (root.your_function) or app (app.your_function). I changed the answer to use build_string only for convenience; it is a good idea to use a separate .kv file in your application as you did.\nfrom kivy.app import App\nfrom kivy.uix.floatlayout import FloatLayout\nfrom kivy.lang import Builder\n\nBuilder.load_string('''\n<Container>:\n Button:\n background_normal: ''\n background_color: 0.5, 0, 1, .5\n size_hint: 0.3, 0.3\n pos_hint: {'center_x' : 0.5 , 'center_y':0.5}\n text:'Push'\n color: 0,1,0.5,1\n # self argument here will be the button object\n on_release: app.button_callback(self)\n''')\n\n\nclass Container(FloatLayout):\n pass\n\n\nclass MyApp(App):\n\n def button_callback(self, my_button):\n print(my_button.text)\n self.count += 1\n my_button.text = f\"on_release {self.count}\"\n\n def build(self):\n self.count = 0\n return Container()\n\n\nif __name__=='__main__':\n MyApp().run()\n\n" ]
[ 0 ]
[]
[]
[ "kivy", "python", "ubuntu" ]
stackoverflow_0074673204_kivy_python_ubuntu.txt
Q: Flutter: Changing the current tab in tab bar view using a button I am creating an app that contains a tab bar on its homepage. I want to be able to navigate to one of the tabs using my FloatingActionButton. In addition, I want to keep the default methods of navigating to that tab, i.e. by swiping on screen or by clicking the tab. I also want to know how to link that tab to some other button. Here is a screenshot of my homepage. A: You need to get the TabBar controller and call its animateTo() method from the button onPressed() handle. import 'package:flutter/material.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', home: new MyTabbedPage(), ); } } class MyTabbedPage extends StatefulWidget { const MyTabbedPage({Key key}) : super(key: key); @override _MyTabbedPageState createState() => new _MyTabbedPageState(); } class _MyTabbedPageState extends State<MyTabbedPage> with SingleTickerProviderStateMixin { final List<Tab> myTabs = <Tab>[ new Tab(text: 'LEFT'), new Tab(text: 'RIGHT'), ]; TabController _tabController; @override void initState() { super.initState(); _tabController = new TabController(vsync: this, length: myTabs.length); } @override void dispose() { _tabController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text("Tab demo"), bottom: new TabBar( controller: _tabController, tabs: myTabs, ), ), body: new TabBarView( controller: _tabController, children: myTabs.map((Tab tab) { return new Center(child: new Text(tab.text)); }).toList(), ), floatingActionButton: new FloatingActionButton( onPressed: () => _tabController.animateTo((_tabController.index + 1) % 2), // Switch tabs child: new Icon(Icons.swap_horiz), ), ); } } If you use a GlobalKey for the MyTabbedPageState you can get the controller from any place, so you can call the animateTo() from any button. class MyApp extends StatelessWidget { static final _myTabbedPageKey = new GlobalKey<_MyTabbedPageState>(); @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', home: new MyTabbedPage( key: _myTabbedPageKey, ), ); } } You could call it from anywhere doing: MyApp._myTabbedPageKey.currentState._tabController.animateTo(...); A: I am super late, but hopefully someone benefits from this. just add this line to your onPressed of your button and make sure to change the index number to your preferred index: DefaultTabController.of(context).animateTo(1); A: You can use TabController: TabController _controller = TabController( vsync: this, length: 3, initialIndex: 0, ); _controller.animateTo(_currentTabIndex); return Scaffold( appBar: AppBar( bottom: TabBar( controller: _controller, tabs: [ ... ], ), ), body: TabBarView( controller: _controller, children: [ ... ], ), ); And than, setState to update screen: int _currentTabIndex = 0; setState(() { _currentTabIndex = 1; }); A: chemamolin's answer above is correct, but for additional clarification/tip, if you want to call your tabcontroller "from anywhere", also make sure the tabcontroller is not a private property of the class by removing the underscore, otherwise the distant class will not be able to see the tabcontroller with the example provided even when using the GlobalKey. In other words, change TabController _tabController; to: TabController tabController; and change MyApp._myTabbedPageKey.currentState._tabController.animateTo(...); to: MyApp._myTabbedPageKey.currentState.tabController.animateTo(...); and everywhere else you reference tabcontroller. A: If you want to jump to a specific page, you can use PageController.jumpToPage(int) However if you need animation, you'd use PageController.animateToPage(page, duration: duration, curve: curve) Simple example demonstrating it. // create a PageController final _controller = PageController(); bool _shouldAnimate = true; // whether we animate or jump @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), floatingActionButton: FloatingActionButton( onPressed: () { if (_shouldAnimate) { // animates to page1 with animation _controller.animateToPage(1, duration: Duration(seconds: 1), curve: Curves.easeOut); } else { // jump to page1 without animation _controller.jumpToPage(1); } }, ), body: PageView( controller: _controller, // assign it to PageView children: <Widget>[ FlutterLogo(colors: Colors.orange), // page0 FlutterLogo(colors: Colors.green), // page1 FlutterLogo(colors: Colors.red), // page2 ], ), ); } A: DefaultTabController( length: 4, initialIndex: 0, child: TabBar( tabs: [ Tab( child: Text( "People", style: TextStyle( color: Colors.black, ), ), ), Tab( child: Text( "Events", style: TextStyle( color: Colors.black, ), ), ), Tab( child: Text( "Places", style: TextStyle( color: Colors.black, ), ), ), Tab( child: Text( "HashTags", style: TextStyle( color: Colors.black, ), ), ), ], ), ) A: i was trying to solve similar issue but passing methods or controllers down the widget tree wasn't a clean option for me. i had requirement to go back to tabbed page from other non-tabbed routes (back to specific tabs). following solution worked for me Inside tabbed page: read route arguments @override Widget build(BuildContext context) { final String? tabId = Get.arguments; _selectedTabIndex = tabId !=null? int.parse(tabId): 0; return Scaffold( .... body: _pages[_selectedPageIndex]['page'] as Widget, bottomNavigationBar: BottomNavigationBar( onTap: _selectPage, ....); } Now the calling page onSubmit:() { // or some other event // do something here Get.offAndToNamed(Routes.homeTabs, arguments: TabIndex.specialTab.index.toString()); //Routes is a const & TabIndex is enum defined somewhere } A: A solution with TabController + Streams Pass a stream into the state object. Pass the new tab index through the stream for the state to update itself. Here's how I'm doing it. import 'package:flutter/material.dart'; class TabsWidget extends StatefulWidget { const TabsWidget({Key? key, this.tabs = const [], this.changeReceiver}) : super(key: key); final List<Tab> tabs; // To change the tab from outside, pass in the tab index through a stream final Stream<int>? changeReceiver; @override State<TabsWidget> createState() => _TabsWidgetState(); } class _TabsWidgetState extends State<TabsWidget> with SingleTickerProviderStateMixin { int _index = 0; late TabController _tabController; @override void initState() { _tabController = TabController(length: widget.tabs.length, vsync: this, initialIndex: _index); // Listen to tab index changes from external sources via this stream widget.changeReceiver?.listen((int newIndex) { setState(() { _index = newIndex; _tabController.animateTo(newIndex); }); }); super.initState(); } @override Widget build(BuildContext context) { if (widget.tabs.isEmpty) return const SizedBox.shrink(); // If no tabs, show nothing return TabBar(tabs: widget.tabs, controller: _tabController, ); } } // Sample usage - main import 'dart:async'; import 'package:flutter/material.dart'; import 'tabs_widget.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { final StreamController<int> tabChangeNotifier = StreamController(); @override Widget build(BuildContext context) { return MaterialApp( title: 'Tab Change Demo', home: Scaffold( appBar: AppBar( title: const Text('Tab Change Demo'), ), body: SingleChildScrollView(child: Column( children: [ const SizedBox(height: 30,), Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ ElevatedButton(onPressed: () => tabChangeNotifier.add(0), child: const Text('Go Orange')), ElevatedButton(onPressed: () => tabChangeNotifier.add(1), child: const Text('Go Red')), ElevatedButton(onPressed: () => tabChangeNotifier.add(2), child: const Text('Go Green')), ],), const SizedBox(height: 30,), TabsWidget(changeReceiver: tabChangeNotifier.stream, tabs: const [ Tab(icon: Icon(Icons.circle, color: Colors.orange,),), Tab(icon: Icon(Icons.circle, color: Colors.red,),), Tab(icon: Icon(Icons.circle, color: Colors.green,),), ],), ], ),), // This trailing comma makes auto-formatting nicer for build methods. ), ); } @override void dispose() { tabChangeNotifier.close(); super.dispose(); } } This is how the above sample looks. A: Use DefaultTabController instead of a local TabController, high enough in your widget tree, and then you'll have access to it from anywhere in that sub tree. Widget build(BuildContext context) { return DefaultTabController( initialIndex: initialIndex, length: tabs.length, child: SizedBox( // From here down you have access to the tab controller width: double.infinity, child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ SomeWidget(), // Has access to the controller TabBar( controller: DefaultTabController.of(context), tabs: tabs.map((tab) => Tab(child: Text(tab.title, style: const TextStyle(color: Colors.black)))).toList(), ), Expanded( child: TabBarView( controller: DefaultTabController.of(context), children: tabs.map((tab) => tab.widget).toList(), ), ), ], ), ), ); } In any point in that tree, you can access the tab controller with DefaultTabController.of(context) and change the tab, like so: DefaultTabController.of(context)?.animateTo(0);
Flutter: Changing the current tab in tab bar view using a button
I am creating an app that contains a tab bar on its homepage. I want to be able to navigate to one of the tabs using my FloatingActionButton. In addition, I want to keep the default methods of navigating to that tab, i.e. by swiping on screen or by clicking the tab. I also want to know how to link that tab to some other button. Here is a screenshot of my homepage.
[ "You need to get the TabBar controller and call its animateTo() method from the button onPressed() handle.\nimport 'package:flutter/material.dart';\n\nvoid main() => runApp(new MyApp());\n\nclass MyApp extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return new MaterialApp(\n title: 'Flutter Demo',\n home: new MyTabbedPage(),\n );\n }\n}\n\nclass MyTabbedPage extends StatefulWidget {\n const MyTabbedPage({Key key}) : super(key: key);\n\n @override\n _MyTabbedPageState createState() => new _MyTabbedPageState();\n}\n\nclass _MyTabbedPageState extends State<MyTabbedPage> with SingleTickerProviderStateMixin {\n final List<Tab> myTabs = <Tab>[\n new Tab(text: 'LEFT'),\n new Tab(text: 'RIGHT'),\n ];\n\n TabController _tabController;\n\n @override\n void initState() {\n super.initState();\n _tabController = new TabController(vsync: this, length: myTabs.length);\n }\n\n @override\n void dispose() {\n _tabController.dispose();\n super.dispose();\n }\n\n @override\n Widget build(BuildContext context) {\n return new Scaffold(\n appBar: new AppBar(\n title: new Text(\"Tab demo\"),\n bottom: new TabBar(\n controller: _tabController,\n tabs: myTabs,\n ),\n ),\n body: new TabBarView(\n controller: _tabController,\n children: myTabs.map((Tab tab) {\n return new Center(child: new Text(tab.text));\n }).toList(),\n ),\n floatingActionButton: new FloatingActionButton(\n onPressed: () => _tabController.animateTo((_tabController.index + 1) % 2), // Switch tabs\n child: new Icon(Icons.swap_horiz),\n ),\n );\n }\n}\n\nIf you use a GlobalKey for the MyTabbedPageState you can get the controller from any place, so you can call the animateTo() from any button.\nclass MyApp extends StatelessWidget {\n static final _myTabbedPageKey = new GlobalKey<_MyTabbedPageState>();\n\n @override\n Widget build(BuildContext context) {\n return new MaterialApp(\n title: 'Flutter Demo',\n home: new MyTabbedPage(\n key: _myTabbedPageKey,\n ),\n );\n }\n}\n\nYou could call it from anywhere doing:\nMyApp._myTabbedPageKey.currentState._tabController.animateTo(...);\n", "I am super late, but hopefully someone benefits from this. just add this line to your onPressed of your button and make sure to change the index number to your preferred index:\nDefaultTabController.of(context).animateTo(1);\n\n", "You can use TabController:\nTabController _controller = TabController(\n vsync: this,\n length: 3,\n initialIndex: 0,\n);\n\n_controller.animateTo(_currentTabIndex);\n\nreturn Scaffold(\n appBar: AppBar(\n bottom: TabBar(\n controller: _controller,\n tabs: [\n ...\n ],\n ),\n ),\n body: TabBarView(\n controller: _controller,\n children: [\n ...\n ],\n ),\n);\n\nAnd than, setState to update screen:\nint _currentTabIndex = 0;\n\nsetState(() {\n _currentTabIndex = 1;\n});\n\n", "chemamolin's answer above is correct, but for additional clarification/tip, if you want to call your tabcontroller \"from anywhere\", also make sure the tabcontroller is not a private property of the class by removing the underscore, otherwise the distant class will not be able to see the tabcontroller with the example provided even when using the GlobalKey. \nIn other words, change \nTabController _tabController;\n\nto: \nTabController tabController;\n\nand change \nMyApp._myTabbedPageKey.currentState._tabController.animateTo(...);\n\nto: \nMyApp._myTabbedPageKey.currentState.tabController.animateTo(...);\n\nand everywhere else you reference tabcontroller.\n", "If you want to jump to a specific page, you can use \nPageController.jumpToPage(int)\n\nHowever if you need animation, you'd use\nPageController.animateToPage(page, duration: duration, curve: curve)\n\n\nSimple example demonstrating it. \n// create a PageController\nfinal _controller = PageController();\nbool _shouldAnimate = true; // whether we animate or jump\n\n@override\nWidget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(),\n floatingActionButton: FloatingActionButton(\n onPressed: () {\n if (_shouldAnimate) {\n // animates to page1 with animation\n _controller.animateToPage(1, duration: Duration(seconds: 1), curve: Curves.easeOut); \n } else {\n // jump to page1 without animation\n _controller.jumpToPage(1);\n }\n },\n ),\n body: PageView(\n controller: _controller, // assign it to PageView\n children: <Widget>[\n FlutterLogo(colors: Colors.orange), // page0\n FlutterLogo(colors: Colors.green), // page1\n FlutterLogo(colors: Colors.red), // page2\n ],\n ),\n );\n}\n\n", "DefaultTabController(\n length: 4,\n initialIndex: 0,\n child: TabBar(\n tabs: [\n Tab(\n child: Text(\n \"People\",\n style: TextStyle(\n color: Colors.black,\n ),\n ),\n ),\n Tab(\n child: Text(\n \"Events\",\n style: TextStyle(\n color: Colors.black,\n ),\n ),\n ),\n Tab(\n child: Text(\n \"Places\",\n style: TextStyle(\n color: Colors.black,\n ),\n ),\n ),\n Tab(\n child: Text(\n \"HashTags\",\n style: TextStyle(\n color: Colors.black,\n ),\n ),\n ),\n ],\n ),\n )\n\n", "i was trying to solve similar issue but passing methods or controllers down the widget tree wasn't a clean option for me. i had requirement to go back to tabbed page from other non-tabbed routes (back to specific tabs).\nfollowing solution worked for me\nInside tabbed page: read route arguments\n@override\n Widget build(BuildContext context) {\n final String? tabId = Get.arguments;\n \n _selectedTabIndex = tabId !=null? int.parse(tabId): 0;\n\n return Scaffold(\n ....\n body: _pages[_selectedPageIndex]['page'] as Widget,\n bottomNavigationBar: BottomNavigationBar(\n onTap: _selectPage,\n ....);\n\n}\n\nNow the calling page\nonSubmit:() { // or some other event\n // do something here\n\n Get.offAndToNamed(Routes.homeTabs,\n arguments: TabIndex.specialTab.index.toString());\n //Routes is a const & TabIndex is enum defined somewhere\n}\n\n", "A solution with TabController + Streams\nPass a stream into the state object. Pass the new tab index through the stream for the state to update itself. Here's how I'm doing it.\nimport 'package:flutter/material.dart';\n\nclass TabsWidget extends StatefulWidget {\n const TabsWidget({Key? key, this.tabs = const [], this.changeReceiver}) : super(key: key);\n final List<Tab> tabs;\n\n // To change the tab from outside, pass in the tab index through a stream\n final Stream<int>? changeReceiver;\n\n @override\n State<TabsWidget> createState() => _TabsWidgetState();\n}\n\nclass _TabsWidgetState extends State<TabsWidget> with SingleTickerProviderStateMixin {\n int _index = 0;\n late TabController _tabController;\n\n @override\n void initState() {\n _tabController = TabController(length: widget.tabs.length, vsync: this, initialIndex: _index);\n\n // Listen to tab index changes from external sources via this stream\n widget.changeReceiver?.listen((int newIndex) {\n setState(() {\n _index = newIndex;\n _tabController.animateTo(newIndex);\n });\n });\n super.initState();\n }\n\n @override\n Widget build(BuildContext context) {\n if (widget.tabs.isEmpty) return const SizedBox.shrink(); // If no tabs, show nothing\n return TabBar(tabs: widget.tabs, controller: _tabController, );\n }\n}\n\n// Sample usage - main\nimport 'dart:async';\n\nimport 'package:flutter/material.dart';\nimport 'tabs_widget.dart';\n\nvoid main() {\n runApp(const MyApp());\n}\n\nclass MyApp extends StatefulWidget {\n const MyApp({Key? key}) : super(key: key);\n\n @override\n State<MyApp> createState() => _MyAppState();\n}\n\nclass _MyAppState extends State<MyApp> {\n final StreamController<int> tabChangeNotifier = StreamController();\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n title: 'Tab Change Demo',\n home: Scaffold(\n appBar: AppBar(\n title: const Text('Tab Change Demo'),\n ),\n body: SingleChildScrollView(child: Column(\n children: [\n const SizedBox(height: 30,),\n Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [\n ElevatedButton(onPressed: () => tabChangeNotifier.add(0), child: const Text('Go Orange')),\n ElevatedButton(onPressed: () => tabChangeNotifier.add(1), child: const Text('Go Red')),\n ElevatedButton(onPressed: () => tabChangeNotifier.add(2), child: const Text('Go Green')),\n ],),\n const SizedBox(height: 30,),\n TabsWidget(changeReceiver: tabChangeNotifier.stream, tabs: const [\n Tab(icon: Icon(Icons.circle, color: Colors.orange,),),\n Tab(icon: Icon(Icons.circle, color: Colors.red,),),\n Tab(icon: Icon(Icons.circle, color: Colors.green,),),\n ],),\n ],\n ),), // This trailing comma makes auto-formatting nicer for build methods.\n ),\n );\n }\n\n @override\n void dispose() {\n tabChangeNotifier.close();\n super.dispose();\n }\n}\n\nThis is how the above sample looks.\n\n", "Use DefaultTabController instead of a local TabController, high enough in your widget tree, and then you'll have access to it from anywhere in that sub tree.\nWidget build(BuildContext context) {\nreturn DefaultTabController(\n initialIndex: initialIndex,\n length: tabs.length,\n child: SizedBox( // From here down you have access to the tab controller\n width: double.infinity,\n child: Column(\n mainAxisSize: MainAxisSize.max,\n mainAxisAlignment: MainAxisAlignment.start,\n crossAxisAlignment: CrossAxisAlignment.start,\n children: [\n SomeWidget(), // Has access to the controller\n TabBar(\n controller: DefaultTabController.of(context),\n tabs:\n tabs.map((tab) => Tab(child: Text(tab.title, style: const TextStyle(color: Colors.black)))).toList(),\n ),\n Expanded(\n child: TabBarView(\n controller: DefaultTabController.of(context),\n children: tabs.map((tab) => tab.widget).toList(),\n ),\n ),\n ],\n ),\n ),\n);\n\n}\nIn any point in that tree, you can access the tab controller with DefaultTabController.of(context) and change the tab, like so:\nDefaultTabController.of(context)?.animateTo(0);\n\n" ]
[ 93, 52, 10, 5, 2, 1, 0, 0, 0 ]
[ "class Tab bar\n\n class TabBarScreen extends StatefulWidget {\n TabBarScreen({Key key}) : super(key: key);\n \n @override\n _TabBarScreenState createState() => _TabBarScreenState();\n }\n \n final List<Tab> tabs = <Tab>[\n Tab(text: 'Page1'),\n Tab(text: 'Page2'),\n ];\n \n class _TabBarScreenState extends State<TabBarScreen> with SingleTickerProviderStateMixin {\n \n TabController tabController;\n \n @override\n void initState() {\n super.initState();\n tabController = new TabController(vsync: this, length: tabs.length);\n }\n \n @override\n void dispose() {\n tabController.dispose();\n super.dispose();\n }\n \n @override\n Widget build(BuildContext context) {\n return DefaultTabController(\n length: 2,\n child: Scaffold(\n backgroundColor: Theme.of(context).primaryColor,\n appBar: AppBar(\n backgroundColor: Theme.of(context).primaryColor,\n centerTitle: true,\n shape: Border(bottom: BorderSide(color: Colors.white)),\n title: Text(\"Tab Bar\",),\n bottom: TabBar(\n controller: tabController,\n tabs: tabs,\n indicatorWeight: 5,\n indicatorColor: Colors.white,\n labelColor: Colors.white,\n ),\n ),\n body: TabBarView(\n controller: tabController,\n children: [\n PageOneScreen(controller: tabController),\n PageTwoScreen(controller: tabController),\n ],\n ),\n ),\n );\n }\n }\n\nclass PageOne\n\n class PageOneScreen extends StatefulWidget {\n @override\n _PageOneScreenState createState() => _PageOneScreenState();\n\n PageOneScreen({controller}) {\n tabController = controller;\n }\n }\n\n TabController tabController;\n\n class _PageOneScreenState extends State<PageOneScreen> {\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n RaisedButton(\n onPressed: () {\n tabController.animateTo(1); // number : index page\n },\n child: Text(\n \"Go To Page 2\",\n ),\n ),\n ],\n );\n }\n }\n\n" ]
[ -1 ]
[ "dart", "flutter" ]
stackoverflow_0050887790_dart_flutter.txt
Q: Async function inside useEffect return undefined I have an async function inside useEffect useEffect(() => { async function fetchData() { const res = await checkLogin(); console.log(res); } fetchData(); }, []); checkLogin returning "Hello world" async function checkLogin() { try { const resp = await linstance.get("/api/auth/user"); setUser(resp.data.user); setEmail(resp.data.email); setId(resp.data.id); return "Hello world"; } catch (error) { return error.response; } } why in the console.log it's print undefined? I want checkLogin response to be "Hello world" (to make it clear) A: Inside checkLogin() your code has try/catch. If try block run successfully, you would get "Hello world" in the console. But most likely your code is falling into the catch block. it is throwing error and error object has no response property. In the catch block catch (error) { // check what is logging here console.log("error in fetchLogin", error) return error.response; }
Async function inside useEffect return undefined
I have an async function inside useEffect useEffect(() => { async function fetchData() { const res = await checkLogin(); console.log(res); } fetchData(); }, []); checkLogin returning "Hello world" async function checkLogin() { try { const resp = await linstance.get("/api/auth/user"); setUser(resp.data.user); setEmail(resp.data.email); setId(resp.data.id); return "Hello world"; } catch (error) { return error.response; } } why in the console.log it's print undefined? I want checkLogin response to be "Hello world" (to make it clear)
[ "Inside checkLogin() your code has try/catch. If try block run successfully, you would get \"Hello world\" in the console.\nBut most likely your code is falling into the catch block. it is throwing error and error object has no response property. In the catch block\n catch (error) {\n // check what is logging here\n console.log(\"error in fetchLogin\", error)\n return error.response;\n}\n\n" ]
[ 2 ]
[ "It looks like you're trying to use the fetchData function inside the useEffect hook, but you're not returning it. The useEffect hook expects the function you pass to it to return a cleanup function, or nothing at all.\nYou can fix this by either returning the fetchData function from the useEffect hook, or by making the fetchData function itself a callback that gets passed to useEffect directly. Here's an example of how you could do that:\nuseEffect(() => {\n async function fetchData() {\n const res = await checkLogin();\n console.log(res);\n }\n\n // Call the fetchData function directly\n fetchData();\n}, []);\n\nAlternatively, you could return the fetchData function from the useEffect hook like this:\nuseEffect(() => {\nasync function fetchData() {\nconst res = await checkLogin();\nconsole.log(res);\n\n}\n// Return the fetchData function so it can be used as a cleanup function\nreturn fetchData;\n}, []);\nEither of these approaches should allow you to see the output from the checkLogin function in the console.\n" ]
[ -1 ]
[ "async_await", "next.js", "react_hooks", "reactjs", "try_catch" ]
stackoverflow_0074678352_async_await_next.js_react_hooks_reactjs_try_catch.txt
Q: My terminal in VS Code is not working and shows History restored *** or/and just blank, how to make my terminal work again? The problem occured while trying to commit my code in GitHub as I forgot to pass the message -m, The code/page got committed but after that my Code terminal never worked again. I tried to solve the terminal by different commands in cmd and powershell as well tried to change the vs code settings, also uninstalled and re-installed the app.I was expecting trminal to be reset to default or at least diplay something, still no any changes.
My terminal in VS Code is not working and shows History restored *** or/and just blank, how to make my terminal work again?
The problem occured while trying to commit my code in GitHub as I forgot to pass the message -m, The code/page got committed but after that my Code terminal never worked again. I tried to solve the terminal by different commands in cmd and powershell as well tried to change the vs code settings, also uninstalled and re-installed the app.I was expecting trminal to be reset to default or at least diplay something, still no any changes.
[]
[]
[ "Check your user settings. Review these terminal.integrated settings that could affect the launch:\n1.terminal.integrated.defaultProfile.{platform} - The default shell profile that the terminal uses.\n2.terminal.integrated.profiles.{platform} - The defined shell profiles. Sets the shell path and arguments.\n3.terminal.integrated.cwd - The current working directory (cwd) for the shell process.\n4.terminal.integrated.env.{platform} - Environment variables that will be added to the shell process.\n5.terminal.integrated.inheritEnv - Whether new shells should inherit their environment from VS Code.\n6.terminal.integrated.automationProfile.{platform} - Shell profile for automation-related terminal usage like tasks and debug.\n7.terminal.integrated.splitCwd - Controls the current working directory a split terminal starts with.\n8.terminal.integrated.windowsEnableConpty - Whether to use ConPTY for Windows terminal process communication.\n" ]
[ -1 ]
[ "git", "git_commit", "github", "terminal", "visual_studio_code" ]
stackoverflow_0074673421_git_git_commit_github_terminal_visual_studio_code.txt
Q: Power Query does not find HTML table I want to read an HTML table via an internal web page, but it is not recognized in Power Query Navigator in Excel, nor is it recognized in Power BI. I have also tried the Web.contents method, unfortunately, this is not recognized by my Power Query. What other possibilities would I have to create a Power Query on this HTML table? A: This is the definitive video for retrieving data from the web in PQ when the standard GUI options don't give you what you want. https://www.youtube.com/watch?v=KVnhUvapQFc
Power Query does not find HTML table
I want to read an HTML table via an internal web page, but it is not recognized in Power Query Navigator in Excel, nor is it recognized in Power BI. I have also tried the Web.contents method, unfortunately, this is not recognized by my Power Query. What other possibilities would I have to create a Power Query on this HTML table?
[ "This is the definitive video for retrieving data from the web in PQ when the standard GUI options don't give you what you want.\nhttps://www.youtube.com/watch?v=KVnhUvapQFc\n" ]
[ 0 ]
[]
[]
[ "excel", "html", "html_table", "powerquery" ]
stackoverflow_0074678426_excel_html_html_table_powerquery.txt
Q: How to call a child class method C# I have a base class and a child class, in the latter there is a method that is not present in the base class. Having several child classes with different methods, I need to declare an array of the type of the base class, but this way I cannot call the methods of the child classes. Here's my code: Base class public class Athlete{ protected string name; public Athlete(string n) { this.name=n; } } Child Class public class Swimmer:Athlete{ string team; public Swimmer(string n, string t):Base(string n) { this.team=t; } public string Swim() { return "I'm swimming!!!!" ; } } Program Athete test = New Swimmer("John","Tigers"); Console.WriteLine(test.Swim()); //Error!! How can I solve this? Thanks in advance to anyone that will help me. A: You're not setting the value of Athlete correctly. It shouldn't pass the type, only the value to initialise the base class. In addition, you're using Base (uppercase B), which in my experience is used to mark a constructor as the "base" constructor in the class, when you have more than on constructor in your class. To set the values of the parent object, you should use base(val) (lowercase) Try changing the constructor signature of Swimmer to the following: public Swimmer(string n, string t) : base(n) { this.team = t; } This will correctly pass the value of n to the constructor of Athlete for you. Full Code: internal class Program { static void Main(string[] arge) { Swimmer s = new Swimmer("Nick", "My Team"); Console.WriteLine(s.Swim()); } } public class Athlete { protected string name; public Athlete(string n) { this.name = n; } } public class Swimmer : Athlete { string team; public Swimmer(string n, string t) : base(n) { this.team = t; } public string Swim() { return "I'm swimming!!!!"; } }
How to call a child class method C#
I have a base class and a child class, in the latter there is a method that is not present in the base class. Having several child classes with different methods, I need to declare an array of the type of the base class, but this way I cannot call the methods of the child classes. Here's my code: Base class public class Athlete{ protected string name; public Athlete(string n) { this.name=n; } } Child Class public class Swimmer:Athlete{ string team; public Swimmer(string n, string t):Base(string n) { this.team=t; } public string Swim() { return "I'm swimming!!!!" ; } } Program Athete test = New Swimmer("John","Tigers"); Console.WriteLine(test.Swim()); //Error!! How can I solve this? Thanks in advance to anyone that will help me.
[ "You're not setting the value of Athlete correctly. It shouldn't pass the type, only the value to initialise the base class. In addition, you're using Base (uppercase B), which in my experience is used to mark a constructor as the \"base\" constructor in the class, when you have more than on constructor in your class. To set the values of the parent object, you should use base(val) (lowercase)\nTry changing the constructor signature of Swimmer to the following:\npublic Swimmer(string n, string t) : base(n)\n{\n this.team = t;\n}\n\nThis will correctly pass the value of n to the constructor of Athlete for you.\nFull Code:\ninternal class Program\n{\n static void Main(string[] arge)\n {\n Swimmer s = new Swimmer(\"Nick\", \"My Team\");\n Console.WriteLine(s.Swim());\n }\n} \n\npublic class Athlete\n{\n protected string name;\n\n public Athlete(string n)\n {\n this.name = n;\n }\n}\n\npublic class Swimmer : Athlete\n{\n string team;\n\n public Swimmer(string n, string t) : base(n)\n {\n this.team = t;\n }\n public string Swim()\n {\n return \"I'm swimming!!!!\";\n }\n}\n\n" ]
[ 0 ]
[ "//base class\npublic class Athlete\n{\n protected string name;\n\n public Athlete(string n)\n {\n name = n;\n }\n}\n// child class\npublic class Swimmer : Athlete\n{\n string team;\n\n public Swimmer(string n, string t) : base(n)\n {\n this.team = t;\n }\n\n public string Swim()\n {\n return \"I'm swimming!!!!\";\n }\n}\n\n//program main method\n Athlete test = new Swimmer(\"John\", \"Tigers\");\n if (test is Swimmer) {\n var swimmer = test as Swimmer;\n Console.WriteLine(swimmer.Swim());\n }\n\n", "I found the solution:\n//program\nConsole.WriteLine(((Swimmer)test).Swim());\n\n" ]
[ -1, -1 ]
[ "c#", "inheritance", "oop" ]
stackoverflow_0074678233_c#_inheritance_oop.txt
Q: pickle data was truncated i created a corpus file then stored in a pickle file. my messages file is a collection of different news articles dataframe. from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer import re ps = PorterStemmer() corpus = [] for i in range(0, len(messages)): review = re.sub('[^a-zA-Z]', ' ', messages['text'][i]) review = review.lower() review = review.split() review = [ps.stem(word) for word in review if not word in stopwords.words('english')] review = ' '.join(review) #print(i) corpus.append(review) import pickle with open('corpus.pkl', 'wb') as f: pickle.dump(corpus, f) same code I ran on my laptop (jupyter notebook) and on google colab. corpus.pkl => Google colab, downloaded with the following code: from google.colab import files files.download('corpus.pkl') corpus1.pkl => saved from jupyter notebook code. now When I run this code: import pickle with open('corpus.pkl', 'rb') as f: # google colab corpus = pickle.load(f) I get the following error: UnpicklingError: pickle data was truncated But this works fine: import pickle with open('corpus1.pkl', 'rb') as f: # jupyter notebook saved corpus = pickle.load(f) The only difference between both is that corpus1.pkl is run and saved through Jupyter notebook (on local) and corpus.pkl is saved on google collab and downloaded. Could anybody tell me why is this happening? for reference.. corpus.pkl => 36 MB corpus1.pkl => 50.5 MB A: i would use pickle file created by my local machine only, that works properly A: problem occurs due to partial download of glove vectors i have uploaded the data through colab upload to session storage and after that simply write this command it works very well. with open('/content/glove_vectors', 'rb') as f: model = pickle.load(f) glove_words = set(model.keys())
pickle data was truncated
i created a corpus file then stored in a pickle file. my messages file is a collection of different news articles dataframe. from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer import re ps = PorterStemmer() corpus = [] for i in range(0, len(messages)): review = re.sub('[^a-zA-Z]', ' ', messages['text'][i]) review = review.lower() review = review.split() review = [ps.stem(word) for word in review if not word in stopwords.words('english')] review = ' '.join(review) #print(i) corpus.append(review) import pickle with open('corpus.pkl', 'wb') as f: pickle.dump(corpus, f) same code I ran on my laptop (jupyter notebook) and on google colab. corpus.pkl => Google colab, downloaded with the following code: from google.colab import files files.download('corpus.pkl') corpus1.pkl => saved from jupyter notebook code. now When I run this code: import pickle with open('corpus.pkl', 'rb') as f: # google colab corpus = pickle.load(f) I get the following error: UnpicklingError: pickle data was truncated But this works fine: import pickle with open('corpus1.pkl', 'rb') as f: # jupyter notebook saved corpus = pickle.load(f) The only difference between both is that corpus1.pkl is run and saved through Jupyter notebook (on local) and corpus.pkl is saved on google collab and downloaded. Could anybody tell me why is this happening? for reference.. corpus.pkl => 36 MB corpus1.pkl => 50.5 MB
[ "i would use pickle file created by my local machine only, that works properly\n", "problem occurs due to partial download of glove vectors i have uploaded the data\nthrough colab upload to session storage and after that simply write this command\nit works very well.\nwith open('/content/glove_vectors', 'rb') as f:\nmodel = pickle.load(f)\nglove_words = set(model.keys())\n\n" ]
[ 0, 0 ]
[]
[]
[ "data_science", "data_science_experience", "pickle", "python" ]
stackoverflow_0061718355_data_science_data_science_experience_pickle_python.txt
Q: how can i extract last digit from input in java import java.text.BreakIterator; import java.util.*; public class Main { public static void main(String args[]) { Scanner in= new Scanner(System.in); System.out.println("nomber"); int n= in.nextInt(); int s= n*n; int l = (""+s).length(); System.out.println(l); } } how can I extract last digit from input in a simple way. Not so complicated like while loop.... java A: Since last digit is also the remainder of dividing by 10, you can use n % 10. A: The simplest way to extract last digit is modulo to 10. Example: 123 % 10 = 3 After that, if you want to continue to extract last digit (it's 2 in this case), you should assign number = number /10 that will return the remain of the number. // Example n = 123 int lastDigit_1 = n % 10; // This will return 3 n = n /10 // This will return 12 because 123 / 10 = 12 int lastDigit2 = n % 10; // This will return 2 n = n /10 // This will return 1 int lastDigit3 = n % 10; ... To implement the above concept, u should try using while loop for better approach. Using while: while(n != 0){ someVariable = n % 10; // YOUR LOGIC HERE n = n / 10; }
how can i extract last digit from input in java
import java.text.BreakIterator; import java.util.*; public class Main { public static void main(String args[]) { Scanner in= new Scanner(System.in); System.out.println("nomber"); int n= in.nextInt(); int s= n*n; int l = (""+s).length(); System.out.println(l); } } how can I extract last digit from input in a simple way. Not so complicated like while loop.... java
[ "Since last digit is also the remainder of dividing by 10, you can use n % 10.\n", "The simplest way to extract last digit is modulo to 10. Example: 123 % 10 = 3\nAfter that, if you want to continue to extract last digit (it's 2 in this case), you should assign number = number /10 that will return the remain of the number.\n// Example n = 123\nint lastDigit_1 = n % 10; // This will return 3\nn = n /10 // This will return 12 because 123 / 10 = 12\nint lastDigit2 = n % 10; // This will return 2\nn = n /10 // This will return 1\nint lastDigit3 = n % 10;\n... \n\nTo implement the above concept, u should try using while loop for better approach.\nUsing while:\nwhile(n != 0){\n someVariable = n % 10;\n // YOUR LOGIC HERE\n n = n / 10;\n}\n\n" ]
[ 0, 0 ]
[]
[]
[ "java" ]
stackoverflow_0074674960_java.txt
Q: Creating threaded popups in PySimpleGUI I have trouble creating either multiple windows or popups using PySimpleGUI. Each window/popup is supposed to be called from a seperate thread and timeout after 2 seconds. Using following implementation results in (as expected) this error: main thread is not in main loop. How do I fix that? def get_info(): while True: info = get_details() if info: layout[] window = sgWindow(...) while True: event, values = window.read(timeout=1000*2) if event in (sg.WIN_CLOSED,): break if event in ('__TIMEOUT__',): window.close() break if event == "X": window.close() close = True break if event == "Y": window.close() close = True break for i in range(x): t = threading.Thread(target=get_info()) t.start() A: This isn't possible because PySimpleGUI is not thread-safe. This means that you can only use it in the main thread of your program. To fix this error, you can use a queue to communicate between the main thread and the other threads. Each thread can add an event to the queue, and the main thread can read from the queue and handle the events as they come in. This way, you can still use PySimpleGUI in the main thread while running your other code in separate threads. import threading import queue import PySimpleGUI as sg # Create a queue to communicate between threads q = queue.Queue() # Define a function to run in a separate thread def get_info(): while True: # Check if we need to exit the thread if x: break # Create a window and show it layout = [] window = sg.Window('Window', layout) window.finalize() window.show() # Read events from the window while True: event, values = window.read(timeout=1000*2) if event in (sg.WIN_CLOSED,): break if event in ('__TIMEOUT__',): # Add an event to the queue to close the window in the main thread q.put('close_window') break if event == "X": # Add an event to the queue to close the window and set the "close" flag in the main thread q.put('close_window_and_flag') break if event == "Y": # Add an event to the queue to close the window and set the "close" flag in the main thread q.put('close_window_and_flag') break # Start the thread t = threading.Thread(target=get_info()) t.start() # Main loop while True: # Check for events in the queue if not q.empty(): event = q.get() if event == 'close_window': # Close the window in the main thread window.close() elif event == 'close_window_and_flag': # Close the window and set the "close" flag in the main thread window.close() close = True
Creating threaded popups in PySimpleGUI
I have trouble creating either multiple windows or popups using PySimpleGUI. Each window/popup is supposed to be called from a seperate thread and timeout after 2 seconds. Using following implementation results in (as expected) this error: main thread is not in main loop. How do I fix that? def get_info(): while True: info = get_details() if info: layout[] window = sgWindow(...) while True: event, values = window.read(timeout=1000*2) if event in (sg.WIN_CLOSED,): break if event in ('__TIMEOUT__',): window.close() break if event == "X": window.close() close = True break if event == "Y": window.close() close = True break for i in range(x): t = threading.Thread(target=get_info()) t.start()
[ "This isn't possible because PySimpleGUI is not thread-safe. This means that you can only use it in the main thread of your program.\nTo fix this error, you can use a queue to communicate between the main thread and the other threads. Each thread can add an event to the queue, and the main thread can read from the queue and handle the events as they come in. This way, you can still use PySimpleGUI in the main thread while running your other code in separate threads.\nimport threading\nimport queue\nimport PySimpleGUI as sg\n\n# Create a queue to communicate between threads\nq = queue.Queue()\n\n# Define a function to run in a separate thread\ndef get_info():\n while True:\n # Check if we need to exit the thread\n if x:\n break\n \n # Create a window and show it\n layout = []\n window = sg.Window('Window', layout)\n window.finalize()\n window.show()\n \n # Read events from the window\n while True:\n event, values = window.read(timeout=1000*2)\n if event in (sg.WIN_CLOSED,):\n break\n if event in ('__TIMEOUT__',):\n # Add an event to the queue to close the window in the main thread\n q.put('close_window')\n break\n if event == \"X\":\n # Add an event to the queue to close the window and set the \"close\" flag in the main thread\n q.put('close_window_and_flag')\n break\n if event == \"Y\":\n # Add an event to the queue to close the window and set the \"close\" flag in the main thread\n q.put('close_window_and_flag')\n break\n\n# Start the thread\nt = threading.Thread(target=get_info())\nt.start()\n\n# Main loop\nwhile True:\n # Check for events in the queue\n if not q.empty():\n event = q.get()\n if event == 'close_window':\n # Close the window in the main thread\n window.close()\n elif event == 'close_window_and_flag':\n # Close the window and set the \"close\" flag in the main thread\n window.close()\n close = True\n\n" ]
[ 1 ]
[]
[]
[ "multithreading", "pysimplegui", "python", "user_interface" ]
stackoverflow_0074678475_multithreading_pysimplegui_python_user_interface.txt
Q: Async / Await not working with FileReader in Javascript I have a simple file opener: <input type="file" onChange={async (e) => { let importedRows = await importTSVFile(e) console.log(importedRows) }} /> My importTSVFile function looks like this: // CLIENT SIDE FUNCTIONS export const importTSVFile = async (e) => { e.preventDefault(); const reader = new FileReader(); reader.onload = async (e) => { //extracting the rows here let newRows = //.... return newRows }; await reader.readAsText(e.target.files[0]); }; However, I think I am getting something wrong with async/await here. The console.log, which attempts to log the return value of importTSVFile (importedRows), is undefined or a promise. What is it that I am misunderstanding here?
Async / Await not working with FileReader in Javascript
I have a simple file opener: <input type="file" onChange={async (e) => { let importedRows = await importTSVFile(e) console.log(importedRows) }} /> My importTSVFile function looks like this: // CLIENT SIDE FUNCTIONS export const importTSVFile = async (e) => { e.preventDefault(); const reader = new FileReader(); reader.onload = async (e) => { //extracting the rows here let newRows = //.... return newRows }; await reader.readAsText(e.target.files[0]); }; However, I think I am getting something wrong with async/await here. The console.log, which attempts to log the return value of importTSVFile (importedRows), is undefined or a promise. What is it that I am misunderstanding here?
[]
[]
[ "export const importTSVFile = async (e) => {\n e.preventDefault();\n const reader = new FileReader();\n let newRows;\n reader.onload = async (e) => {\n //extracting the rows here\n newRows = //....\n };\n\n reader.readAsText(e.target.files[0]);\n await reader.onload;\n\n return newRows;\n};\n\n" ]
[ -2 ]
[ "async_await", "asynchronous", "filereader", "javascript", "promise" ]
stackoverflow_0074678440_async_await_asynchronous_filereader_javascript_promise.txt
Q: How can I write this sql query in django orm? I have a sql query that works like this, but I couldn't figure out how to write this query in django. Can you help me ? select datetime, array_to_json(array_agg(json_build_object(parameter, raw))) as parameters from dbp_istasyondata group by 1 order by 1; A: You can use raw function of django orm. You can write your query like this: YourModel.objects.raw('select * from your table'): #---> Change the model name and query
How can I write this sql query in django orm?
I have a sql query that works like this, but I couldn't figure out how to write this query in django. Can you help me ? select datetime, array_to_json(array_agg(json_build_object(parameter, raw))) as parameters from dbp_istasyondata group by 1 order by 1;
[ "You can use raw function of django orm. You can write your query like this:\nYourModel.objects.raw('select * from your table'): #---> Change the model name and query\n\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_orm", "python" ]
stackoverflow_0074678065_django_django_models_django_orm_python.txt
Q: isHittable function returns false on iOS16 simulator I have function for scrolling used in my UiTests. Here it is func scroll(_ elementQuery: XCUIElement, to toElementQuery: XCUIElement, direction: Direction, swipesCount: Int) { var swipe = 0 let swipeClosure: () -> Void = { switch direction { case .up: elementQuery.swipeUp() case .left: elementQuery.swipeLeft() case .right: elementQuery.swipeRight() case .down: elementQuery.swipeDown() } swipe += 1 } while !toElementQuery.exists && swipe <= swipesCount { swipeClosure() } if toElementQuery.exists { let elementHittable = toElementQuery.isHittable while !toElementQuery.isHittable && swipe <= swipesCount { swipeClosure() } } if !toElementQuery.exists { XCTFail(errorMessage) } else if !toElementQuery.isHittable { XCTFail(errorMessage) } When I use it on iOS 15 simulators it works great. But after downloading Xcode 14 and iOS 16 simulator toElementQuery.isHittable started to return false, even if tap() working great with this element. When I use simulator < 16 iOS toElementQuery.isHittable returns true A: isHittable returns true if the element has a size and is not blocked by any other iOS accessibility element. Has the display of your app changed between the 2 iOS versions? It could be helpful to add the debugDescription of your XCUIApplication on both iOS versions to help debug this issue.
isHittable function returns false on iOS16 simulator
I have function for scrolling used in my UiTests. Here it is func scroll(_ elementQuery: XCUIElement, to toElementQuery: XCUIElement, direction: Direction, swipesCount: Int) { var swipe = 0 let swipeClosure: () -> Void = { switch direction { case .up: elementQuery.swipeUp() case .left: elementQuery.swipeLeft() case .right: elementQuery.swipeRight() case .down: elementQuery.swipeDown() } swipe += 1 } while !toElementQuery.exists && swipe <= swipesCount { swipeClosure() } if toElementQuery.exists { let elementHittable = toElementQuery.isHittable while !toElementQuery.isHittable && swipe <= swipesCount { swipeClosure() } } if !toElementQuery.exists { XCTFail(errorMessage) } else if !toElementQuery.isHittable { XCTFail(errorMessage) } When I use it on iOS 15 simulators it works great. But after downloading Xcode 14 and iOS 16 simulator toElementQuery.isHittable started to return false, even if tap() working great with this element. When I use simulator < 16 iOS toElementQuery.isHittable returns true
[ "isHittable returns true if the element has a size and is not blocked by any other iOS accessibility element.\nHas the display of your app changed between the 2 iOS versions?\nIt could be helpful to add the debugDescription of your XCUIApplication on both iOS versions to help debug this issue.\n" ]
[ 0 ]
[]
[]
[ "ios", "ios16", "swift", "xctest", "xcuitest" ]
stackoverflow_0074517579_ios_ios16_swift_xctest_xcuitest.txt
Q: Cannot register alias 'elasticsearchTemplate' for name 'elasticsearchOperations': Alias would override bean definition 'elasticsearchTemplate' `java.lang.IllegalStateException: Cannot register alias 'elasticsearchTemplate' for name 'elasticsearchOperations': Alias would override bean definition 'elasticsearchTemplate' at org.springframework.beans.factory.support.DefaultListableBeanFactory.checkForAliasCircle(DefaultListableBeanFactory.java:1142) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.core.SimpleAliasRegistry.registerAlias(SimpleAliasRegistry.java:80) ~[spring-core-5.3.22.jar:5.3.22] at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod(ConfigurationClassBeanDefinitionReader.java:210) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:153) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:129) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:343) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:247) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:311) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:112) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:746) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:564) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.3.jar:2.7.3] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.3.jar:2.7.3] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.3.jar:2.7.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.3.jar:2.7.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.3.jar:2.7.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.3.jar:2.7.3] at com.company.CompanyApp.main(CompanyApp.java:33) ~[classes/:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na] at your textjava.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.7.5.jar:2.7.5] Process finished with exit code 0 ___________________________________________________________________________________________________________ Configuration Class @Component @Configuration @EnableElasticsearchRepositories(basePackages = "com.company") @ComponentScan(basePackages = {"com.company"}) public class ElasticSearchRestClientConfig extends AbstractElasticsearchConfiguration{ @Bean public RestHighLevelClient elasticsearchClient() { ClientConfiguration clientConfiguration = ClientConfiguration.builder() .connectedTo("localhost:9200") .build(); return RestClients.create(clientConfiguration).rest(); } @Bean @Primary public ElasticsearchOperations elasticsearchTemplate() { return new ElasticsearchRestTemplate(elasticsearchClient()); } } There is no way I can do this problem.` A: This error message indicates that the elasticsearchTemplate bean has already been defined in the Spring application context, but you are trying to register it again as an alias with the name elasticsearchOperations. Since a bean can only be defined once in the application context, this operation is not allowed and has thrown an IllegalStateException.
Cannot register alias 'elasticsearchTemplate' for name 'elasticsearchOperations': Alias would override bean definition 'elasticsearchTemplate'
`java.lang.IllegalStateException: Cannot register alias 'elasticsearchTemplate' for name 'elasticsearchOperations': Alias would override bean definition 'elasticsearchTemplate' at org.springframework.beans.factory.support.DefaultListableBeanFactory.checkForAliasCircle(DefaultListableBeanFactory.java:1142) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.core.SimpleAliasRegistry.registerAlias(SimpleAliasRegistry.java:80) ~[spring-core-5.3.22.jar:5.3.22] at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod(ConfigurationClassBeanDefinitionReader.java:210) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:153) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:129) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:343) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:247) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:311) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:112) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:746) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:564) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.3.jar:2.7.3] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.3.jar:2.7.3] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.3.jar:2.7.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.3.jar:2.7.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.3.jar:2.7.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.3.jar:2.7.3] at com.company.CompanyApp.main(CompanyApp.java:33) ~[classes/:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na] at your textjava.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.7.5.jar:2.7.5] Process finished with exit code 0 ___________________________________________________________________________________________________________ Configuration Class @Component @Configuration @EnableElasticsearchRepositories(basePackages = "com.company") @ComponentScan(basePackages = {"com.company"}) public class ElasticSearchRestClientConfig extends AbstractElasticsearchConfiguration{ @Bean public RestHighLevelClient elasticsearchClient() { ClientConfiguration clientConfiguration = ClientConfiguration.builder() .connectedTo("localhost:9200") .build(); return RestClients.create(clientConfiguration).rest(); } @Bean @Primary public ElasticsearchOperations elasticsearchTemplate() { return new ElasticsearchRestTemplate(elasticsearchClient()); } } There is no way I can do this problem.`
[ "This error message indicates that the elasticsearchTemplate bean has already been defined in the Spring application context, but you are trying to register it again as an alias with the name elasticsearchOperations. Since a bean can only be defined once in the application context, this operation is not allowed and has thrown an IllegalStateException.\n" ]
[ 0 ]
[]
[]
[ "elasticsearch", "java" ]
stackoverflow_0074671528_elasticsearch_java.txt
Q: Springboot argument based @Autowired dependency is null I'm new to springboot and fiddling around with DI. I'm having a Service public class GreeterService { private ObjectMapper objectMapper; public GreeterService(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } public String greeting() throws JsonProcessingException { return objectMapper.writeValueAsString(new HelloData()); } } this Service is supposed to be created via @Configuration @Configuration public class Config { @Bean public GreeterService greeterService(@Autowired ObjectMapper objectMapper) { return new GreeterService(objectMapper); } } I get the following exception: java.lang.NullPointerException: Cannot invoke "com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(Object)" because "this.objectMapper" is null also making ObjectMapper @Autowired on a field does not work e.g. @Autowired ObjectMapper objectMapper; @Bean public GreeterService greeterService() { return new GreeterService(objectMapper); } main entry in com.example.demo @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } Controller @GetMapping(path = "methodInject") public Object methodInject(GreeterService greeterService) throws JsonProcessingException { return greeterService.greeting(); } Further info: I added to main System.out.println("Is " + beanName + " in ApplicationContext: " + context.containsBean(beanName)); which returns: Is objectMapper in ApplicationContext: true Is greeterService in ApplicationContext: true A: add to Config @Bean public ObjectMapper objectMapper() { return new ObjectMapper(); } and write a simple test to see all beans in spring context @SpringBootTest class Demo1ApplicationTests { @Autowired ApplicationContext context; @Test void contextLoads() { Arrays.stream(context.getBeanDefinitionNames()).forEach(System.out::println); } } A: The code you pasted seems correct. The problem may be more global. Do you run the whole thing as Spring Boot application (with proper main method)? Do you call your service as spring bean? Service should also be autowired, not just java standard new instance. Are your service and config classes in packages that gets scanned?
Springboot argument based @Autowired dependency is null
I'm new to springboot and fiddling around with DI. I'm having a Service public class GreeterService { private ObjectMapper objectMapper; public GreeterService(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } public String greeting() throws JsonProcessingException { return objectMapper.writeValueAsString(new HelloData()); } } this Service is supposed to be created via @Configuration @Configuration public class Config { @Bean public GreeterService greeterService(@Autowired ObjectMapper objectMapper) { return new GreeterService(objectMapper); } } I get the following exception: java.lang.NullPointerException: Cannot invoke "com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(Object)" because "this.objectMapper" is null also making ObjectMapper @Autowired on a field does not work e.g. @Autowired ObjectMapper objectMapper; @Bean public GreeterService greeterService() { return new GreeterService(objectMapper); } main entry in com.example.demo @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } Controller @GetMapping(path = "methodInject") public Object methodInject(GreeterService greeterService) throws JsonProcessingException { return greeterService.greeting(); } Further info: I added to main System.out.println("Is " + beanName + " in ApplicationContext: " + context.containsBean(beanName)); which returns: Is objectMapper in ApplicationContext: true Is greeterService in ApplicationContext: true
[ "add to Config\n@Bean\npublic ObjectMapper objectMapper() {\n return new ObjectMapper();\n} \n\nand write a simple test to see all beans in spring context\n@SpringBootTest\nclass Demo1ApplicationTests {\n\n @Autowired\n ApplicationContext context;\n\n @Test\n void contextLoads() {\n Arrays.stream(context.getBeanDefinitionNames()).forEach(System.out::println);\n }\n}\n\n\n", "The code you pasted seems correct. The problem may be more global.\nDo you run the whole thing as Spring Boot application (with proper main method)?\nDo you call your service as spring bean? Service should also be autowired, not just java standard new instance.\nAre your service and config classes in packages that gets scanned?\n" ]
[ 0, 0 ]
[]
[]
[ "dependency_injection", "java", "spring", "spring_boot" ]
stackoverflow_0074674513_dependency_injection_java_spring_spring_boot.txt
Q: How to make a movie out of images in python I currently try to make a movie out of images, but i could not find anything helpful . Here is my code so far: import time from PIL import ImageGrab x =0 while True: try: x+= 1 ImageGrab().grab().save('img{}.png'.format(str(x)) except: movie = #Idontknow for _ in range(x): movie.save("img{}.png".format(str(_))) movie.save() A: You could consider using an external tool like ffmpeg to merge the images into a movie (see answer here) or you could try to use OpenCv to combine the images into a movie like the example here. I'm attaching below a code snipped I used to combine all png files from a folder called "images" into a video. import cv2 import os image_folder = 'images' video_name = 'video.avi' images = [img for img in os.listdir(image_folder) if img.endswith(".png")] frame = cv2.imread(os.path.join(image_folder, images[0])) height, width, layers = frame.shape video = cv2.VideoWriter(video_name, 0, 1, (width,height)) for image in images: video.write(cv2.imread(os.path.join(image_folder, image))) cv2.destroyAllWindows() video.release() It seems that the most commented section of this answer is the use of VideoWriter. You can look up it's documentation in the link of this answer (static) or you can do a bit of digging of your own. The first parameter is the filename, followed by an integer (fourcc in the documentation, the codec used), the FPS count and a tuple of the dimensions of the frame. If you really like digging in that can of worms, here's the fourcc video codecs list. A: Thanks , but i found an alternative solution using ffmpeg: def save(): os.system("ffmpeg -r 1 -i img%01d.png -vcodec mpeg4 -y movie.mp4") But thank you for your help :) A: Here is a minimal example using moviepy. For me this was the easiest solution. import os import moviepy.video.io.ImageSequenceClip image_folder='folder_with_images' fps=1 image_files = [os.path.join(image_folder,img) for img in os.listdir(image_folder) if img.endswith(".png")] clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps) clip.write_videofile('my_video.mp4') A: I use the ffmpeg-python binding. You can find more information here. import ffmpeg ( ffmpeg .input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25) .output('movie.mp4') .run() ) A: When using moviepy's ImageSequenceClip it is important that the images are in an ordered sequence. While the documentation states that the frames can be ordered alphanumerically under the hood, I found this not to be the case. So, if you are having problems, make sure to manually order the frames first. A: @Wei Shan Lee (and others): Sure, my whole code looks like this import os import moviepy.video.io.ImageSequenceClip from PIL import Image, ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True image_files = [] for img_number in range(1,20): image_files.append(path_to_images + 'image_folder/image_' + str(img_number) + '.png') fps = 30 clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps) clip.write_videofile(path_to_videos + 'my_new_video.mp4') A: I've created a function to do this. Similar to the first answer (using opencv) but wanted to add that for me, ".mp4" format did not work. That's why I use the raise within the function. import cv2 import typing def write_video(video_path_out:str, frames_sequence:typing.Tuple[np.ndarray,...]): if ".mp4" in video_path_out: raise ValueError("[ERROR] This method does not support .mp4; try .avi instead") height, width, _ = frames_sequence[0].shape # 0 means no preprocesing # 1 means each image will be played with 1 sec delay (1fps) out = cv2.VideoWriter(video_path_out,0, 1,(width,height)) for frame in frames_sequence: out.write(frame) out.release() # you can use as much images as you need, I just use 3 for this example # put your img1_path,img2_path, img3_path img1 = cv2.imread(img1_path) img2 = cv2.imread(img2_path) img3 = cv2.imread(img3_path) # img1 can be cv2.imread out; which is a np.ndarray; you can also se PIL # if you'd like to. frames_sequence = [img1,img2,img3] write_video(video_path_out = "mypath_outvideo.avi", frames_sequence = frames_sequence ) Hope it's useful!
How to make a movie out of images in python
I currently try to make a movie out of images, but i could not find anything helpful . Here is my code so far: import time from PIL import ImageGrab x =0 while True: try: x+= 1 ImageGrab().grab().save('img{}.png'.format(str(x)) except: movie = #Idontknow for _ in range(x): movie.save("img{}.png".format(str(_))) movie.save()
[ "You could consider using an external tool like ffmpeg to merge the images into a movie (see answer here) or you could try to use OpenCv to combine the images into a movie like the example here.\nI'm attaching below a code snipped I used to combine all png files from a folder called \"images\" into a video.\nimport cv2\nimport os\n\nimage_folder = 'images'\nvideo_name = 'video.avi'\n\nimages = [img for img in os.listdir(image_folder) if img.endswith(\".png\")]\nframe = cv2.imread(os.path.join(image_folder, images[0]))\nheight, width, layers = frame.shape\n\nvideo = cv2.VideoWriter(video_name, 0, 1, (width,height))\n\nfor image in images:\n video.write(cv2.imread(os.path.join(image_folder, image)))\n\ncv2.destroyAllWindows()\nvideo.release()\n\nIt seems that the most commented section of this answer is the use of VideoWriter. You can look up it's documentation in the link of this answer (static) or you can do a bit of digging of your own. The first parameter is the filename, followed by an integer (fourcc in the documentation, the codec used), the FPS count and a tuple of the dimensions of the frame. If you really like digging in that can of worms, here's the fourcc video codecs list.\n", "Thanks , but i found an alternative solution using ffmpeg:\ndef save():\n os.system(\"ffmpeg -r 1 -i img%01d.png -vcodec mpeg4 -y movie.mp4\")\n\nBut thank you for your help :) \n", "Here is a minimal example using moviepy. For me this was the easiest solution.\nimport os\nimport moviepy.video.io.ImageSequenceClip\nimage_folder='folder_with_images'\nfps=1\n\nimage_files = [os.path.join(image_folder,img)\n for img in os.listdir(image_folder)\n if img.endswith(\".png\")]\nclip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps)\nclip.write_videofile('my_video.mp4')\n\n", "I use the ffmpeg-python binding. You can find more information here.\nimport ffmpeg\n(\n ffmpeg\n .input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25)\n .output('movie.mp4')\n .run()\n)\n\n", "When using moviepy's ImageSequenceClip it is important that the images are in an ordered sequence.\nWhile the documentation states that the frames can be ordered alphanumerically under the hood, I found this not to be the case.\nSo, if you are having problems, make sure to manually order the frames first.\n", "@Wei Shan Lee (and others): Sure, my whole code looks like this\nimport os\nimport moviepy.video.io.ImageSequenceClip\nfrom PIL import Image, ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\nimage_files = []\n\nfor img_number in range(1,20): \n image_files.append(path_to_images + 'image_folder/image_' + str(img_number) + '.png') \n\nfps = 30\n\nclip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps)\nclip.write_videofile(path_to_videos + 'my_new_video.mp4')\n\n", "I've created a function to do this. Similar to the first answer (using opencv) but wanted to add that for me, \".mp4\" format did not work. That's why I use the raise within the function.\nimport cv2\nimport typing\n\ndef write_video(video_path_out:str,\n frames_sequence:typing.Tuple[np.ndarray,...]):\n \n if \".mp4\" in video_path_out: raise ValueError(\"[ERROR] This method does not support .mp4; try .avi instead\")\n height, width, _ = frames_sequence[0].shape\n # 0 means no preprocesing\n # 1 means each image will be played with 1 sec delay (1fps)\n out = cv2.VideoWriter(video_path_out,0, 1,(width,height))\n for frame in frames_sequence:\n out.write(frame)\n out.release()\n\n# you can use as much images as you need, I just use 3 for this example\n# put your img1_path,img2_path, img3_path\n\nimg1 = cv2.imread(img1_path)\nimg2 = cv2.imread(img2_path)\nimg3 = cv2.imread(img3_path)\n# img1 can be cv2.imread out; which is a np.ndarray; you can also se PIL\n# if you'd like to.\nframes_sequence = [img1,img2,img3]\n\nwrite_video(video_path_out = \"mypath_outvideo.avi\",\nframes_sequence = frames_sequence\n)\n\nHope it's useful!\n" ]
[ 147, 54, 29, 16, 1, 0, 0 ]
[]
[]
[ "image", "python", "screenshot", "video" ]
stackoverflow_0044947505_image_python_screenshot_video.txt
Q: How to detect .click() on disabled checkbox js/jQuery: $('input[type=checkbox]').click(function(){ // Does not fire if I click a <input type="checkbox" disabled="disabled" /> }); How do I make something happend in jQuery when someone clicks a disabled checkbox? A: Reading over the comment again regarding using readonly from JoãoSilva. You could use that and connect it with some logic in the click event. Using readonly gives you the disabled look, just like disabled does but it still lets you click it. Use readonly like this: <input type="checkbox" readonly="readonly">​ Then in your script cancel the event if readonly is set. $('input[type=checkbox]').click(function() { var isReadOnly = $(this).attr("readonly") === undefined ? false : true; if (isReadOnly) { return false; } // other code never executed if readonly is true. }); ​ DEMO A: You will not be able to capture the click event reliably across all browsers. Your best bet is to place a transparent element above to capture the click. HTML <div style="display:inline-block; position:relative;"> <input type="checkbox" disabled="disabled" /> <div style="position:absolute; left:0; right:0; top:0; bottom:0;"></div> </div>​ JavaScript $(':checkbox:disabled').next().click(function(){ var checkbox = $(this.prevNode); // Does fire now :) }); Note: This is an idea from this question which I improved on. A: You can't...but you can fake it by placing a div over the input with a transparent background, and define the click function on that div. $('input').each(function(){ if(true == ($(this).prop('disabled'))){ var iTop = $(this).position().top; var iLeft = $(this).position().left; var iWidth = $(this).width(); var iHeight = $(this).height(); $('body').append('<div class="disabledClick" style="position:absolute;top:'+iTop+'px;left:'+iLeft+'px;width:'+iWidth+'px;height:'+iHeight+'px;background:transparent;"></div>'); } }); //delegate a click function for the 'disabledClick'. $('body').on('click', '.disabledClick', function(){ console.log('This is the click event for the disabled checkbox.'); }); Here's the working jsFiddle A: I see no other option as to add <div> block layer over the checkbox. So the solution should be the following: function addDisabledClickHandler(el, handler) { $("<div />").css({ position: "absolute", top: el.position().top, left: el.position().left, width: el.width(), height: el.height() }).click(handler).appendTo("body"); } var el = $("input[type='checkbox']"); addDisabledClickHandler(el, function() { alert("Clicked"); });​ DEMO: http://jsfiddle.net/q6u64/ A: I actually do this quite often to stop people from changing checkboxes if those changes have already been committed to the database. However, if you want to change it or see a click at least.. then I just wrap the input in a label element and check the child input. HTML : <label class="checkbox-label"> <input class="input-checkbox" type="checkbox" name="declared" disabled checked> </label> JQuery: $('.checkbox-label').on(function (e) { e.stopPropagation(); let checkBox = $(this).find('.input-checkbox'); // if checkbox is disabled, do something if (checkBox.prop('disabled')) { // I usually put some enter password to confirm change... but I know you want to just show a click console.log('click') } else { // your checkbox should act as normal console.log('click') } }) Hope this helps :)
How to detect .click() on disabled checkbox
js/jQuery: $('input[type=checkbox]').click(function(){ // Does not fire if I click a <input type="checkbox" disabled="disabled" /> }); How do I make something happend in jQuery when someone clicks a disabled checkbox?
[ "Reading over the comment again regarding using readonly from JoãoSilva. You could use that and connect it with some logic in the click event.\nUsing readonly gives you the disabled look, just like disabled does but it still lets you click it.\nUse readonly like this:\n<input type=\"checkbox\" readonly=\"readonly\">​\n\nThen in your script cancel the event if readonly is set.\n$('input[type=checkbox]').click(function() {\n var isReadOnly = $(this).attr(\"readonly\") === undefined ? false : true;\n\n if (isReadOnly) {\n return false;\n }\n\n // other code never executed if readonly is true.\n});\n​\n\nDEMO\n", "You will not be able to capture the click event reliably across all browsers. Your best bet is to place a transparent element above to capture the click.\nHTML\n<div style=\"display:inline-block; position:relative;\">\n <input type=\"checkbox\" disabled=\"disabled\" />\n <div style=\"position:absolute; left:0; right:0; top:0; bottom:0;\"></div>\n</div>​\n\nJavaScript\n$(':checkbox:disabled').next().click(function(){\n var checkbox = $(this.prevNode);\n // Does fire now :)\n});\n\nNote: This is an idea from this question which I improved on.\n", "You can't...but you can fake it by placing a div over the input with a transparent background, and define the click function on that div.\n$('input').each(function(){\n if(true == ($(this).prop('disabled'))){\n var iTop = $(this).position().top;\n var iLeft = $(this).position().left;\n var iWidth = $(this).width();\n var iHeight = $(this).height();\n $('body').append('<div class=\"disabledClick\" style=\"position:absolute;top:'+iTop+'px;left:'+iLeft+'px;width:'+iWidth+'px;height:'+iHeight+'px;background:transparent;\"></div>'); \n } \n});\n\n//delegate a click function for the 'disabledClick'.\n\n\n$('body').on('click', '.disabledClick', function(){\n console.log('This is the click event for the disabled checkbox.');\n});\n\nHere's the working jsFiddle\n", "I see no other option as to add <div> block layer over the checkbox. So the solution should be the following:\nfunction addDisabledClickHandler(el, handler) {\n $(\"<div />\").css({\n position: \"absolute\",\n top: el.position().top,\n left: el.position().left,\n width: el.width(),\n height: el.height()\n }).click(handler).appendTo(\"body\");\n}\n\nvar el = $(\"input[type='checkbox']\");\naddDisabledClickHandler(el, function() {\n alert(\"Clicked\");\n});​\n\nDEMO: http://jsfiddle.net/q6u64/\n", "I actually do this quite often to stop people from changing checkboxes if those changes have already been committed to the database. However, if you want to change it or see a click at least.. then I just wrap the input in a label element and check the child input.\nHTML :\n<label class=\"checkbox-label\">\n <input class=\"input-checkbox\" type=\"checkbox\" name=\"declared\" disabled checked>\n</label>\n\nJQuery:\n$('.checkbox-label').on(function (e) {\n e.stopPropagation();\n let checkBox = $(this).find('.input-checkbox');\n\n // if checkbox is disabled, do something\n\n if (checkBox.prop('disabled')) {\n // I usually put some enter password to confirm change... but I know you want to just show a click\n\n console.log('click')\n } else {\n // your checkbox should act as normal\n\n console.log('click')\n }\n})\n\nHope this helps :)\n" ]
[ 13, 9, 1, 0, 0 ]
[]
[]
[ "javascript", "jquery" ]
stackoverflow_0012448425_javascript_jquery.txt
Q: Should I raise an exception when getting the size or the position of a file? I'm trying to make a class in Delphi that handles files. I have a property that returns the size of the file and another one that returns the position of the file. I don't know if any error can happen with these calls. Should I raise an exception? My code is: function TFile.GetSize: Int64; var FileSizeHi, FileSizeLo: Cardinal; begin FileSizeLo := GetFileSize(FHandle, @FileSizeHi); if (FileSizeLo = INVALID_FILE_SIZE) and (GetLastError = NO_ERROR) then Result := $FFFFFFFF else Result := FileSizeLo or Int64(FileSizeHi) shl 32; end; function TFile.GetPosition: Int64; var FilePosHi, FilePosLo: Cardinal; begin FilePosHi := 0; FilePosLo := 0; FilePosLo := SetFilePointer(FHandle, FilePosLo, @FilePosHi, FILE_CURRENT); if (FilePosLo = INVALID_SET_FILE_POINTER) and (GetLastError = NO_ERROR) then Result := $FFFFFFFF else Result := FilePosLo or Int64(FilePosHi) shl 32; end; I don't know what error could happen when I call GetFileSize or SetFilePointer (without moving the file pointer). A: Yes, errors can happen with those functions, so I would recommend raising an exception, otherwise the caller doesn't know if it has received an invalid value or not, as $FFFFFFFF is a valid size/position for 64bit values. Perhaps you meant to use -1 ($FFFFFFFFFFFFFFFF) instead? However, whether you raise an exception or not, your GetLastError() check is wrong. It needs to use <> instead of =. When the file function returns $FFFFFFFF for the low value, GetLastError() will return 0 when the low value really is $FFFFFFFF when the high value is non-zero, otherwise GetLastError() will return non-zero when the low/high values are invalid. Try this: function TFile.GetSize: Int64; var FileSizeHi, FileSizeLo: DWORD; begin FileSizeLo := GetFileSize(FHandle, @FileSizeHi); if (FileSizeLo = INVALID_FILE_SIZE) and (GetLastError <> NO_ERROR) then RaiseLastOSError // or: Result := -1 else Result := FileSizeLo or (Int64(FileSizeHi) shl 32); end; function TFile.GetPosition: Int64; var FilePosHi, FilePosLo: DWORD; begin FilePosHi := 0; FilePosLo := 0; FilePosLo := SetFilePointer(FHandle, FilePosLo, @FilePosHi, FILE_CURRENT); if (FilePosLo = INVALID_SET_FILE_POINTER) and (GetLastError <> NO_ERROR) then RaiseLastOSError // or: Result := -1 else Result := FilePosLo or (Int64(FilePosHi) shl 32); end; On a side note, consider using GetFileSizeEx() and SetFilePointerEx() instead, as they operate on 64bit values without breaking them up into low/high parts. A: These are WinAPI calls and you are already checking the return values, so you should be good to go. It is up to the user of your class to check for the return value from your functions. For more information check SetFilePointer() and GetFileSize().
Should I raise an exception when getting the size or the position of a file?
I'm trying to make a class in Delphi that handles files. I have a property that returns the size of the file and another one that returns the position of the file. I don't know if any error can happen with these calls. Should I raise an exception? My code is: function TFile.GetSize: Int64; var FileSizeHi, FileSizeLo: Cardinal; begin FileSizeLo := GetFileSize(FHandle, @FileSizeHi); if (FileSizeLo = INVALID_FILE_SIZE) and (GetLastError = NO_ERROR) then Result := $FFFFFFFF else Result := FileSizeLo or Int64(FileSizeHi) shl 32; end; function TFile.GetPosition: Int64; var FilePosHi, FilePosLo: Cardinal; begin FilePosHi := 0; FilePosLo := 0; FilePosLo := SetFilePointer(FHandle, FilePosLo, @FilePosHi, FILE_CURRENT); if (FilePosLo = INVALID_SET_FILE_POINTER) and (GetLastError = NO_ERROR) then Result := $FFFFFFFF else Result := FilePosLo or Int64(FilePosHi) shl 32; end; I don't know what error could happen when I call GetFileSize or SetFilePointer (without moving the file pointer).
[ "Yes, errors can happen with those functions, so I would recommend raising an exception, otherwise the caller doesn't know if it has received an invalid value or not, as $FFFFFFFF is a valid size/position for 64bit values. Perhaps you meant to use -1 ($FFFFFFFFFFFFFFFF) instead?\nHowever, whether you raise an exception or not, your GetLastError() check is wrong. It needs to use <> instead of =. When the file function returns $FFFFFFFF for the low value, GetLastError() will return 0 when the low value really is $FFFFFFFF when the high value is non-zero, otherwise GetLastError() will return non-zero when the low/high values are invalid.\nTry this:\nfunction TFile.GetSize: Int64;\nvar\n FileSizeHi, FileSizeLo: DWORD;\nbegin\n FileSizeLo := GetFileSize(FHandle, @FileSizeHi);\n if (FileSizeLo = INVALID_FILE_SIZE) and (GetLastError <> NO_ERROR) then\n RaiseLastOSError // or: Result := -1\n else\n Result := FileSizeLo or (Int64(FileSizeHi) shl 32);\nend;\n\nfunction TFile.GetPosition: Int64;\nvar\n FilePosHi, FilePosLo: DWORD;\nbegin\n FilePosHi := 0;\n FilePosLo := 0;\n FilePosLo := SetFilePointer(FHandle, FilePosLo, @FilePosHi, FILE_CURRENT);\n if (FilePosLo = INVALID_SET_FILE_POINTER) and (GetLastError <> NO_ERROR) then\n RaiseLastOSError // or: Result := -1\n else\n Result := FilePosLo or (Int64(FilePosHi) shl 32);\nend;\n\nOn a side note, consider using GetFileSizeEx() and SetFilePointerEx() instead, as they operate on 64bit values without breaking them up into low/high parts.\n", "These are WinAPI calls and you are already checking the return values, so you should be good to go. It is up to the user of your class to check for the return value from your functions. For more information check SetFilePointer() and GetFileSize().\n" ]
[ 1, 0 ]
[]
[]
[ "api", "delphi", "windows" ]
stackoverflow_0074674850_api_delphi_windows.txt
Q: How to store data in seperate memory mdoules I'm working on an image processing pipeline in Python and I'm using Cython for the main computation so that it can run really fast. From early benchmarks, I found a memory bottleneck where the code would not scale at all using multiple threads. I revised the algorithm a bit to reduce the bandwidth required and now it scales to 2 cores (4 threads with hyperthreading) but it still becomes bottlenecked by memory bandwidth. You can find the different versions of the algorithm here if you are curious: https://github.com/2332575Y/ I have confirmed this by running the benchmark on an i7-6700HQ (scales to 4 threads), i5-7600K (scales to 2 threads (cores) as the i5 has no hyper-threading), and an R9-5950X (scales to 4 threads). Also despite the massive performance differences between these CPUs, the relative performance between them is exactly the same difference between the memory speeds. You can find the benchmarks performed by the 6700HQ here: https://github.com/2332575Y/Retina-V3/blob/main/Untitled.ipynb and the 5950x benchmarks are: All of these benchmarks are performed without any manual memory management and since the overall size of the data is relatively small (120MB), I would assume python puts them on a single memory stick (all of the systems have dual-channel memory). I'm not sure if it is possible to somehow tell python to split the data and store it on different physical memory modules so that the algorithm can take advantage of the dual-channel memory. I tried googling ways to do this in C++ but that wasn't successful either. Is memory automatically managed by the OS or is it possible to do this? P.S.: before you comment, I have made sure to split the inputs as evenly as possible. Also, the sampling algorithm is extremely simple (multiply and accumulate), so having a memory bottleneck is not an absurd concept (it is actually pretty common in image processing algorithms). A: The OS manages splitting the program virtual address space to the different physical addresses (Ram sticks, pagefile, etc) this is transparent to python or any programming language, all systems were already using both sticks for read and write. The fact that both float64 and float32 have the same performance means each core cache is almost never used, so consider making better use of it in your algorithms, make your code more cache friendly. While this may seem hard for a loop that just computes a multiplication, you can group computations to reduce the number of times you access the memory. Edit: also consider shifting the work to the GPU or TPU as dedicated gpus are very good at convolutions, and have much faster memories.
How to store data in seperate memory mdoules
I'm working on an image processing pipeline in Python and I'm using Cython for the main computation so that it can run really fast. From early benchmarks, I found a memory bottleneck where the code would not scale at all using multiple threads. I revised the algorithm a bit to reduce the bandwidth required and now it scales to 2 cores (4 threads with hyperthreading) but it still becomes bottlenecked by memory bandwidth. You can find the different versions of the algorithm here if you are curious: https://github.com/2332575Y/ I have confirmed this by running the benchmark on an i7-6700HQ (scales to 4 threads), i5-7600K (scales to 2 threads (cores) as the i5 has no hyper-threading), and an R9-5950X (scales to 4 threads). Also despite the massive performance differences between these CPUs, the relative performance between them is exactly the same difference between the memory speeds. You can find the benchmarks performed by the 6700HQ here: https://github.com/2332575Y/Retina-V3/blob/main/Untitled.ipynb and the 5950x benchmarks are: All of these benchmarks are performed without any manual memory management and since the overall size of the data is relatively small (120MB), I would assume python puts them on a single memory stick (all of the systems have dual-channel memory). I'm not sure if it is possible to somehow tell python to split the data and store it on different physical memory modules so that the algorithm can take advantage of the dual-channel memory. I tried googling ways to do this in C++ but that wasn't successful either. Is memory automatically managed by the OS or is it possible to do this? P.S.: before you comment, I have made sure to split the inputs as evenly as possible. Also, the sampling algorithm is extremely simple (multiply and accumulate), so having a memory bottleneck is not an absurd concept (it is actually pretty common in image processing algorithms).
[ "The OS manages splitting the program virtual address space to the different physical addresses (Ram sticks, pagefile, etc) this is transparent to python or any programming language, all systems were already using both sticks for read and write.\nThe fact that both float64 and float32 have the same performance means each core cache is almost never used, so consider making better use of it in your algorithms, make your code more cache friendly.\nWhile this may seem hard for a loop that just computes a multiplication, you can group computations to reduce the number of times you access the memory.\nEdit: also consider shifting the work to the GPU or TPU as dedicated gpus are very good at convolutions, and have much faster memories.\n" ]
[ 2 ]
[]
[]
[ "memory", "memory_management", "multithreading", "python" ]
stackoverflow_0074678047_memory_memory_management_multithreading_python.txt
Q: Show monday on this chart Im trying to change the bgcolor on this chart - OANDA:SPX500USD - when it is monday The session time for monday is 1700su-1700 NOTE - THE SESSION STARTS 1700 THE PREVIOUS DAY (as seen above - 1700su) I have tried this but it keeps showing tuesday - indicator("test - oanda day change", overlay=true) i_sessionTime = input.session(title="Session Time", defval="1700-1700") bgcolor(dayofweek == 02? color.new(color.silver, 80) : na)``` How can i get it to change the bgcolor for the correct day please? A: // Set the desired day of the week (Monday = 1, Tuesday = 2, etc.) desiredDay = 1 // Use the dayofweek function to get the current day of the week currentDay = dayofweek() // Use the bgcolor function to set the background color of the chart // If the current day is the desired day, set the background color to silver bgcolor(currentDay == desiredDay ? color.new(color.silver, 80) : na)
Show monday on this chart
Im trying to change the bgcolor on this chart - OANDA:SPX500USD - when it is monday The session time for monday is 1700su-1700 NOTE - THE SESSION STARTS 1700 THE PREVIOUS DAY (as seen above - 1700su) I have tried this but it keeps showing tuesday - indicator("test - oanda day change", overlay=true) i_sessionTime = input.session(title="Session Time", defval="1700-1700") bgcolor(dayofweek == 02? color.new(color.silver, 80) : na)``` How can i get it to change the bgcolor for the correct day please?
[ "// Set the desired day of the week (Monday = 1, Tuesday = 2, etc.)\ndesiredDay = 1\n\n// Use the dayofweek function to get the current day of the week\ncurrentDay = dayofweek()\n\n// Use the bgcolor function to set the background color of the chart\n// If the current day is the desired day, set the background color to silver\nbgcolor(currentDay == desiredDay ? color.new(color.silver, 80) : na)\n\n\n" ]
[ 1 ]
[]
[]
[ "pine_script" ]
stackoverflow_0074678478_pine_script.txt
Q: Next.js application not reading environment variables from Azure App Application Settings I am trying to deploy a Next.js application to Azure and I am noticing that the application is not reading from the Application Settings environment variables when I run the application. For example, I created a simple variable called "NEXT_PUBLIC_AZURE_ENV" in the Azure Application Settings. It seems like from the documentation on Next.js that the environment variables are set at build time. Our DevOps team is trying to leverage a build once; deploy anywhere approach and having the application read from the Application Settings is what we are trying to do. Here is the variables declared locally in the local .env file: Here is the next.js.config file, which I added to the env section, not sure if that is needed or not. When I print the variable out, it works: However, once the application is deployed to Azure; the variable to is not being read. Is it possible to read from Application Settings in Azure from Next.js? Thank you! A: To access front-end env variables from an Azure Static app, you need add the env variables inside of your job configuration. For Azure Pipelines, the relevant part should look like: ... inputs: app_location: 'src' api_location: 'api' output_location: 'public' azure_static_web_apps_api_token: $(deployment_token) env: # Add environment variables here HUGO_VERSION: 0.58.0 For Github Actions: ... with: azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }} repo_token: ${{ secrets.GITHUB_TOKEN }} action: 'upload' app_location: 'src' api_location: 'api' output_location: 'public' env: # Add environment variables here HUGO_VERSION: 0.58.0 Examples taken from: https://learn.microsoft.com/en-gb/azure/static-web-apps/build-configuration?tabs=github-actions#environment-variables
Next.js application not reading environment variables from Azure App Application Settings
I am trying to deploy a Next.js application to Azure and I am noticing that the application is not reading from the Application Settings environment variables when I run the application. For example, I created a simple variable called "NEXT_PUBLIC_AZURE_ENV" in the Azure Application Settings. It seems like from the documentation on Next.js that the environment variables are set at build time. Our DevOps team is trying to leverage a build once; deploy anywhere approach and having the application read from the Application Settings is what we are trying to do. Here is the variables declared locally in the local .env file: Here is the next.js.config file, which I added to the env section, not sure if that is needed or not. When I print the variable out, it works: However, once the application is deployed to Azure; the variable to is not being read. Is it possible to read from Application Settings in Azure from Next.js? Thank you!
[ "To access front-end env variables from an Azure Static app, you need add the env variables inside of your job configuration. For Azure Pipelines, the relevant part should look like:\n...\n\ninputs:\n app_location: 'src'\n api_location: 'api'\n output_location: 'public'\n azure_static_web_apps_api_token: $(deployment_token)\nenv: # Add environment variables here\n HUGO_VERSION: 0.58.0\n\nFor Github Actions:\n...\n\nwith:\n azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}\n repo_token: ${{ secrets.GITHUB_TOKEN }}\n action: 'upload'\n app_location: 'src'\n api_location: 'api'\n output_location: 'public'\nenv: # Add environment variables here\n HUGO_VERSION: 0.58.0\n\nExamples taken from: https://learn.microsoft.com/en-gb/azure/static-web-apps/build-configuration?tabs=github-actions#environment-variables\n" ]
[ 0 ]
[]
[]
[ "azure", "azure_web_app_service", "next.js" ]
stackoverflow_0074322830_azure_azure_web_app_service_next.js.txt
Q: MongoDB: Query a array of json object using operation like gte and lte I have a collection of Promo codes like this:- { 'promoCode': 'XMAS22', 'country': 'USA', 'isExpirable': true, 'availability' : [ { 'startTimestamp' : startTimeVal1, 'endTimestamp': endTimeVal1, 'timezone': 'America/New_York' }, { 'startTimestamp' : startTimeVal2, 'endTimestamp': endTimeVal2', 'timezone': 'America/Chicago' }, { 'startTimestamp' : startTimeVal3, 'endTimestamp': endTimeVal3, 'timezone': 'America/Los_Angeles' }, ] }, { 'promoCode': 'HAPPYDAY', 'country': 'USA', 'isExpirable': false, 'availability' : null } Promo Code XMAS22 is expirable in nature. So it has isExpirable status as true and has anvailability array, containing availability based on three timezones. Promo code HAPPYDAY has isExpirable status false, so availability is null. A user sends a timestamp value and a timezone. Something like 1628290101 and 'America/New_York'. The query should retrieve:- { 'promoCode': 'XMAS22', 'country': 'USA' }, { 'promoCode': 'HAPPYDAY', 'country': 'USA' } Promo code XMAS22 should be retrieved if:- isExpirable = true and, timezone value is gte startTimestamp and lte endTimestamp and, timezone = America/New_York Promo code HAPPYDAY should be retrieved because:- isExpirable = false How can I build up the query? A: Query here we assume the user endered timestamp=5 and timezone="America/New_York" its the conditions you said, to pass if isExpirable=false or same timezone and timestamp between the start and end time. finally project to keep only those 2 fields you want, you can remove the _id : 0 also if you want *this is the find way with only query operators to use the index if you have one on startTimestamp and endTimestamp, we could do the same with aggregation in more programatic way with $filter but index wouldn't be used even if you had it. Playmongo find({"$or": [{"isExpirable": {"$eq": false}}, {"$and": [{"availability": {"$elemMatch": {"$and": [{"startTimestamp": {"$lte": 5}}, {"endTimestamp": {"$gte": 5}}, {"timezone": {"$eq": "America/New_York"}}]}}}]}]}, {"projection": {"promoCode": 1, "country": 1}})
MongoDB: Query a array of json object using operation like gte and lte
I have a collection of Promo codes like this:- { 'promoCode': 'XMAS22', 'country': 'USA', 'isExpirable': true, 'availability' : [ { 'startTimestamp' : startTimeVal1, 'endTimestamp': endTimeVal1, 'timezone': 'America/New_York' }, { 'startTimestamp' : startTimeVal2, 'endTimestamp': endTimeVal2', 'timezone': 'America/Chicago' }, { 'startTimestamp' : startTimeVal3, 'endTimestamp': endTimeVal3, 'timezone': 'America/Los_Angeles' }, ] }, { 'promoCode': 'HAPPYDAY', 'country': 'USA', 'isExpirable': false, 'availability' : null } Promo Code XMAS22 is expirable in nature. So it has isExpirable status as true and has anvailability array, containing availability based on three timezones. Promo code HAPPYDAY has isExpirable status false, so availability is null. A user sends a timestamp value and a timezone. Something like 1628290101 and 'America/New_York'. The query should retrieve:- { 'promoCode': 'XMAS22', 'country': 'USA' }, { 'promoCode': 'HAPPYDAY', 'country': 'USA' } Promo code XMAS22 should be retrieved if:- isExpirable = true and, timezone value is gte startTimestamp and lte endTimestamp and, timezone = America/New_York Promo code HAPPYDAY should be retrieved because:- isExpirable = false How can I build up the query?
[ "Query\n\nhere we assume the user endered timestamp=5 and timezone=\"America/New_York\"\nits the conditions you said, to pass if isExpirable=false or same timezone and timestamp between the start and end time.\nfinally project to keep only those 2 fields you want, you can remove the _id : 0 also if you want\n\n*this is the find way with only query operators to use the index if you have one on startTimestamp and endTimestamp, we could do the same with aggregation in more programatic way with $filter but index wouldn't be used even if you had it.\nPlaymongo\nfind({\"$or\": \n [{\"isExpirable\": {\"$eq\": false}},\n {\"$and\": \n [{\"availability\": \n {\"$elemMatch\": \n {\"$and\": \n [{\"startTimestamp\": {\"$lte\": 5}}, {\"endTimestamp\": {\"$gte\": 5}},\n {\"timezone\": {\"$eq\": \"America/New_York\"}}]}}}]}]},\n {\"projection\": {\"promoCode\": 1, \"country\": 1}})\n\n" ]
[ 0 ]
[]
[]
[ "json", "mongodb", "mongodb_query" ]
stackoverflow_0074677293_json_mongodb_mongodb_query.txt
Q: Can someone explain to me how ( (c-65+k)%26)+65) works in a caesar cypher? If c is the numerical value of an uppercase character (i.e. B is 66) and for the sake of argument, k is a key value of 2? I'm new to programming and don't understand how the modulo works in this. I know it takes the value of the remainder, but then wouldn't it simplify like this? c = B = 66 k = 2 I imagine the result should be 'D' (66 - 65 +2)%26 +65 (3)%26 +65 0 + 65 65 = 'A' I must not understand the way % works. A: Key Fact - The ASCII code of the letter"A" is 65. Here is how your cypher works - the original expression in the question title. Take the ASCII value of a letter, subtract the value of "A" from it giving you a 0 based number. Add the key value to this number shifting it by k places. Now divide the number you got above by 26, discard the quotient and use the remainder. This is the modulo operator %. This always keeps you numbers in the 0-25 range, since dividing by 26 will never a have a remainder great than 25. Add 65 to it to convert it into an "encrypted" uppercase letter. This allows the key to be ANY number and still keeps the "encrypted" output within the ASCII range of A-Z. You are interpreting the % operator as division. In reality, it's modulo or forget-the-quotient-I want-the-remainder operator. Example 0%2 is 0 1%2 is 1 2%2 is 0 3%2 is 1 And so on. Modulo is cyclic. A: Modulus is not int division. Modulus gives you the remainder of a division, so 3 / 26 is 0 with a remainder of 3. Therefore, 3 % 26 is 3. A: 3 % 26 is 3, not 0. Modulus is the remainder. Think of modulus 12 on a clock. If it is ten o'clock, and you add 4 hours, 10 + 4 = 14. But on the clock, the hand now points to 2, not 14. No matter how many hours you add, the hand always points to a number from 1 to 12. This is how modulus works. 10 + 4 = 14 14 % 12 = 2 (14 divided by 12 is 1 with remainder 2) 10 + 100 = 110 110 % 12 = 4 (110 divided by 12 is remainder 4) If it is 10 o'clock, and you wait 100 hours, the hand now points to 4. (Using the remainder of a division, dividing by 12 always gives a number from 0 to 11, so think of 12 o'clock as 0 o'clock.) A: (plain_text[i] - 65 + shift_key ) % 26 - 65) A: ((c - 65 + k) % 26) + 65) works, but is non portable and unnecessarily obfuscated. 65 is the ASCII code for 'A' the character constant representing the letter A. c - 65 or better c - 'A' evaluates to the distance of the uppercase letter stored in c from A, hence 1 for the letter B. Adding k operates a shift in the alphabet, but can produce offsets greater than 25, hence the modulo operation to compute the remainder of the division by 26. (c - 65 + k) % 26 gives the offset if the encoded letter. Adding 65 or more appropriately 'A' converts the offset back to an uppercase letter. This expression makes the silent assumption that all uppercase letters are consecutive in the execution character set, which is true for ASCII, but not for older character sets such as EBCDIC. Note also that the above expressions only work for positive values of k. If k is negative, the result of (c - 'a' + k) % 26 + 'a' may be negative too, hence k should be changed to a positive value first with this code: k = k % 26; if (k < 0) k = k + 26; Here is a more readable alternative: char encode_letter(char c, int k) { k = k % 26; if (k < 0) k = k + 26; if (c >= 'A' && c <= 'Z') return (c - 'A' + k) % 26 + 'A'; else if (c >= 'a' && c <= 'a') return (c - 'a' + k) % 26 + 'a'; else return c; }
Can someone explain to me how ( (c-65+k)%26)+65) works in a caesar cypher?
If c is the numerical value of an uppercase character (i.e. B is 66) and for the sake of argument, k is a key value of 2? I'm new to programming and don't understand how the modulo works in this. I know it takes the value of the remainder, but then wouldn't it simplify like this? c = B = 66 k = 2 I imagine the result should be 'D' (66 - 65 +2)%26 +65 (3)%26 +65 0 + 65 65 = 'A' I must not understand the way % works.
[ "Key Fact - The ASCII code of the letter\"A\" is 65.\nHere is how your cypher works - the original expression in the question title.\n\nTake the ASCII value of a letter, subtract the value of \"A\" from it giving you a 0 based number.\nAdd the key value to this number shifting it by k places. \nNow divide the number you got above by 26, discard the quotient and use the remainder. This is the modulo operator %. This always keeps you numbers in the 0-25 range, since dividing by 26 will never a have a remainder great than 25. \nAdd 65 to it to convert it into an \"encrypted\" uppercase letter. \n\nThis allows the key to be ANY number and still keeps the \"encrypted\" output within the ASCII range of A-Z.\nYou are interpreting the % operator as division. In reality, it's modulo or forget-the-quotient-I want-the-remainder operator. \nExample \n\n0%2 is 0\n1%2 is 1\n2%2 is 0\n3%2 is 1\n\nAnd so on. Modulo is cyclic.\n", "Modulus is not int division. Modulus gives you the remainder of a division, so 3 / 26 is 0 with a remainder of 3. Therefore, 3 % 26 is 3.\n", "3 % 26 is 3, not 0. Modulus is the remainder. Think of modulus 12 on a clock. If it is ten o'clock, and you add 4 hours, 10 + 4 = 14. But on the clock, the hand now points to 2, not 14. No matter how many hours you add, the hand always points to a number from 1 to 12. This is how modulus works.\n10 + 4 = 14\n14 % 12 = 2 (14 divided by 12 is 1 with remainder 2)\n10 + 100 = 110\n110 % 12 = 4 (110 divided by 12 is remainder 4)\nIf it is 10 o'clock, and you wait 100 hours, the hand now points to 4.\n(Using the remainder of a division, dividing by 12 always gives a number from 0 to 11, so think of 12 o'clock as 0 o'clock.)\n", "(plain_text[i] - 65 + shift_key ) % 26 - 65)\n", "((c - 65 + k) % 26) + 65) works, but is non portable and unnecessarily obfuscated.\n65 is the ASCII code for 'A' the character constant representing the letter A. c - 65 or better c - 'A' evaluates to the distance of the uppercase letter stored in c from A, hence 1 for the letter B.\nAdding k operates a shift in the alphabet, but can produce offsets greater than 25, hence the modulo operation to compute the remainder of the division by 26. (c - 65 + k) % 26 gives the offset if the encoded letter.\nAdding 65 or more appropriately 'A' converts the offset back to an uppercase letter.\nThis expression makes the silent assumption that all uppercase letters are consecutive in the execution character set, which is true for ASCII, but not for older character sets such as EBCDIC.\nNote also that the above expressions only work for positive values of k. If k is negative, the result of (c - 'a' + k) % 26 + 'a' may be negative too, hence k should be changed to a positive value first with this code:\n k = k % 26;\n if (k < 0)\n k = k + 26;\n\nHere is a more readable alternative:\nchar encode_letter(char c, int k) {\n k = k % 26;\n if (k < 0)\n k = k + 26;\n\n if (c >= 'A' && c <= 'Z')\n return (c - 'A' + k) % 26 + 'A';\n else\n if (c >= 'a' && c <= 'a')\n return (c - 'a' + k) % 26 + 'a';\n else\n return c;\n}\n\n" ]
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "c", "caesar_cipher", "modulo" ]
stackoverflow_0032917695_c_caesar_cipher_modulo.txt
Q: Location not showing properly tinymce Image upload I am trying to add image upload plugin to tinymce. But it creates the image url without one directory. Like follows: present -> localhost/blog/includes/tinymce/images/home-about.png <br> what I want to have -> localhost/blog/admin/includes/tinymce/images/home-about.png I want to add admin directory to this url. Actually, this url is showing in the blog post in home directory here This is my tinymce.init code: <script> const example_image_upload_handler = (blobInfo, progress) => new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.withCredentials = false; xhr.open('POST', 'includes/tinymce/postAccepter.php'); xhr.upload.onprogress = (e) => { progress(e.loaded / e.total * 100); }; xhr.onload = () => { if (xhr.status === 403) { reject({ message: 'HTTP Error: ' + xhr.status, remove: true }); return; } if (xhr.status < 200 || xhr.status >= 300) { reject('HTTP Error: ' + xhr.status); return; } const json = JSON.parse(xhr.responseText); if (!json || typeof json.location != 'string') { reject('Invalid JSON: ' + xhr.responseText); return; } resolve(json.location); }; xhr.onerror = () => { reject('Image upload failed due to a XHR Transport error. Code: ' + xhr.status); }; const formData = new FormData(); formData.append('file', blobInfo.blob(), blobInfo.filename()); xhr.send(formData); }); tinymce.init({ selector: 'textarea#default', plugins: 'code media image', height: 500, branding: false, elementpath: false, toolbar: 'link image insert | undo redo | formatselect | bold italic underline forecolor removeformat | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent | table blockquote codesample code', block_unsupported_drop: false, images_upload_url: 'admin/includes/tinymce/postAccepter.php', automatic_uploads: true, images_upload_base_path: 'tinymce/images', images_upload_credentials: true, images_upload_handler: example_image_upload_handler, images_reuse_filename: true, }); </script> And this is the postAccepter.php: <?php /*************************************************** * Only these origins are allowed to upload images * ***************************************************/ $accepted_origins = array("http://localhost", "http://192.168.1.1", "http://example.com"); /********************************************* * Change this line to set the upload folder * *********************************************/ $imageFolder = "images/"; if (isset($_SERVER['HTTP_ORIGIN'])) { // same-origin requests won't set an origin. If the origin is set, it must be valid. if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) { header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); } else { header("HTTP/1.1 403 Origin Denied"); return; } } // Don't attempt to process the upload on an OPTIONS request if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { header("Access-Control-Allow-Methods: POST, OPTIONS"); return; } reset ($_FILES); $temp = current($_FILES); if (is_uploaded_file($temp['tmp_name'])){ /* If your script needs to receive cookies, set images_upload_credentials : true in the configuration and enable the following two headers. */ // header('Access-Control-Allow-Credentials: true'); // header('P3P: CP="There is no P3P policy."'); // Sanitize input if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) { header("HTTP/1.1 400 Invalid file name."); return; } // Verify extension if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) { header("HTTP/1.1 400 Invalid extension."); return; } // Accept upload if there was no origin, or if it is an accepted origin $filetowrite = $imageFolder . $temp['name']; move_uploaded_file($temp['tmp_name'], $filetowrite); // Determine the base URL $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? "https://" : "http://"; $baseurl = $protocol . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER['REQUEST_URI']), "/") . "/"; // Respond to the successful upload with JSON. // Use a location key to specify the path to the saved image resource. // { location : '/your/uploaded/image/file'} echo json_encode(array('location' => $baseurl . $filetowrite)); } else { // Notify editor that the upload failed header("HTTP/1.1 500 Server Error"); } ?> enter image description here I tried to fix it but I cannot. Help appreciated Thanks! A: convert_urls: false, worked for me!!!!
Location not showing properly tinymce Image upload
I am trying to add image upload plugin to tinymce. But it creates the image url without one directory. Like follows: present -> localhost/blog/includes/tinymce/images/home-about.png <br> what I want to have -> localhost/blog/admin/includes/tinymce/images/home-about.png I want to add admin directory to this url. Actually, this url is showing in the blog post in home directory here This is my tinymce.init code: <script> const example_image_upload_handler = (blobInfo, progress) => new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.withCredentials = false; xhr.open('POST', 'includes/tinymce/postAccepter.php'); xhr.upload.onprogress = (e) => { progress(e.loaded / e.total * 100); }; xhr.onload = () => { if (xhr.status === 403) { reject({ message: 'HTTP Error: ' + xhr.status, remove: true }); return; } if (xhr.status < 200 || xhr.status >= 300) { reject('HTTP Error: ' + xhr.status); return; } const json = JSON.parse(xhr.responseText); if (!json || typeof json.location != 'string') { reject('Invalid JSON: ' + xhr.responseText); return; } resolve(json.location); }; xhr.onerror = () => { reject('Image upload failed due to a XHR Transport error. Code: ' + xhr.status); }; const formData = new FormData(); formData.append('file', blobInfo.blob(), blobInfo.filename()); xhr.send(formData); }); tinymce.init({ selector: 'textarea#default', plugins: 'code media image', height: 500, branding: false, elementpath: false, toolbar: 'link image insert | undo redo | formatselect | bold italic underline forecolor removeformat | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent | table blockquote codesample code', block_unsupported_drop: false, images_upload_url: 'admin/includes/tinymce/postAccepter.php', automatic_uploads: true, images_upload_base_path: 'tinymce/images', images_upload_credentials: true, images_upload_handler: example_image_upload_handler, images_reuse_filename: true, }); </script> And this is the postAccepter.php: <?php /*************************************************** * Only these origins are allowed to upload images * ***************************************************/ $accepted_origins = array("http://localhost", "http://192.168.1.1", "http://example.com"); /********************************************* * Change this line to set the upload folder * *********************************************/ $imageFolder = "images/"; if (isset($_SERVER['HTTP_ORIGIN'])) { // same-origin requests won't set an origin. If the origin is set, it must be valid. if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) { header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); } else { header("HTTP/1.1 403 Origin Denied"); return; } } // Don't attempt to process the upload on an OPTIONS request if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { header("Access-Control-Allow-Methods: POST, OPTIONS"); return; } reset ($_FILES); $temp = current($_FILES); if (is_uploaded_file($temp['tmp_name'])){ /* If your script needs to receive cookies, set images_upload_credentials : true in the configuration and enable the following two headers. */ // header('Access-Control-Allow-Credentials: true'); // header('P3P: CP="There is no P3P policy."'); // Sanitize input if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) { header("HTTP/1.1 400 Invalid file name."); return; } // Verify extension if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) { header("HTTP/1.1 400 Invalid extension."); return; } // Accept upload if there was no origin, or if it is an accepted origin $filetowrite = $imageFolder . $temp['name']; move_uploaded_file($temp['tmp_name'], $filetowrite); // Determine the base URL $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? "https://" : "http://"; $baseurl = $protocol . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER['REQUEST_URI']), "/") . "/"; // Respond to the successful upload with JSON. // Use a location key to specify the path to the saved image resource. // { location : '/your/uploaded/image/file'} echo json_encode(array('location' => $baseurl . $filetowrite)); } else { // Notify editor that the upload failed header("HTTP/1.1 500 Server Error"); } ?> enter image description here I tried to fix it but I cannot. Help appreciated Thanks!
[ "convert_urls: false,\n\nworked for me!!!!\n" ]
[ 0 ]
[]
[]
[ "javascript", "php", "tinymce" ]
stackoverflow_0074678349_javascript_php_tinymce.txt
Q: use Elasticsearch, for h in one['hits']['hits']: KeyError: 'hits' the es codeenter image description here wrong error I use above code to do elasticsearch, but meet the wrong error, for h in one['hits']['hits']: KeyError: 'hits' A: It looks like you are trying to iterate through the hits returned by an Elasticsearch query, but the hits key is not present in the one dictionary. This is likely because your Elasticsearch query did not return any results, or because there was an error in the query itself. If you want to iterate through the hits returned by an Elasticsearch query, you should first check that the hits key is present in the one dictionary. You can do this using an if statement, like this: if 'hits' in one: for h in one['hits']['hits']: # do something with each hit here Alternatively, you can use a try...except block to handle the KeyError if it occurs: try: for h in one['hits']['hits']: # do something with each hit here except KeyError: print("No hits found in Elasticsearch query") It is also a good idea to check the status of the Elasticsearch query by looking at the status_code of the response. If the query was successful, the status_code should be 200. If there was an error in the query, the status_code will be different and you can use it to troubleshoot the problem.
use Elasticsearch, for h in one['hits']['hits']: KeyError: 'hits'
the es codeenter image description here wrong error I use above code to do elasticsearch, but meet the wrong error, for h in one['hits']['hits']: KeyError: 'hits'
[ "It looks like you are trying to iterate through the hits returned by an Elasticsearch query, but the hits key is not present in the one dictionary. This is likely because your Elasticsearch query did not return any results, or because there was an error in the query itself.\nIf you want to iterate through the hits returned by an Elasticsearch query, you should first check that the hits key is present in the one dictionary. You can do this using an if statement, like this:\nif 'hits' in one:\n for h in one['hits']['hits']:\n # do something with each hit here\n\n\nAlternatively, you can use a try...except block to handle the KeyError if it occurs:\ntry:\n for h in one['hits']['hits']:\n # do something with each hit here\nexcept KeyError:\n print(\"No hits found in Elasticsearch query\")\n\nIt is also a good idea to check the status of the Elasticsearch query by looking at the status_code of the response. If the query was successful, the status_code should be 200. If there was an error in the query, the status_code will be different and you can use it to troubleshoot the problem.\n" ]
[ 0 ]
[]
[]
[ "data_retrieval", "elasticsearch", "http", "information_retrieval", "python" ]
stackoverflow_0074665990_data_retrieval_elasticsearch_http_information_retrieval_python.txt
Q: Nuxt Cannot find module @nuxt/ufo from /app/cilent. No changes were made I have a docker image running a nuxt application that i restarted today and with no other changes being made other than the restart i am now getting this error ... ERROR Cannot find module '@nuxt/ufo' from '/app/client' A: Same problem here. Manually installing @nuxt/ufo solves the problem: npm install @nuxt/ufo If your docker is based on node:12-buster, you can login into the instance and run the command there (using docker exec -it <docker process> bash). It will fix the issue for now. The permanent solution is to add @nuxt/ufoto package.json and recreate your docker image. "@nuxt/ufo": "^0.5.4", A: Delete the /node_modules folder, and install the modules again npm i A: Error can be by requiring "ufo" npm package. Try it if above solution don't work: https://github.com/unjs/ufo#readme npm i ufo --save (it's old @nuxt/ufo package) A: I had the similar problem, I was using pnpm to install dependency. Changed to npm worked like a charm. Delete node_modules/ and any .lock file created by other package manager. Also if using nuxt2+ its better if you use node v14 for some reason most of the dependencies are in the edge of deprecation. This means nuxt wants everyone to migrate to nuxt3 as soon as possible.
Nuxt Cannot find module @nuxt/ufo from /app/cilent. No changes were made
I have a docker image running a nuxt application that i restarted today and with no other changes being made other than the restart i am now getting this error ... ERROR Cannot find module '@nuxt/ufo' from '/app/client'
[ "Same problem here. Manually installing @nuxt/ufo solves the problem:\nnpm install @nuxt/ufo\n\nIf your docker is based on node:12-buster, you can login into the instance and run the command there (using docker exec -it <docker process> bash). It will fix the issue for now.\nThe permanent solution is to add @nuxt/ufoto package.json and recreate your docker image.\n\"@nuxt/ufo\": \"^0.5.4\",\n\n", "Delete the /node_modules folder, and install the modules again\nnpm i\n\n", "Error can be by requiring \"ufo\" npm package.\nTry it if above solution don't work:\nhttps://github.com/unjs/ufo#readme\n\nnpm i ufo --save\n\n(it's old @nuxt/ufo package)\n", "I had the similar problem, I was using pnpm to install dependency. Changed to npm worked like a charm. Delete node_modules/ and any .lock file created by other package manager. Also if using nuxt2+ its better if you use node v14 for some reason most of the dependencies are in the edge of deprecation. This means nuxt wants everyone to migrate to nuxt3 as soon as possible.\n" ]
[ 3, 1, 0, 0 ]
[]
[]
[ "nuxt.js", "nuxt_i18n", "vue.js" ]
stackoverflow_0065722038_nuxt.js_nuxt_i18n_vue.js.txt
Q: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'webservice_again.CustomUser' that has not been installed Complete Error: "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'webservice_again.CustomUser' that has not been installed model.py from builtins import ValueError from datetime import date import django from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractBaseUser from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, password= None, full_name="ABC",type = 0): if not email: raise ValueError("Email Required.") if not password: raise ValueError("Password Required.") user_obj =self.model( self.normalize_email(email) ) user_obj.set_password(password) user_obj.full_name = full_name user_obj.type = type user_obj.save(using = self._db) return user_obj class CustomUser(AbstractBaseUser): email =models.EmailField(unique=True, max_length=255) full_name = models.CharField(max_length=255, blank=False) dob = models.DateField(default=date.today) type = models.IntegerField(default=0) create_time = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] objects = CustomUserManager() def get_full_name(self): return self.full_name def __str__(self): return self.full_name settings.py INSTALLED_APPS = [ 'webservice_again', 'web_service', 'rest_framework', 'rest_framework.authtoken', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] AUTH_USER_MODEL = "webservice_again.CustomUser" Guys, I know this question is duplicate, but after going through all the provided solutions, i am asking this solution. Any help is appreciated. A: By default django looks for models in models.py. Try changing model.py file to models.py. If you somehow have a models folder which houses all your model files, then import the CustomUser model in __init__.py file located within the models folder. This should solve it!
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'webservice_again.CustomUser' that has not been installed
Complete Error: "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'webservice_again.CustomUser' that has not been installed model.py from builtins import ValueError from datetime import date import django from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractBaseUser from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, password= None, full_name="ABC",type = 0): if not email: raise ValueError("Email Required.") if not password: raise ValueError("Password Required.") user_obj =self.model( self.normalize_email(email) ) user_obj.set_password(password) user_obj.full_name = full_name user_obj.type = type user_obj.save(using = self._db) return user_obj class CustomUser(AbstractBaseUser): email =models.EmailField(unique=True, max_length=255) full_name = models.CharField(max_length=255, blank=False) dob = models.DateField(default=date.today) type = models.IntegerField(default=0) create_time = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] objects = CustomUserManager() def get_full_name(self): return self.full_name def __str__(self): return self.full_name settings.py INSTALLED_APPS = [ 'webservice_again', 'web_service', 'rest_framework', 'rest_framework.authtoken', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] AUTH_USER_MODEL = "webservice_again.CustomUser" Guys, I know this question is duplicate, but after going through all the provided solutions, i am asking this solution. Any help is appreciated.
[ "By default django looks for models in models.py. Try changing model.py file to models.py. If you somehow have a models folder which houses all your model files, then import the CustomUser model in __init__.py file located within the models folder. This should solve it!\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_users", "python" ]
stackoverflow_0055203871_django_django_models_django_users_python.txt
Q: Celery worker running tensorflow unable to create CUDA event I am loading tensorflow model to the celery worker but when I try to run a task on the worker, it shows the following error: [2018-09-19 10:29:39,753: INFO/MainProcess] Received task: analyze_atom[f6bb76cc-aa16-4761-a7cf-0ed111886ff8] [2018-09-19 10:29:41,198: WARNING/ForkPoolWorker-2] paper checkpoint1 takes 1.433300495147705 senconds 2018-09-19 10:29:41.318467: E tensorflow/core/grappler/clusters/utils.cc:81] Failed to get device properties, error code: 3 2018-09-19 10:29:42.650529: E tensorflow/stream_executor/event.cc:40] could not create CUDA event: CUDA_ERROR_NOT_INITIALIZED [2018-09-19 10:29:42,673: ERROR/MainProcess] Process 'ForkPoolWorker-2' pid:3782 exited with 'signal 11 (SIGSEGV)' [2018-09-19 10:29:42,704: ERROR/MainProcess] Task handler raised error: WorkerLostError('Worker exited prematurely: signal 11 (SIGSEGV).',) Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/billiard/pool.py", line 1223, in mark_as_worker_lost human_status(exitcode)), billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 11 (SIGSEGV). This is a tensorflow model and when the celery is started the model is loaded successfully on GPU, here is the work started log: totalMemory: 15.90GiB freeMemory: 15.61GiB 2018-09-19 10:35:38.431559: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1435] Adding visible gpu devices: 0 2018-09-19 10:35:38.793007: I tensorflow/core/common_runtime/gpu/gpu_device.cc:923] Device interconnect StreamExecutor with strength 1 edge matrix: 2018-09-19 10:35:38.793054: I tensorflow/core/common_runtime/gpu/gpu_device.cc:929] 0 2018-09-19 10:35:38.793063: I tensorflow/core/common_runtime/gpu/gpu_device.cc:942] 0: N 2018-09-19 10:35:38.793487: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1053] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 15131 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:08.0, compute capability: 6.0) 2018-09-19 10:35:40.552010: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1435] Adding visible gpu devices: 0 2018-09-19 10:35:40.552073: I tensorflow/core/common_runtime/gpu/gpu_device.cc:923] Device interconnect StreamExecutor with strength 1 edge matrix: 2018-09-19 10:35:40.552080: I tensorflow/core/common_runtime/gpu/gpu_device.cc:929] 0 2018-09-19 10:35:40.552085: I tensorflow/core/common_runtime/gpu/gpu_device.cc:942] 0: N 2018-09-19 10:35:40.552327: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1053] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 15131 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:08.0, compute capability: 6.0) 2018-09-19 10:35:41.304281: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1435] Adding visible gpu devices: 0 2018-09-19 10:35:41.304336: I tensorflow/core/common_runtime/gpu/gpu_device.cc:923] Device interconnect StreamExecutor with strength 1 edge matrix: 2018-09-19 10:35:41.304344: I tensorflow/core/common_runtime/gpu/gpu_device.cc:929] 0 2018-09-19 10:35:41.304348: I tensorflow/core/common_runtime/gpu/gpu_device.cc:942] 0: N 2018-09-19 10:35:41.304574: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1053] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 15131 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:08.0, compute capability: 6.0) 2018-09-19 10:35:43.013963: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1435] Adding visible gpu devices: 0 2018-09-19 10:35:43.014025: I tensorflow/core/common_runtime/gpu/gpu_device.cc:923] Device interconnect StreamExecutor with strength 1 edge matrix: 2018-09-19 10:35:43.014033: I tensorflow/core/common_runtime/gpu/gpu_device.cc:929] 0 2018-09-19 10:35:43.014038: I tensorflow/core/common_runtime/gpu/gpu_device.cc:942] 0: N 2018-09-19 10:35:43.037554: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1053] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 15131 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:08.0, compute capability: 6.0) 2018-09-19 10:35:43.916442: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1435] Adding visible gpu devices: 0 2018-09-19 10:35:43.916500: I tensorflow/core/common_runtime/gpu/gpu_device.cc:923] Device interconnect StreamExecutor with strength 1 edge matrix: 2018-09-19 10:35:43.916507: I tensorflow/core/common_runtime/gpu/gpu_device.cc:929] 0 2018-09-19 10:35:43.916512: I tensorflow/core/common_runtime/gpu/gpu_device.cc:942] 0: N 2018-09-19 10:35:43.916752: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1053] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 15131 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:08.0, compute capability: 6.0) 2018-09-19 10:35:44.137238: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1435] Adding visible gpu devices: 0 2018-09-19 10:35:44.137296: I tensorflow/core/common_runtime/gpu/gpu_device.cc:923] Device interconnect StreamExecutor with strength 1 edge matrix: 2018-09-19 10:35:44.137304: I tensorflow/core/common_runtime/gpu/gpu_device.cc:929] 0 2018-09-19 10:35:44.137308: I tensorflow/core/common_runtime/gpu/gpu_device.cc:942] 0: N 2018-09-19 10:35:44.137563: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1053] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 15131 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:08.0, compute capability: 6.0) [2018-09-19 10:35:44,650: INFO/MainProcess] Connected to amqp://yjyx:**@118.178.129.156:5672/yjyx [2018-09-19 10:35:44,667: INFO/MainProcess] mingle: searching for neighbors [2018-09-19 10:35:45,716: INFO/MainProcess] mingle: sync with 1 nodes [2018-09-19 10:35:45,717: INFO/MainProcess] mingle: sync complete [2018-09-19 10:35:45,750: INFO/MainProcess] celery@yjyx-gpu-1 ready. I also see that the GPU memory is allocated: I am using supervisor to run celery and here is supervisor config: [program:celeryworker_paperanalyzer] process_name=%(process_num)02d directory=/home/yjyx/yijiao_src/yijiao_main command=celery worker -A project.celerytasks.celery_worker_init -Q paperanalyzer -c 2 --loglevel=INFO user=yjyx numprocs=1 stdout_logfile=/home/yjyx/log/celeryworker_paperanalyzer0.log stderr_logfile=/home/yjyx/log/celeryworker_paperanalyzer1.log stdout_logfile_maxbytes=50MB ; maximum size of logfile before rotation stderr_logfile_maxbytes=50MB stderr_logfile_backups=10 ; number of backed up logfiles stdout_logfile_backups=10 autostart=false autorestart=false startsecs=5 stopwaitsecs=8 killasgroup=true priority=1000 Here is celery task code snippet: @shared_task(name="analyze_atom", queue="paperanalyzer") def analyze_atom(image_urls, targetdir=target_path, studentuid=None): try: if targetdir is not None and os.path.exists(targetdir): os.chdir(targetdir) paper = Paper(image_urls, studentuid) for image_url in paper.image_urls: if type(image_url) == str: paper.analyze(image_url) # tensorflow inference get called within paper.analyze elif type(image_url) == dict: paper.analyze(image_url['url'], str(image_url['pn']), image_url.get('cormode', 0)) return paper.data except Exception as e: logger.log(40, traceback.print_exc()) logger.log(40, e) return {} I am sure the whole procedure should be OK, actually, I used opencv within paper.analyze to handle the job, and, it works well, now I just change opencv to tensorflow. Env: Python3.6.4; Tensorflow 1.8; celery 4.0.2; OS: Centos 7.2 Any help will be really appreciated. :-) Thanks. Wesley A: Changing things to single-threaded is an easy fix. You can resolve this issue by adding -P solo to your celery command i.e: celery -app APP worker -P solo --loglelvel=info Note: APP is your app name.
Celery worker running tensorflow unable to create CUDA event
I am loading tensorflow model to the celery worker but when I try to run a task on the worker, it shows the following error: [2018-09-19 10:29:39,753: INFO/MainProcess] Received task: analyze_atom[f6bb76cc-aa16-4761-a7cf-0ed111886ff8] [2018-09-19 10:29:41,198: WARNING/ForkPoolWorker-2] paper checkpoint1 takes 1.433300495147705 senconds 2018-09-19 10:29:41.318467: E tensorflow/core/grappler/clusters/utils.cc:81] Failed to get device properties, error code: 3 2018-09-19 10:29:42.650529: E tensorflow/stream_executor/event.cc:40] could not create CUDA event: CUDA_ERROR_NOT_INITIALIZED [2018-09-19 10:29:42,673: ERROR/MainProcess] Process 'ForkPoolWorker-2' pid:3782 exited with 'signal 11 (SIGSEGV)' [2018-09-19 10:29:42,704: ERROR/MainProcess] Task handler raised error: WorkerLostError('Worker exited prematurely: signal 11 (SIGSEGV).',) Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/billiard/pool.py", line 1223, in mark_as_worker_lost human_status(exitcode)), billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 11 (SIGSEGV). This is a tensorflow model and when the celery is started the model is loaded successfully on GPU, here is the work started log: totalMemory: 15.90GiB freeMemory: 15.61GiB 2018-09-19 10:35:38.431559: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1435] Adding visible gpu devices: 0 2018-09-19 10:35:38.793007: I tensorflow/core/common_runtime/gpu/gpu_device.cc:923] Device interconnect StreamExecutor with strength 1 edge matrix: 2018-09-19 10:35:38.793054: I tensorflow/core/common_runtime/gpu/gpu_device.cc:929] 0 2018-09-19 10:35:38.793063: I tensorflow/core/common_runtime/gpu/gpu_device.cc:942] 0: N 2018-09-19 10:35:38.793487: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1053] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 15131 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:08.0, compute capability: 6.0) 2018-09-19 10:35:40.552010: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1435] Adding visible gpu devices: 0 2018-09-19 10:35:40.552073: I tensorflow/core/common_runtime/gpu/gpu_device.cc:923] Device interconnect StreamExecutor with strength 1 edge matrix: 2018-09-19 10:35:40.552080: I tensorflow/core/common_runtime/gpu/gpu_device.cc:929] 0 2018-09-19 10:35:40.552085: I tensorflow/core/common_runtime/gpu/gpu_device.cc:942] 0: N 2018-09-19 10:35:40.552327: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1053] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 15131 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:08.0, compute capability: 6.0) 2018-09-19 10:35:41.304281: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1435] Adding visible gpu devices: 0 2018-09-19 10:35:41.304336: I tensorflow/core/common_runtime/gpu/gpu_device.cc:923] Device interconnect StreamExecutor with strength 1 edge matrix: 2018-09-19 10:35:41.304344: I tensorflow/core/common_runtime/gpu/gpu_device.cc:929] 0 2018-09-19 10:35:41.304348: I tensorflow/core/common_runtime/gpu/gpu_device.cc:942] 0: N 2018-09-19 10:35:41.304574: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1053] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 15131 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:08.0, compute capability: 6.0) 2018-09-19 10:35:43.013963: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1435] Adding visible gpu devices: 0 2018-09-19 10:35:43.014025: I tensorflow/core/common_runtime/gpu/gpu_device.cc:923] Device interconnect StreamExecutor with strength 1 edge matrix: 2018-09-19 10:35:43.014033: I tensorflow/core/common_runtime/gpu/gpu_device.cc:929] 0 2018-09-19 10:35:43.014038: I tensorflow/core/common_runtime/gpu/gpu_device.cc:942] 0: N 2018-09-19 10:35:43.037554: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1053] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 15131 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:08.0, compute capability: 6.0) 2018-09-19 10:35:43.916442: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1435] Adding visible gpu devices: 0 2018-09-19 10:35:43.916500: I tensorflow/core/common_runtime/gpu/gpu_device.cc:923] Device interconnect StreamExecutor with strength 1 edge matrix: 2018-09-19 10:35:43.916507: I tensorflow/core/common_runtime/gpu/gpu_device.cc:929] 0 2018-09-19 10:35:43.916512: I tensorflow/core/common_runtime/gpu/gpu_device.cc:942] 0: N 2018-09-19 10:35:43.916752: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1053] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 15131 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:08.0, compute capability: 6.0) 2018-09-19 10:35:44.137238: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1435] Adding visible gpu devices: 0 2018-09-19 10:35:44.137296: I tensorflow/core/common_runtime/gpu/gpu_device.cc:923] Device interconnect StreamExecutor with strength 1 edge matrix: 2018-09-19 10:35:44.137304: I tensorflow/core/common_runtime/gpu/gpu_device.cc:929] 0 2018-09-19 10:35:44.137308: I tensorflow/core/common_runtime/gpu/gpu_device.cc:942] 0: N 2018-09-19 10:35:44.137563: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1053] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 15131 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:08.0, compute capability: 6.0) [2018-09-19 10:35:44,650: INFO/MainProcess] Connected to amqp://yjyx:**@118.178.129.156:5672/yjyx [2018-09-19 10:35:44,667: INFO/MainProcess] mingle: searching for neighbors [2018-09-19 10:35:45,716: INFO/MainProcess] mingle: sync with 1 nodes [2018-09-19 10:35:45,717: INFO/MainProcess] mingle: sync complete [2018-09-19 10:35:45,750: INFO/MainProcess] celery@yjyx-gpu-1 ready. I also see that the GPU memory is allocated: I am using supervisor to run celery and here is supervisor config: [program:celeryworker_paperanalyzer] process_name=%(process_num)02d directory=/home/yjyx/yijiao_src/yijiao_main command=celery worker -A project.celerytasks.celery_worker_init -Q paperanalyzer -c 2 --loglevel=INFO user=yjyx numprocs=1 stdout_logfile=/home/yjyx/log/celeryworker_paperanalyzer0.log stderr_logfile=/home/yjyx/log/celeryworker_paperanalyzer1.log stdout_logfile_maxbytes=50MB ; maximum size of logfile before rotation stderr_logfile_maxbytes=50MB stderr_logfile_backups=10 ; number of backed up logfiles stdout_logfile_backups=10 autostart=false autorestart=false startsecs=5 stopwaitsecs=8 killasgroup=true priority=1000 Here is celery task code snippet: @shared_task(name="analyze_atom", queue="paperanalyzer") def analyze_atom(image_urls, targetdir=target_path, studentuid=None): try: if targetdir is not None and os.path.exists(targetdir): os.chdir(targetdir) paper = Paper(image_urls, studentuid) for image_url in paper.image_urls: if type(image_url) == str: paper.analyze(image_url) # tensorflow inference get called within paper.analyze elif type(image_url) == dict: paper.analyze(image_url['url'], str(image_url['pn']), image_url.get('cormode', 0)) return paper.data except Exception as e: logger.log(40, traceback.print_exc()) logger.log(40, e) return {} I am sure the whole procedure should be OK, actually, I used opencv within paper.analyze to handle the job, and, it works well, now I just change opencv to tensorflow. Env: Python3.6.4; Tensorflow 1.8; celery 4.0.2; OS: Centos 7.2 Any help will be really appreciated. :-) Thanks. Wesley
[ "Changing things to single-threaded is an easy fix. You can resolve this issue by adding -P solo to your celery command\ni.e:\ncelery -app APP worker -P solo --loglelvel=info\n\nNote: APP is your app name.\n" ]
[ 0 ]
[]
[]
[ "celery", "python", "tensorflow" ]
stackoverflow_0052397450_celery_python_tensorflow.txt
Q: How to send json formatted messages to Slack through Cloud functions? I am trying to send a json formatted message to Slack through a Cloud function using slack_sdk, if I send it like this (not formatted) it works. client = WebClient(token='xoxb-25.......') try: response = client.chat_postMessage(channel='#random', text=DICTIONARY) I found the documentation on Slack that chat_postMessage supports sending json formats by setting the HTTP headers: Content-type: application/json Authorization: Bearer xoxb-25xxxxxxx-xxxx How would that work applied in my code above? I want to send a big python dictionary and would like to receive it formatted in the Slack channel. I tried adding it in multiple ways and deployment fails. This is the documentation: https://api.slack.com/web A: Bit late, but I hope this can help others who stumble upon this issue in the future. I think that you've misunderstood the documentation. The JSON support allows for accepting POST message bodies in JSON format, as only application/x-www-form-urlencoded format was supported earlier. Read more here. To answer your question, you can try to send the dictionary by formatting it or in a code block as Slack API supports markdown. Reference- Slack Text Formatting. Sample Code- from slack_sdk import WebClient import json client = WebClient(token="xoxb........-") json_message = { "title": "Tom Sawyer", "author": "Twain, Mark", "year_written": 1862, "edition": "Random House", "price": 7.75 } # format and send as a text block formatted_text = f"```{json.dumps(json_message, indent = 2)}```" client.chat_postMessage(channel = "#general", text = formatted_text) # format and send as a code block formatted_code_block = json.dumps(json_message, indent = 2) client.chat_postMessage(channel = "#general", text = formatted_code_block) Output-
How to send json formatted messages to Slack through Cloud functions?
I am trying to send a json formatted message to Slack through a Cloud function using slack_sdk, if I send it like this (not formatted) it works. client = WebClient(token='xoxb-25.......') try: response = client.chat_postMessage(channel='#random', text=DICTIONARY) I found the documentation on Slack that chat_postMessage supports sending json formats by setting the HTTP headers: Content-type: application/json Authorization: Bearer xoxb-25xxxxxxx-xxxx How would that work applied in my code above? I want to send a big python dictionary and would like to receive it formatted in the Slack channel. I tried adding it in multiple ways and deployment fails. This is the documentation: https://api.slack.com/web
[ "Bit late, but I hope this can help others who stumble upon this issue in the future.\nI think that you've misunderstood the documentation. The JSON support allows for accepting POST message bodies in JSON format, as only application/x-www-form-urlencoded format was supported earlier. Read more here.\nTo answer your question, you can try to send the dictionary by formatting it or in a code block as Slack API supports markdown.\nReference- Slack Text Formatting.\nSample Code-\nfrom slack_sdk import WebClient\nimport json\nclient = WebClient(token=\"xoxb........-\")\n\njson_message = {\n \"title\": \"Tom Sawyer\",\n \"author\": \"Twain, Mark\",\n \"year_written\": 1862,\n \"edition\": \"Random House\",\n \"price\": 7.75\n}\n\n# format and send as a text block\nformatted_text = f\"```{json.dumps(json_message, indent = 2)}```\"\nclient.chat_postMessage(channel = \"#general\", text = formatted_text)\n\n# format and send as a code block\nformatted_code_block = json.dumps(json_message, indent = 2)\nclient.chat_postMessage(channel = \"#general\", text = formatted_code_block)\n\nOutput-\n\n" ]
[ 0 ]
[]
[]
[ "google_cloud_functions", "python", "slack", "slack_api" ]
stackoverflow_0073580490_google_cloud_functions_python_slack_slack_api.txt
Q: Handling SQL Custom Type as JSON Response using Hibernate + JPA + Spring Web I have an entity class with a custom type field among other fields @Entity @Table(name = "something") public class Test { @Id private Integer id; private <SomethingHere> customTypeObject; // Other fields, getters, and setters not shown } Using that class I am generating a json representation of the data using repository.findAll() @Controller public class TestController { @AutoWired private TestRepository repo @GetMapping("/test") private List<Test> test() { return repo.findAll(); } } The JSON response to the user is intended to display the fields within the custom type in JSON format. If I label the customTypeObject as a String, the reponse is something like below [{id: 1, customTypeObject: "(1,2)"}] Whereas I would prefer a response like [{id: 1, customTypeObject: { A: 1, B: 2 }}] I realize I could do this by creating another entity class for the custom type where I manually type out the fields but I plan on increasing the number of fields in the custom type frequently during the development process so I would prefer if the program would keep track of the fields for me. Is there any way this could be accomplished? A: If I label the customTypeObject as a String, the reponse is something like below [{id: 1, customTypeObject: "(1,2)"}] based on your example, I assume you are storing a JSON string. You can create a DTO class and use mapstruct to define a mapper from your entity to DTO. You can you fasterxml to parse the string to object // entity class @Entity @Table(name = "something") public class Test { @Id private Integer id; private String customTypeObject; // Other fields, getters, and setters not shown } // DTO class public class TestDTO { // same fields as Entity private Map<String,Object> customTypeObject; // or private Object customTypeObject; } // mapper class @Mapper public interface TestMapper { TestMapper INSTANCE = Mappers.getMapper(TestMapper.class); ObjectMapper objectMapper = new ObjectMapper(); @Mappings({ @Mapping(source = "test.customTypeObject", target = "customTypeObject", qualifiedByName = "parseCustomObject") }) TestDTO entityToDto(Test test) List<TestDTO> entitiesToDto(List<Test> tests) // the return type of this method must be the same as the datatype for the field in the dto class @Named("parseCustomObject") static Map<String,Object> getCustomObject(String objStr) throws JsonProcessingException { Map<String, Object> objectMap = new HashMap<>(); if (Objects.nonNull(objStr)) { objectMap = objectMapper.readValue(objStr, Map.class); } return objectMap; } } // controller or service class @Controller public class TestController { @AutoWired private TestRepository repo @GetMapping("/test") private List<TestDTO> test() { List<Test> t = repo.findAll(); return TestMapper.INSTANCE.entitiesToDto(t); } } A: You can also use either GSON (com.google.code.gson) or JSONObject (org.json.JSONObject) to create the JSON body manually this way you can manipulate it as needed here is a link to an article that should be helpful https://www.baeldung.com/java-org-json https://www.baeldung.com/jackson-vs-gson A: Since you are using Spring, and Spring uses Jackson ObjectMapper, you could create another class to your customTypeObject with the respective getter methods to the fields you want to show (probably best to use Lombok's @Getter so you don't need to write getters), if you have a getter method Jackson will automatically create the json for you. A: If you use JPA with Hibernate, I recommend to use Hibernate Types for mapping JSON column into POJO, Map, or even JsonNode. Here is an example explaining how to use it A: If the JSON string can contain an unpredictable amount of fields, you can use the @JsonAnySetter annotation on a method in the class to handle the dynamic properties. For similar effect in serialization use @JsonAnyGetter. public class CustomType { @JsonProperty private int knownProperty; private Map<String, Object> additionalProperties = new HashMap<>(); public CustomType(int knownProperty) { this.knownProperty = knownProperty; } @JsonAnySetter public void setAdditionalProperty(String key, Object value) { this.additionalProperties.put(key, value); } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { // wrapped with Collections.unmodifiableMap for safety return Collections.unmodifiableMap(this.additionalProperties); } } Usage: CustomType customTypeObject = new CustomType(1); customTypeObject.setAdditionalProperty("something", 2); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(customTypeObject); // json == "{ \"knownProperty\":1, \"something\":2 }" CustomType customTypeObject2 = mapper.readValue(json, CustomType.class); // customTypeObject2 is logically equal to customTypeObject A: Yes, it is possible to convert the custom type object to a JSON object in the response. One way to do this is to use the Jackson library, which is a popular JSON processing library for Java. First, you would need to add the Jackson dependency to your project. In Maven, you can do this by adding the following dependency to your pom.xml file: <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.2</version> </dependency> Next, you can use the ObjectMapper class from the Jackson library to convert the custom type object to a JSON object. The ObjectMapper class provides methods to convert Java objects to and from JSON. Here is an example of how you can use the ObjectMapper class to convert a custom type object to a JSON object in your controller: @Controller public class TestController { @Autowired private TestRepository repo; @Autowired private ObjectMapper objectMapper; // inject the ObjectMapper bean @GetMapping("/test") private List<Test> test() { List<Test> tests = repo.findAll(); // convert the custom type objects to JSON objects tests.forEach(test -> { String json = objectMapper.writeValueAsString(test.getCustomTypeObject()); test.setCustomTypeObject(json); }); return tests; } } The JSON object that is generated from the ObjectMapper will have the same structure as the custom type object, with each field in the custom type object being mapped to a property in the JSON object. Alternatively, you can also use the @JsonValue annotation on the getter method of the customTypeObject field to tell Jackson to use the value returned by the getter method as the JSON representation of the field. Here is an example: @Entity @Table(name = "something") public class Test { @Id private Integer id; private <SomethingHere> customTypeObject; @JsonValue public <SomethingHere> getCustomTypeObject() { return customTypeObject; } // Other fields, getters, and setters not shown } With the @JsonValue annotation, you don't need to manually convert the custom type object to a JSON object in your controller. The Jackson library will automatically use the value returned by the getter method as the JSON representation of the customTypeObject field. A: If you want to save a Custom object in the database, then you can create your own Hibernate Convertors Custom Types JPA Converter FYI, But may be out of scope You can also try updating the toString() method of your custom object's class. From your question, it is unclear where you want the desired representation, is it in a database or in a Field in UI?
Handling SQL Custom Type as JSON Response using Hibernate + JPA + Spring Web
I have an entity class with a custom type field among other fields @Entity @Table(name = "something") public class Test { @Id private Integer id; private <SomethingHere> customTypeObject; // Other fields, getters, and setters not shown } Using that class I am generating a json representation of the data using repository.findAll() @Controller public class TestController { @AutoWired private TestRepository repo @GetMapping("/test") private List<Test> test() { return repo.findAll(); } } The JSON response to the user is intended to display the fields within the custom type in JSON format. If I label the customTypeObject as a String, the reponse is something like below [{id: 1, customTypeObject: "(1,2)"}] Whereas I would prefer a response like [{id: 1, customTypeObject: { A: 1, B: 2 }}] I realize I could do this by creating another entity class for the custom type where I manually type out the fields but I plan on increasing the number of fields in the custom type frequently during the development process so I would prefer if the program would keep track of the fields for me. Is there any way this could be accomplished?
[ "\nIf I label the customTypeObject as a String, the reponse is something like below [{id: 1, customTypeObject: \"(1,2)\"}]\n\nbased on your example, I assume you are storing a JSON string. You can create a DTO class and use mapstruct to define a mapper from your entity to DTO. You can you fasterxml to parse the string to object\n// entity class\n@Entity\n@Table(name = \"something\") \npublic class Test {\n @Id\n private Integer id;\n\n private String customTypeObject;\n\n // Other fields, getters, and setters not shown\n}\n\n// DTO class\npublic class TestDTO {\n\n // same fields as Entity \n\n private Map<String,Object> customTypeObject;\n // or private Object customTypeObject;\n\n}\n\n// mapper class\n@Mapper\npublic interface TestMapper {\n\n TestMapper INSTANCE = Mappers.getMapper(TestMapper.class);\n ObjectMapper objectMapper = new ObjectMapper();\n\n @Mappings({\n @Mapping(source = \"test.customTypeObject\", target = \"customTypeObject\", qualifiedByName = \"parseCustomObject\")\n })\n TestDTO entityToDto(Test test)\n \n List<TestDTO> entitiesToDto(List<Test> tests) \n\n // the return type of this method must be the same as the datatype for the field in the dto class\n @Named(\"parseCustomObject\")\n static Map<String,Object> getCustomObject(String objStr) throws JsonProcessingException {\n Map<String, Object> objectMap = new HashMap<>();\n if (Objects.nonNull(objStr)) {\n objectMap = objectMapper.readValue(objStr, Map.class);\n }\n return objectMap;\n }\n\n}\n\n// controller or service class\n@Controller \npublic class TestController {\n @AutoWired\n private TestRepository repo\n\n @GetMapping(\"/test\")\n private List<TestDTO> test() {\n List<Test> t = repo.findAll();\n return TestMapper.INSTANCE.entitiesToDto(t);\n }\n}\n\n\n\n\n", "You can also use either GSON (com.google.code.gson) or JSONObject (org.json.JSONObject) to create the JSON body manually this way you can manipulate it as needed here is a link to an article that should be helpful\n\nhttps://www.baeldung.com/java-org-json\n\nhttps://www.baeldung.com/jackson-vs-gson\n\n\n", "Since you are using Spring, and Spring uses Jackson ObjectMapper, you could create another class to your customTypeObject with the respective getter methods to the fields you want to show (probably best to use Lombok's @Getter so you don't need to write getters), if you have a getter method Jackson will automatically create the json for you.\n", "If you use JPA with Hibernate, I recommend to use Hibernate Types for mapping JSON column into POJO, Map, or even JsonNode.\nHere is an example explaining how to use it\n", "If the JSON string can contain an unpredictable amount of fields, you can use the @JsonAnySetter annotation on a method in the class to handle the dynamic properties. For similar effect in serialization use @JsonAnyGetter.\npublic class CustomType {\n\n @JsonProperty\n private int knownProperty;\n\n private Map<String, Object> additionalProperties = new HashMap<>();\n\n public CustomType(int knownProperty) {\n this.knownProperty = knownProperty;\n }\n\n @JsonAnySetter\n public void setAdditionalProperty(String key, Object value) {\n this.additionalProperties.put(key, value);\n }\n\n @JsonAnyGetter\n public Map<String, Object> getAdditionalProperties() {\n // wrapped with Collections.unmodifiableMap for safety\n return Collections.unmodifiableMap(this.additionalProperties);\n }\n}\n\nUsage:\n CustomType customTypeObject = new CustomType(1);\n customTypeObject.setAdditionalProperty(\"something\", 2);\n\n ObjectMapper mapper = new ObjectMapper();\n String json = mapper.writeValueAsString(customTypeObject);\n\n // json == \"{ \\\"knownProperty\\\":1, \\\"something\\\":2 }\"\n\n CustomType customTypeObject2 = mapper.readValue(json, CustomType.class);\n\n // customTypeObject2 is logically equal to customTypeObject \n\n", "Yes, it is possible to convert the custom type object to a JSON object in the response. One way to do this is to use the Jackson library, which is a popular JSON processing library for Java.\nFirst, you would need to add the Jackson dependency to your project. In Maven, you can do this by adding the following dependency to your pom.xml file:\n<dependency>\n <groupId>com.fasterxml.jackson.core</groupId>\n <artifactId>jackson-databind</artifactId>\n <version>2.10.2</version>\n</dependency>\n\nNext, you can use the ObjectMapper class from the Jackson library to convert the custom type object to a JSON object. The ObjectMapper class provides methods to convert Java objects to and from JSON.\nHere is an example of how you can use the ObjectMapper class to convert a custom type object to a JSON object in your controller:\n@Controller\npublic class TestController {\n @Autowired\n private TestRepository repo;\n\n @Autowired\n private ObjectMapper objectMapper; // inject the ObjectMapper bean\n\n @GetMapping(\"/test\")\n private List<Test> test() {\n List<Test> tests = repo.findAll();\n\n // convert the custom type objects to JSON objects\n tests.forEach(test -> {\n String json = objectMapper.writeValueAsString(test.getCustomTypeObject());\n test.setCustomTypeObject(json);\n });\n\n return tests;\n }\n}\n\nThe JSON object that is generated from the ObjectMapper will have the same structure as the custom type object, with each field in the custom type object being mapped to a property in the JSON object.\nAlternatively, you can also use the @JsonValue annotation on the getter method of the customTypeObject field to tell Jackson to use the value returned by the getter method as the JSON representation of the field. Here is an example:\n @Entity\n@Table(name = \"something\") \npublic class Test {\n @Id\n private Integer id;\n\n private <SomethingHere> customTypeObject;\n\n @JsonValue\n public <SomethingHere> getCustomTypeObject() {\n return customTypeObject;\n }\n\n // Other fields, getters, and setters not shown\n}\n\nWith the @JsonValue annotation, you don't need to manually convert the custom type object to a JSON object in your controller. The Jackson library will automatically use the value returned by the getter method as the JSON representation of the customTypeObject field.\n", "If you want to save a Custom object in the database, then you can create your own Hibernate Convertors\n\nCustom Types\nJPA Converter FYI, But may be out of scope\n\nYou can also try updating the toString() method of your custom object's class.\n\nFrom your question, it is unclear where you want the desired representation, is it in a database or in a Field in UI?\n\n" ]
[ 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "hibernate", "java", "jpa", "spring", "spring_boot" ]
stackoverflow_0074539464_hibernate_java_jpa_spring_spring_boot.txt
Q: open cv can't open/read file: check file path/integrity I am creating a face detection algorithm which should take in images from a folder as input but I get this error: import dlib import argparse import cv2 import sys import time import process_dlib_boxes # construct the argument parser parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', default=r"C:\Users\awais\OneDrive\Documents\Greenwich Uni work\Face detec work\images folder", help='path to the input image') parser.add_argument('-u', '--upsample', type=float, help='factor by which to upsample the image, default None, ' + 'pass 1, 2, 3, ...') args = vars(parser.parse_args()) # read the image and convert to RGB color format image = cv2.imread(args['input']) image_cvt = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # path for saving the result image save_name = f"outputs/{args['input'].split('/')[-1].split('.')[0]}_u{args['upsample']}.jpg" # initilaize the Dlib face detector according to the upsampling value detector = dlib.get_frontal_face_detector() i get this error: [ WARN:0@0.138] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp (239) cv::findDecoder imread_('C:\Users\awais\OneDrive\Documents\Greenwich Uni work\Face detec work\images folder'): can't open/read file: check file path/integrity Traceback (most recent call last): File "C:\Users\awais\OneDrive\Documents\Greenwich Uni work\Face detec work\face_det_image.py", line 20, in <module> image_cvt = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor' A: I assume the problem is that cv2.imread is returning None because it is unable to read the input image. This can happen if the file path provided to cv2.imread is incorrect or if the file does not exist. You can try printing the value of args['input'] to make sure it is correct and points to a valid image file. You can also try using the os.path.isfile function to check if the file exists before trying to read it. Here is an example: import dlib import argparse import cv2 import sys import time import os import process_dlib_boxes # construct the argument parser parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', default=r"C:\Users\awais\OneDrive\Documents\Greenwich Uni work\Face detec work\images folder", help='path to the input image') parser.add_argument('-u', '--upsample', type=float, help='factor by which to upsample the image, default None, ' + 'pass 1, 2, 3, ...') args = vars(parser.parse_args()) # check if the input file exists if not os.path.isfile(args['input']): print(f"Error: The file {args['input']} does not exist") sys.exit(1) # read the image and convert to RGB color format image = cv2.imread(args['input']) image_cvt = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # path for saving the result image save_name = f"outputs/{args['input'].split('/')[-1].split('.')[0]}_u{args['upsample']}.jpg" # initilaize the Dlib face detector according to the upsampling value detector = dlib.get_frontal_face_detector() A: imread() is meant to read single image files, not entire folders. You must pass a path to a file, not a path to an entire directory. You passed a path to a directory. That is why imread() failed.
open cv can't open/read file: check file path/integrity
I am creating a face detection algorithm which should take in images from a folder as input but I get this error: import dlib import argparse import cv2 import sys import time import process_dlib_boxes # construct the argument parser parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', default=r"C:\Users\awais\OneDrive\Documents\Greenwich Uni work\Face detec work\images folder", help='path to the input image') parser.add_argument('-u', '--upsample', type=float, help='factor by which to upsample the image, default None, ' + 'pass 1, 2, 3, ...') args = vars(parser.parse_args()) # read the image and convert to RGB color format image = cv2.imread(args['input']) image_cvt = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # path for saving the result image save_name = f"outputs/{args['input'].split('/')[-1].split('.')[0]}_u{args['upsample']}.jpg" # initilaize the Dlib face detector according to the upsampling value detector = dlib.get_frontal_face_detector() i get this error: [ WARN:0@0.138] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp (239) cv::findDecoder imread_('C:\Users\awais\OneDrive\Documents\Greenwich Uni work\Face detec work\images folder'): can't open/read file: check file path/integrity Traceback (most recent call last): File "C:\Users\awais\OneDrive\Documents\Greenwich Uni work\Face detec work\face_det_image.py", line 20, in <module> image_cvt = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
[ "I assume the problem is that cv2.imread is returning None because it is unable to read the input image. This can happen if the file path provided to cv2.imread is incorrect or if the file does not exist.\nYou can try printing the value of args['input'] to make sure it is correct and points to a valid image file. You can also try using the os.path.isfile function to check if the file exists before trying to read it. Here is an example:\nimport dlib\nimport argparse\nimport cv2\nimport sys\nimport time\nimport os\n\nimport process_dlib_boxes\n\n# construct the argument parser\nparser = argparse.ArgumentParser()\nparser.add_argument('-i', '--input', default=r\"C:\\Users\\awais\\OneDrive\\Documents\\Greenwich Uni work\\Face detec work\\images folder\",\n help='path to the input image')\nparser.add_argument('-u', '--upsample', type=float,\n help='factor by which to upsample the image, default None, ' +\n 'pass 1, 2, 3, ...')\nargs = vars(parser.parse_args())\n\n# check if the input file exists\nif not os.path.isfile(args['input']):\n print(f\"Error: The file {args['input']} does not exist\")\n sys.exit(1)\n\n# read the image and convert to RGB color format\nimage = cv2.imread(args['input'])\nimage_cvt = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n# path for saving the result image\nsave_name = f\"outputs/{args['input'].split('/')[-1].split('.')[0]}_u{args['upsample']}.jpg\"\n# initilaize the Dlib face detector according to the upsampling value\ndetector = dlib.get_frontal_face_detector()\n\n", "imread() is meant to read single image files, not entire folders.\nYou must pass a path to a file, not a path to an entire directory.\nYou passed a path to a directory. That is why imread() failed.\n" ]
[ 0, 0 ]
[]
[]
[ "cv2", "file", "path", "python" ]
stackoverflow_0074677763_cv2_file_path_python.txt
Q: How to align two UILabels on the Y axis of the center of the first line of text please see the image below for two examples of what is to be achived the alignment should be on the Center Y of the first lines of each UILabels and should work regardless of font size or font. currently we have implemented this with different constraints to the top of the super view for different font and font size combinations. the constraint to align the center of the two UILabels does not work since the text of the second UILabel is not fixed and can have several lines. also the text is dynamic, so it is not known where the text will wrap to create the first line, thus it cannot be shown in an one line UILabel with the rest of the text in another one below. currently this is implemented using UIKit, but if there is an easy solution in SwiftUI we can put these two labels in a SwiftUI component. so a SwiftUI solution would also be welcomed. A: That's an interesting problem! You can try using the centerYAnchor for the label on the left, and the firstBaselineAnchor for the label on the right... that will align the center Y with the text baseline, which isn't quite what you want. To find the correct offset to apply, you can use the information from UIFont about the size of the characters. I'd probably start with capHeight * 0.5 and see if that looks or feels right. Something like: leftLabel.centerYAnchor.constraint(equalTo: rightLabel.firstBaseLineAnchor, constant: rightFont.capHeight * 0.5) This is a more difficult problem in SwiftUI, I think, because resolved font metrics aren't directly available to you. A: Your comments said "it should be on the glyphs" ... but, without additional information, my guess is that "real world" usage would not really need that level of precision. For example: While the glyphs are not perfectly center-Y aligned, it seems unlikely you'd run into a case where the first line of the "rightLabel" is " ' " ' " or . , . , .. This layout can be easily done with only a few constraints - no need to do any calculations: The "Positioning" label would, of course, be set .hidden = true so it would never be seen. If you really, really want glyph-precision, you'll need to calculate the Glyph bounding box for the left-label the Glyph bounding box for first line of the right-label calculate the "character box" offsets to align the Glyph Y-centers and then position the two labels accordingly, or use Core Text to draw the text (instead of using UILabel). Probably more work than necessary -- unless your actual use-case demands it.
How to align two UILabels on the Y axis of the center of the first line of text
please see the image below for two examples of what is to be achived the alignment should be on the Center Y of the first lines of each UILabels and should work regardless of font size or font. currently we have implemented this with different constraints to the top of the super view for different font and font size combinations. the constraint to align the center of the two UILabels does not work since the text of the second UILabel is not fixed and can have several lines. also the text is dynamic, so it is not known where the text will wrap to create the first line, thus it cannot be shown in an one line UILabel with the rest of the text in another one below. currently this is implemented using UIKit, but if there is an easy solution in SwiftUI we can put these two labels in a SwiftUI component. so a SwiftUI solution would also be welcomed.
[ "That's an interesting problem! You can try using the centerYAnchor for the label on the left, and the firstBaselineAnchor for the label on the right... that will align the center Y with the text baseline, which isn't quite what you want.\nTo find the correct offset to apply, you can use the information from UIFont about the size of the characters. I'd probably start with capHeight * 0.5 and see if that looks or feels right. Something like:\nleftLabel.centerYAnchor.constraint(equalTo: rightLabel.firstBaseLineAnchor, constant: rightFont.capHeight * 0.5)\n\nThis is a more difficult problem in SwiftUI, I think, because resolved font metrics aren't directly available to you.\n", "Your comments said \"it should be on the glyphs\" ... but, without additional information, my guess is that \"real world\" usage would not really need that level of precision.\nFor example:\n\nWhile the glyphs are not perfectly center-Y aligned, it seems unlikely you'd run into a case where the first line of the \"rightLabel\" is \" ' \" ' \" or . , . , ..\nThis layout can be easily done with only a few constraints - no need to do any calculations:\n\nThe \"Positioning\" label would, of course, be set .hidden = true so it would never be seen.\nIf you really, really want glyph-precision, you'll need to calculate\n\nthe Glyph bounding box for the left-label\nthe Glyph bounding box for first line of the right-label\ncalculate the \"character box\" offsets to align the Glyph Y-centers\n\nand then position the two labels accordingly, or use Core Text to draw the text (instead of using UILabel).\nProbably more work than necessary -- unless your actual use-case demands it.\n" ]
[ 2, 1 ]
[]
[]
[ "ios", "swiftui", "swiftui_alignment_guide", "uikit", "xcode" ]
stackoverflow_0074653366_ios_swiftui_swiftui_alignment_guide_uikit_xcode.txt
Q: How to detect if the video reached a certain duration with jquery? I have an HTML video tag that plays a video with a duration of 02:40: <video class="video" controls controlsList="nodownload" id="video_player" stream-type="on-demand"> <source id="update_video_source" src="./video.mp4" type="video/mp4" /> Your browser does not support the video tag. </video> I would like to know how to use jquery to add an event listener capable of showing an alert when the video duration reaches 45 seconds. A: To add an event listener that shows an alert when the video duration reaches 45 seconds in jQuery, you can use the timeupdate event of the HTMLMediaElement interface, which is triggered whenever the time position of the media changes. Here is an example: // Select the video element let video = $('#video_player'); // Add a timeupdate event listener to the video video.on('timeupdate', function() { // Check if the video duration is 45 seconds if (this.currentTime === 45) { // Show an alert alert('The video duration is 45 seconds!'); } }); In this example, i use the $('#video_player') jQuery selector to select the video element with the id attribute set to video_player. We then add an event listener to the timeupdate event of the video element using the on method. The event listener function is called whenever the timeupdate event is triggered, which occurs whenever the time position of the media changes. Inside the event listener function, we check if the currentTime property of the video element is equal to 45 seconds. If it is, we show an alert using the alert function.
How to detect if the video reached a certain duration with jquery?
I have an HTML video tag that plays a video with a duration of 02:40: <video class="video" controls controlsList="nodownload" id="video_player" stream-type="on-demand"> <source id="update_video_source" src="./video.mp4" type="video/mp4" /> Your browser does not support the video tag. </video> I would like to know how to use jquery to add an event listener capable of showing an alert when the video duration reaches 45 seconds.
[ "To add an event listener that shows an alert when the video duration reaches 45 seconds in jQuery, you can use the timeupdate event of the HTMLMediaElement interface, which is triggered whenever the time position of the media changes.\nHere is an example:\n// Select the video element\nlet video = $('#video_player');\n\n// Add a timeupdate event listener to the video\nvideo.on('timeupdate', function() {\n // Check if the video duration is 45 seconds\n if (this.currentTime === 45) {\n // Show an alert\n alert('The video duration is 45 seconds!');\n }\n});\n\nIn this example, i use the $('#video_player') jQuery selector to select the video element with the id attribute set to video_player. We then add an event listener to the timeupdate event of the video element using the on method.\nThe event listener function is called whenever the timeupdate event is triggered, which occurs whenever the time position of the media changes. Inside the event listener function, we check if the currentTime property of the video element is equal to 45 seconds. If it is, we show an alert using the alert function.\n" ]
[ 4 ]
[]
[]
[ "javascript", "jquery" ]
stackoverflow_0074678522_javascript_jquery.txt
Q: 'UIActivityViewController' doesn't work on iOS 15 iPad I used this code: let activityController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil) if let popoverPC = activityController.popoverPresentationController { popoverPC.sourceView = centerView } self.present(activityController, animated: true, completion: {}) This code worked on iOS 14.5 for iPad, after install iOS 15 it's doesn't work. any idea ? my UIActivityViewController empty area, look screen A: Found a similar issue on iPadOS 16. Resolved by adding popoverPC.sourceRect = CGRect(...) /* arbitrary rect */ or popoverPC.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
'UIActivityViewController' doesn't work on iOS 15 iPad
I used this code: let activityController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil) if let popoverPC = activityController.popoverPresentationController { popoverPC.sourceView = centerView } self.present(activityController, animated: true, completion: {}) This code worked on iOS 14.5 for iPad, after install iOS 15 it's doesn't work. any idea ? my UIActivityViewController empty area, look screen
[ "Found a similar issue on iPadOS 16. Resolved by adding\npopoverPC.sourceRect = CGRect(...) /* arbitrary rect */\n\nor\npopoverPC.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)\n\n" ]
[ 0 ]
[]
[]
[ "ios15", "ipad", "swift", "uiactivityviewcontroller" ]
stackoverflow_0069567746_ios15_ipad_swift_uiactivityviewcontroller.txt
Q: Make elements visible based on radio check value not working I'm creating an RSVP form where if a user selects that they are attending, only then would the dietary options be presented. I'm creating these options dynamically via php. For example, if there are 4 invites sent out in an RSVP, 4 options will exist for each user, i.e Name 1 - Are you attending the wedding? Yes / No - Dietary requirements Veg / Non veg Name 2 - Are you attending the wedding? Yes / No - Dietary requirements Veg / Non veg etc ... The dietary options are hidden by default (as I only want them appearing if they select yes to attendance). As such, if a user clicks "yes", then I'm trying to make that element visible. With my approach below, the dietary options do not show if "yes" is checked. I thought this may be because my fields are being generated dynamically, so I also experimented with a on change function, but it yielded the same results. (function ($) { // loop through elements with same class and check if checked $(".member__attendance-input").each(function(i, obj) { var $this = $(this); console.log(obj); if( $this.is(':checked')) { console.log("it's checked"); // make .member__dietary visible for that member $this.parent(".member").addClass("show-dietary-options"); } }); }) (jQuery); // $("document").on("change", ".member__attendance-input", function(){ // if($(this).checked){ // console.log("it's checked"); // } // }); .rsvp{ padding: 60px 0; } form{ padding: 40px; border: 1px solid #000000; } .input-label{ margin: 0 20px 0 0; } .member{ margin-bottom: 30px; } .member__name{ display: block; margin-bottom: 15px; } .member__options{ margin-bottom: 20px; } .member__dietary{ opacity: 0; height: 0; } .show-dietary-options .member__dietary{ opacity:1; height: auto; } <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <div class="rsvp"> <div class="container"> <div class="row"> <div class="col-12"> <form> <!-- member 1 --> <div class="member d-flex flex-column"> <span class="member__name">Name 1</span> <div class="member__attendance member__options d-flex"> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-yes-0" type="radio" name="attending-0" value="yes" required /> <label class="input-label" for="attending-yes-0">Yes</label> </div> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-no-0" type="radio" name="attending-0" value="no" required /> <label class="input-label" for="attending-no-0">No</label> </div> </div> <div class="member__dietary member__dietary--0 member__options d-flex"> <div class="member__dietary-option"> <input id="diet-veg-0" type="radio" name="diet-0" value="veg" required /> <label for="diet-veg-0" class="input-label">Vegetarian / Vegan</label> </div> <div class="member__dietary-option"> <input id="diet-nonveg-0" type="radio" name="diet-0" value="nonveg" required /> <label for="diet-nonveg-0" class="input-label">Non-vegetarian</label> </div> </div> </div> <!-- member 2 --> <div class="member d-flex flex-column"> <span class="member__name">Name 2</span> <div class="member__attendance member__options d-flex"> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-yes-1" type="radio" name="attending-1" value="yes" required /> <label class="input-label" for="attending-yes-1">Yes</label> </div> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-no-1" type="radio" name="attending-1" value="no" required /> <label class="input-label" for="attending-no-1">No</label> </div> </div> <div class="member__dietary member__dietary--1 member__options d-flex"> <div class="member__dietary-option"> <input id="diet-veg-1" type="radio" name="diet-1" value="veg" required /> <label for="diet-veg-1" class="input-label">Vegetarian / Vegan</label> </div> <div class="member__dietary-option"> <input id="diet-nonveg-1" type="radio" name="diet-1" value="nonveg" required /> <label for="diet-nonveg-1" class="input-label">Non-vegetarian</label> </div> </div> </div> </form> </div> </div> </div> </div> If it helps, here is the PHP snippet in which these fields are generated dynamically based on the number of people in the database. <?php foreach ($party_members as $index=>$member){ ?> <div class="member d-flex flex-column"> <span class="member__name"><?php echo $member; ?></span> <div class="member__attendance member__options d-flex"> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-yes-<?php echo $index; ?>" type="radio" name="attending-<?php echo $index; ?>" value="yes" required/> <label class="input-label side-label" for="attending-yes-<?php echo $index; ?>">Yes</label> </div> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-no-<?php echo $index; ?>" type="radio" name="attending-<?php echo $index; ?>" value="no" required/> <label class="input-label side-label" for="attending-no-<?php echo $index; ?>">No</label> </div> </div> <div class="member__dietary member__dietary--<?php echo $index; ?> member__options d-flex"> <div class="member__dietary-option"> <input id="diet-veg-<?php echo $index; ?>" type="radio" name="diet-<?php echo $index; ?>" value="veg" required/> <label for="diet-veg-<?php echo $index; ?>" class="input-label side-label">Vegetarian / Vegan</label> </div> <div class="member__dietary-option"> <input id="diet-nonveg-<?php echo $index; ?>" type="radio" name="diet-<?php echo $index; ?>" value="nonveg" required/> <label for="diet-nonveg-<?php echo $index; ?>" class="input-label side-label">Non-vegetarian</label> </div> </div> </div> <?php } How can I show the dietary options only when that user selects "yes" to attendance? Edit Have managed to show the dietary fields, but they yield mixed results. Clicking yes and then no, sometimes still keeps the dietary options available. Sometimes when clicking yes on other options (such as all of them), doesn't make them appear. Latest: (function ($) { $(".member__attendance-input").click(function() { var $this = $(this); var checkedVal = $(".member__attendance-input:checked").val(); if( checkedVal == "yes" ) { $this.closest(".member").children(".member__dietary").addClass("member__dietary--show"); } else { $this.closest(".member").children(".member__dietary").removeClass("member__dietary--show"); } }); }) (jQuery); .rsvp{ padding: 60px 0; } form{ padding: 40px; border: 1px solid #000000; } .input-label{ margin: 0 20px 0 0; } .member{ margin-bottom: 30px; } .member__name{ display: block; margin-bottom: 15px; } .member__options{ margin-bottom: 20px; } .member__dietary{ opacity: 0; height: 0; } .member__dietary--show{ opacity:1; height: auto; } <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <div class="rsvp"> <div class="container"> <div class="row"> <div class="col-12"> <form> <!-- member 1 --> <div class="member d-flex flex-column"> <span class="member__name">Name 1</span> <div class="member__attendance member__options d-flex"> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-yes-0" type="radio" name="attending-0" value="yes" required /> <label class="input-label" for="attending-yes-0">Yes</label> </div> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-no-0" type="radio" name="attending-0" value="no" required /> <label class="input-label" for="attending-no-0">No</label> </div> </div> <div class="member__dietary member__dietary--0 member__options d-flex"> <div class="member__dietary-option"> <input id="diet-veg-0" type="radio" name="diet-0" value="veg" required /> <label for="diet-veg-0" class="input-label">Vegetarian / Vegan</label> </div> <div class="member__dietary-option"> <input id="diet-nonveg-0" type="radio" name="diet-0" value="nonveg" required /> <label for="diet-nonveg-0" class="input-label">Non-vegetarian</label> </div> </div> </div> <!-- member 2 --> <div class="member d-flex flex-column"> <span class="member__name">Name 2</span> <div class="member__attendance member__options d-flex"> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-yes-1" type="radio" name="attending-1" value="yes" required /> <label class="input-label" for="attending-yes-1">Yes</label> </div> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-no-1" type="radio" name="attending-1" value="no" required /> <label class="input-label" for="attending-no-1">No</label> </div> </div> <div class="member__dietary member__dietary--1 member__options d-flex"> <div class="member__dietary-option"> <input id="diet-veg-1" type="radio" name="diet-1" value="veg" required /> <label for="diet-veg-1" class="input-label">Vegetarian / Vegan</label> </div> <div class="member__dietary-option"> <input id="diet-nonveg-1" type="radio" name="diet-1" value="nonveg" required /> <label for="diet-nonveg-1" class="input-label">Non-vegetarian</label> </div> </div> </div> </form> </div> </div> </div> </div>
Make elements visible based on radio check value not working
I'm creating an RSVP form where if a user selects that they are attending, only then would the dietary options be presented. I'm creating these options dynamically via php. For example, if there are 4 invites sent out in an RSVP, 4 options will exist for each user, i.e Name 1 - Are you attending the wedding? Yes / No - Dietary requirements Veg / Non veg Name 2 - Are you attending the wedding? Yes / No - Dietary requirements Veg / Non veg etc ... The dietary options are hidden by default (as I only want them appearing if they select yes to attendance). As such, if a user clicks "yes", then I'm trying to make that element visible. With my approach below, the dietary options do not show if "yes" is checked. I thought this may be because my fields are being generated dynamically, so I also experimented with a on change function, but it yielded the same results. (function ($) { // loop through elements with same class and check if checked $(".member__attendance-input").each(function(i, obj) { var $this = $(this); console.log(obj); if( $this.is(':checked')) { console.log("it's checked"); // make .member__dietary visible for that member $this.parent(".member").addClass("show-dietary-options"); } }); }) (jQuery); // $("document").on("change", ".member__attendance-input", function(){ // if($(this).checked){ // console.log("it's checked"); // } // }); .rsvp{ padding: 60px 0; } form{ padding: 40px; border: 1px solid #000000; } .input-label{ margin: 0 20px 0 0; } .member{ margin-bottom: 30px; } .member__name{ display: block; margin-bottom: 15px; } .member__options{ margin-bottom: 20px; } .member__dietary{ opacity: 0; height: 0; } .show-dietary-options .member__dietary{ opacity:1; height: auto; } <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <div class="rsvp"> <div class="container"> <div class="row"> <div class="col-12"> <form> <!-- member 1 --> <div class="member d-flex flex-column"> <span class="member__name">Name 1</span> <div class="member__attendance member__options d-flex"> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-yes-0" type="radio" name="attending-0" value="yes" required /> <label class="input-label" for="attending-yes-0">Yes</label> </div> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-no-0" type="radio" name="attending-0" value="no" required /> <label class="input-label" for="attending-no-0">No</label> </div> </div> <div class="member__dietary member__dietary--0 member__options d-flex"> <div class="member__dietary-option"> <input id="diet-veg-0" type="radio" name="diet-0" value="veg" required /> <label for="diet-veg-0" class="input-label">Vegetarian / Vegan</label> </div> <div class="member__dietary-option"> <input id="diet-nonveg-0" type="radio" name="diet-0" value="nonveg" required /> <label for="diet-nonveg-0" class="input-label">Non-vegetarian</label> </div> </div> </div> <!-- member 2 --> <div class="member d-flex flex-column"> <span class="member__name">Name 2</span> <div class="member__attendance member__options d-flex"> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-yes-1" type="radio" name="attending-1" value="yes" required /> <label class="input-label" for="attending-yes-1">Yes</label> </div> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-no-1" type="radio" name="attending-1" value="no" required /> <label class="input-label" for="attending-no-1">No</label> </div> </div> <div class="member__dietary member__dietary--1 member__options d-flex"> <div class="member__dietary-option"> <input id="diet-veg-1" type="radio" name="diet-1" value="veg" required /> <label for="diet-veg-1" class="input-label">Vegetarian / Vegan</label> </div> <div class="member__dietary-option"> <input id="diet-nonveg-1" type="radio" name="diet-1" value="nonveg" required /> <label for="diet-nonveg-1" class="input-label">Non-vegetarian</label> </div> </div> </div> </form> </div> </div> </div> </div> If it helps, here is the PHP snippet in which these fields are generated dynamically based on the number of people in the database. <?php foreach ($party_members as $index=>$member){ ?> <div class="member d-flex flex-column"> <span class="member__name"><?php echo $member; ?></span> <div class="member__attendance member__options d-flex"> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-yes-<?php echo $index; ?>" type="radio" name="attending-<?php echo $index; ?>" value="yes" required/> <label class="input-label side-label" for="attending-yes-<?php echo $index; ?>">Yes</label> </div> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-no-<?php echo $index; ?>" type="radio" name="attending-<?php echo $index; ?>" value="no" required/> <label class="input-label side-label" for="attending-no-<?php echo $index; ?>">No</label> </div> </div> <div class="member__dietary member__dietary--<?php echo $index; ?> member__options d-flex"> <div class="member__dietary-option"> <input id="diet-veg-<?php echo $index; ?>" type="radio" name="diet-<?php echo $index; ?>" value="veg" required/> <label for="diet-veg-<?php echo $index; ?>" class="input-label side-label">Vegetarian / Vegan</label> </div> <div class="member__dietary-option"> <input id="diet-nonveg-<?php echo $index; ?>" type="radio" name="diet-<?php echo $index; ?>" value="nonveg" required/> <label for="diet-nonveg-<?php echo $index; ?>" class="input-label side-label">Non-vegetarian</label> </div> </div> </div> <?php } How can I show the dietary options only when that user selects "yes" to attendance? Edit Have managed to show the dietary fields, but they yield mixed results. Clicking yes and then no, sometimes still keeps the dietary options available. Sometimes when clicking yes on other options (such as all of them), doesn't make them appear. Latest: (function ($) { $(".member__attendance-input").click(function() { var $this = $(this); var checkedVal = $(".member__attendance-input:checked").val(); if( checkedVal == "yes" ) { $this.closest(".member").children(".member__dietary").addClass("member__dietary--show"); } else { $this.closest(".member").children(".member__dietary").removeClass("member__dietary--show"); } }); }) (jQuery); .rsvp{ padding: 60px 0; } form{ padding: 40px; border: 1px solid #000000; } .input-label{ margin: 0 20px 0 0; } .member{ margin-bottom: 30px; } .member__name{ display: block; margin-bottom: 15px; } .member__options{ margin-bottom: 20px; } .member__dietary{ opacity: 0; height: 0; } .member__dietary--show{ opacity:1; height: auto; } <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <div class="rsvp"> <div class="container"> <div class="row"> <div class="col-12"> <form> <!-- member 1 --> <div class="member d-flex flex-column"> <span class="member__name">Name 1</span> <div class="member__attendance member__options d-flex"> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-yes-0" type="radio" name="attending-0" value="yes" required /> <label class="input-label" for="attending-yes-0">Yes</label> </div> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-no-0" type="radio" name="attending-0" value="no" required /> <label class="input-label" for="attending-no-0">No</label> </div> </div> <div class="member__dietary member__dietary--0 member__options d-flex"> <div class="member__dietary-option"> <input id="diet-veg-0" type="radio" name="diet-0" value="veg" required /> <label for="diet-veg-0" class="input-label">Vegetarian / Vegan</label> </div> <div class="member__dietary-option"> <input id="diet-nonveg-0" type="radio" name="diet-0" value="nonveg" required /> <label for="diet-nonveg-0" class="input-label">Non-vegetarian</label> </div> </div> </div> <!-- member 2 --> <div class="member d-flex flex-column"> <span class="member__name">Name 2</span> <div class="member__attendance member__options d-flex"> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-yes-1" type="radio" name="attending-1" value="yes" required /> <label class="input-label" for="attending-yes-1">Yes</label> </div> <div class="member__attendance-option"> <input class="member__attendance-input" id="attending-no-1" type="radio" name="attending-1" value="no" required /> <label class="input-label" for="attending-no-1">No</label> </div> </div> <div class="member__dietary member__dietary--1 member__options d-flex"> <div class="member__dietary-option"> <input id="diet-veg-1" type="radio" name="diet-1" value="veg" required /> <label for="diet-veg-1" class="input-label">Vegetarian / Vegan</label> </div> <div class="member__dietary-option"> <input id="diet-nonveg-1" type="radio" name="diet-1" value="nonveg" required /> <label for="diet-nonveg-1" class="input-label">Non-vegetarian</label> </div> </div> </div> </form> </div> </div> </div> </div>
[]
[]
[ "try add removeClass(\"member__dietary\")\n" ]
[ -1 ]
[ "html", "javascript", "jquery", "php" ]
stackoverflow_0074678200_html_javascript_jquery_php.txt
Q: problems with s7-1200 modbus TCP/IP SATUS 7006 ALWAYS I try to read registers through a modbus client in an s7-1200, I have tried to follow the siemens guide and it seems that all the parameters are correct, nothing seems strange, it always gives me status 7006 and the busy bit is always 1 A: Update your question with information on n how the MB_client FB configured. Your issue can't be answer without more information.
problems with s7-1200 modbus TCP/IP SATUS 7006 ALWAYS
I try to read registers through a modbus client in an s7-1200, I have tried to follow the siemens guide and it seems that all the parameters are correct, nothing seems strange, it always gives me status 7006 and the busy bit is always 1
[ "Update your question with information on n how the MB_client FB configured. Your issue can't be answer without more information.\n" ]
[ 0 ]
[]
[]
[ "plc", "siemens", "tia_portal" ]
stackoverflow_0074181443_plc_siemens_tia_portal.txt
Q: Use rails github_api to upload csv file to github repo Is there a way to upload csv file from UI and rails will upload it to github repo either with or without github_api? A: If your application can support installing/declaring octokit (as in here), you can use that library for your GitHub goals: client = Octokit::Client.new(:access_token => "YOUR_GITHUB_TOKEN") Or: client = Octokit::Client.new( client_id: ENV['GITHUB_CLIENT_ID'], client_secret: ENV['GITHUB_CLIENT_SECRET'], ) client.user(ENV['GITHUB_CLIENT_ID'], :headers => { "X-GitHub-OTP" => "2fa-token"}) Then, using create_contents: client.create_contents("username/repositoryName", "branchName", "path/to/yourFile.csv", "file...content")
Use rails github_api to upload csv file to github repo
Is there a way to upload csv file from UI and rails will upload it to github repo either with or without github_api?
[ "If your application can support installing/declaring octokit (as in here), you can use that library for your GitHub goals:\nclient = Octokit::Client.new(:access_token => \"YOUR_GITHUB_TOKEN\")\n\nOr:\nclient = Octokit::Client.new(\n client_id: ENV['GITHUB_CLIENT_ID'],\n client_secret: ENV['GITHUB_CLIENT_SECRET'],\n)\nclient.user(ENV['GITHUB_CLIENT_ID'], :headers => { \"X-GitHub-OTP\" => \"2fa-token\"})\n\nThen, using create_contents:\nclient.create_contents(\"username/repositoryName\", \"branchName\", \"path/to/yourFile.csv\", \"file...content\")\n\n" ]
[ 0 ]
[]
[]
[ "github", "ruby_on_rails", "upload" ]
stackoverflow_0074662102_github_ruby_on_rails_upload.txt
Q: Generate .cfg from golang program I am working on a Golang project which needs to dump system configuration to a designated path. Are there any libraries that can generate .cfg file from inside a golang program? I tried to search for Viper but could not find a suitable example which reads/writes to a .cfg file. It supports JSON, toml and other formats. A: It doesn't support the .cfg file format out of the box, but it's possible to create a custom configuration file type by implementing the Marshaler and Unmarshaler interfaces, like: package main import ( "fmt" "io" "os" "github.com/spf13/viper" ) type cfgFile struct { Config map[string]string } func (c *cfgFile) Marshal(w io.Writer) error { for k, v := range c.Config { if _, err := fmt.Fprintf(w, "%s = %s\n", k, v); err != nil { return err } } return nil } func (c *cfgFile) Unmarshal(r io.Reader) error { c.Config = make(map[string]string) var key, value string for { _, err := fmt.Fscanf(r, "%s = %s\n", &key, &value) if err != nil { if err == io.EOF { break } return err } c.Config[key] = value } return nil } func main() { // Create a new Viper instance. v := viper.New() // Set the configuration file type to use the custom cfgFile type. v.SetConfigType("cfg") // Set the configuration file path. v.SetConfigFile("config.cfg") // Set the configuration file type marshaler and unmarshaler. v.SetConfigMarshaler(&cfgFile{}, viper.MarshalFunc(func(v interface{}, w io.Writer) error { return v.(*cfgFile).Marshal(w) })) v.SetConfigTypeUnmarshaler("cfg", viper.UnmarshalFunc(func(r io.Reader, v interface{}) error { return v.(*cfgFile).Unmarshal(r) })) // Read the configuration file. if err := v.ReadInConfig(); err != nil { fmt.Printf("Error reading config file: %s\n", err) return } // Get a value from the configuration. value := v.GetString("key") fmt.Println(value) // Set a value in the configuration. v.Set("key", "value") // Write the configuration to the file. if err := v.WriteConfig(); err != nil { fmt.Printf("Error writing config file: %s\n", err) return } }
Generate .cfg from golang program
I am working on a Golang project which needs to dump system configuration to a designated path. Are there any libraries that can generate .cfg file from inside a golang program? I tried to search for Viper but could not find a suitable example which reads/writes to a .cfg file. It supports JSON, toml and other formats.
[ "It doesn't support the .cfg file format out of the box, but it's possible to create a custom configuration file type by implementing the Marshaler and Unmarshaler interfaces, like:\npackage main\n\nimport (\n \"fmt\"\n \"io\"\n \"os\"\n\n \"github.com/spf13/viper\"\n)\n\ntype cfgFile struct {\n Config map[string]string\n}\n\nfunc (c *cfgFile) Marshal(w io.Writer) error {\n for k, v := range c.Config {\n if _, err := fmt.Fprintf(w, \"%s = %s\\n\", k, v); err != nil {\n return err\n }\n }\n return nil\n}\n\nfunc (c *cfgFile) Unmarshal(r io.Reader) error {\n c.Config = make(map[string]string)\n var key, value string\n for {\n _, err := fmt.Fscanf(r, \"%s = %s\\n\", &key, &value)\n if err != nil {\n if err == io.EOF {\n break\n }\n return err\n }\n c.Config[key] = value\n }\n return nil\n}\n\nfunc main() {\n // Create a new Viper instance.\n v := viper.New()\n\n // Set the configuration file type to use the custom cfgFile type.\n v.SetConfigType(\"cfg\")\n\n // Set the configuration file path.\n v.SetConfigFile(\"config.cfg\")\n\n // Set the configuration file type marshaler and unmarshaler.\n v.SetConfigMarshaler(&cfgFile{}, viper.MarshalFunc(func(v interface{}, w io.Writer) error {\n return v.(*cfgFile).Marshal(w)\n }))\n v.SetConfigTypeUnmarshaler(\"cfg\", viper.UnmarshalFunc(func(r io.Reader, v interface{}) error {\n return v.(*cfgFile).Unmarshal(r)\n }))\n\n // Read the configuration file.\n if err := v.ReadInConfig(); err != nil {\n fmt.Printf(\"Error reading config file: %s\\n\", err)\n return\n }\n\n // Get a value from the configuration.\n value := v.GetString(\"key\")\n fmt.Println(value)\n\n // Set a value in the configuration.\n v.Set(\"key\", \"value\")\n\n // Write the configuration to the file.\n if err := v.WriteConfig(); err != nil {\n fmt.Printf(\"Error writing config file: %s\\n\", err)\n return\n }\n}\n\n" ]
[ 0 ]
[]
[]
[ "config", "go" ]
stackoverflow_0074678566_config_go.txt
Q: Create a nested list object with an arbitrary depth I want to create a nested list object. In this way, the user enters a positive integer, then add empty lists to the initial list, equal to the number entered by the user. The second list should be added to the first list, the third list should be added to the second list, the fourth list should be added to the third list, and so on. How can I do this using Python? Example in the picture: A: a = [] for _ in range(x): a = [a]
Create a nested list object with an arbitrary depth
I want to create a nested list object. In this way, the user enters a positive integer, then add empty lists to the initial list, equal to the number entered by the user. The second list should be added to the first list, the third list should be added to the second list, the fourth list should be added to the third list, and so on. How can I do this using Python? Example in the picture:
[ "a = []\nfor _ in range(x):\n a = [a]\n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0074678460_python.txt
Q: Chart.js not loading on reload I'm having a pretty strange issue with Chart.js in Meteor. I have one chart on the page that gets its data using Session.get('values'); to get their information. This works fine if you change routes using the menu. However if you push the reload button on the page the chart loads in but the data doesn't, if I hover over the data points on the chart it just shows the label without any number or anything. If I run the Session.get('values'); in the console it returns the data fine, and as soon as I click a menu item and then click back on the one with the chart in it, it loads fine! I am using Template.templatename.onRendered(); to load in the chart data otherwise the chart doesn't load at all. Any help is appreciated! A: Found a simple solution to this. Just declare a new variable, say for example chartUpdated. Then in your created or mounted hook, after you have updated the dynamic values to the chart object, update this.chartUpdated to true. data() { return { chartUpdated: false, areaChartData: { labels: [], datasets: [ { label: '', data: [], borderColor: colors.themeColor1, pointBackgroundColor: colors.foregroundColor, pointBorderColor: colors.themeColor1, pointHoverBackgroundColor: colors.themeColor1, pointHoverBorderColor: colors.foregroundColor, pointRadius: 4, pointBorderWidth: 2, pointHoverRadius: 5, fill: true, borderWidth: 2, backgroundColor: colors.themeColor1_10 } ] } }; }, async created() { const response = await axios.get('https://yourapi.com') const data = response.data.data this.areaChartData.labels = data.map((x) => x.day) this.areaChartData.datasets[0].data = data.map((x) => x.total_member) this.chartUpdated = true } Then in your template <area-chart v-if="chartUpdated" :data="areaChartData" container-class="chart" shadow />
Chart.js not loading on reload
I'm having a pretty strange issue with Chart.js in Meteor. I have one chart on the page that gets its data using Session.get('values'); to get their information. This works fine if you change routes using the menu. However if you push the reload button on the page the chart loads in but the data doesn't, if I hover over the data points on the chart it just shows the label without any number or anything. If I run the Session.get('values'); in the console it returns the data fine, and as soon as I click a menu item and then click back on the one with the chart in it, it loads fine! I am using Template.templatename.onRendered(); to load in the chart data otherwise the chart doesn't load at all. Any help is appreciated!
[ "Found a simple solution to this.\nJust declare a new variable, say for example chartUpdated.\nThen in your created or mounted hook, after you have updated the dynamic values to the chart object, update this.chartUpdated to true.\ndata() {\n return {\n chartUpdated: false,\n areaChartData: {\n labels: [],\n datasets: [\n {\n label: '',\n data: [],\n borderColor: colors.themeColor1,\n pointBackgroundColor: colors.foregroundColor,\n pointBorderColor: colors.themeColor1,\n pointHoverBackgroundColor: colors.themeColor1,\n pointHoverBorderColor: colors.foregroundColor,\n pointRadius: 4,\n pointBorderWidth: 2,\n pointHoverRadius: 5,\n fill: true,\n borderWidth: 2,\n backgroundColor: colors.themeColor1_10\n }\n ]\n }\n };\n },\n async created() {\n const response = await axios.get('https://yourapi.com')\n const data = response.data.data\n this.areaChartData.labels = data.map((x) => x.day)\n this.areaChartData.datasets[0].data = data.map((x) => x.total_member)\n this.chartUpdated = true\n }\n\nThen in your template\n<area-chart v-if=\"chartUpdated\" :data=\"areaChartData\" container-class=\"chart\" shadow />\n\n" ]
[ 0 ]
[]
[]
[ "chart.js", "charts", "javascript", "meteor" ]
stackoverflow_0034268825_chart.js_charts_javascript_meteor.txt