logs
stringlengths
104
251k
> nosetests -v testgen.test_generator('a', 'a') ... ok testgen.test_generator('a', 'b') ... FAIL testgen.test_generator('b', 'b') ... ok ====================================================================== FAIL: testgen.test_generator('a', 'b') ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.5/site-packages/nose-0.10.1-py2.5.egg/nose/case.py", line 203, in runTest self.test(*self.arg) File "testgen.py", line 7, in check_em assert a == b AssertionError ---------------------------------------------------------------------- Ran 3 tests in 0.006s FAILED (failures=1)
node* tortoise(begin), * hare(begin); while(hare = hare->next) { if(hare == tortoise) { throw std::logic_error("There's a cycle"); } hare = hare->next; if(hare == tortoise) { throw std::logic_error("There's a cycle"); } tortoise = tortoise->next; }
import pandas as pd df = pd.DataFrame([[10, 20, 30], [100, 200, 300]], columns=['foo', 'bar', 'baz']) def get_methods(object, spacing=20): methodList = [] for method_name in dir(object): try: if callable(getattr(object, method_name)): methodList.append(str(method_name)) except Exception: methodList.append(str(method_name)) processFunc = (lambda s: ' '.join(s.split())) or (lambda s: s) for method in methodList: try: print(str(method.ljust(spacing)) + ' ' + processFunc(str(getattr(object, method).__doc__)[0:90])) except Exception: print(method.ljust(spacing) + ' ' + ' getattr() failed') get_methods(df['foo'])
function room1 () local move = io.read() if move == "south" then return room3() elseif move == "east" then return room2() else print("invalid move") return room1() -- stay in the same room end end function room2 () local move = io.read() if move == "south" then return room4() elseif move == "west" then return room1() else print("invalid move") return room2() end end function room3 () local move = io.read() if move == "north" then return room1() elseif move == "east" then return room4() else print("invalid move") return room3() end end function room4 () print("congratulations!") end
public class ModelBinder : IModelBinder { public object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState) { object model = Activator.CreateInstance(modelType); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(model); foreach (PropertyDescriptor descriptor in properties) { string key = modelName + "." + descriptor.Name; object value = ModelBinders.GetBinder(descriptor.PropertyType).GetValue(controllerContext, key, descriptor.PropertyType, modelState); if (value != null) { try { descriptor.SetValue(model, value); continue; } catch { string errorMessage = String.Format("The value '{0}' is invalid for property '{1}'.", value, key); string attemptedValue = Convert.ToString(value); modelState.AddModelError(key, attemptedValue, errorMessage); } } } return model; } }
protected void CheckServerVersion(ServerVersion version) { if ((version.Major <= 7 || (version.Major > 9)) { throw new ConnectionFailureException( StringConnectionInfo.ConnectToInvalidVersion(version.ToString()) ); } }
>>> import _elementtidy >>> xhtml, log = _elementtidy.fixup("<html></html>") >>> print log line 1 column 1 - Warning: missing <!DOCTYPE> declaration line 1 column 7 - Warning: discarding unexpected </html> line 1 column 14 - Warning: inserting missing 'title' element
>>> import _elementtidy >>> xhtml, log = _elementtidy.fixup("<html></html>") >>> print log line 1 column 1 - Warning: missing <!DOCTYPE> declaration line 1 column 7 - Warning: discarding unexpected </html> line 1 column 14 - Warning: inserting missing 'title' element
#!/usr/bin/python """ Display the per-commit size of the current git branch. """ import subprocess import re import sys def main(argv): git = subprocess.Popen(["git", "log", "--shortstat", "--reverse", "--pretty=oneline"], stdout=subprocess.PIPE) out, err = git.communicate() total_files, total_insertions, total_deletions = 0, 0, 0 for line in out.split('\n'): if not line: continue if line[0] != ' ': # This is a description line hash, desc = line.split(" ", 1) else: # This is a stat line data = re.findall( ' (\d+) files changed, (\d+) insertions\(\+\), (\d+) deletions\(-\)', line) files, insertions, deletions = ( int(x) for x in data[0] ) total_files += files total_insertions += insertions total_deletions += deletions print "%s: %d files, %d lines" % (hash, total_files, total_insertions - total_deletions) if __name__ == '__main__': sys.exit(main(sys.argv))
public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue> { IDictionary<TKey, TValue> _dict; public ReadOnlyDictionary(IDictionary<TKey, TValue> backingDict) { _dict = backingDict; } public void Add(TKey key, TValue value) { throw new InvalidOperationException(); } public bool ContainsKey(TKey key) { return _dict.ContainsKey(key); } public ICollection<TKey> Keys { get { return _dict.Keys; } } public bool Remove(TKey key) { throw new InvalidOperationException(); } public bool TryGetValue(TKey key, out TValue value) { return _dict.TryGetValue(key, out value); } public ICollection<TValue> Values { get { return _dict.Values; } } public TValue this[TKey key] { get { return _dict[key]; } set { throw new InvalidOperationException(); } } public void Add(KeyValuePair<TKey, TValue> item) { throw new InvalidOperationException(); } public void Clear() { throw new InvalidOperationException(); } public bool Contains(KeyValuePair<TKey, TValue> item) { return _dict.Contains(item); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { _dict.CopyTo(array, arrayIndex); } public int Count { get { return _dict.Count; } } public bool IsReadOnly { get { return true; } } public bool Remove(KeyValuePair<TKey, TValue> item) { throw new InvalidOperationException(); } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _dict.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((System.Collections.IEnumerable)_dict).GetEnumerator(); } }
HKEY hKey; LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, &hKey); bool bExistsAndSuccess (lRes == ERROR_SUCCESS); bool bDoesNotExistsSpecifically (lRes == ERROR_FILE_NOT_FOUND); std::wstring strValueOfBinDir; std::wstring strKeyDefaultValue; GetStringRegKey(hKey, L"BinDir", strValueOfBinDir, L"bad"); GetStringRegKey(hKey, L"", strKeyDefaultValue, L"bad"); LONG GetDWORDRegKey(HKEY hKey, const std::wstring &strValueName, DWORD &nValue, DWORD nDefaultValue) { nValue = nDefaultValue; DWORD dwBufferSize(sizeof(DWORD)); DWORD nResult(0); LONG nError = ::RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, reinterpret_cast<LPBYTE>(&nResult), &dwBufferSize); if (ERROR_SUCCESS == nError) { nValue = nResult; } return nError; } LONG GetBoolRegKey(HKEY hKey, const std::wstring &strValueName, bool &bValue, bool bDefaultValue) { DWORD nDefValue((bDefaultValue) ? 1 : 0); DWORD nResult(nDefValue); LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue); if (ERROR_SUCCESS == nError) { bValue = (nResult != 0) ? true : false; } return nError; } LONG GetStringRegKey(HKEY hKey, const std::wstring &strValueName, std::wstring &strValue, const std::wstring &strDefaultValue) { strValue = strDefaultValue; WCHAR szBuffer[512]; DWORD dwBufferSize = sizeof(szBuffer); ULONG nError; nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize); if (ERROR_SUCCESS == nError) { strValue = szBuffer; } return nError; }
Public Class ProductPresenter Private mView As IProductView Private mProductService As IProductService Public Sub New(ByVal View As IProductView) Me.New(View, New ProductService()) End Sub Public Sub New(ByVal View As IProductView, ByVal ProductService As IProductService) mView = View mProductService = ProductService End Sub Public Sub OnViewLoad() If mView.PageIsPostBack = False Then PopulateProductsList() End If End Sub Public Sub PopulateProductsList() Try Dim ProductList As List(Of Product) = mProductService.GetProducts() mView.Products = ProductList Catch ex As Exception Throw ex End Try End Sub End Class
PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t t/01basic...........1/4 # Failed test 'use SGML::Parser::OpenSP;' # at t/01basic.t line 14. # Tried to use 'SGML::Parser::OpenSP'. # Error: Can't load '/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle' for module SGML::Parser::OpenSP: dlopen(/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle, 2): Symbol not found: __ZTI15SGMLApplication # Referenced from: /Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle # Expected in: dynamic lookup # at (eval 3) line 2 # Compilation failed in require at (eval 3) line 2. # BEGIN failed--compilation aborted at (eval 3) line 2.
PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t t/01basic...........1/4 # Failed test 'use SGML::Parser::OpenSP;' # at t/01basic.t line 14. # Tried to use 'SGML::Parser::OpenSP'. # Error: Can't load '/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle' for module SGML::Parser::OpenSP: dlopen(/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle, 2): Symbol not found: __ZTI15SGMLApplication # Referenced from: /Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle # Expected in: dynamic lookup # at (eval 3) line 2 # Compilation failed in require at (eval 3) line 2. # BEGIN failed--compilation aborted at (eval 3) line 2.
function customError($level,$message,$file,$line,$context) { echo "Sorry, an error has occured on line $line.<br />"; echo "The function that caused the error says $message.<br />"; die(); } set_error_handler("customError"); echo($imAFakeVariable);
function() { HRESULT error = S_OK; if(SUCCEEDED(Operation1())) { if(SUCCEEDED(Operation2())) { if(SUCCEEDED(Operation3())) { if(SUCCEEDED(Operation4())) { } else { error = OPERATION4FAILED; } } else { error = OPERATION3FAILED; } } else { error = OPERATION2FAILED; } } else { error = OPERATION1FAILED; } return error; }
$ echo A > foo $ git add foo $ git commit -m 'A' foo Created commit a1f085f: A 1 files changed, 1 insertions(+), 0 deletions(-) create mode 100644 foo $ echo B >> foo $ git add foo $ echo C >> foo $ cat foo A B C $ git checkout ./foo $ cat foo A B $ git checkout HEAD ./foo $ cat foo A
$ echo A > foo $ git add foo $ git commit -m 'A' foo Created commit a1f085f: A 1 files changed, 1 insertions(+), 0 deletions(-) create mode 100644 foo $ echo B >> foo $ git add foo $ echo C >> foo $ cat foo A B C $ git checkout ./foo $ cat foo A B $ git checkout HEAD ./foo $ cat foo A
EventType clr20r3, P1 consolefaxtest.exe, P2 1.0.0.0, P3 48bb146b, P4 consolefaxtest, P5 1.0.0.0, P6 48bb146b, P7 1, P8 80, P9 system.io.filenotfoundexception, P10 NIL.
Unhandled Exception: System.IO.FileNotFoundException: Operation failed. at FAXCOMEXLib.FaxDocumentClass.ConnectedSubmit(FaxServer pFaxServer)
EventType clr20r3, P1 consolefaxtest.exe, P2 1.0.0.0, P3 48bb146b, P4 consolefaxtest, P5 1.0.0.0, P6 48bb146b, P7 1, P8 80, P9 system.io.filenotfoundexception, P10 NIL.
Unhandled Exception: System.IO.FileNotFoundException: Operation failed. at FAXCOMEXLib.FaxDocumentClass.ConnectedSubmit(FaxServer pFaxServer)
"HealthMonitor-10" daemon prio=1 tid=0x0868d1c0 nid=0x2b72 waiting for monitor entry [0xbe5ff000..0xbe5ff4d4] at java.lang.Thread.dumpThreads(Native Method) at java.lang.Thread.getStackTrace(Thread.java:1383)
"HealthMonitor-10" daemon prio=1 tid=0x0868d1c0 nid=0x2b72 waiting for monitor entry [0xbe5ff000..0xbe5ff4d4] at java.lang.Thread.dumpThreads(Native Method) at java.lang.Thread.getStackTrace(Thread.java:1383)
<error> <serverVariables> <item> <value> </item> </serverVariables> <queryString> <item name=""> <value string=""> </item> </queryString> </error>
System.Data.ConstraintException : Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
System.Data.ConstraintException : Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
import sys import os import errno try: os.kill(int(sys.argv[1]), 0) except OSError, err: if err.errno == errno.ESRCH: print "Not running" elif err.errno == errno.EPERM: print "No permission to signal this process!" else: print "Unknown error" else: print "Running"
static void Main(string[] args) { var reader = new BinaryReader(new DeviceStream(@"\\.\PhysicalDrive3")); var writer = new BinaryWriter(new FileStream(@"g:\test.dat", FileMode.Create)); var buffer = new byte[MB]; int count; int loopcount=0; try{ while((count=reader.Read(buffer,0,MB))>0) { writer.Write(buffer,0,count); System.Console.Write('.'); if(loopcount%100==0) { System.Console.WriteLine(); System.Console.WriteLine("100MB written"); writer.Flush(); } loopcount++; } } catch(Exception e) { Console.WriteLine(e.Message); } reader.Close(); writer.Flush(); writer.Close(); }
Traceback (most recent call last): ... results = cursor.fetchall() dbi.operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s in FETCH
Traceback (most recent call last): ... results = cursor.fetchall() dbi.operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s in FETCH
public static int Factorial(int f) { if (f<0 || f>12) { throw new ArgumentException("Out of range for integer factorial"); } int [] fact={1,1,2,6,24,120,720,5040,40320,362880,3628800, 39916800,479001600}; return fact[f]; }
PHP Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable to relay for chris.mahan@gmail.com in c:\inetpub\wwwroot\mailtest.php on line 12
PHP Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable to relay for chris.mahan@gmail.com in c:\inetpub\wwwroot\mailtest.php on line 12
NameVirtualHost * <VirtualHost *:80> ServerName dev.blog.slaven.net.au ServerAlias dev.blog.slaven.net.au ServerAdmin user@host.com DocumentRoot "c:/Project Data/OtherProjects/slaven.net.au/blog/" ErrorLog "logs/blog.slaven.localhost-error.log" CustomLog "logs/blog.slaven.localhost-access.log" common <Directory "c:/Project Data/OtherProjects/slaven.net.au/blog/"> Options Indexes FollowSymLinks MultiViews AllowOverride all Order allow,deny Allow from all </Directory> </VirtualHost>
UPDATE staging_table SET status_code = 'FAIL_TEST_1' WHERE status_code IS NULL AND ISDATE(ntext_column1) = 0; UPDATE staging_table SET status_code = 'FAIL_TEST_2' WHERE status_code IS NULL AND ISNUMERIC(ntext_column2) = 0; etc...
UPDATE staging_table SET status_code = 'FAIL_TEST_1' WHERE status_code IS NULL AND ISDATE(ntext_column1) = 0; UPDATE staging_table SET status_code = 'FAIL_TEST_2' WHERE status_code IS NULL AND ISNUMERIC(ntext_column2) = 0; etc...
public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> make, params object[] parms) { using (var connection = CreateConnection()) { using (var command = CreateCommand(CommandType.Text, sql, connection, parms)) { command.CommandTimeout = dataBaseSettings.ReadCommandTimeout; using (var reader = command.ExecuteReader()) { while (reader.Read()) { yield return make(reader); } } } } }
Private Sub TextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles TextBox1.TextChanged, _ TextBox2.TextChanged, _ TextBox3.TextChanged End Sub
-- PREPARE SET NOCOUNT ON -- VARIABLES DECLARE @tblName NVARCHAR(150) DECLARE @colName NVARCHAR(150) DECLARE @tblID int DECLARE @first bit DECLARE @lookFor nvarchar(250) DECLARE @replaceWith nvarchar(250) -- CHANGE PARAMETERS SET @lookFor = ('bla') SET @replaceWith = '' -- TEXT VALUE DATA TYPES DECLARE @supportedTypes TABLE ( xtype NVARCHAR(20) ) INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('varchar','char','nvarchar','nchar','xml','ntext','text') --INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('text') -- ALL USER TABLES DECLARE cur_tables CURSOR FOR SELECT SO.name, SO.id FROM SYSOBJECTS SO WHERE XTYPE='U' OPEN cur_tables FETCH NEXT FROM cur_tables INTO @tblName, @tblID WHILE @@FETCH_STATUS = 0 BEGIN ------------------------------------------------------------------------------------------- -- START INNER LOOP - All text columns, generate statement ------------------------------------------------------------------------------------------- DECLARE @temp VARCHAR(max) DECLARE @count INT SELECT @count = COUNT(name) FROM SYSCOLUMNS WHERE ID = @tblID AND XTYPE IN (SELECT xtype FROM @supportedTypes) IF @count > 0 BEGIN -- fetch supported columns for table DECLARE cur_columns CURSOR FOR SELECT name FROM SYSCOLUMNS WHERE ID = @tblID AND XTYPE IN (SELECT xtype FROM @supportedTypes) OPEN cur_columns FETCH NEXT FROM cur_columns INTO @colName -- generate opening UPDATE cmd PRINT 'UPDATE ' + @tblName + ' SET' SET @first = 1 -- loop through columns and create replaces WHILE @@FETCH_STATUS = 0 BEGIN IF (@first=0) PRINT ',' PRINT @colName + ' = REPLACE(convert(nvarchar(max),' + @colName + '),''' + @lookFor + ''',''' + @replaceWith + ''')' SET @first = 0 FETCH NEXT FROM cur_columns INTO @colName END PRINT 'GO' CLOSE cur_columns DEALLOCATE cur_columns END ------------------------------------------------------------------------------------------- -- END INNER ------------------------------------------------------------------------------------------- FETCH NEXT FROM cur_tables INTO @tblName, @tblID END CLOSE cur_tables DEALLOCATE cur_tables
Server: Msg 7399, Level 16, State 1, Procedure <storedProcedureName>, Line 18 OLE DB provider 'SQLOLEDB' reported an error. OLE/DB Provider 'SQLOLEDB' ::GetSchemaLock returned 0x80004005: OLE DB provider SQLOLEDB supported the Schema Lock interface, but returned 0x80004005 for GetSchemaLock .]. OLE/DB provider returned message: Connection is busy with results for another command OLE DB error trace [OLE/DB Provider 'SQLOLEDB' ::CreateSession returned 0x80004005.
Server: Msg 7399, Level 16, State 1, Procedure <storedProcedureName>, Line 18 OLE DB provider 'SQLOLEDB' reported an error. OLE/DB Provider 'SQLOLEDB' ::GetSchemaLock returned 0x80004005: OLE DB provider SQLOLEDB supported the Schema Lock interface, but returned 0x80004005 for GetSchemaLock .]. OLE/DB provider returned message: Connection is busy with results for another command OLE DB error trace [OLE/DB Provider 'SQLOLEDB' ::CreateSession returned 0x80004005.
LinqEntity item = new LinqEntity(){ Id = 1, Name = "OldName", Surname = "OldSurname"}; context.LinqEntities.Attach(item); item.Name = "John"; item.Surname = "Doe"; context.SubmitChanges();
public List<int> parsePageNumbers(string input) { if (string.IsNullOrEmpty(input)) throw new InvalidOperationException("Input string is empty."); var pageNos = input.Split(','); var ret = new List<int>(); foreach(string pageString in pageNos) { if (pageString.Contains("-")) { parsePageRange(ret, pageString); } else { ret.Add(parsePageNumber(pageString)); } } ret.Sort(); return ret.Distinct().ToList(); } private int parsePageNumber(string pageString) { int ret; if (!int.TryParse(pageString, out ret)) { throw new InvalidOperationException( string.Format("Page number '{0}' is not valid.", pageString)); } return ret; } private void parsePageRange(List<int> pageNumbers, string pageNo) { var pageRange = pageNo.Split('-'); if (pageRange.Length != 2) throw new InvalidOperationException( string.Format("Page range '{0}' is not valid.", pageNo)); int startPage = parsePageNumber(pageRange[0]), endPage = parsePageNumber(pageRange[1]); if (startPage > endPage) { throw new InvalidOperationException( string.Format("Page number {0} is greater than page number {1}" + " in page range '{2}'", startPage, endPage, pageNo)); } pageNumbers.AddRange(Enumerable.Range(startPage, endPage - startPage + 1)); }
Public Function Exists(col, index) As Boolean On Error GoTo ExistsTryNonObject Dim o As Object Set o = col(index) Exists = True Exit Function ExistsTryNonObject: Exists = ExistsNonObject(col, index) End Function Private Function ExistsNonObject(col, index) As Boolean On Error GoTo ExistsNonObjectErrorHandler Dim v As Variant v = col(index) ExistsNonObject = True Exit Function ExistsNonObjectErrorHandler: ExistsNonObject = False End Function
Public Function Exists(ByVal key As Variant, ByRef col As Collection) As Boolean 'Returns True if item with key exists in collection On Error Resume Next Const ERR_OBJECT_TYPE As Long = 438 Dim item As Variant 'Try reach item by key item = col.item(key) 'If no error occurred, key exists If Err.Number = 0 Then Exists = True 'In cases where error 438 is thrown, it is likely that 'the item does exist, but is an object that cannot be Let ElseIf Err.Number = ERR_OBJECT_TYPE Then 'Try reach object by key Set item = col.item(key) 'If an object was found, the key exists If Not item Is Nothing Then Exists = True End If End If Err.Clear End Function
DATA_BLOB blobIn, blobOut; blobIn.pbData=const_cast<BYTE*>(data); blobIn.cbData=length; CryptUnprotectData(&blobIn, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &blobOut); std::wstring _decrypted; _decrypted.assign((LPCWSTR)blobOut.pbData,(LPCWSTR)blobOut.pbData+blobOut.cbData/sizeof(WCHAR));
DATA_BLOB blobIn, blobOut; blobIn.pbData=const_cast<BYTE*>(data); blobIn.cbData=length; CryptUnprotectData(&blobIn, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &blobOut); std::wstring _decrypted; _decrypted.assign((LPCWSTR)blobOut.pbData,(LPCWSTR)blobOut.pbData+blobOut.cbData/sizeof(WCHAR));
Label l; MultipleLookupField mlf; protected override void CreateChildControls() { base.CreateChildControls(); SPList list = SPContext.Current.Web.Lists["Shared Documents"]; if (list != null && list.Items.Count > 0) { LiteralControl lit = new LiteralControl("Associate tasks to " + list.Items[0].Name); this.Controls.Add(lit); mlf = new MultipleLookupField(); mlf.ControlMode = SPControlMode.Edit; mlf.FieldName = "Related"; mlf.ItemId = list.Items[0].ID; mlf.ListId = list.ID; mlf.ID = "Related"; this.Controls.Add(mlf); Button b = new Button(); b.Text = "Change"; b.Click += new EventHandler(bClick); this.Controls.Add(b); l = new Label(); this.Controls.Add(l); } } void bClick(object sender, EventArgs e) { l.Text = ""; foreach (SPFieldLookupValue val in (SPFieldLookupValueCollection)mlf.Value) { l.Text += val.LookupValue.ToString() + " "; } SPListItem listitem = mlf.List.Items[0]; listitem["Related"] = mlf.Value; listitem.Update(); mlf.Value = listitem["Related"]; } protected override void OnInit(EventArgs e) { base.OnInit(e); EnsureChildControls(); }
ByteComparator.obj : error LNK2019: unresolved external symbol "int __cdecl does_not_exist(void)" (?does_not_exist@@YAHXZ) referenced in function "void __cdecl TextScan(struct FileTextStats &,char const *,char const *,bool,bool,__int64)" (?TextScan@@YAXAAUFileTextStats@@PBD1_N2_J@Z)
ByteComparator.obj : error LNK2019: unresolved external symbol "int __cdecl does_not_exist(void)" (?does_not_exist@@YAHXZ) referenced in function "void __cdecl TextScan(struct FileTextStats &,char const *,char const *,bool,bool,__int64)" (?TextScan@@YAXAAUFileTextStats@@PBD1_N2_J@Z)
public class RandomString { /** * Generate a random string. */ public String nextString() { for (int idx = 0; idx < buf.length; ++idx) buf[idx] = symbols[random.nextInt(symbols.length)]; return new String(buf); } public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String lower = upper.toLowerCase(Locale.ROOT); public static final String digits = "0123456789"; public static final String alphanum = upper + lower + digits; private final Random random; private final char[] symbols; private final char[] buf; public RandomString(int length, Random random, String symbols) { if (length < 1) throw new IllegalArgumentException(); if (symbols.length() < 2) throw new IllegalArgumentException(); this.random = Objects.requireNonNull(random); this.symbols = symbols.toCharArray(); this.buf = new char[length]; } /** * Create an alphanumeric string generator. */ public RandomString(int length, Random random) { this(length, random, alphanum); } /** * Create an alphanumeric strings from a secure generator. */ public RandomString(int length) { this(length, new SecureRandom()); } /** * Create session identifiers. */ public RandomString() { this(21); } }
static ExType TestException<ExType>(string message) where ExType:Exception { ExType ex = new ExType(); ex.Message = message; return ex; }
static ExType TestException<ExType>(string message) where ExType:Exception { Exception ex1 = new Exception(); ExType ex = new Exception(message); return ex; }
static ExType TestException<ExType>(string message) where ExType:Exception { Exception ex1 = new Exception(); ExType ex = (ExType)(new Exception(message)); return ex; }
static ExType TestException<ExType>(string message) where ExType:Exception, new () { ExType ex = (ExType)Activator.CreateInstance(typeof(ExType), message); return ex; }
static void TestException<E>(string message) where E : Exception { throw Activator.CreateInstance(typeof(E), message) as E; }
static void TestException<E>(string message) where E : Exception { throw Activator.CreateInstance(typeof(E), message) as E; }
static void TestException<E>(string message) where E : Exception, new() { try { return Activator.CreateInstance(typeof(E), message) as E; } catch(MissingMethodException ex) { return new E(); } }
public static void createFile(String customerPath, String filename, byte[] fileData) throws IOException { customerPath = getFullPath(customerPath + filename); File newFile = new File(customerPath); if (!newFile.getParentFile().exists()) { newFile.getParentFile().mkdirs(); } FileOutputStream outputStream = new FileOutputStream(newFile); outputStream.write(fileData); outputStream.close(); }
public static void createFile(String customerPath, String filename, byte[] fileData) throws IOException { customerPath = getFullPath(customerPath + filename); File newFile = new File(customerPath); if (!newFile.getParentFile().exists()) { newFile.getParentFile().mkdirs(); } FileOutputStream outputStream = new FileOutputStream(newFile); outputStream.write(fileData); outputStream.close(); }
/** * Generate a random hex encoded string token of the specified length * * @param length * @return random hex string */ public static synchronized String generateUniqueToken(Integer length){ byte random[] = new byte[length]; Random randomGenerator = new Random(); StringBuffer buffer = new StringBuffer(); randomGenerator.nextBytes(random); for (int j = 0; j < random.length; j++) { byte b1 = (byte) ((random[j] & 0xf0) >> 4); byte b2 = (byte) (random[j] & 0x0f); if (b1 < 10) buffer.append((char) ('0' + b1)); else buffer.append((char) ('A' + (b1 - 10))); if (b2 < 10) buffer.append((char) ('0' + b2)); else buffer.append((char) ('A' + (b2 - 10))); } return (buffer.toString()); } @Test public void testGenerateUniqueToken(){ Set set = new HashSet(); String token = null; int size = 16; /* Seems like we should be able to generate 500K tokens * without a duplicate */ for (int i=0; i<500000; i++){ token = Utility.generateUniqueToken(size); if (token.length() != size * 2){ fail("Incorrect length"); } else if (set.contains(token)) { fail("Duplicate token generated"); } else{ set.add(token); } } }
StackTraceElement[] stack = Thread.currentThread ().getStackTrace (); StackTraceElement main = stack[stack.length - 1]; String mainClass = main.getClassName ();
Private Function GetImageFromRow(ByRef row As DataRowView, ByVal columnName As String) As Bitmap Dim oImage As Bitmap = New Bitmap("c:\default.jpg") Try If Not IsDBNull(row(columnName)) Then If row(columnName) IsNot Nothing Then Dim mStream As New System.IO.MemoryStream(CType(row(columnName), Byte())) If mStream.Length > 0 Then Dim b(Convert.ToInt32(mStream.Length - 1)) As Byte mStream.Read(b, 0, Convert.ToInt32(mStream.Length - 1)) Dim position As Integer = 0 For index As Integer = 0 To b.Length - 3 If b(index) = &HFF And b(index + 1) = &HD8 And b(index + 2) = &HFF Then position = index Exit For End If Next If position > 0 Then Dim jpgStream As New System.IO.MemoryStream(b, position, b.Length - position) oImage = New Bitmap(jpgStream) End If End If End If End If Catch ex As Exception Throw New ApplicationException(ex.Message, ex) End Try Return oImage End Function
Unhandled Exception: System.Configuration.ConfigurationErrorsException: An error occurred executing the configuration section handler for connectionStrings. ---> System.Configuration.ConfigurationErrorsException: Failed to encrypt the section 'connectionStrings' using provider 'RsaProtectedConfigurationProvider'. Error message from the provider: Object already exists. ---> System.Security.Cryptography.CryptographicException: Object already exists
Unhandled Exception: System.Configuration.ConfigurationErrorsException: An error occurred executing the configuration section handler for connectionStrings. ---> System.Configuration.ConfigurationErrorsException: Failed to encrypt the section 'connectionStrings' using provider 'RsaProtectedConfigurationProvider'. Error message from the provider: Object already exists. ---> System.Security.Cryptography.CryptographicException: Object already exists
tf destroy [/keephistory] itemspec1 [;versionspec] [itemspec2...itemspecN] [/stopat:versionspec] [/preview] [/startcleanup] [/noprompt] Versionspec: Date/Time Dmm/dd/yyyy or any .Net Framework-supported format or any of the date formats of the local machine Changeset number Cnnnnnn Label Llabelname Latest version T Workspace Wworkspacename;workspaceowner
package dependecyinjection; import java.util.ServiceLoader; public abstract class FooService { public static FooService getService() { ServiceLoader<FooService> loader = ServiceLoader.load(FooService.class); for (FooService service : loader) { return provider; } throw new Exception ("No service"); } public abstract int fooOperation(); } package dependecyinjection; public class FooImpl extends FooService { @Override public int fooOperation() { return 2; } }
SERVICE_TABLE_ENTRY ServiceStartTable[] = { { "ServiceName", ServiceMain }, { 0, 0 } }; if (!StartServiceCtrlDispatcher(ServiceStartTable)) { DWORD err = GetLastError(); if (err == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) return false; }
import os def doc_to_text_catdoc(filename): (fi, fo, fe) = os.popen3('catdoc -w "%s"' % filename) fi.close() retval = fo.read() erroroutput = fe.read() fo.close() fe.close() if not erroroutput: return retval else: raise OSError("Executing the command caused an error: %s" % erroroutput) # similar doc_to_text_antiword()
function getChats() { xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { return; } var url="getchat.php?latest="+latest; xmlHttp.onreadystatechange=stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); } function GetXmlHttpObject() { var xmlHttp=null; try { xmlHttp=new XMLHttpRequest(); } catch (e) { try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; }
new Ajax.Request('/some_url', { method:'get', onSuccess: function(transport){ var response = transport.responseText || "no response text"; alert("Success! \n\n" + response); }, onFailure: function(){ alert('Something went wrong...') } });
Building native extensions. This could take a while... ERROR: Error installing sqlite3-ruby: ERROR: Failed to build gem native extension. c:/ruby/bin/ruby.exe extconf.rb install sqlite3-ruby --platform Win32 checking for fdatasync() in rt.lib... no checking for sqlite3.h... no nmake 'nmake' is not recognized as an internal or external command, operable program or batch file. Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4 for inspection. Results logged to c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4/ext/sqlite3_api/gem_make.out
Building native extensions. This could take a while... ERROR: Error installing sqlite3-ruby: ERROR: Failed to build gem native extension. c:/ruby/bin/ruby.exe extconf.rb install sqlite3-ruby --platform Win32 checking for fdatasync() in rt.lib... no checking for sqlite3.h... no nmake 'nmake' is not recognized as an internal or external command, operable program or batch file. Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4 for inspection. Results logged to c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4/ext/sqlite3_api/gem_make.out
DateFormat formatter = new SimpleDateFormat("MM/dd/yy"); try { Date date = formatter.parse("01/29/02"); } catch (ParseException e) { e.printStackTrace(); }
public partial class updateProgressTest : System.Web.UI.Page { protected void btnTest_OnClick(object sender, EventArgs e) { System.Threading.Thread.Sleep(1000); this.lblTest.Text = "I was changed on the server! Yay!"; } }
<style type='text/css'> .input label.focused { background-color: #EEEEEE; font-style: italic; } </style> <script type='text/javascript' src='jquery.js'></script> <script type='text/javascript'> $(document).ready(function() { $('.input :radio').focus(updateSelectedStyle); $('.input :radio').blur(updateSelectedStyle); $('.input :radio').change(updateSelectedStyle); }) function updateSelectedStyle() { $('.input :radio').removeClass('focused').next().removeClass('focused'); $('.input :radio:checked').addClass('focused').next().addClass('focused'); } </script>
ErrorLog "|/usr/bin/cronolog /path/to/logs/%Y-%m-%d/error.log" CustomLog "|/usr/bin/cronolog /path/to/logs/%Y-%m-%d/access.log" combined
ErrorLog "|/usr/bin/cronolog /path/to/logs/%Y-%m-%d/error.log" CustomLog "|/usr/bin/cronolog /path/to/logs/%Y-%m-%d/access.log" combined
public static T CreateWrapper<T>(Exception innerException, params object[] parameterValues) where T : Exception, new() { if (parameterValues == null) { parameterValues = new object[0]; } Exception exception = null; StringBuilder builder = new StringBuilder(); MethodBase method = new StackFrame(2).GetMethod(); ParameterInfo[] parameters = method.GetParameters(); builder.AppendFormat(CultureInfo.InvariantCulture, ExceptionFormat, new object[] { method.DeclaringType.Name, method.Name }); if ((parameters.Length > 0) || (parameterValues.Length > 0)) { builder.Append(GetParameterList(parameters, parameterValues)); } exception = (Exception)Activator.CreateInstance(typeof(T), new object[] { builder.ToString(), innerException }); return (T)exception; }
private void TextBox_LostKeyboardFocus(object sender, RoutedEventArgs e) { var box = sender as TextBox; var binding = box.GetBindingExpression(TextBox.TextProperty); if (binding.HasError) binding.UpdateTarget(); }
var ctx = new Data.MobileServerDataDataContext(Common.DatabasePath); var deviceSessionRecord = ctx.Sessions.First(sess => sess.SessionRecId == args.DeviceSessionId); deviceSessionRecord.IsActive = false; deviceSessionRecord.Disconnected = DateTime.Now; ctx.SubmitChanges();
public static void flashWindow(JFrame frame) throws InterruptedException { int sleepTime = 50; frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); Thread.sleep(sleepTime); frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); Thread.sleep(sleepTime); frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); }
private class SomeSafeHandle : SafeHandleZeroOrMinusOneIsInvalid { public SomeSafeHandle() : base(true) { } protected override bool ReleaseHandle() { return NativeMethods.CloseHandle(handle); } }
DWORD GetProgramFilesDir(PCTSTR pszComputer, PTSTR pszPath, DWORD& nPath) { DWORD n; HKEY hHKLM; if ((n = RegConnectRegistry(pszComputer, HKEY_LOCAL_MACHINE, &hHKLM)) == ERROR_SUCCESS) { HKEY hWin; if ((n = RegOpenKeyEx(hHKLM, _T("Software\\Microsoft\\Windows\\CurrentVersion"), 0, KEY_READ, &hWin)) == ERROR_SUCCESS) { DWORD nType, cbPath = nPath * sizeof(TCHAR); n = RegQueryValueEx(hWin, _T("ProgramFilesDir"), NULL, &nType, reinterpret_cast<PBYTE>(pszPath), &cbPath); nPath = cbPath / sizeof(TCHAR); RegCloseKey(hWin); } RegCloseKey(hHKLM); } return n; }
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.Collections.ArrayList.get_Item(Int32 index) at System.Windows.Forms.ToolStripItemCollection.get_Item(Int32 index) at System.Windows.Forms.ToolStrip.OnPaint(PaintEventArgs e) at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs) at System.Windows.Forms.Control.WmPaint(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.ToolStrip.WndProc(Message& m) at System.Windows.Forms.MenuStrip.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
function isRunning($pid){ try{ $result = shell_exec(sprintf("ps %d", $pid)); if( count(preg_split("/\n/", $result)) > 2){ return true; } }catch(Exception $e){} return false; }
<Declarations> <Literal Editable="true"> <ID>signature</ID> <Default>signature</Default> </Literal> <Literal> <ID>Exception</ID> <Function>SimpleTypeName(global::System.NotImplementedException)</Function> </Literal> </Declarations>
using(var validation = new ValidationScope()) { ValidateTable1(); ValidateTable2(); ValidateTable3(); if(validation.Haserrors) { MessageBox.Show(validation.ValidationSummary); return; } DoSomethingElse(); }
Application Specific Information: iPhone Simulator 1.0 (70), iPhone OS 2.0 (5A331) *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIView 0x34efd0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key kramerImage.'
Application Specific Information: iPhone Simulator 1.0 (70), iPhone OS 2.0 (5A331) *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIView 0x34efd0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key kramerImage.'
def find_subclasses(module, clazz): for name in dir(module): o = getattr(module, name) try: if (o != clazz) and issubclass(o, clazz): yield name, o except TypeError: pass
SQL> select * from xx,abc; select * from xx,abc * ERROR at line 1: ORA-00942: table or view does not exist SQL> select owner,table_name from all_tables where table_name in ('XX','ABC'); OWNER TABLE_NAME ------------------------------ ------------------------------ MWATSON XX SQL>
$ ./bootstrap --prefix /home/nlucaroni/godi $ ./bootstrap_stage2 .: 1: godi_confdir: not found Error: Command fails with code 2: /bin/sh Failure!
$ ./bootstrap --prefix /home/nlucaroni/godi $ ./bootstrap_stage2 .: 1: godi_confdir: not found Error: Command fails with code 2: /bin/sh Failure!
[DllImport ("iphlpapi.dll", SetLastError=true)] public static extern int GetAdaptersInfo( byte[] ip, ref int size );
private void TextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { e.Handled = true; }
> ===> Configuring for conf-opengl-6 > Checking the suggestion > Include=/usr/include/GL/gl.h Library=/<GLU+GL> > Checking /usr: > Include=/usr/include/GL/gl.h Library=/usr/lib/<GLU+GL> > Checking /usr: > Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/<GLU+GL> > Checking /usr/local: > Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/<GLU+GL> > Exception: Failure "Cannot find library". > Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1022: Command returned with non-zero exit code > Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1375: Command returned with non-zero exit code ### Error: Command fails with code 1: godi_console
> ===> Configuring for conf-opengl-6 > Checking the suggestion > Include=/usr/include/GL/gl.h Library=/<GLU+GL> > Checking /usr: > Include=/usr/include/GL/gl.h Library=/usr/lib/<GLU+GL> > Checking /usr: > Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/<GLU+GL> > Checking /usr/local: > Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/<GLU+GL> > Exception: Failure "Cannot find library". > Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1022: Command returned with non-zero exit code > Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1375: Command returned with non-zero exit code ### Error: Command fails with code 1: godi_console
[Test] void TestThatExceptionIsRaisedWhenStringLengthLargerThen100() [Test] void TestThatStringLengthOf99IsAccepted()