Search Results

Search found 5915 results on 237 pages for 'practices'.

Page 113/237 | < Previous Page | 109 110 111 112 113 114 115 116 117 118 119 120  | Next Page >

  • Which options do I have for Java process communication?

    - by Dmitriy Matveev
    We have a place in a code of such form: void processParam(Object param) { wrapperForComplexNativeObject result = jniCallWhichMayCrash(param); processResult(result); } processParam - method which is called with many different arguments. jniCallWhichMayCrash - a native method which is intended to do some complex processing of it's parameter and to create some complex object. It can crash in some cases. wrapperForComplexNativeObject - wrapper type generated by SWIG processResult - a method written in pure Java which processes it's parameter by creation of several kinds (by the kinds I'm not meaning classes, maybe some like hierarchies) of objects: 1 - Some non-unique objects which are referencing each other (from the same hierarchy), these objects can have duplicates created from the invocations of processParam() method with different parameter values. Since it's costly to keep all the duplicates it's necessary to cache them. 2 - Some unique objects which are referencing each other (from the same hierarchy) and some of the objects of 1st kind. After processParam is executed for each of the arguments from some set the data created in processResult will be processed together. The problem is in fact that jniCallWhichMayCrash method may crash the entire JVM and this will be very bad. The reason of crash may be such that it can happen for one argument value and not for the other. We've decided that it's better to ignore crashes inside of JVM and just skip some chunks of data when such crashes occur. In order to do this we should run processParam function inside of separate process and pass the result somehow (HOW? HOW?! This is a question) to the main process and in case of any crashes we will only lose some part of data (It's ok) without lose of everything else. So for now the main problem is implementation of transport between different processes. Which options do I have? I can think about serialization and transmitting of binary data by the streams, but serialization may be not very fast due to object complexity. Maybe I have some other options of implementing this?

    Read the article

  • Why doesn't String's hashCode() cache 0?

    - by polygenelubricants
    I noticed in the Java 6 source code for String that hashCode only caches values other than 0. The difference in performance is exhibited by the following snippet: public class Main{ static void test(String s) { long start = System.currentTimeMillis(); for (int i = 0; i < 10000000; i++) { s.hashCode(); } System.out.format("Took %d ms.%n", System.currentTimeMillis() - start); } public static void main(String[] args) { String z = "Allocator redistricts; strict allocator redistricts strictly."; test(z); test(z.toUpperCase()); } } Running this in ideone.com gives the following output: Took 1470 ms. Took 58 ms. So my questions are: Why doesn't String's hashCode() cache 0? What is the probability that a Java string hashes to 0? What's the best way to avoid the performance penalty of recomputing the hash value every time for strings that hash to 0? Is this the best-practice way of caching values? (i.e. cache all except one?) For your amusement, each line here is a string that hash to 0: pollinating sandboxes amusement & hemophilias schoolworks = perversive electrolysissweeteners.net constitutionalunstableness.net grinnerslaphappier.org BLEACHINGFEMININELY.NET WWW.BUMRACEGOERS.ORG WWW.RACCOONPRUDENTIALS.NET Microcomputers: the unredeemed lollipop... Incentively, my dear, I don't tessellate a derangement. A person who never yodelled an apology, never preened vocalizing transsexuals.

    Read the article

  • How do you handle multiple (overlapping) projects in trac?

    - by Oliver Giesen
    We are using trac and are really satisfied with it. However, out of the box, trac is best suited for single-project environments only. I'd be interested to hear about the various approaches people take to make it work with multiple projects nevertheless and their experiences with them. Are there any plugins to recommend? Any patches, tweaks or whatnots? Are you maybe even using an entirely different bug-tracking system that offers all of trac's functionality plus multi-project support? We recently started managing a second project ourselves which generally works okay but also has some drawbacks, especially where the two projects overlap because of common library code we wrote that is used in both projects. How do you handle this? (I'll attach our own current approach as an answer to this post.)

    Read the article

  • Number of characters recommended for a statement

    - by liaK
    Hi, I have been using Qt 4.5 and so do C++. I have been told that it's a standard practice to maintain the length of each statement in the application to 80 characters. Even in Qt creator we can make a right border visible so that we can know whether we are crossing the 80 characters limit. But my question is, Is it really a standard being followed? Because in my application, I use indenting and all, so it's quite common that I cross the boundary. Other cases include, there might be a error statement which will be a bit explanatory one and which is in an inner block of code, so it too will cross the boundary. Usually my variable names look bit lengthier so as to make the names meaningful. When I call the functions of the variable names, again I will cross. Function names will not be in fewer characters either. I agree a horizontal scroll bar shows up and it's quite annoying to move back and forth. So, for function calls including multiple arguments, when the boundary is reached I will make the forth coming arguments in the new line. But besides that, for a single statement (for e.g a very long error message which is in double quotes " " or like longfun1()->longfun2()->...) if I use an \ and split into multiple lines, the readability becomes very poor. So is it a good practice to have those statement length restrictions? If this restriction in statement has to be followed? I don't think it depends on a specific language anyway. I added C++ and Qt tags since if it might. Any pointers regarding this are welcome.

    Read the article

  • Rapid Opening and Closing System.IO.StreamWriter in C#

    - by ccomet
    Suppose you have a file that you are programmatically logging information into with regards to a process. Kinda like your typical debug Console.WriteLine, but due to the nature of the code you're testing, you don't have a console to write onto so you have to write it somewhere like a file. My current program uses System.IO.StreamWriter for this task. My question is about the approach to using the StreamWriter. Is it better to open just one StreamWriter instance, do all of the writes, and close it when the entire process is done? Or is it a better idea to open a new StreamWriter instance to write a line into the file, then immediately close it, and do this for every time something needs to be written in? In the latter approach, this would probably be facilitated by a method that would do just that for a given message, rather than bloating the main process code with excessive amounts of lines. But having a method to aid in that implementation doesn't necessarily make it the better choice. Are there significant advantages to picking one approach or the other? Or are they functionally equivalent, leaving the choice on the shoulders of the programmer?

    Read the article

  • Is it a good or bad practice to call instance methods from a java constructor?

    - by Steve
    There are several different ways I can initialize complex objects (with injected dependencies and required set-up of injected members), are all seem reasonable, but have various advantages and disadvantages. I'll give a concrete example: final class MyClass { private final Dependency dependency; @Inject public MyClass(Dependency dependency) { this.dependency = dependency; dependency.addHandler(new Handler() { @Override void handle(int foo) { MyClass.this.doSomething(foo); } }); doSomething(0); } private void doSomething(int foo) { dependency.doSomethingElse(foo+1); } } As you can see, the constructor does 3 things, including calling an instance method. I've been told that calling instance methods from a constructor is unsafe because it circumvents the compiler's checks for uninitialized members. I.e. I could have called doSomething(0) before setting this.dependency, which would have compiled but not worked. What is the best way to refactor this? Make doSomething static and pass in the dependency explicitly? In my actual case I have three instance methods and three member fields that all depend on one another, so this seems like a lot of extra boilerplate to make all three of these static. Move the addHandler and doSomething into an @Inject public void init() method. While use with Guice will be transparent, it requires any manual construction to be sure to call init() or else the object won't be fully-functional if someone forgets. Also, this exposes more of the API, both of which seem like bad ideas. Wrap a nested class to keep the dependency to make sure it behaves properly without exposing additional API:class DependencyManager { private final Dependency dependency; public DependecyManager(Dependency dependency) { ... } public doSomething(int foo) { ... } } @Inject public MyClass(Dependency dependency) { DependencyManager manager = new DependencyManager(dependency); manager.doSomething(0); } This pulls instance methods out of all constructors, but generates an extra layer of classes, and when I already had inner and anonymous classes (e.g. that handler) it can become confusing - when I tried this I was told to move the DependencyManager to a separate file, which is also distasteful because it's now multiple files to do a single thing. So what is the preferred way to deal with this sort of situation?

    Read the article

  • Is it a good practice to perform direct database access in the code-behind of an ASP.NET page?

    - by patricks418
    Hi, I am an experienced developer but I am new to web application development. Now I am in charge of developing a new web application and I could really use some input from experienced web developers out there. I'd like to understand exactly what experienced web developers do in the code-behind pages. At first I thought it was best to have a rule that all the database access and business logic should be performed in classes external to the code-behind pages. My thought was that only logic necessary for the web form would be performed in the code-behind. I still think that all the business logic should be performed in other classes but I'm beginning to think it would be alright if the code-behind had access to the database to query it directly rather than having to call other classes to receive a dataset or collection back. Any input would be appreciated.

    Read the article

  • How to differentiate between exceptions i can show the user, and ones i can't?

    - by Ian Boyd
    i have some business logic that traps some logically invalid situations, e.g. trying to reverse a transaction that was already reversed. In this case the correct action is to inform the user: Transaction already reversed or Cannot reverse a reversing transaction or You do not have permission to reverse transactions or This transaction is on a session that has already been closed or This transaction is too old to be reversed The question is, how do i communicate these exceptional cases back to the calling code, so they can show the user? Do i create a separate exception for each case: catch (ETransactionAlreadyReversedException) MessageBox.Show('Transaction already reversed') catch (EReversingAReversingTransactionException) MessageBox.Show('Cannot reverse a reversing transaction') catch (ENoPermissionToReverseTranasctionException) MessageBox.Show('You do not have permission to reverse transactions') catch (ECannotReverseTransactionOnAlredyClosedSessionException) MessageBox.Show('This transaction is on a session that has already been closed') catch (ECannotReverseTooOldTransactionException) MessageBox.Show('This transaction is too old to be reversed') Downside for this is that when there's a new logical case to show the user: Tranasctions created by NSL cannot be reversed i don't simply show the user a message, and instead it leaks out as an unhandled excpetion, when really it should be handled with another MessageBox. The alternative is to create a single exception class: `EReverseTransactionException` With the understanding that any exception of this type is a logical check, that should be handled with a message box: catch (EReverseTransactionException) But it's still understood that any other exceptions, ones that involve, for example, an memory ECC parity error, continue unhandled. In other words, i don't convert all errors that can be thrown by the ReverseTransaction() method into EReverseTransactionException, only ones that are logically invalid cause of the user.

    Read the article

  • #Define Compiler Directive in C#

    - by pm_2
    In C, I could declare a compiler directive as follows: #define MY_NUMBER 10 However, in C#, I only appear to be able to do this: #define MY_NUMBER Which is obviously useless in this case. Is this correct, or am I doing something wrong? If not, can anyone suggest a way of doing this, either at namespace or solution level? I thought of maybe creating a static class, but that seems to be overkill for one value.

    Read the article

  • Should every class have its own namespace?

    - by thehouse
    Something that has been troubling me for a while: The current wisdom is that types should be kept in a namespace that only contains functions which are part of the type's non-member interface (see C++ Coding Standards Sutter and Alexandrescu or here) to prevent ADL pulling in unrelated definitions. Does this imply that all classes must have a namespace of their own? If we assume that a class may be augmented in the future by the addition of non-member functions, then it can never be safe to put two types in the same namespace as either one of them may introduce non-member functions that could interfere with the other. The reason I ask is that namespaces are becoming cumbersome for me. I'm writing a header-only library and I find myself using classes names such as project::component::class_name::class_name. Their implementations call helper functions but as these can't be in the same namespace they also have to be fully qualified!

    Read the article

  • Processing forms that generate many rows in DB

    - by Zack
    I'm wondering what the best approach to take here is. I've got a form that people use to register for a class and a lot of times the manager of a company will register multiple people for the class at the same time. Presently, they'd have to go through the registration process multiple times and resubmit the form once for every person they want to register. What I want to do is give the user a form that has a single <input/> for one person to register with, along with all the other fields they'll need to fill out (Email, phone number, etc); if they want to add more people, they'll be able to press a button and a new <input/> will be generated. This part I know how to do, but I'm including it to best describe what I'm aiming to do. The part I don't know how to approach is processing that data the form submits, I need some way of making a new row in the Registrant table for every <input/> that's added and include the same contact information (phone, email, etc) as the first row with that row. For the record, I'm using the Django framework for my back-end code. What's the best approach here? Should it just POST the form x times for x people, or is there a less "brute force" way of handling this?

    Read the article

  • How to avoid nested functions when using AJAX?

    - by Fletcher Moore
    Sequential Asynchronous calls are gross. Is there a more readable solution? The problem is this is hard to follow: ajaxOne(function() { // do something ajaxTwo(function() { // do something ajaxThree() }); }); where the anonymous functions are callbacks that are called on server response. I'm using a third party API to make the AJAX calls, so I need a generic solution.

    Read the article

  • Why would you precede the main() function in C with a data type?

    - by Milktrader
    Many are familiar with the hello world program in C #include <stdio.h> main () { printf ("hello world"); return 0; } Why do some precede the main () function with int as in: int main() Also, I've seen the word 'void' entered inside the () as in: int main(void) It seems like extra typing for nothing, but maybe it's a best practice that pays dividends in other situations? Also, why precede main() with an int if you're returning a character string? If anything, one would expect: char main(void) I'm also foggy about why we return 0 at the end of the function.

    Read the article

  • SELECT product from subclass: How many queries do I need?

    - by Stefano
    I am building a database similar to the one described here where I have products of different type, each type with its own attributes. I report a short version for convenience product_type ============ product_type_id INT product_type_name VARCHAR product ======= product_id INT product_name VARCHAR product_type_id INT -> Foreign key to product_type.product_type_id ... (common attributes to all product) magazine ======== magazine_id INT title VARCHAR product_id INT -> Foreign key to product.product_id ... (magazine-specific attributes) web_site ======== web_site_id INT name VARCHAR product_id INT -> Foreign key to product.product_id ... (web-site specific attributes) This way I do not need to make a huge table with a column for each attribute of different product types (most of which will then be NULL) How do I SELECT a product by product.product_id and see all its attributes? Do I have to make a query first to know what type of product I am dealing with and then, through some logic, make another query to JOIN the right tables? Or is there a way to join everything together? (if, when I retrieve the information about a product_id there are a lot of NULL, it would be fine at this point). Thank you

    Read the article

  • Is it advisable to have an interface as the return type?

    - by wb
    I have a set of classes with the same functions but with different logic. However, each class function can return a number of objects. It is safe to set the return type as the interface? Each class (all using the same interface) is doing this with different business logic. protected IMessage validateReturnType; <-- This is in an abstract class public bool IsValid() <-- This is in an abstract class { return (validateReturnType.GetType() == typeof(Success)); } public IMessage Validate() { if (name.Length < 5) { validateReturnType = new Error("Name must be 5 characters or greater."); } else { validateReturnType = new Success("Name is valid."); } return validateReturnType; } Are there any pitfalls with unit testing the return type of an function? Also, is it considered bad design to have functions needing to be run in order for them to succeed? In this example, Validate() would have to be run before IsValid() or else IsValid() would always return false. Thank you.

    Read the article

  • Alternative to jQuery .data()?

    - by thebossman
    I'm a big fan of jQuery's .data() method, but I can't always use it. Often times I am rendering html templates that I pass via AJAX and I need to attach metadata to each of the elements in the template. For example: <ul> {% for item in itemlist %} <li metadata="{{ item.metadata }}">{{ item.name }}</li> {% endfor %} </ul> I know attaching attributes to store data is bad practice (and it might not even work in older versions of IE). What is the best practice? Is there a good alternative to this method?

    Read the article

  • How can I make an iterator that never ends?

    - by Soldier.moth
    I was just wondering what the easiest way to iterate over a set indefinitely, i.e. when it reaches the end it next(); calls the first object. I'm assuming that this is not an already predefined function in Java, so just looking for the easiest way to implement this in Java.

    Read the article

  • Returning back to the results after editing

    - by Parhs
    Hello, I am developing an application which has several CRUD actions... I am using Java and i am forced to use Struts framework. My problem is: I have a search page which returns some results.The user can click at a result and then he goes to another edit-page... He may apply changes or not...What i need is a way to return at the result page again and at the same scroll position.Javascript must be enabled for this project however.. I am wondering which is the best practice to achieve this effect... A solution would be to save the last search URL but i know that this wouldnt work if the user has multiple results. I know how to do it but i am lloking for a good practice!

    Read the article

  • Where to place the login/authentication related actions in MVC

    - by rogeriopvl
    I've searched around and found that when implementing an authentication module in MVC architecture some people opt to place the login related actions in the User controller while others place it in a controller dedicated to authentication only. In pseudo-java-like code: class UserController extends Controller { public login() { //... } } Accessed with http://mydomain.com/user/login. vs. class AuthController extends Controller { public login() { //... } } Accessed with http://mydomain.com/auth/login. I would like to know which approach is better, and why. That is, if there's really any difference at all. Thanks in advance.

    Read the article

  • Is this multi line if statement too complex?

    - by AndHeCodedIt
    I am validating input on a form and attempting to prompt the user of improper input(s) based on the combination of controls used. For example, I have 2 combo boxes and 3 text boxes. The 2 combo boxes must always have a value other than the first (default) value, but one of three, or two of three, or all text boxes can be filled to make the form valid. In one such scenario I have a 6 line if statement to try to make the test easily readable: if ((!String.Equals(ComboBoxA.SelectedValue.ToString(), DEFAULT_COMBO_A_CHOICE.ToString()) && !String.IsNullOrEmpty(TextBoxA.Text) && !String.Equals(ComboBoxB.SelectedValue.ToString(), DEFAULT_COMBO_B_CHOICE.ToString())) || (!String.IsNullOrEmpty(TextBoxB.Text) || !String.IsNullOrEmpty(TextBoxC.Text))) { //Do Some Validation } I have 2 questions: Should this type of if statement be avoided at all cost? Would it be better to enclose this test in another method? (This would be a good choice as this validation will happen in more than one scenario) Thanks for your input(s)!

    Read the article

  • effective counter for unique number of visits in PHP & MySQL

    - by Adnan
    Hello, I am creating a counter for unique number of visits on a post, so what I have until now is a table for storing data like this; cvp_post_id | cvp_ip | cvp_user_id In cases a registered user visits a post, for the first time a record is inserted with cpv_post_id and cvp_user_id, so for his next visit I query the table and if the record is available I do not count him as a new visitor. In cases of an anonymous user the same happens but now the cvp_ip and cpv_post_id are used. My concerns is that I do a query every time anyone visits a post for checking if there has been a visit, what would be a more effective way for doing this?

    Read the article

  • Comparing objects and inheritance

    - by ereOn
    Hi, In my program I have the following class hierarchy: class Base // Base is an abstract class { }; class A : public Base { }; class B : public Base { }; I would like to do the following: foo(const Base& one, const Base& two) { if (one == two) { // Do something } else { // Do something else } } I have issues regarding the operator==() here. Of course comparing an instance A and an instance of B makes no sense but comparing two instances of Base should be possible. (You can't compare a Dog and a Cat however you can compare two Animals) I would like the following results: A == B = false A == A = true or false, depending on the effective value of the two instances B == B = true or false, depending on the effective value of the two instances My question is: is this a good design/idea ? Is this even possible ? What functions should I write/overload ? My apologies if the question is obviously stupid or easy, I have some serious fever right now and my thinking abilities are somewhat limited :/ Thank you.

    Read the article

  • Best practice question

    - by sid_com
    Hello! Which version would you prefer? #!/usr/bin/env perl use warnings; use strict; use 5.010; my $p = 7; # 33 my $prompt = ' : '; my $key = 'very important text'; my $value = 'Hello, World!'; my $length = length $key . $prompt; $p -= $length; Option 1: $key = $key . ' ' x $p . $prompt; Option 2: if ( $p > 0 ) { $key = $key . ' ' x $p . $prompt; } else { $key = $key . $prompt; } say "$key$value"

    Read the article

< Previous Page | 109 110 111 112 113 114 115 116 117 118 119 120  | Next Page >