Java how to change number dynamically in terminal [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Recently I working on one a simulation project. I need to show home temperature status.
int homeTemp = 20;
System.out.println(homeTemp + " Degree");
Example Output: 20 Degree
I want to update the degree value dynamically and real-time in the terminal after running the code.
Trying to show this more realistic and similative way and I want to change that terminal output dynamically like (20 degrees> Every 5-10 second update value random(current temperature +- 5 degrees)
Is that possible to do this in Java?

It's way more complicated than you'd think. There isn't really such a thing as a 'terminal' to java. There is a stream of bytes that flow into the process, and a stream of bytes that flow out. If you write, for example:
java -jar someapp.jar >somefile.txt
then it starts to make sense that 'update a value' becomes impossible (yes, you can overwrite bytes in a file, but that >somefile.txt could also be >/dev/printer, and you can't exactly ask the printer to grow legs, walk over to the desk of the gal who just grabbed the paper out of it, swallow the paper back in, and unprint what it printed before.
Various terminals have 'rich support' and have certain byte sequences that don't print as characters but affect it in some other way: Move the 'cursor' around, make the background of any future text to be shown blue, clear the screen, etcetera.
That's how one would do this: Send these escape codes (Print them). Both the codes you need to send, as well as figuring out if the thing you are printing to even supports them, is OS dependent and are there are a lot of options, thus, java doesn't ship out of the box with a library that tries to sail this mess.
But, good news!
They do exist! Lanterna for example. You'd have to add the jar to your project (or add the group/artifact/version to your dependencies list if you use e.g. maven, gradle, or some other build system that takes care of this for you).
Alternatively, don't make a terminal app but a swing (desktop, graphical user interface) one, where updating a JTextField or what not is trivial.

Is that possible to that in Java? Thank you
Yes.
You're welcome :)
Learn how to use threads and the runnable interface as well as how to keep track of time in threads)
The internet in general (and this site... you should really do a search first) will have all the info you need.

Related

Question about modelling a railway system [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am currently working on a task, where I have to build a railway simulation project in java (university project).
There are three types of rolling stock: wagon, locomotive and multiple unit.
All types of the rolling stock have a name and a length.
In addition, there are also three types of wagons and locomotives.
Here is a simple UML diagram that I created.
Now, I still have to implement this "feature":
"The multiple unit ID is composed according to the same rules as for locomotives. For this reason, locomotives and multiple units share the same ID space. A multiple unit has a special type of coupling and can therefore only be composed with the same series of multiple units"
What is the best way to use the same ID space for locomotives and multiple units?
Is this a good model or should I use interfaces instead? I would appreciate feedback and tips. Thanks in advance!
What is the best way to use the same ID space for locomotives and multiple units?
Doesn't matter, as long as it is unique. Just use a serial number or, if you want to have one that isn't tied to a single counter, use a fully random one (of 128 bits or more). Why not use a standard while you're at it.
One question you should ask yourself is: is this ID going to be used on the wagons? If so, a short, statically serial number (or string) certainly makes more sense. Probably there will be some registration body so in that case you have your centralized counter right there. Never forget to check if your model matches the real world!
It makes some sense to prefix the ID with the type of transport, although in that case I think it is not really using the same space anymore.
Is this a good model or should I use interfaces instead? I would appreciate feedback and tips.
EDIT: WRONG, I ASSUMED ALL ROLLING STOCK WOULD HAVE AN ID!!!
No, this is fine, you have operations on the ID after all. And you're probably going to add other functionality that it similar for all child classes to the rolling stock. Note that many environments have methods to extract an interface and replace the existing references to that interface. Refactoring is not something you want to do, but it is there when you need it.
EDIT:
If you have an ID just for locomotives and rolling stock then there are two options. Probably best is to insert an intermediate abstract class that defines an IdentifyableRollingStock intermediate class. There are other options out there such as creating an optional ID, or using a decorator pattern. It is a bit strange if wagons cannot be identified though, in NL I'm pretty sure that all rolling stock is identifiable.
I'm just left wondering if all rolling stock really has a name. I can see some cargo wagons just having a number. That's another real world check right there.
OT
A multiple unit has a special type of coupling and can therefore only be composed with the same series of multiple units"
The person who wrote that should be shot into orbit. Well be nice and make it the ISS. Going round and round and round...

Importing massive dataset to Neo4j is extremely slow [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a rather large dataset, ~68 million data points. The data is currently stored in MongoDB and I have written a Java program that goes through the data to link data points together and place them in the Neo4j database using Cypher commands. I ran this program with a test set of data (~1.5 million) and it worked, ran it overnight. Now when I try to import the whole dataset, the program is extremely slow. Ran the whole weekend and only ~350,000 data points have made it. Through some short testing, it seems like Neo4j is the bottleneck. It's been half an hour since I stopped the Java program but Neo4j's CPU usage is at 100% and new nodes are still being added (from the Java program). Is there anyway to overcome this bottleneck? I've thought about multithreading, but since I'm trying to create a network, there are lots of dependencies and non-thread-safe operations being performed. Thanks for your help!
EDIT: The data I have is a list of users. The data that is contained is the user id, and an array of the user's friends' ids. My Cypher queries look a little like this:
"u:USER {id:" + currentID + "}) CREATE (u)-[:FRIENDS {ts:" + timeStamp}]->(u" + connectionID + ":USER {id:" + connectionID + "})"
Sorry if this is really terrible, pretty new to this
You should first look at this:
neo4j import slowing down
If you still decide to DIY, there's a few things you should look out for: First, make sure you don't try to import all your data in one transaction, otherwise your code will spend most of the time suspended by the Garbage Collector. Second, ensure you have given plenty of memory to the Neo4j process (or your application if you're using an embedded instance of Neo4j). 68 million nodes is trivial for Neo4j, but if the Cypher you're generating is constantly looking things up to e.g. create new relationships, then you'll run into severe paging issues if you don't allocate enough memory. Finally, if you are looking up nodes by properties (rather than by id) then you should be using labels and schema indexes:
http://neo4j.com/news/labels-and-schema-indexes-in-neo4j/
Did you configure neo4j.properties and neo4j-wrapper.conf files?
It is highly recommended to adjust the values according to the amount of RAM available on your machine.
in conf/neo4j-wrapper.conf I usually use for a 12GB RAM server
wrapper.java.initmemory=8000
wrapper.java.maxmemory=8000
in conf/neo4j.properties I set
dbms.pagecache.memory=8000
See http://neo4j.com/blog/import-10m-stack-overflow-questions/ for a complete example to import 10M nodes in a few minutes, it's a good starting point
SSD are also recommended to speed up import.
One thing I learned when loading bulk data into a database was to switch off indexing temporarily on the destination table(s). Otherwise every new record added caused a separate update to the indexes, resulting in a lot of work on the disk. It was much quicker to re-index the whole table in a separate operation after the data load was complete. YMMV.

Calculating the Beat/Minute in a Audio File in Android [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to calculate the beat per minute in a Audio File in android , I have just a small clue , There is a Visualizer Library which creates a DIGITAL BAR effect with the Audio files wave , I can check for the beat with this , Is this the correct solution or is there any proper way to do this ? I want to categorize Audio files in a proper way. According to the Beat/minute in a File.
Any help would be greatfull
Beats per minute can be calculated with multiple levels, a simple energy calculator which you are referring to by the should level meter or VAD (voice/ audio activity detector) can be somewhat simple to make, where as a proper pitch detector, this is a complex process and isolating the beat of music segment can be complex since perception of a beat is complex.
If you are simply interested in energy calculator/ beat like feature what you can do is have a two running averages and see how large is your signal relative to the other.
X= [x1……xn] input audio samples, separate the buffers into smaller segment say 100 samples. n=100,
Take the absolute value for this array abs(X),
Simple one pole smoothing function can be made with
X_filtered_long= X_filtered_long . (1-alpha) + abs(X). alpha // alpha is .02, value depends on the sample rate, signals and what beat of interest
Create the second filtered signals
X_filtered_short= X_filtered_short . (1-beta) + abs(X). beta // beta is .2
If (X_filtered_short > X_filtered_long)
Detected_beat= 1;
InsideBeat=+1;
else
Detected_beat= 0;
InsideBeat=0;
If you want to, "I want to categorize Audio files in a proper way. According to the Beat/minute in a File." This can only be done with finger printing the audio with parameters such as MFCC.
Good reference would be
Automatic genre classification of music content: a survey
Scaringella, N. ; Zoia, G. ; Mlynek, D.
Signal Processing Magazine, IEEE
Volume: 23 , Issue: 2
What you're asking here is tremendously difficult.
Audio analysis to get the beats is usually done with complex mathematical manipulation of the audio data, by transforming the audio signal from the time-domain to the frequency-domain using signal-processing techniques. There are whole books dedicated to this subject.
Visualizers like the one you mention internally use many of these DSP techniques and it would probably be an even worse nightmare to analyze the visualizer data than the audio data.
Even if you manage to find a library that does this for you, the results would be very unreliable. Maybe for electronic music where the beats are more obvious you would get better results than for classical music or jazz.

How to make a custom video player W/ embed options! Rare [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
First question: What would be the best language to create a video player in? / Anyone point me in the direction of a tut that can help me write said script?
Second Question: How can I code such player to echo a embed code for each video: Ala youtube/break/viemo.
^ whats amazing to me, is the fact I searched google for a day and a half and haven't even come close to someone explaining how to build a video player, let alone have a option for it to spit out a embed code or any other sharing options.
Usage info: Once the player is finished it will be imported into wordpress, so I can have total control of each video and manage them accordingly. Not asking for help for importing to WP but any tips would be great.
{Please don't point me to VideoJS or any other video service, as I will make my own and not pay for a license.}
In general, a video player is a picture gallery, where twenty four (or more) pictures are displayed in order every second during the entire duration of the film. Twenty four is the lowest limit for a person to visually confuse static pictures with motion, for better effects I would recommend thirty or more.
The second component of a video player is typically a music player, which displays many "frames" of music per second, which blend through the digital to analog playback system into something resembling continuous sound.
Getting these two subsystems to operate without letting one get ahead of the other is generally required for a "video playback" system. There are many "already done" systems, but it sounds like you envision building your own (to add in unique "features").
Keep in mind that there are very large volumes of data moving around in "video playback". This means that if it is possible, compressing the data is vital for reasonable performance. Compression routines are not as simple as they seem, and the major video codecs are those that do a good job of balancing CPU cycles to decompress, file size, and resulting image quality.
Assuming you really don't want to write a video player, but just want to use someone else's video player "with enhancements", you will be at the mercy of how well built the existing video player is, whether or not it supports any kind of customization, and if it does, how well it supports the customization you have in mind.
Since speed is such a consideration, even though more advanced languages exist, traditionally these things are done in C, assembly, or even hardware acceleration chips.
These are my thought, although you should try to search a little better... Tutorials are very easy to find ...
You could use Flash / ActionScript to create a custom video player. It's still common on the net, although more and more non-flash players are rising (HTML5). I still prefer Flash because of the performance, but keep in mind that iPhone / iPad doesn't support Flash...
If you are going to script your own videoplayer in Flash, this tutorial will set you off to create your own implementation...
For your second question:
Just create a database with a unique ID for every video URL your player will have. When you create the embed code you can include this unique ID as a URL var to the main video player.
From there on you can call your player page with URL vars (example: http://www.yourlink.com?videoid=ID).
When you embed your SWF object you can then pass the videoid along with a FlashVar, or prefetch the matching video URL and send that URL with a FlashVar to your SWF. It's not so complicated, more info can be found here.
try osmf.org. You can either use the strobe media playback with it or build your own player around it. OSMF is pretty robust

Music library for using with threads [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I would like to write programs that play music ( audio or midi or even pure tones will be ok)
But I would like to use it with threads, a thread play a sound while other thread play other sound.
Threads 1 * Can play pure tones in different intensity and frecuency
(to form a more complex envelop, creating the "timbre" of the sound))
Threads 2 * A group of threads 1 could play different notes in a given timbre
(to form chords from an instrument sound)
Threads 3 * A group of threads 2 could play chords in different notes
(to represent a musician)
Threads 4 * A group of threads 3 can become an orchestra! =)
The hard part here I think is that I want to output different sounds at same time, preprocessing that would be the typical way, but if the mix of sound can be done live, it becomes really more interesting.
Any ideas, experiences, libraries or info would help, thanks in advance!
I don't think threads are what you want here. The synchronization would be too difficult. What you probably want to do (and what I did for a similar application years ago), was maintain a data structure of active notes (could be implemented with class instances, or closures, or whatever works), and for each sample, call each item in the structure, sum the output (I'd recommend using signed 16bit math at this point, so your values are in a range of -32767 to +32768). To mix just sum the various signals.
Something like the following:
#ts = A clock, in eg, seconds, passed in to your calls for generation purposes.
sample = sum([notefunc(ts) for notefunc in notes])
#Now convert the sample to whatever format needed for your media lib
#Update notes array
... and repeat that loop 44100 times/sec. Some sort of buffering would probably be needed. Actual realtime was tricky. Back when I was playing around with this stuff (~2000 on a 233mhz G3 Powerbook) I could get real time with one or two simple notes, but not more.
You may want to have a look at the GStreamer framework. It allows you model audiostreams as "pipelines" composed of elements. Parallel elements will be automatically processed in different threads. Elements can be kept in sync using "clocks".
Have a look at the manual. The first 10 chapters will give you a good overview of the possibilities. (And it reads quickly.)
Looking at the list of plugins there seems to be some support for midi.
jMusic seems to have a comprehensive library. The links page on their site has further resources too.
[n.b. I haven't used this in anger; I looked at it some years back and went for a commercial package instead...]
hth, R
Here is an interesting blog that joins the music and software together. This page of the blog is dedicated to threading and lock free algorithms in musical software and there is a list of libraries. Also here is another list that you will be interested in.
Think about using Juce library ( http://www.rawmaterialsoftware.com/juce.php).
It's a C++ crossplatform library.
It has many different features ( http://www.rawmaterialsoftware.com/jucefeatures.php) in addition to audio function:
Threads syncronization functions
Gui building and graphics features
Support for VST plugins
Midi support
Double licensed (GPL 2.0 or proprietary licenses) allow you to redistribute your work or write closed source applications.
A lot of professional audio application are written with this library, like MAX/MSP ( http://en.wikipedia.org/wiki/Max_%28software%29 )
I would recommend JFugue.
I have used this library myself for programming music using multiple threads.
As an experiment, I have adapted an existing Piano module that is also using JFugue.

Categories

Resources