Search Results

Search found 1868 results on 75 pages for 'cast'.

Page 3/75 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Convert to list after Cast<T>

    - by Timmie Sarjanen
    Hi, I need to convert an IQueryable to List(is it possible to convert to IList?). There had not been an problem if it was not that i need to Cast because I have interfaces to my objects. I've tried most things but for some reason I must run Cast first and then ToList() which generates System.NullReferenceException. How do I solve this? public IQueryable GetPhrases() { return (from r in _repository.All<Phrase>() select r).Cast<IPhrase() }

    Read the article

  • How to prevent CAST errors on SSIS ?

    - by manitra
    Hello, The question Is it possible to ask SSIS to cast a value and return NULL in case the cast is not allowed instead of throwing an error ? My environment I'm using Visual Studio 2005 and Sql Server 2005 on Windows Server 2003. The general context Just in case you're curious, here is my use case. I have to store data coming from somewhere in a generic table (key/value structure with history) witch contains some sort of value that can be strings, numbers or dates. The structure is something like this : table Values { Id int, Date datetime, -- for history Key nvarchar(50) not null, Value nvarchar(50), DateValue datetime, NumberValue numeric(19,9) } I want to put the raw value in the Value column and try to put the same value in the DateValue column when i'm able to cast it to Datetime in the NumberValue column when i'm able to cast it to a number Those two typed columns would make all sort of aggregation and manipulation much easier and faster later. That's it, now you know why i'm asking this strange question. ============ Thanks in advance for your help.

    Read the article

  • Primitive type 'short' - casting in Java

    - by gemm
    Hello, I have a question about the primitive type 'short' in Java. I am using JDK 1.6. If I have the following: short a = 2; short b = 3; short c = a + b; the compiler does not want to compile - it says that it "cannot convert from int to short" and suggests that I make a cast to short, so this: short c = (short) (a + b); really works. But my question is why do I need to cast? The values of a and b are in the range of short - the range of short values is {-32,768, 32767}. I also need to cast when I want to perform the operations -, *, / (I haven't checked for others). If I do the same for primitive type int, I do not need to cast aa+bb to int. The following works fine: int aa = 2; int bb = 3; int cc = aa +bb; I discovered this while designing a class where I needed to add two variables of type short, and the compiler wanted me to make a cast. If I do this with two variables of type int, I don't need to cast. Thank you very much in advance. A small remark: the same thing also happens with the primitive type byte. So, this workes: byte a = 2; byte b = 3; byte c = (byte) (a + b); but this not: byte a = 2; byte b = 3; byte c = a + b; For long, float, double, and int, there is no need to cast. Only for short and byte values.

    Read the article

  • How to cast C struct just another struct type if their memory size are equal?

    - by Eonil
    I have 2 matrix structs means equal data but have different form like these: // Matrix type 1. typedef float Scalar; typedef struct { Scalar e[4]; } Vector; typedef struct { Vector e[4]; } Matrix; // Matrix type 2 (you may know this if you're iPhone developer) struct CATransform3D { CGFloat m11, m12, m13, m14; CGFloat m21, m22, m23, m24; CGFloat m31, m32, m33, m34; CGFloat m41, m42, m43, m44; }; typedef struct CATransform3D CATransform3D; Their memory size are equal. So I believe there is a way to convert these types without any pointer operations or copy like this: // Implemented from external lib. CATransform3D CATransform3DMakeScale (CGFloat sx, CGFloat sy, CGFloat sz); Matrix m = (Matrix)CATransform3DMakeScale ( 1, 2, 3 ); Is this possible? Currently compiler prints an "error: conversion to non-scalar type requested" message.

    Read the article

  • Moq: Unable to cast to interface

    - by Pickels
    Hello, earlier today I asked this question. So since moq creates it's own class from an interface I wasn't able to cast it to a different class. So it got me wondering what if I created a ICustomPrincipal and tried to cast to that. This is how my mocks look: var MockHttpContext = new Mock<HttpContextBase>(); var MockPrincipal = new Mock<ICustomPrincipal>(); MockHttpContext.SetupGet(h => h.User).Returns(MockPrincipal.Object); In the method I am trying to test the follow code gives the error(again): var user = (ICustomPrincipal)httpContext.User; The error is the following: Unable to cast object of type 'IPrincipalProxy4081807111564298854aabfc890edcc8' to type 'MyProject.Web.ICustomPrincipal'. I guess I still need some practice with interfaces and moq but shouldn't I be able to cast the class that moq created back to ICustomPrincipal? I know httpContext.User returns an IPrincipal so maybe something gets lost there? Well if anybody can help me I would appreciate that. Pickels Edit: As requested the full code of the method I am testing. It's still not finished but this is what I have so far: public bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } var user = (ICustomPrincipal)httpContext.User; if (!user.Identity.IsAuthenticated) { return false; } return true; }

    Read the article

  • Performance: float to int cast and clipping result to range

    - by durandai
    I'm doing some audio processing with float. The result needs to be converted back to PCM samples, and I noticed that the cast from float to int is surprisingly expensive. Whats furthermore frustrating that I need to clip the result to the range of a short (-32768 to 32767). While I would normally instictively assume that this could be assured by simply casting float to short, this fails miserably in Java, since on the bytecode level it results in F2I followed by I2S. So instead of a simple: int sample = (short) flotVal; I needed to resort to this ugly sequence: int sample = (int) floatVal; if (sample > 32767) { sample = 32767; } else if (sample < -32768) { sample = -32768; } Is there a faster way to do this? (about ~6% of the total runtime seems to be spent on casting, while 6% seem to be not that much at first glance, its astounding when I consider that the processing part involves a good chunk of matrix multiplications and IDCT) EDIT The cast/clipping code above is (not surprisingly) in the body of a loop that reads float values from a float[] and puts them into a byte[]. I have a test suite that measures total runtime on several test cases (processing about 200MB of raw audio data). The 6% were concluded from the runtime difference when the cast assignment "int sample = (int) floatVal" was replaced by assigning the loop index to sample. EDIT @leopoldkot: I'm aware of the truncation in Java, as stated in the original question (F2I, I2S bytecode sequence). I only tried the cast to short because I assumed that Java had an F2S bytecode, which it unfortunately does not (comming originally from an 68K assembly background, where a simple "fmove.w FP0, D0" would have done exactly what I wanted).

    Read the article

  • Warning: cast increases required alignment

    - by dash-tom-bang
    I'm recently working on this platform for which a legacy codebase issues a large number of "cast increases required alignment to N" warnings, where N is the size of the target of the cast. struct Message { int32_t id; int32_t type; int8_t data[16]; }; int32_t GetMessageInt(const Message& m) { return *reinterpret_cast<int32_t*>(&data[0]); } Hopefully it's obvious that a "real" implementation would be a bit more complex, but the basic point is that I've got data coming from somewhere, I know that it's aligned (because I need the id and type to be aligned), and yet I get the message that the cast is increasing the alignment, in the example case, to 4. Now I know that I can suppress the warning with an argument to the compiler, and I know that I can cast the bit inside the parentheses to void* first, but I don't really want to go through every bit of code that needs this sort of manipulation (there's a lot because we load a lot of data off of disk, and that data comes in as char buffers so that we can easily pointer-advance), but can anyone give me any other thoughts on this problem? I mean, to me it seems like such an important and common option that you wouldn't want to warn, and if there is actually the possibility of doing it wrong then suppressing the warning isn't going to help. Finally, can't the compiler know as I do how the object in question is actually aligned in the structure, so it should be able to not worry about the alignment on that particular object unless it got bumped a byte or two?

    Read the article

  • How to save transferred MP3 on Centova cast?

    - by cHAKE
    We have uploaded and transferred the mp3 files on centova cast successfully with Filezilla. We know how to update the media library We know how to create playlists We know how to drag the songs into different playlists We know how to save the media or the playlists BUT, we are losing all the media library saved files (songs) the moment we get new files in media library. However we want to keep the media library and playlist saved.

    Read the article

  • C# - Cast object to IList<T> based on Type

    - by blu
    I am trying out a little reflection and have a question on how the cast the result object to an IList. Here is the reflection: private void LoadBars(Type barType) { // foo has a method that returns bars Type foo = typeof(Foo); MethodInfo method = foo.GetMethod("GetBars") .MakeGenericMethod(bar); object obj = method.Invoke(foo, new object[] { /* arguments here */ }); // how can we cast obj to an IList<Type> - barType } How can we cast the result of method.Invoke to an IList of Type from the barType argument?

    Read the article

  • Call the cast operator of template base class within the derived class

    - by yoni
    I have a template class, called Cell, here the definition: template <class T> class OneCell { ..... } I have a cast operator from Cell to T, here virtual operator const T() const { ..... } Now i have derived class, called DCell, here template <class T> class DCell : public Cell<T> { ..... } I need to override the Cell's cast operator (insert a little if), but after I need to call the Cell's cast operator. In other methods it's should be something like virtual operator const T() const { if (...) { return Cell<T>::operator const T; } else throw ... } but i got a compiler error error: argument of type 'const int (Cell::)()const' does not match 'const int' What can I do? Thank you, and sorry about my poor English.

    Read the article

  • Cast integer to real

    - by Dave Jarvis
    Question How do you cast an INTEGER value as a REAL value? Attempts CAST( Y.YEAR AS REAL), but that failed (the documentation indicates you cannot CAST or CONVERT values to REALs. Y.YEAR + 0.0, but that failed, too. Error Message Using udf_slope fails due to: Can't initialize function 'slope'; slope() requires a real as parameter 2 Code SELECT D.AMOUNT, Y.YEAR, slope(D.AMOUNT, Y.YEAR + 0.0) as SLOPE, intercept(D.AMOUNT, Y.YEAR + 0.0) as INTERCEPT FROM YEAR_REF Y, DAILY D Here, D.AMOUNT is a FLOAT and Y.YEAR is an INTEGER. Thank you!

    Read the article

  • Why won't this SQL CAST work?

    - by Kev
    I have a nvarchar(50) column in a SQL Server 2000 table defined as follows: TaskID nvarchar(50) NULL I need to fill this column with some random SQL Unique Identifiers (I am unable to change the column type to uniqueidentifier). I tried this: UPDATE TaskData SET TaskID = CAST(NEWID() AS nvarchar) but I got the following error: Msg 8115, Level 16, State 2, Line 1 Arithmetic overflow error converting expression to data type nvarchar. I also tried: UPDATE TaskData SET TaskID = CAST(NEWID() AS nvarchar(50)) but then got this error: Msg 8152, Level 16, State 6, Line 1 String or binary data would be truncated. I don't understand why this doesn't work but this does: DECLARE @TaskID nvarchar(50) SET @TaskID = CAST(NEW() AS nvarchar(50)) I also tried CONVERT(nvarchar, NEWID()) and CONVERT(nvarchar(50), NEWID()) but got the same errors.

    Read the article

  • How to cast/convert form Object in an byte[] array

    - by maddash
    I've got a maybe simple problem, but at the moment I am not able to solve it. I have an Object and I need to convert it into a byte[]. public byte[] GetMapiPropertyBytes(string propIdentifier) { return (byte[])this.GetMapiProperty(propIdentifier); //InvalidCastException } Exception: Unable to cast COM object of type 'System.__ComObject' to class type 'System.Byte[]'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface. So far so good - I've tried to serialize it, but I got another exception - NOT serializable Could someone help me? I need a method to convert it...

    Read the article

  • Nhibernate - How to get rid of unwanted text cast

    - by Nicolas Cornu
    Hello, I am using Nhibernate 2 and PostgreSql The above code generate a query with a cast on expression res = _session.CreateCriteria(typeof(C)) .Add(Restrictions.Eq("Exp", Exp)) .AddOrder(new Order("Fr", false)) .SetMaxResults(MW) .List<C>(); Exp is a character varying(30) In the query: SELECT ... FROM table WHERE Exp = 'text':: text ... I want to get rid of cast 'text":: text beacause the index is not used. Nicolas

    Read the article

  • SQL Server cast fails with arithmetic overflow

    - by Jamie Ide
    According to the entry for decimal and numeric data types in SQL Server 2008 Books Online, precision is: p (precision) The maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point. The precision must be a value from 1 through the maximum precision of 38. The default precision is 18. However, the second select below fails with "Arithmetic overflow error converting int to data type numeric." SELECT CAST(123456789 as decimal(9,0)) SELECT CAST(123456789 as decimal(9,1))

    Read the article

  • How can I cast authoritatively in asp classic?

    - by Tchalvak
    In asp classic, the cint() function or procedure or whatever it is won't allow me to cast arbitrary strings, like "bob" or "null" or anything like that. Is there anything that will allow me to simply cast integers, numeric strings, and arbitrary strings to actual integers, with some sane default like 0 for strings?

    Read the article

  • Intermittent "Specified cast is invalid" with StructureMap injected data context

    - by FreshCode
    I am intermittently getting an System.InvalidCastException: Specified cast is not valid. error in my repository layer when performing an abstracted SELECT query mapped with LINQ. The error can't be caused by a mismatched database schema since it works intermittently and it's on my local dev machine. Could it be because StructureMap is caching the data context between page requests? If so, how do I tell StructureMap v2.6.1 to inject a new data context argument into my repository for each request? Update: I found this question which correlates my hunch that something was being re-used. Looks like I need to call Dispose on my injected data context. Not sure how I'm going to do this to all my repositories without copypasting a lot of code. Edit: These errors are popping up all over the place whenever I refresh my local machine too quickly. Doesn't look like it's happening on my remote deployment box, but I can't be sure. I changed all my repositories' StructureMap life cycles to HttpContextScoped() and the error persists. Code: public ActionResult Index() { // error happens here, which queries my page repository var page = _branchService.GetPage("welcome"); if (page != null) ViewData["Welcome"] = page.Body; ... } Repository: GetPage boils down to a filtered query mapping in my page repository. public IQueryable<Page> GetPages() { var pages = from p in _db.Pages let categories = GetPageCategories(p.PageId) let revisions = GetRevisions(p.PageId) select new Page { ID = p.PageId, UserID = p.UserId, Slug = p.Slug, Title = p.Title, Description = p.Description, Body = p.Text, Date = p.Date, IsPublished = p.IsPublished, Categories = new LazyList<Category>(categories), Revisions = new LazyList<PageRevision>(revisions) }; return pages; } where _db is an injected data context as an argument, stored in a private variable which I reuse for SELECT queries. Error: Specified cast is not valid. Exception Details: System.InvalidCastException: Specified cast is not valid. Stack Trace: [InvalidCastException: Specified cast is not valid.] System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +4539 System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +207 System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +500 System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute(Expression expression) +50 System.Linq.Queryable.FirstOrDefault(IQueryable`1 source) +383 Manager.Controllers.SiteController.Index() in C:\Projects\Manager\Manager\Controllers\SiteController.cs:68 lambda_method(Closure , ControllerBase , Object[] ) +79 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +258 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39 System.Web.Mvc.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() +125 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +640 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +312 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +709 System.Web.Mvc.Controller.ExecuteCore() +162 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +58 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +453 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +371

    Read the article

  • [JP ???] Google Cast SDK ??

    [JP 日本語] Google Cast SDK 概要 Chromecast 向けアプリケーションを開発される皆さんのために Google Cast SDK が公開されました。このエピソードでは、Google Cast SDK の概要についてお話... From: Google Developers Views: 301 10 ratings Time: 05:17 More in Science & Technology

    Read the article

  • Cast to delegate type fails in JScript.NET

    - by dnewcome
    I am trying to do async IO using BeginRead() in JScript.NET, but I can't get the callback function to work correctly. Here is the code: function readFileAsync() { var fs : FileStream = new FileStream( 'test.txt', FileMode.Open, FileAccess.Read ); var result : IAsyncResult = fs.BeginRead( new byte[8], 0, 8, readFileCallback ), fs ); Thread.Sleep( Timeout.Infinite ); } var readFileCallback = function( result : IAsyncResult ) : void { print( 'ListenerCallback():' ); } The exception is a cast failure: Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'Microsoft.JScript.Closure' to type 'System.AsyncCallback'. at JScript 0.readFileAsync(Object this, VsaEngine vsa Engine) at JScript 0.Global Code() at JScript Main.Main(String[] ) I have tried doing an explicit cast both to AsyncCallback and to the base MulticastDelegate and Delegate types to no avail. Delegates are supposed to be created automatically, obviating the need for creating a new AsyncCallback explicitly, eg: BeginRead( ... new AsyncDelegate( readFileCallback), object ); And in fact if you try to create the delegate explicitly the compiler issues an error. I must be missing something here.

    Read the article

  • Converting Openfire IM datetime values in SQL Server to / from VARCHAR(15) and DATETIME data types

    - by Brian Biales
    A client is using Openfire IM for their users, and would like some custom queries to audit user conversations (which are stored by Openfire in tables in the SQL Server database). Because Openfire supports multiple database servers and multiple platforms, the designers chose to store all date/time stamps in the database as 15 character strings, which get converted to Java Date objects in their code (Openfire is written in Java).  I did some digging around, and, so I don't forget and in case someone else will find this useful, I will put the simple algorithms here for converting back and forth between SQL DATETIME and the Java string representation. The Java string representation is the number of milliseconds since 1/1/1970.  SQL Server's DATETIME is actually represented as a float, the value being the number of days since 1/1/1900, the portion after the decimal point representing the hours/minutes/seconds/milliseconds... as a fractional part of a day.  Try this and you will see this is true:     SELECT CAST(0 AS DATETIME) and you will see it returns the date 1/1/1900. The difference in days between SQL Server's 0 date of 1/1/1900 and the Java representation's 0 date of 1/1/1970 is found easily using the following SQL:   SELECT DATEDIFF(D, '1900-01-01', '1970-01-01') which returns 25567.  There are 25567 days between these dates. So to convert from the Java string to SQL Server's date time, we need to convert the number of milliseconds to a floating point representation of the number of days since 1/1/1970, then add the 25567 to change this to the number of days since 1/1/1900.  To convert to days, you need to divide the number by 1000 ms/s, then by  60 seconds/minute, then by 60 minutes/hour, then by 24 hours/day.  Or simply divide by 1000*60*60*24, or 86400000.   So, to summarize, we need to cast this string as a float, divide by 86400000 milliseconds/day, then add 25567 days, and cast the resulting value to a DateTime.  Here is an example:   DECLARE @tmp as VARCHAR(15)   SET @tmp = '1268231722123'   SELECT @tmp as JavaTime, CAST((CAST(@tmp AS FLOAT) / 86400000) + 25567 AS DATETIME) as SQLTime   To convert from SQL datetime back to the Java time format is not quite as simple, I found, because floats of that size do not convert nicely to strings, they end up in scientific notation using the CONVERT function or CAST function.  But I found a couple ways around that problem. You can convert a date to the number of  seconds since 1/1/1970 very easily using the DATEDIFF function, as this value fits in an Int.  If you don't need to worry about the milliseconds, simply cast this integer as a string, and then concatenate '000' at the end, essentially multiplying this number by 1000, and making it milliseconds since 1/1/1970.  If, however, you do care about the milliseconds, you will need to use DATEPART to get the milliseconds part of the date, cast this integer to a string, and then pad zeros on the left to make sure this is three digits, and concatenate these three digits to the number of seconds string above.  And finally, I discovered by casting to DECIMAL(15,0) then to VARCHAR(15), I avoid the scientific notation issue.  So here are all my examples, pick the one you like best... First, here is the simple approach if you don't care about the milliseconds:   DECLARE @tmp as VARCHAR(15)   DECLARE @dt as DATETIME   SET @dt = '2010-03-10 14:35:22.123'   SET @tmp = CAST(DATEDIFF(s, '1970-01-01 00:00:00' , @dt) AS VARCHAR(15)) + '000'   SELECT @tmp as JavaTime, @dt as SQLTime If you want to keep the milliseconds:   DECLARE @tmp as VARCHAR(15)   DECLARE @dt as DATETIME   DECLARE @ms as int   SET @dt = '2010-03-10 14:35:22.123'   SET @ms as DATEPART(ms, @dt)   SET @tmp = CAST(DATEDIFF(s, '1970-01-01 00:00:00' , @dt) AS VARCHAR(15))           + RIGHT('000' + CAST(@ms AS VARCHAR(3)), 3)   SELECT @tmp as JavaTime, @dt as SQLTime Or, in one fell swoop:   DECLARE @dt as DATETIME   SET @dt = '2010-03-10 14:35:22.123'   SELECT @dt as SQLTime     , CAST(DATEDIFF(s, '1970-01-01 00:00:00' , @dt) AS VARCHAR(15))           + RIGHT('000' + CAST( DATEPART(ms, @dt) AS VARCHAR(3)), 3) as JavaTime   And finally, a way to simply reverse the math used converting from Java date to SQL date. Note the parenthesis - watch out for operator precedence, you want to subtract, then multiply:   DECLARE @dt as DATETIME   SET @dt = '2010-03-10 14:35:22.123'   SELECT @dt as SQLTime     , CAST(CAST((CAST(@dt as Float) - 25567.0) * 86400000.0 as DECIMAL(15,0)) as VARCHAR(15)) as JavaTime Interestingly, I found that converting to SQL Date time can lose some accuracy, when I converted the time above to Java time then converted  that back to DateTime, the number of milliseconds is 120, not 123.  As I am not interested in the milliseconds, this is ok for me.  But you may want to look into using DateTime2 in SQL Server 2008 for more accuracy.

    Read the article

  • java.lang.ClassCastException: org.postgresql.jdbc4.Jdbc4Connection cannot be cast to org.postgresql.jdbc4.Jdbc4Connection

    - by ???????? ??????
    I want to get PGConnection from posgresql connection in JBOSS AS7 (Data source postgresql-9.0-801.jdbc4.jar) I've got cast exception when used (WrappedConnection)connection So now I use reflection(JDK 1.7): private static PGConnection getPGConnection(Connection connection) throws SQLException { if(connection instanceof PGConnection) { return (PGConnection)connection; } try { Class[] parms = null; Method method =(connection.getClass()).getMethod("getUnderlyingConnection", parms); return (PGConnection) jdbc4Conn; } catch ... and catch exception java.lang.ClassCastException: org.postgresql.jdbc4.Jdbc4Connection cannot be cast to org.postgresql.jdbc4.Jdbc4Connection It is the same class!!! Haw could it be?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >