qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
238,004
|
<p>I have an access database with 3 tables.</p>
<ul>
<li>People </li>
<li>Gifts</li>
<li>PeopleGifts</li>
</ul>
<p>Using VS 2008, what is the quickest way to get a page up and running which allows me to run queries against these tables and do basic inserts.</p>
<p>I want to have comboboxs bound to fields in the table so a user can click on a person and click on a gift and they click "Add".</p>
|
[
{
"answer_id": 238033,
"author": "Tim Scott",
"author_id": 29493,
"author_profile": "https://Stackoverflow.com/users/29493",
"pm_score": 0,
"selected": false,
"text": "public interface IOleDbDataGateway\n{\n void ExecuteNonQuery(string sql, params object[] args);\n object ExecuteScalar(string sql, params object[] args);\n DataTable FillDataTable(string sql, params object[] args);\n}\n\npublic class OleDbDataGateway : IOleDbDataGateway\n{\n private readonly string connectionString;\n\n public OleDbDataGateway(string connectionString)\n {\n this.connectionString = connectionString;\n }\n\n public void ExecuteNonQuery(string sql, params object[] args)\n {\n if (args != null)\n {\n sql = string.Format(sql, args);\n }\n var connection = new OleDbConnection(connectionString);\n var command = new OleDbCommand(sql, connection);\n connection.Open();\n try\n {\n command.ExecuteNonQuery();\n }\n finally\n {\n connection.Close();\n }\n }\n\n public object ExecuteScalar(string sql, params object[] args)\n {\n if (args != null)\n {\n sql = string.Format(sql, args);\n }\n var connection = new OleDbConnection(connectionString);\n var command = new OleDbCommand(sql, connection);\n connection.Open();\n try\n {\n return command.ExecuteScalar();\n }\n finally\n {\n connection.Close();\n }\n }\n\n public DataTable FillDataTable(string sql, params object[] args)\n {\n if (args != null)\n {\n sql = string.Format(sql, args);\n }\n var connection = new OleDbConnection(connectionString);\n var adapter = new OleDbDataAdapter(sql, connection);\n var table = new DataTable();\n connection.Open();\n try\n {\n adapter.Fill(table);\n }\n finally\n {\n connection.Close();\n }\n return table;\n }\n}\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
238,008
|
<p>For a simple linked list in which random access to list elements is not a requirement, are there any significant advantages (performance or otherwise) to using <code>std::list</code> instead of <code>std::vector</code>? If backwards traversal is required, would it be more efficient to use <code>std::slist</code> and <code>reverse()</code> the list prior to iterating over its elements?</p>
|
[
{
"answer_id": 238023,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 7,
"selected": true,
"text": "vector vector list vector list"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17035/"
] |
238,010
|
<p>How is it done? What steps do I need to take and what pitfalls and gotchas are there to consider?</p>
|
[
{
"answer_id": 238018,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 4,
"selected": false,
"text": "inline int saturate_to_255 (int a)\n{\n int y;\n asm (\"usat %0, #8, %1\\n\\t\" : \"=r\"(y) : \"r\"(a));\n return y;\n}\n inline int saturate_to_255 (int a)\n{\n if (a < 0) a =0;\n if (a > 255) a = 255;\n return a;\n}\n"
},
{
"answer_id": 248718,
"author": "Hans Sjunnesson",
"author_id": 8683,
"author_profile": "https://Stackoverflow.com/users/8683",
"pm_score": 5,
"selected": true,
"text": "inline int asm_saturate_to_255 (int a) {\n int y;\n __asm__(\"usat %0, #8, %1\\n\\t\" : \"=r\"(y) : \"r\"(a));\n return y;\n}\n"
},
{
"answer_id": 44217667,
"author": "Kamil.S",
"author_id": 5329717,
"author_profile": "https://Stackoverflow.com/users/5329717",
"pm_score": 2,
"selected": false,
"text": "void foo(void) {\n#if TARGET_CPU_ARM64\n __asm (\"sub sp, sp, #0x60\");\n __asm (\"str x29, [sp, #0x50]\");\n#endif\n}\n"
},
{
"answer_id": 70076727,
"author": "crifan",
"author_id": 1616263,
"author_profile": "https://Stackoverflow.com/users/1616263",
"pm_score": -1,
"selected": false,
"text": "arm64 -ansi -std __asm__ asm __asm AT&T syntax GNU syntax UNIX syntax Intel syntax ARM syntax GNU/GCC GNU/UNIX syntax asm(\"assembly code\");\n__asm__(\"assembly code\");\n asm asm-qualifiers ( AssemblerTemplate \n : OutputOperands \n [ : InputOperands\n [ : Clobbers ] ])\n clang ARM64 // inline asm code inside iOS ObjC code\n__attribute__((always_inline)) long svc_0x80_syscall(int syscall_number, const char * pathname, struct stat * stat_info) {\n register const char * x0_pathname asm (\"x0\") = pathname; // first arg\n register struct stat * x1_stat_info asm (\"x1\") = stat_info; // second arg\n register int x16_syscall_number asm (\"x16\") = syscall_number; // special syscall number store to x16\n\n register int x4_ret asm(\"x4\") = -1; // store result\n\n __asm__ volatile(\n \"svc #0x80\\n\"\n \"mov x4, x0\\n\"\n : \"=r\"(x4_ret)\n : \"r\"(x0_pathname), \"r\"(x1_stat_info), \"r\"(x16_syscall_number)\n// : \"x0\", \"x1\", \"x4\", \"x16\"\n );\n return x4_ret;\n}\n // normal ObjC code\n#import <sys/syscall.h>\n\n...\n int openResult = -1;\n struct stat stat_info;\n const char * filePathStr = [filePath UTF8String];\n...\n // call inline asm function\n openResult = svc_0x80_syscall(SYS_stat64, filePathStr, &stat_info);\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8683/"
] |
238,013
|
<p>I have an application running only on Windows and a batch file that launches it.
I want to invoke this batch file from Linux, meaning something like Linux batch will launch the windows batch with parameters and this in its turn run my application.</p>
<p>Can I do that? How?</p>
|
[
{
"answer_id": 238021,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 5,
"selected": true,
"text": "ssh user@windows-box c:/path/to/batch.cmd\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9855/"
] |
238,036
|
<p>I'm working on an app which scrapes data from a website and I was wondering how I should go about getting the data. Specifically I need data contained in a number of div tags which use a specific CSS class - Currently (for testing purposes) I'm just checking for </p>
<pre><code>div class = "classname"
</code></pre>
<p>in each line of HTML - This works, but I can't help but feel there is a better solution out there. </p>
<p>Is there any nice way where I could give a class a line of HTML and have some nice methods like:</p>
<pre><code>boolean usesClass(String CSSClassname);
String getText();
String getLink();
</code></pre>
|
[
{
"answer_id": 238063,
"author": "dave",
"author_id": 14355,
"author_profile": "https://Stackoverflow.com/users/14355",
"pm_score": 3,
"selected": false,
"text": "Parser parser = new Parser(htmlInput);\nCssSelectorNodeFilter cssFilter = \n new CssSelectorNodeFilter(\"DIV.targetClassName\");\nNodeList nodes = parser.parse(cssFilter);\n"
},
{
"answer_id": 238115,
"author": "Fernando Miguélez",
"author_id": 34880,
"author_profile": "https://Stackoverflow.com/users/34880",
"pm_score": 4,
"selected": false,
"text": "import java.io.IOException;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.htmlcleaner.HtmlCleaner;\nimport org.htmlcleaner.TagNode;\n\n/**\n * @author Fernando Miguélez Palomo <fernandoDOTmiguelezATgmailDOTcom>\n */\npublic class TestHtmlParse\n{\n static final String className = \"tags\";\n static final String url = \"http://www.stackoverflow.com\";\n\n TagNode rootNode;\n\n public TestHtmlParse(URL htmlPage) throws IOException\n {\n HtmlCleaner cleaner = new HtmlCleaner();\n rootNode = cleaner.clean(htmlPage);\n }\n\n List getDivsByClass(String CSSClassname)\n {\n List divList = new ArrayList();\n\n TagNode divElements[] = rootNode.getElementsByName(\"div\", true);\n for (int i = 0; divElements != null && i < divElements.length; i++)\n {\n String classType = divElements[i].getAttributeByName(\"class\");\n if (classType != null && classType.equals(CSSClassname))\n {\n divList.add(divElements[i]);\n }\n }\n\n return divList;\n }\n\n public static void main(String[] args)\n {\n try\n {\n TestHtmlParse thp = new TestHtmlParse(new URL(url));\n\n List divs = thp.getDivsByClass(className);\n System.out.println(\"*** Text of DIVs with class '\"+className+\"' at '\"+url+\"' ***\");\n for (Iterator iterator = divs.iterator(); iterator.hasNext();)\n {\n TagNode divElement = (TagNode) iterator.next();\n System.out.println(\"Text child nodes of DIV: \" + divElement.getText().toString());\n }\n }\n catch(Exception e)\n {\n e.printStackTrace();\n }\n }\n}\n"
},
{
"answer_id": 7115646,
"author": "Mike Samuel",
"author_id": 20394,
"author_profile": "https://Stackoverflow.com/users/20394",
"pm_score": 2,
"selected": false,
"text": "nu.validator"
},
{
"answer_id": 8779677,
"author": "igr",
"author_id": 511837,
"author_profile": "https://Stackoverflow.com/users/511837",
"pm_score": 2,
"selected": false,
"text": "Jerry doc = jerry(html);\ndoc.$(\"div#jodd p.neat\").css(\"color\", \"red\").addClass(\"ohmy\");\n doc.form(\"#myform\", new JerryFormHandler() {\n public void onForm(Jerry form, Map<String, String[]> parameters) {\n // process form and parameters\n }\n});\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15075/"
] |
238,050
|
<p>I am trying to issue a SQL update statement with nHibernate (2.0.1GA) like this:</p>
<pre><code>sqlstring = string.Format("set nocount on;update myusers set geo=geography::Point({0}, {1}, 4326) where userid={2};", mlat, mlong, userid);
_session.CreateSQLQuery(sqlstring).ExecuteUpdate();
</code></pre>
<p>However I receive the following error: 'geography@p0' is not a recognized built-in function name.</p>
<p>I thought CreateSQLQuery would just pass the SQL I gave it and execute it...guess not. Any ideas on how I can do that within the context of nHibernate?</p>
|
[
{
"answer_id": 650451,
"author": "Chris Shaffer",
"author_id": 6744,
"author_profile": "https://Stackoverflow.com/users/6744",
"pm_score": 3,
"selected": true,
"text": "set nocount on;update myusers set geo=geography@p0({0}, {1}, 4326) where userid={2};\n"
},
{
"answer_id": 15247716,
"author": "mattk",
"author_id": 353957,
"author_profile": "https://Stackoverflow.com/users/353957",
"pm_score": 0,
"selected": false,
"text": "loc const string Query = @\"SELECT {location.*}\nFROM {location}\nWHERE {location}.STDistance(:loc) is not null\nORDER BY {location}.STDistance(:loc)\";\n Point return session\n .CreateSQLQuery(Query)\n .AddEntity(\"location\", typeof (Location))\n .SetString(\"loc\", \"Point (53.39006999999999 -3.0084007)\")\n .SetMaxResults(1)\n .UniqueResult<Location>();\n"
},
{
"answer_id": 29878949,
"author": "Yosoyadri",
"author_id": 1161893,
"author_profile": "https://Stackoverflow.com/users/1161893",
"pm_score": 0,
"selected": false,
"text": "CREATE FUNCTION GetPoint \n(\n @lat float,\n @lng float,\n @srid int\n)\nRETURNS geography\nAS\nBEGIN\n\ndeclare @point geography = geography::Point(@lat, @lng, @srid);\n\nRETURN @point\n\nEND\nGO\n dbo.GetPoint(@Latitude, @Longitude, 4326)\n geography::Point(@Latitude, @Longitude, 4326);\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1975/"
] |
238,071
|
<p>What is the simplest, fastest way to complete the PHP code below such that the output is in a user-friendly format (for example, "October 27, 2006")?</p>
<pre><code>$result = mysql_query("SELECT my_timestamp FROM some_table WHERE id=42", $DB_CONN);
$row = mysql_fetch_array($result);
$formatted_date = ???($row['my_timestamp']);
echo $formatted_date;
</code></pre>
|
[
{
"answer_id": 238077,
"author": "Aron Rotteveel",
"author_id": 11568,
"author_profile": "https://Stackoverflow.com/users/11568",
"pm_score": 6,
"selected": true,
"text": "$result = mysql_query(\"SELECT DATE_FORMAT(my_timestamp, '%M %d, %Y) AS my_timestamp FROM some_table WHERE id=42\", $DB_CONN);\n$row = mysql_fetch_array($result);\n$formatted_date = $row['my_timestamp'];\necho $formatted_date;\n $result = mysql_query(\"SELECT my_timestamp FROM some_table WHERE id=42\", $DB_CONN);\n$row = mysql_fetch_array($result);\n$formatted_date = strftime('%B %d, %y', $row['my_timestamp']);\necho $formatted_date;\n"
},
{
"answer_id": 238171,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 3,
"selected": false,
"text": "$timestamp = new DateTime($row['my_timestamp']);\necho $timestamp->format('F j, Y') . '<br />';\necho $timestamp->format('F j, Y g:ia');\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2659/"
] |
238,073
|
<p>When scripting in bash or any other shell in *NIX, while running a command that will take more than a few seconds, a progress bar is needed.</p>
<p>For example, copying a big file, opening a big tar file.</p>
<p>What ways do you recommend to add progress bars to shell scripts?</p>
|
[
{
"answer_id": 238094,
"author": "Mitch Haile",
"author_id": 28807,
"author_profile": "https://Stackoverflow.com/users/28807",
"pm_score": 11,
"selected": true,
"text": "\\r \\n \\n echo -ne \\n \\r echo -ne '##### (33%)\\r'\nsleep 1\necho -ne '############# (66%)\\r'\nsleep 1\necho -ne '####################### (100%)\\r'\necho -ne '\\n'\n"
},
{
"answer_id": 238140,
"author": "Diomidis Spinellis",
"author_id": 20520,
"author_profile": "https://Stackoverflow.com/users/20520",
"pm_score": 6,
"selected": false,
"text": "SIGINFO SIGUSR1 dd lsof $ pmonitor -c gzip\n/home/dds/data/mysql-2015-04-01.sql.gz 58.06%\n"
},
{
"answer_id": 3330813,
"author": "leebert",
"author_id": 401730,
"author_profile": "https://Stackoverflow.com/users/401730",
"pm_score": 4,
"selected": false,
"text": "srcdir=$1\noutfile=$2\n\n\ntar -Ocf - $srcdir | pv -i 1 -w 50 -berps `du -bs $srcdir | awk '{print $1}'` | 7za a -si $outfile\n"
},
{
"answer_id": 3330834,
"author": "Daenyth",
"author_id": 350351,
"author_profile": "https://Stackoverflow.com/users/350351",
"pm_score": 7,
"selected": false,
"text": "i=1\nsp=\"/-\\|\"\necho -n ' '\nwhile true\ndo\n printf \"\\b${sp:i++%${#sp}:1}\"\ndone\n sp='/-\\|'\nprintf ' '\nwhile true; do\n printf '\\b%.1s' \"$sp\"\n sp=${sp#?}${sp%???}\ndone\n sp=\"/-\\|\"\nsc=0\nspin() {\n printf \"\\b${sp:sc++:1}\"\n ((sc==${#sp})) && sc=0\n}\nendspin() {\n printf \"\\r%s\\n\" \"$@\"\n}\n\nuntil work_done; do\n spin\n some_work ...\ndone\nendspin\n"
},
{
"answer_id": 3388588,
"author": "Wojtek",
"author_id": 348793,
"author_profile": "https://Stackoverflow.com/users/348793",
"pm_score": 4,
"selected": false,
"text": "$ tar -c --checkpoint=1000 --checkpoint-action=dot /var\n...\n $ tar -c --checkpoint=.1000 /var\n"
},
{
"answer_id": 3554912,
"author": "Noah Spurrier",
"author_id": 319432,
"author_profile": "https://Stackoverflow.com/users/319432",
"pm_score": 2,
"selected": false,
"text": "gzip --list untar_progress () \n{ \n TARBALL=$1\n BLOCKING_FACTOR=$(gzip --list ${TARBALL} |\n perl -MPOSIX -ane '$.==2 && print ceil $F[1]/50688')\n tar --blocking-factor=${BLOCKING_FACTOR} --checkpoint=1 \\\n --checkpoint-action='ttyout=Wrote %u% \\r' -zxf ${TARBALL}\n}\n"
},
{
"answer_id": 6863190,
"author": "Seth Wegner",
"author_id": 868024,
"author_profile": "https://Stackoverflow.com/users/868024",
"pm_score": 6,
"selected": false,
"text": "pv"
},
{
"answer_id": 10814641,
"author": "DeathFromAbove",
"author_id": 1425808,
"author_profile": "https://Stackoverflow.com/users/1425808",
"pm_score": -1,
"selected": false,
"text": "tar xzvf pippo.tgz |xargs -L 19 |xargs -I@ echo -n \".\"\n"
},
{
"answer_id": 16337150,
"author": "akiuni",
"author_id": 2342951,
"author_profile": "https://Stackoverflow.com/users/2342951",
"pm_score": -1,
"selected": false,
"text": "#!/bin/bash\n\necho \"getting script inode\"\ninode=`ls -i ./script.sh | cut -d\" \" -f1`\necho $inode\n\necho \"getting the script size\"\nsize=`cat script.sh | wc -c`\necho $size\n\necho \"executing script\"\n./script.sh &\npid=$!\necho \"child pid = $pid\"\n\nwhile true; do\n let offset=`lsof -o0 -o -p $pid | grep $inode | awk -F\" \" '{print $7}' | cut -d\"t\" -f 2`\n let percent=100*$offset/$size\n echo -ne \" $percent %\\r\"\ndone\n"
},
{
"answer_id": 16348366,
"author": "romeror",
"author_id": 2344918,
"author_profile": "https://Stackoverflow.com/users/2344918",
"pm_score": 4,
"selected": false,
"text": "while :;do echo -n .;sleep 1;done &\ntrap \"kill $!\" EXIT #Die with parent if we die prematurely\ntar zxf packages.tar.gz; # or any other command here\nkill $! && trap \" \" EXIT #Kill the loop and unset the trap or else the pid might get reassigned and we might end up killing a completely different process\n . tar"
},
{
"answer_id": 19726222,
"author": "janr",
"author_id": 1171193,
"author_profile": "https://Stackoverflow.com/users/1171193",
"pm_score": -1,
"selected": false,
"text": "#!/bin/bash\n# Updates the progress bar\n# Parameters: 1. Percentage value\nupdate_progress_bar()\n{\n if [ $# -eq 1 ];\n then\n if [[ $1 == [0-9]* ]];\n then\n if [ $1 -ge 0 ];\n then\n if [ $1 -le 100 ];\n then\n local val=$1\n local max=100\n\n echo -n \"[\"\n\n for j in $(seq $max);\n do\n if [ $j -lt $val ];\n then\n echo -n \"=\"\n else\n if [ $j -eq $max ];\n then\n echo -n \"]\"\n else\n echo -n \".\"\n fi\n fi\n done\n\n echo -ne \" \"$val\"%\\r\"\n\n if [ $val -eq $max ];\n then\n echo \"\"\n fi\n fi\n fi\n fi\n fi\n}\n\nupdate_progress_bar 0\n# Further (time intensive) actions and progress bar updates\nupdate_progress_bar 100\n"
},
{
"answer_id": 22454218,
"author": "tPSU",
"author_id": 3428793,
"author_profile": "https://Stackoverflow.com/users/3428793",
"pm_score": 2,
"selected": false,
"text": "#!/bin/sh\n(\necho \"10\" ; sleep 1\necho \"# Updating mail logs\" ; sleep 1\necho \"20\" ; sleep 1\necho \"# Resetting cron jobs\" ; sleep 1\necho \"50\" ; sleep 1\necho \"This line will just be ignored\" ; sleep 1\necho \"75\" ; sleep 1\necho \"# Rebooting system\" ; sleep 1\necho \"100\" ; sleep 1\n) |\nzenity --progress \\\n --title=\"Update System Logs\" \\\n --text=\"Scanning mail logs...\" \\\n --percentage=0\n\nif [ \"$?\" = -1 ] ; then\n zenity --error \\\n --text=\"Update canceled.\"\nfi\n"
},
{
"answer_id": 24818227,
"author": "thedk",
"author_id": 442474,
"author_profile": "https://Stackoverflow.com/users/442474",
"pm_score": 2,
"selected": false,
"text": "$ bar file1 | wc -l \n$ pv file1 | wc -l\n $ tail -n 100 file1 | bar | wc -l\n$ tail -n 100 file1 | pv | wc -l\n $ copy <(bar file1) file2\n$ copy <(pv file1) file2\n bar --in-file /dev/rmt/1cbn --out-file \\\n tape-restore.tar --size 2.4g --buffer-size 64k\n"
},
{
"answer_id": 26290342,
"author": "synthesizerpatel",
"author_id": 210613,
"author_profile": "https://Stackoverflow.com/users/210613",
"pm_score": 0,
"selected": false,
"text": "#!/bin/sh\n#\n# Copyright (C) Nathan Ramella (nar+progress-script@remix.net) 2010 \n# LGPLv2 license\n# If you use this, send me an email to say thanks and let me know what your product\n# is so I can tell all my friends I'm a big man on the internet!\n\nprogress_filter() {\n\n local START=$(date +\"%s\")\n local SIZE=1\n local DURATION=1\n local BLKSZ=51200\n local TMPFILE=/tmp/tmpfile\n local PROGRESS=/tmp/tftp.progress\n local BYTES_LAST_CYCLE=0\n local BYTES_THIS_CYCLE=0\n\n rm -f ${PROGRESS}\n\n dd bs=$BLKSZ of=${TMPFILE} 2>&1 \\\n | grep --line-buffered -E '[[:digit:]]* bytes' \\\n | awk '{ print $1 }' >> ${PROGRESS} &\n\n # Loop while the 'dd' exists. It would be 'more better' if we\n # actually looked for the specific child ID of the running \n # process by identifying which child process it was. If someone\n # else is running dd, it will mess things up.\n\n # My PID handling is dumb, it assumes you only have one running dd on\n # the system, this should be fixed to just get the PID of the child\n # process from the shell.\n\n while [ $(pidof dd) -gt 1 ]; do\n\n # PROTIP: You can sleep partial seconds (at least on linux)\n sleep .5 \n\n # Force dd to update us on it's progress (which gets\n # redirected to $PROGRESS file.\n # \n # dumb pid handling again\n pkill -USR1 dd\n\n local BYTES_THIS_CYCLE=$(tail -1 $PROGRESS)\n local XFER_BLKS=$(((BYTES_THIS_CYCLE-BYTES_LAST_CYCLE)/BLKSZ))\n\n # Don't print anything unless we've got 1 block or more.\n # This allows for stdin/stderr interactions to occur\n # without printing a hash erroneously.\n\n # Also makes it possible for you to background 'scp',\n # but still use the /dev/stdout trick _even_ if scp\n # (inevitably) asks for a password. \n #\n # Fancy!\n\n if [ $XFER_BLKS -gt 0 ]; then\n printf \"#%0.s\" $(seq 0 $XFER_BLKS)\n BYTES_LAST_CYCLE=$BYTES_THIS_CYCLE\n fi\n done\n\n local SIZE=$(stat -c\"%s\" $TMPFILE)\n local NOW=$(date +\"%s\")\n\n if [ $NOW -eq 0 ]; then\n NOW=1\n fi\n\n local DURATION=$(($NOW-$START))\n local BYTES_PER_SECOND=$(( SIZE / DURATION ))\n local KBPS=$((SIZE/DURATION/1024))\n local MD5=$(md5sum $TMPFILE | awk '{ print $1 }')\n\n # This function prints out ugly stuff suitable for eval() \n # rather than a pretty string. This makes it a bit more \n # flexible if you have a custom format (or dare I say, locale?)\n\n printf \"\\nDURATION=%d\\nBYTES=%d\\nKBPS=%f\\nMD5=%s\\n\" \\\n $DURATION \\\n $SIZE \\\n $KBPS \\\n $MD5\n}\n echo \"wget\"\nwget -q -O /dev/stdout http://www.blah.com/somefile.zip | progress_filter\n\necho \"tftp\"\ntftp -l /dev/stdout -g -r something/firmware.bin 192.168.1.1 | progress_filter\n\necho \"scp\"\nscp user@192.168.1.1:~/myfile.tar /dev/stdout | progress_filter\n"
},
{
"answer_id": 26735825,
"author": "lukassos",
"author_id": 3594655,
"author_profile": "https://Stackoverflow.com/users/3594655",
"pm_score": 2,
"selected": false,
"text": "pv bar dd dd if=\"$input_drive_path\" of=\"$output_file_path\" pv dd if=\"$input_drive_path\" | pv | dd of=\"$output_file_path\" STDOUT 7.46GB 0:33:40 [3.78MB/s] [ <=> ]\n 15654912+0 records in\n 15654912+0 records out\n 8015314944 bytes (8.0 GB) copied, 2020.49 s, 4.0 MB/s\n"
},
{
"answer_id": 28044986,
"author": "fearside",
"author_id": 4473863,
"author_profile": "https://Stackoverflow.com/users/4473863",
"pm_score": 6,
"selected": false,
"text": "#!/bin/bash\n# 1. Create ProgressBar function\n# 1.1 Input is currentState($1) and totalState($2)\nfunction ProgressBar {\n# Process data\n let _progress=(${1}*100/${2}*100)/100\n let _done=(${_progress}*4)/10\n let _left=40-$_done\n# Build progressbar string lengths\n _fill=$(printf \"%${_done}s\")\n _empty=$(printf \"%${_left}s\")\n\n# 1.2 Build progressbar strings and print the ProgressBar line\n# 1.2.1 Output example: \n# 1.2.1.1 Progress : [########################################] 100%\nprintf \"\\rProgress : [${_fill// /#}${_empty// /-}] ${_progress}%%\"\n\n}\n\n# Variables\n_start=1\n\n# This accounts as the \"totalState\" variable for the ProgressBar function\n_end=100\n\n# Proof of concept\nfor number in $(seq ${_start} ${_end})\ndo\n sleep 0.1\n ProgressBar ${number} ${_end}\ndone\nprintf '\\nFinished!\\n'\n"
},
{
"answer_id": 29297604,
"author": "auino",
"author_id": 1194426,
"author_profile": "https://Stackoverflow.com/users/1194426",
"pm_score": 0,
"selected": false,
"text": "#!/bin/python\nfrom time import sleep\nimport sys\n\nif len(sys.argv) != 3:\n print \"Usage:\", sys.argv[0], \"<total_time>\", \"<progressbar_size>\"\n exit()\n\nTOTTIME=float(sys.argv[1])\nBARSIZE=float(sys.argv[2])\n\nPERCRATE=100.0/TOTTIME\nBARRATE=BARSIZE/TOTTIME\n\nfor i in range(int(TOTTIME)+1):\n sys.stdout.write('\\r')\n s = \"[%-\"+str(int(BARSIZE))+\"s] %d%% \"\n sys.stdout.write(s % ('='*int(BARRATE*i), int(PERCRATE*i)))\n sys.stdout.flush()\n SLEEPTIME = 1.0\n if i == int(TOTTIME): SLEEPTIME = 0.1\n sleep(SLEEPTIME)\nprint \"\"\n progressbar.py python progressbar.py 10 50\n 50 10"
},
{
"answer_id": 30454143,
"author": "Sundeep471",
"author_id": 1838678,
"author_profile": "https://Stackoverflow.com/users/1838678",
"pm_score": 2,
"selected": false,
"text": "while true; do sleep 0.25 && echo -ne \"\\r\\\\\" && sleep 0.25 && echo -ne \"\\r|\" && sleep 0.25 && echo -ne \"\\r/\" && sleep 0.25 && echo -ne \"\\r-\"; done;\n while true; do sleep 0.25 && echo -ne \"\\rActivity: \\\\\" && sleep 0.25 && echo -ne \"\\rActivity: |\" && sleep 0.25 && echo -ne \"\\rActivity: /\" && sleep 0.25 && echo -ne \"\\rActivity: -\"; done;\n while true; do sleep 0.25 && echo -ne \"\\r\" && sleep 0.25 && echo -ne \"\\r>\" && sleep 0.25 && echo -ne \"\\r>>\" && sleep 0.25 && echo -ne \"\\r>>>\"; sleep 0.25 && echo -ne \"\\r>>>>\"; done;\n while true; do sleep .25 && echo -ne \"\\r:Active:\" && sleep .25 && echo -ne \"\\r:aCtive:\" && sleep .25 && echo -ne \"\\r:acTive:\" && sleep .25 && echo -ne \"\\r:actIve:\" && sleep .25 && echo -ne \"\\r:actiVe:\" && sleep .25 && echo -ne \"\\r:activE:\"; done;\n"
},
{
"answer_id": 31125424,
"author": "Zarko Zivanov",
"author_id": 5062839,
"author_profile": "https://Stackoverflow.com/users/5062839",
"pm_score": 1,
"selected": false,
"text": "preparebar() {\n# $1 - bar length\n# $2 - bar char\n barlen=$1\n barspaces=$(printf \"%*s\" \"$1\")\n barchars=$(printf \"%*s\" \"$1\" | tr ' ' \"$2\")\n}\n progressbar() {\n# $1 - number (-1 for clearing the bar)\n# $2 - max number\n if [ $1 -eq -1 ]; then\n printf \"\\r $barspaces\\r\"\n else\n barch=$(($1*barlen/$2))\n barsp=$((barlen-barch))\n printf \"\\r[%.${barch}s%.${barsp}s]\\r\" \"$barchars\" \"$barspaces\"\n fi\n}\n preparebar 50 \"#\"\n progressbar 35 80\n [##################### ]\n progressbar -1 80\n progressbar() {\n# $1 - number\n# $2 - max number\n# $3 - number of '#' characters\n if [ $1 -eq -1 ]; then\n printf \"\\r %*s\\r\" \"$3\"\n else\n i=$(($1*$3/$2))\n j=$(($3-i))\n printf \"\\r[%*s\" \"$i\" | tr ' ' '#'\n printf \"%*s]\\r\" \"$j\"\n fi\n}\n progressbar 35 80 50\n >&2"
},
{
"answer_id": 34708674,
"author": "Juan Eduardo Castaño Nestares",
"author_id": 1922181,
"author_profile": "https://Stackoverflow.com/users/1922181",
"pm_score": 2,
"selected": false,
"text": "for a in {1..100}; do sleep .1s; echo $a| dialog --gauge \"waiting\" 7 30; done\n #!/bin/bash\nINIT=`/bin/date +%s`\nNOW=$INIT\nFUTURE=`/bin/date -d \"$1\" +%s`\n[ $FUTURE -a $FUTURE -eq $FUTURE ] || exit\nDIFF=`echo \"$FUTURE - $INIT\"|bc -l`\n\nwhile [ $INIT -le $FUTURE -a $NOW -lt $FUTURE ]; do\n NOW=`/bin/date +%s`\n STEP=`echo \"$NOW - $INIT\"|bc -l`\n SLEFT=`echo \"$FUTURE - $NOW\"|bc -l`\n MLEFT=`echo \"scale=2;$SLEFT/60\"|bc -l`\n TEXT=\"$SLEFT seconds left ($MLEFT minutes)\";\n TITLE=\"Waiting $1: $2\"\n sleep 1s\n PTG=`echo \"scale=0;$STEP * 100 / $DIFF\"|bc -l`\n echo $PTG| dialog --title \"$TITLE\" --gauge \"$TEXT\" 7 72\ndone\n\nif [ \"$2\" == \"\" ]; then msg=\"Espera terminada: $1\";audio=\"Listo\";\nelse msg=$2;audio=$2;fi \n\n/usr/bin/notify-send --icon=stock_appointment-reminder-excl \"$msg\"\nespeak -v spanish \"$audio\"\n Wait \"34 min\" \"warm up the oven\" Wait \"dec 31\" \"happy new year\""
},
{
"answer_id": 35314522,
"author": "CH55",
"author_id": 5908091,
"author_profile": "https://Stackoverflow.com/users/5908091",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n\n # 1. Create ProgressBar function\n # 1.1 Input is currentState($1) and totalState($2)\n function ProgressBar {\n # Process data\nlet _progress=(${1}*100/${2}*100)/100\nlet _done=(${_progress}*4)/10\nlet _left=40-$_done\n# Build progressbar string lengths\n_fill=$(printf \"%${_done}s\")\n_empty=$(printf \"%${_left}s\")\n\n# 1.2 Build progressbar strings and print the ProgressBar line\n# 1.2.1 Output example:\n# 1.2.1.1 Progress : [########################################] 100%\nprintf \"\\rProgress : [${_fill// /#}${_empty// /-}] ${_progress}%%\"\n\n}\n\nfunction rman_check {\nsqlplus -s / as sysdba <<EOF\nset heading off\nset feedback off\nselect\nround((sofar/totalwork) * 100,0) pct_done\nfrom\nv\\$session_longops\nwhere\ntotalwork > sofar\nAND\nopname NOT LIKE '%aggregate%'\nAND\nopname like 'RMAN%';\nexit\nEOF\n}\n\n# Variables\n_start=1\n\n# This accounts as the \"totalState\" variable for the ProgressBar function\n_end=100\n\n_rman_progress=$(rman_check)\n#echo ${_rman_progress}\n\n# Proof of concept\n#for number in $(seq ${_start} ${_end})\n\nwhile [ ${_rman_progress} -lt 100 ]\ndo\n\nfor number in _rman_progress\ndo\nsleep 10\nProgressBar ${number} ${_end}\ndone\n\n_rman_progress=$(rman_check)\n\ndone\nprintf '\\nFinished!\\n'\n"
},
{
"answer_id": 36493802,
"author": "casper.dcl",
"author_id": 3896283,
"author_profile": "https://Stackoverflow.com/users/3896283",
"pm_score": 2,
"selected": false,
"text": "'\\r' + $some_sort_of_progress_msg 7z a -r newZipFile myFolder tqdm $ sudo pip install tqdm\n$ # now have fun\n$ 7z a -r -bd newZipFile myFolder | tqdm >> /dev/null\n$ # if we know the expected total, we can have a bar!\n$ 7z a -r -bd newZipFile myFolder | grep -o Compressing | tqdm --total $(find myFolder -type f | wc -l) >> /dev/null\n tqdm -h $ find / -name '*.py' -exec cat \\{} \\; | tqdm --unit loc --unit_scale True | wc -l\n tqdm"
},
{
"answer_id": 37285172,
"author": "nexace",
"author_id": 5728799,
"author_profile": "https://Stackoverflow.com/users/5728799",
"pm_score": -1,
"selected": false,
"text": "[####### ] (10%) Creating directory tree\n #!/bin/bash\n\nif [ \"$#\" -eq 0 ]; then echo \"x is \\\"time in seconds\\\" and z is \\\"message\\\"\"; echo \"Usage: progressbar x z\"; exit; fi\nprogressbar() {\n local loca=$1; local loca2=$2;\n declare -a bgcolors; declare -a fgcolors;\n for i in {40..46} {100..106}; do\n bgcolors+=(\"$i\")\n done\n for i in {30..36} {90..96}; do\n fgcolors+=(\"$i\")\n done\n local u=$(( 50 - loca ));\n local y; local t;\n local z; z=$(printf '%*s' \"$u\");\n local w=$(( loca * 2 ));\n local bouncer=\".oO°Oo.\";\n for ((i=0;i<loca;i++)); do\n t=\"${bouncer:((i%${#bouncer})):1}\"\n bgcolor=\"\\\\E[${bgcolors[RANDOM % 14]}m \\\\033[m\"\n y+=\"$bgcolor\";\n done\n fgcolor=\"\\\\E[${fgcolors[RANDOM % 14]}m\"\n echo -ne \" $fgcolor$t$y$z$fgcolor$t \\\\E[96m(\\\\E[36m$w%\\\\E[96m)\\\\E[92m $fgcolor$loca2\\\\033[m\\r\"\n};\ntimeprogress() {\n local loca=\"$1\"; local loca2=\"$2\";\n loca=$(bc -l <<< scale=2\\;\"$loca/50\")\n for i in {1..50}; do\n progressbar \"$i\" \"$loca2\";\n sleep \"$loca\";\n done\n printf \"\\n\"\n};\ntimeprogress \"$1\" \"$2\"\n"
},
{
"answer_id": 37787262,
"author": "purushothaman poovai",
"author_id": 5201274,
"author_profile": "https://Stackoverflow.com/users/5201274",
"pm_score": -1,
"selected": false,
"text": "sleep 12&\nwhile pgrep sleep &> /dev/null;do echo -en \"#\";sleep 0.5;done\n"
},
{
"answer_id": 38276931,
"author": "pbatey",
"author_id": 2683294,
"author_profile": "https://Stackoverflow.com/users/2683294",
"pm_score": -1,
"selected": false,
"text": "#!/bin/bash\nfunction lines {\n local file=$1\n local default=$2\n if [[ -f $file ]]; then\n wc -l $file | awk '{print $1}';\n else\n echo $default\n fi\n}\n\nfunction bar {\n local items=$1\n local total=$2\n local size=$3\n percent=$(($items*$size/$total % $size))\n left=$(($size-$percent))\n chars=$(local s=$(printf \"%${percent}s\"); echo \"${s// /=}\")\n echo -ne \"[$chars>\";\n printf \"%${left}s\"\n echo -ne ']\\r'\n}\n\nfunction clearbar {\n local size=$1\n printf \" %${size}s \"\n echo -ne \"\\r\"\n}\n\nfunction progress {\n local pid=$1\n local total=$2\n local file=$3\n\n bar 0 100 50\n while [[ \"$(ps a | awk '{print $1}' | grep $pid)\" ]]; do\n bar $(lines $file 0) $total 50\n sleep 1\n done\n clearbar 50\n wait $pid\n return $?\n}\n target=$(lines build.log 1000)\n(mvn clean install > build.log 2>&1) &\nprogress $! $target build.log\n [===============================================> ]\n"
},
{
"answer_id": 39898465,
"author": "Édouard Lopez",
"author_id": 802365,
"author_profile": "https://Stackoverflow.com/users/802365",
"pm_score": 6,
"selected": false,
"text": "progress-bar.sh progress-bar() {\n local duration=${1}\n\n\n already_done() { for ((done=0; done<$elapsed; done++)); do printf \"▇\"; done }\n remaining() { for ((remain=$elapsed; remain<$duration; remain++)); do printf \" \"; done }\n percentage() { printf \"| %s%%\" $(( (($elapsed)*100)/($duration)*100/100 )); }\n clean_line() { printf \"\\r\"; }\n\n for (( elapsed=1; elapsed<=$duration; elapsed++ )); do\n already_done; remaining; percentage\n sleep 1\n clean_line\n done\n clean_line\n}\n progress-bar 100\n"
},
{
"answer_id": 40901103,
"author": "cprn",
"author_id": 1347707,
"author_profile": "https://Stackoverflow.com/users/1347707",
"pm_score": 5,
"selected": false,
"text": "#!/bin/sh\n\nBAR='####################' # this is full bar, e.g. 20 chars\n\nfor i in {1..20}; do\n echo -ne \"\\r${BAR:0:$i}\" # print $i chars of $BAR from 0 position\n sleep .1 # wait 100ms between \"frames\"\ndone\n {1..20} echo stdout echo -n echo -e \"\\r\" $i for $i cp #!/bin/sh\n\nsrc=\"/path/to/source/file\"\ntgt=\"/path/to/target/file\"\n\ncp \"$src\" \"$tgt\" & # the & forks the `cp` process so the rest\n # of the code runs without waiting (async)\n\nBAR='####################'\n\nsrc_size=$(stat -c%s \"$src\") # how much there is to do\n\nwhile true; do\n tgt_size=$(stat -c%s \"$tgt\") # how much has been done so far\n i=$(( $tgt_size * 20 / $src_size ))\n echo -ne \"\\r${BAR:0:$i}\"\n if [ $tgt_size == $src_size ]; then\n echo \"\" # add a new line at the end\n break; # break the loop\n fi\n sleep .1\ndone\n foo=$(bar) bar stdout $foo stat stdout stat -c %s #!/bin/sh\nsrc_size=$(gzip -l \"$src\" | tail -n1 | tr -s ' ' | cut -d' ' -f3)\n gzip -l tail -n1 tr -s ' ' cut -d' ' -f3 /usr/lib/progress_bar.sh $BAR #!/bin/bash\n\nBAR_length=50\nBAR_character='#'\nBAR=$(printf %${BAR_length}s | tr ' ' $BAR_character)\n\nwork_todo=$(get_work_todo) # how much there is to do\n\nwhile true; do\n work_done=$(get_work_done) # how much has been done so far\n i=$(( $work_done * $BAR_length / $work_todo ))\n echo -ne \"\\r${BAR:0:$i}\"\n if [ $work_done == $work_todo ]; then\n echo \"\"\n break;\n fi\n sleep .1\ndone\n printf printf %50s tr ' ' '#' #!/bin/bash\n\nsrc=\"/path/to/source/file\"\ntgt=\"/path/to/target/file\"\n\nfunction get_work_todo() {\n echo $(stat -c%s \"$src\")\n}\n\nfunction get_work_done() {\n [ -e \"$tgt\" ] && # if target file exists\n echo $(stat -c%s \"$tgt\") || # echo its size, else\n echo 0 # echo zero\n}\n\ncp \"$src\" \"$tgt\" & # copy in the background\n\nsource /usr/lib/progress_bar.sh # execute the progress bar\n $! progress_bar.sh ${} ${foo:A:B} : man bash $() foo=$(bar) bar $foo | return man bash echo -ne \"\\r${BAR:0:$i}\" Bad substitution echo -ne \"\\r$(expr \"x$name\" : \"x.\\{0,$num_skip\\}\\(.\\{0,$num_keep\\}\\)\")\" #!/bin/sh\n\nsrc=100\ntgt=0\n\nget_work_todo() {\n echo $src\n}\n\ndo_work() {\n echo \"$(( $1 + 1 ))\"\n}\n\nBAR_length=50\nBAR_character='#'\nBAR=$(printf %${BAR_length}s | tr ' ' $BAR_character)\nwork_todo=$(get_work_todo) # how much there is to do\nwork_done=0\nwhile true; do\n work_done=\"$(do_work $work_done)\"\n i=$(( $work_done * $BAR_length / $work_todo ))\n n=$(( $BAR_length - $i ))\n printf \"\\r$(expr \"x$BAR\" : \"x.\\{0,$n\\}\\(.\\{0,$i\\}\\)\")\"\n if [ $work_done = $work_todo ]; then\n echo \"\\n\"\n break;\n fi\n sleep .1\ndone\n"
},
{
"answer_id": 43692366,
"author": "Adriano_Pinaffo",
"author_id": 6201770,
"author_profile": "https://Stackoverflow.com/users/6201770",
"pm_score": 2,
"selected": false,
"text": "#!/bin/bash\n#\n# Progress bar by Adriano Pinaffo\n# Available at https://github.com/adriano-pinaffo/progressbar.sh\n# Inspired on work by Edouard Lopez (https://github.com/edouard-lopez/progress-bar.sh)\n# Version 1.0\n# Date April, 28th 2017\n\nfunction error {\n echo \"Usage: $0 [SECONDS]\"\n case $1 in\n 1) echo \"Pass one argument only\"\n exit 1\n ;;\n 2) echo \"Parameter must be a number\"\n exit 2\n ;;\n *) echo \"Unknown error\"\n exit 999\n esac\n}\n\n[[ $# -ne 1 ]] && error 1\n[[ $1 =~ ^[0-9]+$ ]] || error 2\n\nduration=${1}\nbarsize=$((`tput cols` - 7))\nunity=$(($barsize / $duration))\nincrement=$(($barsize%$duration))\nskip=$(($duration/($duration-$increment)))\ncurr_bar=0\nprev_bar=\nfor (( elapsed=1; elapsed<=$duration; elapsed++ ))\ndo\n # Elapsed\nprev_bar=$curr_bar\n let curr_bar+=$unity\n [[ $increment -eq 0 ]] || { \n [[ $skip -eq 1 ]] &&\n { [[ $(($elapsed%($duration/$increment))) -eq 0 ]] && let curr_bar++; } ||\n { [[ $(($elapsed%$skip)) -ne 0 ]] && let curr_bar++; }\n }\n [[ $elapsed -eq 1 && $increment -eq 1 && $skip -ne 1 ]] && let curr_bar++\n [[ $(($barsize-$curr_bar)) -eq 1 ]] && let curr_bar++\n [[ $curr_bar -lt $barsize ]] || curr_bar=$barsize\n for (( filled=0; filled<=$curr_bar; filled++ )); do\n printf \"▇\"\n done\n\n # Remaining\n for (( remain=$curr_bar; remain<$barsize; remain++ )); do\n printf \" \"\n done\n\n # Percentage\n printf \"| %s%%\" $(( ($elapsed*100)/$duration))\n\n # Return\n sleep 1\n printf \"\\r\"\ndone\nprintf \"\\n\"\nexit 0\n"
},
{
"answer_id": 45676666,
"author": "Mike Q",
"author_id": 1618630,
"author_profile": "https://Stackoverflow.com/users/1618630",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n\nfunction progress_bar() {\n bar=\"\"\n total=10\n [[ -z $1 ]] && input=0 || input=${1}\n x=\"##\"\n for i in `seq 1 10`; do\n if [ $i -le $input ] ;then\n bar=$bar$x\n else\n bar=\"$bar \"\n fi\n done\n #pct=$((200*$input/$total % 2 + 100*$input/$total))\n pct=$(($input*10))\n echo -ne \"Progress : [ ${bar} ] (${pct}%) \\r\" \n sleep 1\n if [ $input -eq 10 ] ;then\n echo -ne '\\n'\n fi\n\n}\n progress_bar 1\necho \"doing something ...\"\nprogress_bar 2\necho \"doing something ...\"\nprogress_bar 3\necho \"doing something ...\"\nprogress_bar 8\necho \"doing something ...\"\nprogress_bar 10\n"
},
{
"answer_id": 48389432,
"author": "Qub3r",
"author_id": 1591346,
"author_profile": "https://Stackoverflow.com/users/1591346",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/env bash\n\nmain() {\n for (( i = 0; i <= 100; i=$i + 1)); do\n progress_bar \"$i\"\n sleep 0.1;\n done\n progress_bar \"done\"\n exit 0\n}\n\nprogress_bar() {\n if [ \"$1\" == \"done\" ]; then\n spinner=\"X\"\n percent_done=\"100\"\n progress_message=\"Done!\"\n new_line=\"\\n\"\n else\n spinner='/-\\|'\n percent_done=\"${1:-0}\"\n progress_message=\"$percent_done %\"\n fi\n\n percent_none=\"$(( 100 - $percent_done ))\"\n [ \"$percent_done\" -gt 0 ] && local done_bar=\"$(printf '#%.0s' $(seq -s ' ' 1 $percent_done))\"\n [ \"$percent_none\" -gt 0 ] && local none_bar=\"$(printf '~%.0s' $(seq -s ' ' 1 $percent_none))\"\n\n # print the progress bar to the screen\n printf \"\\r Progress: [%s%s] %s %s${new_line}\" \\\n \"$done_bar\" \\\n \"$none_bar\" \\\n \"${spinner:x++%${#spinner}:1}\" \\\n \"$progress_message\"\n}\n\nmain \"$@\"\n"
},
{
"answer_id": 52581824,
"author": "Vagiz Duseev",
"author_id": 2472360,
"author_profile": "https://Stackoverflow.com/users/2472360",
"pm_score": 4,
"selected": false,
"text": "[##################################################] 100% (137921 / 137921 bytes)\n [######################### ] 50% (15 / 30 seconds)\n PROGRESS_BAR_WIDTH=50 # progress bar length in characters\n\ndraw_progress_bar() {\n # Arguments: current value, max value, unit of measurement (optional)\n local __value=$1\n local __max=$2\n local __unit=${3:-\"\"} # if unit is not supplied, do not display it\n\n # Calculate percentage\n if (( $__max < 1 )); then __max=1; fi # anti zero division protection\n local __percentage=$(( 100 - ($__max*100 - $__value*100) / $__max ))\n\n # Rescale the bar according to the progress bar width\n local __num_bar=$(( $__percentage * $PROGRESS_BAR_WIDTH / 100 ))\n\n # Draw progress bar\n printf \"[\"\n for b in $(seq 1 $__num_bar); do printf \"#\"; done\n for s in $(seq 1 $(( $PROGRESS_BAR_WIDTH - $__num_bar ))); do printf \" \"; done\n printf \"] $__percentage%% ($__value / $__max $__unit)\\r\"\n}\n file_size uploaded_bytes # Uploading a file\nfile_size=137921\n\nwhile true; do\n # Get current value of uploaded bytes\n uploaded_bytes=$(some_function_that_reports_progress)\n\n # Draw a progress bar\n draw_progress_bar $uploaded_bytes $file_size \"bytes\"\n\n # Check if we reached 100%\n if [ $uploaded_bytes == $file_size ]; then break; fi\n sleep 1 # Wait before redrawing\ndone\n# Go to the newline at the end of upload\nprintf \"\\n\"\n"
},
{
"answer_id": 53094295,
"author": "Hello World",
"author_id": 1452435,
"author_profile": "https://Stackoverflow.com/users/1452435",
"pm_score": 2,
"selected": false,
"text": "progreSh 40"
},
{
"answer_id": 53616678,
"author": "polle",
"author_id": 10744942,
"author_profile": "https://Stackoverflow.com/users/10744942",
"pm_score": 4,
"selected": false,
"text": "source ./progress_bar.sh\necho \"This is some output\"\nsetup_scroll_area\nsleep 1\necho \"This is some output 2\"\ndraw_progress_bar 10\nsleep 1\necho \"This is some output 3\"\ndraw_progress_bar 50\nsleep 1\necho \"This is some output 4\"\ndraw_progress_bar 90\nsleep 1\necho \"This is some output 5\"\ndestroy_scroll_area\n #!/bin/bash\n\n# This code was inspired by the open source C code of the APT progress bar\n# http://bazaar.launchpad.net/~ubuntu-branches/ubuntu/trusty/apt/trusty/view/head:/apt-pkg/install-progress.cc#L233\n\n#\n# Usage:\n# Source this script\n# setup_scroll_area\n# draw_progress_bar 10\n# draw_progress_bar 90\n# destroy_scroll_area\n#\n\n\nCODE_SAVE_CURSOR=\"\\033[s\"\nCODE_RESTORE_CURSOR=\"\\033[u\"\nCODE_CURSOR_IN_SCROLL_AREA=\"\\033[1A\"\nCOLOR_FG=\"\\e[30m\"\nCOLOR_BG=\"\\e[42m\"\nRESTORE_FG=\"\\e[39m\"\nRESTORE_BG=\"\\e[49m\"\n\nfunction setup_scroll_area() {\n lines=$(tput lines)\n let lines=$lines-1\n # Scroll down a bit to avoid visual glitch when the screen area shrinks by one row\n echo -en \"\\n\"\n\n # Save cursor\n echo -en \"$CODE_SAVE_CURSOR\"\n # Set scroll region (this will place the cursor in the top left)\n echo -en \"\\033[0;${lines}r\"\n\n # Restore cursor but ensure its inside the scrolling area\n echo -en \"$CODE_RESTORE_CURSOR\"\n echo -en \"$CODE_CURSOR_IN_SCROLL_AREA\"\n\n # Start empty progress bar\n draw_progress_bar 0\n}\n\nfunction destroy_scroll_area() {\n lines=$(tput lines)\n # Save cursor\n echo -en \"$CODE_SAVE_CURSOR\"\n # Set scroll region (this will place the cursor in the top left)\n echo -en \"\\033[0;${lines}r\"\n\n # Restore cursor but ensure its inside the scrolling area\n echo -en \"$CODE_RESTORE_CURSOR\"\n echo -en \"$CODE_CURSOR_IN_SCROLL_AREA\"\n\n # We are done so clear the scroll bar\n clear_progress_bar\n\n # Scroll down a bit to avoid visual glitch when the screen area grows by one row\n echo -en \"\\n\\n\"\n}\n\nfunction draw_progress_bar() {\n percentage=$1\n lines=$(tput lines)\n let lines=$lines\n # Save cursor\n echo -en \"$CODE_SAVE_CURSOR\"\n\n # Move cursor position to last row\n echo -en \"\\033[${lines};0f\"\n\n # Clear progress bar\n tput el\n\n # Draw progress bar\n print_bar_text $percentage\n\n # Restore cursor position\n echo -en \"$CODE_RESTORE_CURSOR\"\n}\n\nfunction clear_progress_bar() {\n lines=$(tput lines)\n let lines=$lines\n # Save cursor\n echo -en \"$CODE_SAVE_CURSOR\"\n\n # Move cursor position to last row\n echo -en \"\\033[${lines};0f\"\n\n # clear progress bar\n tput el\n\n # Restore cursor position\n echo -en \"$CODE_RESTORE_CURSOR\"\n}\n\nfunction print_bar_text() {\n local percentage=$1\n\n # Prepare progress bar\n let remainder=100-$percentage\n progress_bar=$(echo -ne \"[\"; echo -en \"${COLOR_FG}${COLOR_BG}\"; printf_new \"#\" $percentage; echo -en \"${RESTORE_FG}${RESTORE_BG}\"; printf_new \".\" $remainder; echo -ne \"]\");\n\n # Print progress bar\n if [ $1 -gt 99 ]\n then\n echo -ne \"${progress_bar}\"\n else\n echo -ne \"${progress_bar}\"\n fi\n}\n\nprintf_new() {\n str=$1\n num=$2\n v=$(printf \"%-${num}s\" \"$str\")\n echo -ne \"${v// /$str}\"\n}\n"
},
{
"answer_id": 53720296,
"author": "Zibri",
"author_id": 236062,
"author_profile": "https://Stackoverflow.com/users/236062",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\ntot=$(wc -c /proc/$$/fd/255 | awk '/ /{print $1}')\nnow() {\necho $(( 100* ($(awk '/^pos:/{print $2}' < /proc/$$/fdinfo/255)-166) / (tot-166) )) \"%\"\n}\nnow;\nnow;\nnow;\nnow;\nnow;\nnow;\nnow;\nnow;\nnow;\n 0 %\n12 %\n25 %\n37 %\n50 %\n62 %\n75 %\n87 %\n100 %\n"
},
{
"answer_id": 62185347,
"author": "Khalil Gharbaoui",
"author_id": 5641227,
"author_profile": "https://Stackoverflow.com/users/5641227",
"pm_score": 1,
"selected": false,
"text": "function spinner() {\n local PID=\"$1\"\n local str=\"${2:-Processing!}\"\n local delay=\"0.1\"\n # tput civis # hide cursor\n while ( kill -0 $PID 2>/dev/null )\n do\n printf \"\\e[38;5;$((RANDOM%257))m%s\\r\\e[0m\" \"[$(date '+%d/%m/%Y %H:%M:%S')][ $str ]\"; sleep \"$delay\"\n printf \"\\e[38;5;$((RANDOM%257))m%s\\r\\e[0m\" \"[$(date '+%d/%m/%Y %H:%M:%S')][ $str ]\"; sleep \"$delay\"\n printf \"\\e[38;5;$((RANDOM%257))m%s\\r\\e[0m\" \"[$(date '+%d/%m/%Y %H:%M:%S')][ $str ]\"; sleep \"$delay\"\n done\n printf \"\\e[38;5;$((RANDOM%257))m%s\\r\\e[0m\" \"[$(date '+%d/%m/%Y %H:%M:%S')][ ✅ ✅ ✅ Done! ✅ ✅ ✅ ]\"; sleep \"$delay\"\n # tput cnorm # restore cursor\n\n return 0\n}\n # your long running proccess pushed to the background\nsleep 20 &\n\n# spinner capture-previous-proccess-id string\nspinner $! 'Working!'\n [04/06/2020 03:22:24][ Seeding! ]\n"
},
{
"answer_id": 63101790,
"author": "Damian Czapiewski",
"author_id": 1274664,
"author_profile": "https://Stackoverflow.com/users/1274664",
"pm_score": 2,
"selected": false,
"text": "for $bar = \\r -ne echo \\r function progress {\n bar=''\n for (( x=0; x <= 100; x++ )); do\n sleep 0.25\n bar=\"${bar}=\"\n echo -ne \"$bar ${x}%\\r\"\n done\n echo -e \"\\n\"\n}\n $ progress\n> ========== 10% # here: after 2.5 seconds\n $ progress\n> ============================== 30% # here: after 7.5 seconds\n function progress {\n bar=''\n for (( x=0; x <= 100; x++ )); do\n sleep 0.05\n bar=\"${bar} \"\n\n echo -ne \"\\r\"\n echo -ne \"\\e[43m$bar\\e[0m\"\n\n local left=\"$(( 100 - $x ))\"\n printf \" %${left}s\"\n echo -n \"${x}%\"\n done\n echo -e \"\\n\"\n}\n \\e[43m \\e[0m"
},
{
"answer_id": 63877277,
"author": "James Yang",
"author_id": 4691964,
"author_profile": "https://Stackoverflow.com/users/4691964",
"pm_score": 0,
"selected": false,
"text": "current length / total size ver_big_file.json awk awk '\n function bar(x){s=\"\";i=0;while (i++ < x) s=s \"#\";return s}\n BEGIN{\n (\"ls -l \" ARGV[1]) | getline total;\n split(total,array);\n total=array[5];\n }\n {\n cur+=length($0)+1;\n percent=int(cur / total * 100);\n printf \"LINE %s:%s %s%%\\r\", NR, bar(percent*.8), percent \n }\n END {print}' very_big_file.json | grep \"keyword\" | ...\n"
},
{
"answer_id": 64932365,
"author": "Dustin Michels",
"author_id": 7576819,
"author_profile": "https://Stackoverflow.com/users/7576819",
"pm_score": 3,
"selected": false,
"text": "BAR='##############################'\nFILL='------------------------------'\ntotalLines=$(wc -l $file | awk '{print $1}') # num. lines in file\nbarLen=30\n\n# --- iterate over lines in csv file ---\ncount=0\nwhile IFS=, read -r _ col1 col2 col3; do\n # update progress bar\n count=$(($count + 1))\n percent=$((($count * 100 / $totalLines * 100) / 100))\n i=$(($percent * $barLen / 100))\n echo -ne \"\\r[${BAR:0:$i}${FILL:$i:barLen}] $count/$totalLines ($percent%)\"\n\n # other stuff\n (...)\ndone <$file\n [##----------------------------] 17128/218210 (7%)\n"
},
{
"answer_id": 65532561,
"author": "WinEunuuchs2Unix",
"author_id": 6929343,
"author_profile": "https://Stackoverflow.com/users/6929343",
"pm_score": 3,
"selected": false,
"text": "notify-send #!/bin/bash\n\n# Show a progress bar at step number $1 (from 0 to 100)\n\n\nfunction is_int() { test \"$@\" -eq \"$@\" 2> /dev/null; } \n\n# Parameter 1 must be integer\nif ! is_int \"$1\" ; then\n echo \"Not an integer: ${1}\"\n exit 1\nfi\n\n# Parameter 1 must be >= 0 and <= 100\nif [ \"$1\" -ge 0 ] && [ \"$1\" -le 100 ] 2>/dev/null\nthen\n :\nelse\n echo bad volume: ${1}\n exit 1\nfi\n\n# Main function designed for quickly copying to another program \nMain () {\n\n Bar=\"\" # Progress Bar / Volume level\n Len=25 # Length of Progress Bar / Volume level\n Div=4 # Divisor into Volume for # of blocks\n Fill=\"▒\" # Fill up to $Len\n Arr=( \"▉\" \"▎\" \"▌\" \"▊\" ) # UTF-8 left blocks: 7/8, 1/4, 1/2, 3/4\n\n FullBlock=$((${1} / Div)) # Number of full blocks\n PartBlock=$((${1} % Div)) # Size of partial block (array index)\n\n while [[ $FullBlock -gt 0 ]]; do\n Bar=\"$Bar${Arr[0]}\" # Add 1 full block into Progress Bar\n (( FullBlock-- )) # Decrement full blocks counter\n done\n\n # If remainder zero no partial block, else append character from array\n if [[ $PartBlock -gt 0 ]]; then\n Bar=\"$Bar${Arr[$PartBlock]}\"\n fi\n\n while [[ \"${#Bar}\" -lt \"$Len\" ]]; do\n Bar=\"$Bar$Fill\" # Pad Progress Bar with fill character\n done\n\n echo Volume: \"$1 $Bar\"\n exit 0 # Remove this line when copying into program\n} # Main\n\nMain \"$@\"\n #!/bin/bash\n\n# test_progress_bar3\n\nMain () {\n\n tput civis # Turn off cursor\n for ((i=0; i<=100; i++)); do\n CurrLevel=$(./progress_bar3 \"$i\") # Generate progress bar 0 to 100\n echo -ne \"$CurrLevel\"\\\\r # Reprint overtop same line\n sleep .04\n done\n echo -e \\\\n # Advance line to keep last progress\n echo \"$0 Done\"\n tput cnorm # Turn cursor back on\n} # Main\n\nMain \"$@\"\n notify-send main VolumeBar tvpowered exit 0 main notify-send VolumeBar $CurrVolume\n# Ask Ubuntu: https://askubuntu.com/a/871207/307523\nnotify-send --urgency=critical \"tvpowered\" \\\n -h string:x-canonical-private-synchronous:volume \\\n --icon=/usr/share/icons/gnome/48x48/devices/audio-speakers.png \\\n \"Volume: $CurrVolume $Bar\"\n notify-send -h string:x-canonical-private-synchronous:volume \\\n volume anything volume"
},
{
"answer_id": 68298090,
"author": "F. Hauri - Give Up GitHub",
"author_id": 1765658,
"author_profile": "https://Stackoverflow.com/users/1765658",
"pm_score": 4,
"selected": false,
"text": "integer UTF-8 parallelise sha1sum read -t <float seconds> && break sleep mysmiley=$(printf '%b' \\\\U1F60E)\n printf -v mysmiley '%b' \\\\U1F60E\n var=$(command) command $var TIMEFORMAT=\"%R\"\ntime for ((i=2500;i--;)){ mysmiley=$(printf '%b' \\\\U1F60E);}\n2.292\ntime for ((i=2500;i--;)){ printf -v mysmiley '%b' \\\\U1F60E;}\n0.017\nbc -l <<<'2.292/.017'\n134.82352941176470588235\n $mysmiley printf -v echo $mysmiley \n\n function percent(){\n local p=00$(($1*100000/$2))\n printf -v \"$3\" %.2f ${p::-3}.${p: -3}\n}\n # percent <integer to compare> <reference integer> <variable name>\npercent 33333 50000 testvar\nprintf '%8s%%\\n' \"$testvar\"\n 66.67%\n ▏ ▎ ▍ ▌ ▋ ▊ ▉ █ printf -v chars '\\\\U258%X ' {15..8}\nprintf \"$chars\\\\n\"\n▏ ▎ ▍ ▌ ▋ ▊ ▉ █ \n string with graphic width percentBar percentBar () { \n local prct totlen=$((8*$2)) lastchar barstring blankstring;\n printf -v prct %.2f \"$1\"\n ((prct=10#${prct/.}*totlen/10000, prct%8)) &&\n printf -v lastchar '\\\\U258%X' $(( 16 - prct%8 )) ||\n lastchar=''\n printf -v barstring '%*s' $((prct/8)) ''\n printf -v barstring '%b' \"${barstring// /\\\\U2588}$lastchar\"\n printf -v blankstring '%*s' $(((totlen-prct)/8)) ''\n printf -v \"$3\" '%s%s' \"$barstring\" \"$blankstring\"\n}\n # percentBar <float percent> <int string width> <variable name>\npercentBar 42.42 $COLUMNS bar1\necho \"$bar1\"\n█████████████████████████████████▉ \n percentBar 42.24 $COLUMNS bar2\nprintf \"%s\\n\" \"$bar1\" \"$bar2\"\n█████████████████████████████████▉ \n█████████████████████████████████▊ \n percentBar 72.1 24 bar\nprintf 'Show this: \\e[44;33;1m%s\\e[0m at %s%%\\n' \"$bar\" 72.1\n for i in {0..10000..33} 10000;do i=0$i\n printf -v p %0.2f ${i::-2}.${i: -2}\n percentBar $p $((COLUMNS-9)) bar\n printf '\\r|%s|%6.2f%%' \"$bar\" $p\n read -srt .002 _ && break # console sleep avoiding fork\ndone\n\n|███████████████████████████████████████████████████████████████████████|100.00%\n\nclear; for i in {0..10000..33} 10000;do i=0$i\n printf -v p %0.2f ${i::-2}.${i: -2}\n percentBar $p $((COLUMNS-7)) bar\n printf '\\r\\e[47;30m%s\\e[0m%6.2f%%' \"$bar\" $p\n read -srt .002 _ && break\ndone\n printf '\\n\\n\\n\\n\\n\\n\\n\\n\\e[8A\\e7'&&for i in {0..9999..99} 10000;do \n o=1 i=0$i;printf -v p %0.2f ${i::-2}.${i: -2}\n for l in 1 2 3 5 8 13 20 40 $((COLUMNS-7));do\n percentBar $p $l bar$((o++));done\n [ \"$p\" = \"100.00\" ] && read -rst .8 _;printf \\\\e8\n printf '%s\\e[48;5;23;38;5;41m%s\\e[0m%6.2f%%%b' 'In 1 char width: ' \\\n \"$bar1\" $p ,\\\\n 'with 2 chars: ' \"$bar2\" $p ,\\\\n 'or 3 chars: ' \\\n \"$bar3\" $p ,\\\\n 'in 5 characters: ' \"$bar4\" $p ,\\\\n 'in 8 chars: ' \\\n \"$bar5\" $p .\\\\n 'There are 13 chars: ' \"$bar6\" $p ,\\\\n '20 chars: '\\\n \"$bar7\" $p ,\\\\n 'then 40 chars' \"$bar8\" $p \\\n ', or full width:\\n' '' \"$bar9\" $p ''\n ((10#$i)) || read -st .5 _; read -st .1 _ && break\ndone\n sha1sum /proc percentBar percent sha1progress percent(){ local p=00$(($1*100000/$2));printf -v \"$3\" %.2f ${p::-3}.${p: -3};}\nsha1Progress() { \n local -i totsize crtpos cols=$(tput cols) sha1in sha1pid\n local sha1res percent prctbar\n exec {sha1in}< <(exec sha1sum -b - <\"$1\")\n sha1pid=$!\n read -r totsize < <(stat -Lc %s \"$1\")\n while ! read -ru $sha1in -t .025 sha1res _; do\n read -r _ crtpos < /proc/$sha1pid/fdinfo/0\n percent $crtpos $totsize percent\n percentBar $percent $((cols-8)) prctbar\n printf '\\r\\e[44;38;5;25m%s\\e[0m%6.2f%%' \"$prctbar\" $percent;\n\n done\n printf \"\\r%s %s\\e[K\\n\" $sha1res \"$1\"\n}\n 25 ms exec {sha1in}< <( ... ) sha1sum -b - <\"$1\" fd/0 while ! read -ru $sha1in -t .025 sha1res _ 25 ms /proc/$sha1pid/fdinfo/0 $sha1pid"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13523/"
] |
238,081
|
<p>So, when playing with the development I can just set <code>settings.DEBUG</code> to <code>True</code> and if an error occures I can see it nicely formatted, with good stack trace and request information.</p>
<p>But on kind of production site I'd rather use <code>DEBUG=False</code> and show visitors some standard error 500 page with information that I'm working on fixing this bug at this moment ;)<br>
At the same time I'd like to have some way of logging all those information (stack trace and request info) to a file on my server - so I can just output it to my console and watch errors scroll, email the log to me every hour or something like this.</p>
<p>What logging solutions would you recomend for a django-site, that would meet those simple requirements? I have the application running as <code>fcgi</code> server and I'm using apache web server as frontend (although thinking of going to lighttpd).</p>
|
[
{
"answer_id": 238111,
"author": "James Bennett",
"author_id": 28070,
"author_profile": "https://Stackoverflow.com/users/28070",
"pm_score": 8,
"selected": true,
"text": "DEBUG = False ADMINS process_exception() process_exception() got_request_exception"
},
{
"answer_id": 6395837,
"author": "EMP",
"author_id": 20336,
"author_profile": "https://Stackoverflow.com/users/20336",
"pm_score": 6,
"selected": false,
"text": "settings.py LOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n # Include the default Django email handler for errors\n # This is what you'd get without configuring logging at all.\n 'mail_admins': {\n 'class': 'django.utils.log.AdminEmailHandler',\n 'level': 'ERROR',\n # But the emails are plain text by default - HTML is nicer\n 'include_html': True,\n },\n # Log to a text file that can be rotated by logrotate\n 'logfile': {\n 'class': 'logging.handlers.WatchedFileHandler',\n 'filename': '/var/log/django/myapp.log'\n },\n },\n 'loggers': {\n # Again, default Django configuration to email unhandled exceptions\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n # Might as well log any errors anywhere else in Django\n 'django': {\n 'handlers': ['logfile'],\n 'level': 'ERROR',\n 'propagate': False,\n },\n # Your own app - this assumes all your logger names start with \"myapp.\"\n 'myapp': {\n 'handlers': ['logfile'],\n 'level': 'WARNING', # Or maybe INFO or DEBUG\n 'propagate': False\n },\n },\n}\n"
},
{
"answer_id": 19267228,
"author": "Mike O'Connor",
"author_id": 2861967,
"author_profile": "https://Stackoverflow.com/users/2861967",
"pm_score": 4,
"selected": false,
"text": "LOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n # Include the default Django email handler for errors\n # This is what you'd get without configuring logging at all.\n 'mail_admins': {\n 'class': 'django.utils.log.AdminEmailHandler',\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n # But the emails are plain text by default - HTML is nicer\n 'include_html': True,\n },\n # Log to a text file that can be rotated by logrotate\n 'logfile': {\n 'class': 'logging.handlers.WatchedFileHandler',\n 'filename': '/home/username/public_html/djangoprojectname/logfilename.log'\n },\n },\n 'loggers': {\n # Again, default Django configuration to email unhandled exceptions\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n # Might as well log any errors anywhere else in Django\n 'django': {\n 'handlers': ['logfile'],\n 'level': 'ERROR',\n 'propagate': False,\n },\n # Your own app - this assumes all your logger names start with \"myapp.\"\n 'myapp': {\n 'handlers': ['logfile'],\n 'level': 'DEBUG', # Or maybe INFO or WARNING\n 'propagate': False\n },\n },\n}\n"
},
{
"answer_id": 39106487,
"author": "jozxyqk",
"author_id": 1888983,
"author_profile": "https://Stackoverflow.com/users/1888983",
"pm_score": 1,
"selected": false,
"text": "fcgi #!/home/user/env/bin/python\nsys.stderr = open('/home/user/fcgi_errors', 'a')\n"
},
{
"answer_id": 70617888,
"author": "lam vu Nguyen",
"author_id": 11945463,
"author_profile": "https://Stackoverflow.com/users/11945463",
"pm_score": 0,
"selected": false,
"text": "pip install print() logging.debug()"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4172/"
] |
238,102
|
<p>I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following:</p>
<pre><code>fun (head : rest) = ...
</code></pre>
<p>So when I pass in a list, <code>head</code> will be the first element, and <code>rest</code> will be the trailing elements.</p>
<p>Likewise, in Python, I can automatically unpack tuples:</p>
<pre><code>(var1, var2) = func_that_returns_a_tuple()
</code></pre>
<p>I want to do something similar with lists in Python. Right now, I have a function that returns a list, and a chunk of code that does the following:</p>
<pre><code>ls = my_func()
(head, rest) = (ls[0], ls[1:])
</code></pre>
<p>I wondered if I could somehow do that in one line in Python, instead of two.</p>
|
[
{
"answer_id": 238124,
"author": "James Bennett",
"author_id": 28070,
"author_profile": "https://Stackoverflow.com/users/28070",
"pm_score": 7,
"selected": true,
"text": "split_list = lambda lst: (lst[0], lst[1:])\nhead, rest = split_list(my_func())\n head, *rest = my_func()\n"
},
{
"answer_id": 238126,
"author": "kender",
"author_id": 4172,
"author_profile": "https://Stackoverflow.com/users/4172",
"pm_score": 2,
"selected": false,
"text": "def x(func):\n y = func()\n return y[0], y[1:]\n\n# then, instead of calling my_func() call x(my_func)\n(head, rest) = x(my_func) # that's one line :)\n"
},
{
"answer_id": 238170,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 5,
"selected": false,
"text": "f (x : s) = e f e f x : s x s f (x : s) e x, y = y, x x y x = y y = x let where (head, tail) = (x[0], x[1:]) where x = my_func()\n (head, tail) = (lambda x: (x[0], x[1:]))(my_func())\n"
},
{
"answer_id": 238185,
"author": "Jake",
"author_id": 24730,
"author_profile": "https://Stackoverflow.com/users/24730",
"pm_score": 1,
"selected": false,
"text": "\ndef peel(iterable,result=tuple):\n '''Removes the requested items from the iterable and stores the remaining in a tuple\n >>> x,y,z=peel('test')\n >>> print repr(x),repr(y),z\n 't' 'e' ('s', 't')\n '''\n def how_many_unpacked():\n import inspect,opcode\n f = inspect.currentframe().f_back.f_back\n if ord(f.f_code.co_code[f.f_lasti])==opcode.opmap['UNPACK_SEQUENCE']:\n return ord(f.f_code.co_code[f.f_lasti+1])\n raise ValueError(\"Must be a generator on RHS of a multiple assignment!!\")\n iterator=iter(iterable)\n hasItems=True\n amountToUnpack=how_many_unpacked()-1\n next=None\n for num in xrange(amountToUnpack):\n if hasItems: \n try:\n next = iterator.next()\n except StopIteration:\n next = None\n hasItems = False\n yield next\n if hasItems:\n yield result(iterator)\n else:\n yield None\n"
},
{
"answer_id": 239676,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 2,
"selected": false,
"text": "def head_tail(lst):\n it = iter(list)\n yield it.next()\n yield it\n\n>>> a, tail = head_tail([1,2,3,4,5])\n>>> b, tail = head_tail(tail)\n>>> a,b,tail\n(1, 2, <listiterator object at 0x2b1c810>)\n>>> list(tail)\n[3, 4]\n"
},
{
"answer_id": 240018,
"author": "giltay",
"author_id": 21106,
"author_profile": "https://Stackoverflow.com/users/21106",
"pm_score": 2,
"selected": false,
"text": "def recursive_sum(x):\n try:\n head, tail = x[0], x[1:]\n return head + recursive-sum(tail)\n except IndexError: # empty list: [][0] raises IndexError\n return 0\n head, tail for frob in eggs.frob_list:\n try:\n frob.spam += 1\n except AttributeError:\n eggs.no_spam_count += 1\n def iterative_sum(x):\n ret_val = 0\n for i in x:\n ret_val += i\n return ret_val\n"
},
{
"answer_id": 11588095,
"author": "Martin Blech",
"author_id": 113643,
"author_profile": "https://Stackoverflow.com/users/113643",
"pm_score": 2,
"selected": false,
"text": "from pyfpm import Unpacker\n\nunpacker = Unpacker()\n\nunpacker('head :: tail') << (1, 2, 3)\n\nunpacker.head # 1\nunpacker.tail # (2, 3)\n from pyfpm import match_args\n\n@match_args('head :: tail')\ndef f(head, tail):\n return (head, tail)\n\nf(1) # (1, ())\nf(1, 2, 3, 4) # (1, (2, 3, 4))\n"
},
{
"answer_id": 52082215,
"author": "Lyndsy Simon",
"author_id": 1336699,
"author_profile": "https://Stackoverflow.com/users/1336699",
"pm_score": 1,
"selected": false,
"text": "fun (head : rest) = ... def my_method(head, *rest):\n # ...\n my_list = ['alpha', 'bravo', 'charlie', 'delta', 'echo']\nhead, *rest = my_list\nassert head == 'alpha'\nassert rest == ['bravo', 'charlie', 'delta', 'echo']\n first, *middle, last = my_list\nassert first == 'alpha'\nassert last == 'echo'\nassert middle == ['bravo', 'charlie', 'delta']\n\nfirst, *middle, last = ['alpha', 'bravo']\nassert first == 'alpha'\nassert last == 'bravo'\nassert middle == []\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28804/"
] |
238,110
|
<p>I am trying to get the signature on the method below to work. As this is an Anonymous Type I have some trouble, any help would be great.</p>
<p>When I looked at sortedGameList.ToList() in a QuickWatch window I get the signature </p>
<pre><code>System.Collections.Generic.List<<>f__AnonymousType0<System.DateTime,System.Linq.IGrouping<System.DateTime,DC.FootballLeague.Web.Models.Game>>>
</code></pre>
<p>Many Thanks</p>
<p>Donald</p>
<pre><code> public List<IGrouping<DateTime, Game>> getGamesList(int leagueID)
{
var sortedGameList =
from g in Games
group g by g.Date into s
select new { Date = s.Key, Games = s };
return sortedGameList.ToList();
}
</code></pre>
|
[
{
"answer_id": 238127,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 3,
"selected": false,
"text": "public class GamesWithDate {\n public DateTime Date { get; set; }\n public List<Game> Games { get; set; }\n}\n var sortedGameList =\n from g in Games\n group g by g.Date into s\n select new GamesWithDate { Date = s.Key, Games = s };\n"
},
{
"answer_id": 238129,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 4,
"selected": true,
"text": "public List<IGrouping<DateTime, Game>> getGamesList(int leagueID)\n{\n var sortedGameList =\n from g in Games\n group g by g.Date;\n\n return sortedGameList.ToList();\n}\n"
},
{
"answer_id": 238132,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": false,
"text": "public class GameGroup\n{\n public DateTime TheDate {get;set;}\n public List<Game> TheGames {get;set;}\n}\n public List<GameGroup> getGamesGroups(int leagueID)\n{\n List<GameGroup> sortedGameList =\n Games\n .GroupBy(game => game.Date)\n .OrderBy(g => g.Key)\n .Select(g => new GameGroup(){TheDate = g.Key, TheGames = g.ToList()})\n .ToList();\n\n return sortedGameList;\n}\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17584/"
] |
238,173
|
<p>Similar to <a href="https://stackoverflow.com/questions/233030/worst-php-practice-found-in-your-experience">this question</a>...</p>
<p>What are the worst practices you actually found in Java code?</p>
<p>Mine are:</p>
<ul>
<li>using instance variables in servlets (it's not just bad practice but bug, actually)</li>
<li>using Collection implementations like HashMap, and not using the appropriate interfaces</li>
<li>using seemingly cryptic class names like SmsMaker (SmsFactory) or CommEnvironment (CommunicationContext)</li>
</ul>
|
[
{
"answer_id": 238189,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 4,
"selected": false,
"text": "if (expensiveFunction() > aVar)\n aVar = expensiveFunction();\nfor (int i=0; i < expensiveFunction(); ++i)\n System.out.println(expensiveFunction());\n"
},
{
"answer_id": 238258,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 5,
"selected": false,
"text": "public interface InterfaceAntiPattern {\n boolean BAD_IDEA = true;\n int THIS_SUCKS = 1;\n}\n"
},
{
"answer_id": 238302,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 3,
"selected": false,
"text": "CollectionUtils IOUtils"
},
{
"answer_id": 238333,
"author": "asalamon74",
"author_id": 21348,
"author_profile": "https://Stackoverflow.com/users/21348",
"pm_score": 8,
"selected": true,
"text": "catch( Exception e ) {}\n"
},
{
"answer_id": 238383,
"author": "jb.",
"author_id": 7918,
"author_profile": "https://Stackoverflow.com/users/7918",
"pm_score": 4,
"selected": false,
"text": "static class Identity{\n ...\n public static User user; \n ...\n }\n\n class foo{\n\n void bar(){\n someEntity.setCreator(Identity.user); \n }\n\n }\n"
},
{
"answer_id": 238970,
"author": "madlep",
"author_id": 14160,
"author_profile": "https://Stackoverflow.com/users/14160",
"pm_score": 4,
"selected": false,
"text": "DefaultConcreteMutableAbstractWhizzBangImpl"
},
{
"answer_id": 247899,
"author": "Steve B.",
"author_id": 19479,
"author_profile": "https://Stackoverflow.com/users/19479",
"pm_score": 5,
"selected": false,
"text": "if{\n if{\n if{\n if{\n if{\n if{\n if{\n if{\n ....\n"
},
{
"answer_id": 1219428,
"author": "Peter Lawrey",
"author_id": 57695,
"author_profile": "https://Stackoverflow.com/users/57695",
"pm_score": 5,
"selected": false,
"text": "System.exit if(properties.size()>10000) System.exit(0); synchronized(\"one\") { } synchronized(object) { object = ...; } try { Integer i = null; i.intValue(); } catch(NullPointerException e) { e.printStackTrace(); } new Integer(text).intValue() or worse new Integer(0).getClass()"
},
{
"answer_id": 1220910,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "List needsToBeSorted = new List ();\n...blah blah blah...\n\nSet sorted = new TreeSet ();\nfor (int i = 0; i < needsToBeSorted; i++)\n sorted.add (needsToBeSorted.get (i));\n\nneedsToBeSorted.clear ();\nfor (Iterator i = sorted.iterator (); i.hasNext ();)\n needsToBeSorted.add (i.next ());\n"
},
{
"answer_id": 1220934,
"author": "Peter Štibraný",
"author_id": 47190,
"author_profile": "https://Stackoverflow.com/users/47190",
"pm_score": 5,
"selected": false,
"text": "class Singletons {\n public static final MyException myException = new MyException();\n}\n\nclass Test {\n public void doSomething() throws MyException {\n throw Singletons.myException;\n }\n}\n"
},
{
"answer_id": 1503092,
"author": "slim",
"author_id": 7512,
"author_profile": "https://Stackoverflow.com/users/7512",
"pm_score": 3,
"selected": false,
"text": "Foobar f = new Foobar(foobar_id);\nf = f.retrieve();\n Foobar f = Foobar.retrieve(foobar_id);\n Foobar f = new Foobar(foobar_id); // implicit retrieve\n Foobar f = new Foobar();\nf.retrieve(foobar_id); // but not f = ...\n"
},
{
"answer_id": 1503934,
"author": "Prabhu R",
"author_id": 77087,
"author_profile": "https://Stackoverflow.com/users/77087",
"pm_score": 2,
"selected": false,
"text": "while(i < MAX_VALUE)\n{\n try\n {\n while(true)\n {\n array[j] = //some operation on the array;\n j++; \n\n }\n }\n catch(Exception e)\n {\n j = 0;\n }\n}\n"
},
{
"answer_id": 3360657,
"author": "cringe",
"author_id": 834,
"author_profile": "https://Stackoverflow.com/users/834",
"pm_score": 2,
"selected": false,
"text": "Short result = new Short(new Integer(new Double(d).intValue()).shortValue());\n"
},
{
"answer_id": 4026029,
"author": "barrymac",
"author_id": 218635,
"author_profile": "https://Stackoverflow.com/users/218635",
"pm_score": 0,
"selected": false,
"text": " public DataObjectList (GenerateList (massive signature involving 14 parameters, three of which are collections and one is a collection of collections) \ntry { \n\n250 lines of code to retrieve the data which calls a stored proc that parses some of it and basically contains GUI logic\n\n } catch (Exception e) {\n return new DataObjectList(e, filterFields);\n }\n DataObjectList dataObjectList= EntireSystemObject.getDataObjectList Generator().generateDataObjectList (viewAsUserCode, processedDataRowHandler, folderQuery, pageNumber, listCount, sortColumns, sortDirections, groupField, filters, firstRun, false, false, resetView);\n\ndataObjectList.setData(processedDataRowHandler.getData());\n\nif (dataObjectList.getErrorException() == null) {\n\ndo stuff for GUI, I think, put lots of things into maps ... 250 lines or so\n\n }\n return dataObjectList;\n } else {\n\nput a blank version into the GUI and then \n\n throw new DWRErrorException(\"List failed due to list generation error\", \"list failed due to list generation error for folder: \" + folderID + \", column: \" + columnID, List.getErrorException(), ListInfo);\n }\n"
},
{
"answer_id": 4673354,
"author": "S E",
"author_id": 545199,
"author_profile": "https://Stackoverflow.com/users/545199",
"pm_score": 1,
"selected": false,
"text": "int sval, eval, stepv, i;\ndouble d;\n if (/*someCondition*/)\n {\n sval = 360;//(all values multiplied by 20)\n eval = -271;\n stepv = -10;\n }\n else if (/*someCondition*/)\n {\n sval = 320;\n eval = -601;\n stepv = -10;\n }\n else if (/*someCondition*/)\n {\n sval = 0;\n eval = -311;\n stepv = -10;\n\n }\n else\n {\n sval = 360;\n eval = -601;\n stepv = -10;\n }\n for (i = sval; i > eval; i = i + stepv)\n {\n d = i;\n d = d / 20.0;\n //do some more stuff in loop\n }\n"
},
{
"answer_id": 4673492,
"author": "TheCottonSilk",
"author_id": 545691,
"author_profile": "https://Stackoverflow.com/users/545691",
"pm_score": 2,
"selected": false,
"text": "try {\n /* open file */\n}\ncatch(Exception e) {\n e.printStackTrace();\n}\n\ntry {\n /* read file content */\n}\ncatch (Exception e) {\n e.printStackTrace();\n}\n\ntry {\n /* close the file */\n}\ncatch (Exception e) {\n e.printStackTrace();\n}\n"
},
{
"answer_id": 4991408,
"author": "CodeClimber",
"author_id": 355620,
"author_profile": "https://Stackoverflow.com/users/355620",
"pm_score": 4,
"selected": false,
"text": "public static boolean isNull(int value) {\n Integer integer = new Integer(value);\n\n if(integer == null) {\n return true;\n } else {\n return false;\n }\n}\n if(value == null) {\n"
},
{
"answer_id": 5023649,
"author": "Tomas Andrle",
"author_id": 35440,
"author_profile": "https://Stackoverflow.com/users/35440",
"pm_score": 3,
"selected": false,
"text": "boolean negate( boolean shouldNegate, boolean value ) {\n return (shouldNegate?(!value):value;\n}\n boolean isNotNull( Object o ) {\n return o != null;\n}\n /**\n*\n*\n*/\n /**\n* A constructor. Takes no parameters and creates a new instance of MyClass.\n*/\npublic MyClass() {\n}\n"
},
{
"answer_id": 9292054,
"author": "MrJames",
"author_id": 1211095,
"author_profile": "https://Stackoverflow.com/users/1211095",
"pm_score": 0,
"selected": false,
"text": "DataObject operation_file = boFactory....\n\ntry{operation_file.setString(\"file_name\", Constants.getTagValue(\"file_name\", eElementOp));}catch (Exception e){operation_file.setString(\"file_name\",\"\");}\ntry{operation_file.setDate(\"proposed_execution_date\", sdf.parse(Constants.getTagValue(\"proposed_execution_date\", eElementOp)));}catch (Exception e){operation_file.setString(\"proposed_execution_date\",null);}\ntry{operation_file.setString(\"instructions\", Constants.getTagValue(\"instructions\", eElementOp));}catch (Exception e){operation_file.setString(\"instructions\",\"\");}\ntry{operation_file.setString(\"description\", Constants.getTagValue(\"description\", eElementOp));}catch (Exception e){operation_file.setString(\"description\",\"\");}\n"
},
{
"answer_id": 9292172,
"author": "Jivings",
"author_id": 334274,
"author_profile": "https://Stackoverflow.com/users/334274",
"pm_score": 1,
"selected": false,
"text": "AbstractTableComponentListeningBehaviourPanel.java"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686/"
] |
238,178
|
<p>I need the "Select Data Source" dialog added to my application so that the user can manually select a range (or ranges) in Excel and the range is pasted in my text box. This functionality is everywhere in Excel (most notably when selecting a range for a chart). How can I easily do this?</p>
|
[
{
"answer_id": 238932,
"author": "dbb",
"author_id": 25675,
"author_profile": "https://Stackoverflow.com/users/25675",
"pm_score": 0,
"selected": false,
"text": "Dim myRange As Range\n On Error Resume Next\n Set myRange = Application.InputBox(prompt:=\"Select the cells you want\", Type:=8)\n On Error GoTo 0\n If myRange Is Nothing Then\n MsgBox \"User cancelled\"\n Else\n MsgBox \"User selected \" & myRange.Address\n End If\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16794/"
] |
238,183
|
<p>Every time I do an <code>hg diff file.ext</code> I end up using a console diff application. I would like to use Kdiff3 or WinMerge (I'm using Windows).</p>
<p>Is there a way to change that? I can't find a reference in Mercurial documentation (<strong>I'm not talking about merge!</strong>). </p>
|
[
{
"answer_id": 241018,
"author": "Tute",
"author_id": 4386,
"author_profile": "https://Stackoverflow.com/users/4386",
"pm_score": 7,
"selected": true,
"text": "[extensions]\nhgext.extdiff=\n\n[extdiff]\ncmd.vdiff = kdiff3\n hg vdiff file.ext\n"
},
{
"answer_id": 1445060,
"author": "Marcus Leon",
"author_id": 47281,
"author_profile": "https://Stackoverflow.com/users/47281",
"pm_score": 3,
"selected": false,
"text": "[extdiff]\ncmd.kdiff3 =\n hg kdiff\n"
},
{
"answer_id": 4520949,
"author": "Ken",
"author_id": 552641,
"author_profile": "https://Stackoverflow.com/users/552641",
"pm_score": 2,
"selected": false,
"text": "[extensions] \nhgext.extdiff = \n\n[extdiff] \ncmd.kdiff3 =\n\n[merge-tools] \nkdiff3.args = $base $local $other -o $output\n"
},
{
"answer_id": 39371137,
"author": "musa",
"author_id": 370336,
"author_profile": "https://Stackoverflow.com/users/370336",
"pm_score": 3,
"selected": false,
"text": "git difftool ~/.hgrc hg difftool [extensions]\nextdiff =\n\n[extdiff]\ncmd.vimdiff = vimdiff\n\n[alias]\ndifftool = !for file in $(hg status -n); do hg vimdiff $file; done\n [alias]\ndifftool = !FOR /f %F IN ('hg status -nmar') DO hg vimdiff %F\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4386/"
] |
238,184
|
<p>My application uses measurement instruments that are connected to the PC. I want to make it possible to use similar instruments from different vendors. </p>
<p>So I defined an interface: </p>
<pre><code>interface IMeasurementInterface
{
void Initialize();
void Close();
}
</code></pre>
<p>So far so good. Before a measurement I need to setup the instrument and this means for different instruments very different parameters. So I want to define a method that takes parameters that can have different structures:</p>
<pre><code>interface IMeasurementInterface
{
void Initialize();
void Close();
void Setup(object Parameters);
}
</code></pre>
<p>I will then cast the object to whatever I need. Is this the way to go?</p>
|
[
{
"answer_id": 238210,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 4,
"selected": false,
"text": "public interface IMeasurement<PARAMTYPE> where PARAMTYPE : Parameters\n{\n void Init();\n void Close();\n void Setup(PARAMTYPE p);\n}\n\npublic abstract class Parameters\n{\n\n}\n public class DeviceOne : IMeasurement<ParametersForDeviceOne>\n{\n public void Init() { }\n public void Close() { }\n public void Setup(ParametersForDeviceOne p) { }\n}\n\npublic class ParametersForDeviceOne : Parameters\n{\n\n}\n"
},
{
"answer_id": 239204,
"author": "computinglife",
"author_id": 17224,
"author_profile": "https://Stackoverflow.com/users/17224",
"pm_score": 1,
"selected": false,
"text": "class DeviceInterface\n {\n void Initialize(IController & Controller);\n void Close();\n bool ChangeParameter(const string & Name, const string & Value); \n bool GetParam(string & Name, string &Value );\n }\n interface IController\n {\n Initialize(DeviceSpecific & Params);\n Close();\n bool ChangeParameter(string & Name, string & Value);\n bool ChangeParams(string & Name[], string &Value []);\n }\n IController objController = new MeasurementDevice(MeasureParram);\n\nDeviceInterface MeasureDevice = new DeviceInterface(objController);\n\nstring Value;\n\nMeasureDevice.GetParam(\"Temperature\", Value);\n\nif (ConvertStringToInt(Value) > 80)\n {\n MeasureDevice.ChangeParameter(\"Shutdown\", \"True\");\n RaiseAlert();\n }\n"
},
{
"answer_id": 239267,
"author": "Mike Minutillo",
"author_id": 358,
"author_profile": "https://Stackoverflow.com/users/358",
"pm_score": 1,
"selected": false,
"text": "public interface IMeasurementInterface\n{\n void Initialize();\n void Close();\n void Setup( IConfigurer config );\n}\n\npublic interface IConfigurer\n{\n void ApplyTo( object obj );\n}\n\npublic abstract ConfigurerBase<T> : IConfigurer where T : IMeasurementInterface\n{\n protected abstract void ApplyTo( T item );\n\n void IConfigurator.ApplyTo(object obj )\n {\n var item = obj as T;\n if( item == null )\n throw new InvalidOperationException(\"Configurer can't be applied to this type\");\n ApplyTo(item);\n }\n}\n"
},
{
"answer_id": 239716,
"author": "RS Conley",
"author_id": 7890,
"author_profile": "https://Stackoverflow.com/users/7890",
"pm_score": 1,
"selected": false,
"text": "interface IMeasurementInterface\n{\n void Initialize();\n void Close();\n void Setup();\n void Read (FileReader as <whatever read file object you are using>)\n void Store (FileReader as <whatever read file object you are using>)\n string Name();\n}\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30507/"
] |
238,194
|
<p>I use <a href="http://www.crockford.com/javascript/jsmin.html" rel="nofollow noreferrer">jsmin</a> to compress my javascript files before uploading them to production.</p>
<p>Since I tend to have one "code-behind" javascript file per page, I wind up doing this a lot.</p>
<p>I installed a Windows Powertoy that adds a context menu item in Windows Explorer, so I can "Open Command Window Here". When I click that, the command prompt opens up in the right directory. That saves a little bit of typing.</p>
<p>However, I still have to type something like:</p>
<pre><code>jsmin <script.js> script.min.js
</code></pre>
<p>To get it to work. This is a hassle.</p>
<p>I'd like to create a context menu item that will allow me to right-click on a *.js file and select "jsmin-compress this file." Then jsmin would be invoked, and the original file would be compressed into "original_filename.<b>min</b>.js"</p>
<p>How can I do this?</p>
|
[
{
"answer_id": 238204,
"author": "Andrew Cox",
"author_id": 27907,
"author_profile": "https://Stackoverflow.com/users/27907",
"pm_score": 0,
"selected": false,
"text": "jsmin %1 script.min.js\n"
},
{
"answer_id": 238216,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 0,
"selected": false,
"text": " Set jsminPath=\"C:\\SomePath\\jsmin.exe\"\n %~d1 \n CD %~d1%~p1 \n %jsminPath% \"%~n1.js\" \"%~n1.min.js\" \n"
},
{
"answer_id": 238256,
"author": "duckyflip",
"author_id": 7370,
"author_profile": "https://Stackoverflow.com/users/7370",
"pm_score": 1,
"selected": false,
"text": "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\JSFile\\shell\\JSMinify]\n@=\"JSMinify\" \n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\JSFile\\shell\\JSMinify\\Command]\n@=\"cmd.exe /c \\\"implement whatever cmd-friendly functions you want here (can use %1 and %%f) \"\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28118/"
] |
238,196
|
<p>I have an XML that needs to be databound to a <strong>WPF TreeView</strong>. Here the XML can have different structure. The TreeView should be databound generic enough to load any permutation of hierarchy. However an <strong>XAttribute</strong> on the nodes (called <strong>Title</strong>) should be databound to the TreeViewItem's <strong>header text</strong> and <strong>not the nodename</strong>.</p>
<p>XML to be bound:</p>
<pre><code><Wizard>
<Section Title="Home">
<Loop Title="Income Loop">
<Page Title="Employer Income"/>
<Page Title="Parttime Job Income"/>
<Page Title="Self employment Income"/>
</Loop>
</Section>
<Section Title="Deductions">
<Loop Title="Deductions Loop">
<Page Title="Travel spending"/>
<Page Title="Charity spending"/>
<Page Title="Dependents"/>
</Loop>
</Section>
</Wizard>
</code></pre>
<p>XAML:</p>
<pre><code><Window x:Class="Wpf.DataBinding.TreeViewer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Wpf.DataBinding"
Title="TreeViewer" Height="300" Width="300">
<Window.Resources>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Elements}" x:Key="TVTemplate">
<TreeViewItem Header="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
</Window.Resources>
<StackPanel>
<TreeView x:Name="_treeView" Style="{StaticResource TVallExpanded}"
ItemsSource="{Binding Path=Root.Elements}"
ItemTemplate="{StaticResource TVTemplate}" />
</StackPanel>
</Window>
</code></pre>
<p>XAML's codebehind that loads XML to XDocument and binds it to TreeView</p>
<pre><code>public partial class TreeViewer : Window
{
public TreeViewer()
{
InitializeComponent();
XDocument doc = XDocument.Parse(File.ReadAllText(@"C:\MyWizard.xml"));
_treeView.DataContext = doc;
}
}
</code></pre>
<p>So in the XAML markup we are binding Name to TreeViewItem's header.</p>
<pre><code><TreeViewItem Header="{Binding Path=Name}"/>
</code></pre>
<p>However, I want to bind it to <strong>Title</strong> attribute of Section, Loop and Page in the Xml above. I read that it's not possible to use XPath while binding XDocument. But there has to be a way to bind the <strong>Title</strong> attribute to TreeViewItem's Header text. I tried using @Title, .[@Title] etc. But none seemed to work.</p>
<p>This <a href="http://social.msdn.microsoft.com/forums/en-US/wpf/thread/edd843b7-b378-4c2d-926f-c053dbd7b340" rel="nofollow noreferrer">thread on MSDN Forums</a> has a similar discussion.</p>
<p>Any pointers would be greatly helpful.</p>
|
[
{
"answer_id": 238253,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<XmlDataProvider\n x:Key=\"rxPartData\"\n XPath=\"RegexParts\">\n <x:XData>\n <RegexParts\n xmlns=\"\">\n <Category\n Name=\"Character class\"\n ToolTip=\"Sets of characters used in matching\">\n <RegexPart\n Regex=\"[%]\"\n Hint=\"Positive character group\"\n ToolTip=\"Matches any character in the specified group (replace % with one or more characters)\" />\n <!-- yadda -->\n </Category>\n </RegexParts>\n </x:XData>\n</XmlDataProvider>\n <!-- Category data template -->\n<HierarchicalDataTemplate\n DataType=\"Category\"\n ItemsSource=\"{Binding XPath=*}\">\n <TextBlock\n Focusable=\"False\"\n Text=\"{Binding XPath=@Name}\"\n ToolTip=\"{StaticResource CategoryTooltip}\"\n ToolTipService.InitialShowDelay=\"0\"\n ToolTipService.ShowDuration=\"{x:Static sys:Int32.MaxValue}\"\n ToolTipService.HasDropShadow=\"True\" />\n</HierarchicalDataTemplate>\n<!-- RegexPart data template -->\n<HierarchicalDataTemplate\n DataType=\"RegexPart\"\n ItemsSource=\"{Binding XPath=*}\">\n <WrapPanel\n Focusable=\"False\"\n ToolTip=\"{StaticResource RegexPartTooltip}\"\n ToolTipService.InitialShowDelay=\"0\"\n ToolTipService.ShowDuration=\"{x:Static sys:Int32.MaxValue}\"\n ToolTipService.HasDropShadow=\"True\">\n <TextBlock\n Text=\"{Binding XPath=@Regex}\" />\n <TextBlock\n Text=\" - \" />\n <TextBlock\n Text=\"{Binding XPath=@Hint}\" />\n </WrapPanel>\n</HierarchicalDataTemplate>\n <TreeView\n Name=\"_regexParts\"\n DockPanel.Dock=\"Top\"\n SelectedItemChanged=\"RegexParts_SelectedItemChanged\"\n ItemsSource=\"{Binding Source={StaticResource rxPartData}, XPath=/RegexParts/Category}\"\n ToolTip=\"Click the + to expand a category; click a part to insert it\">\n</TreeView>\n"
},
{
"answer_id": 238282,
"author": "Vin",
"author_id": 1747,
"author_profile": "https://Stackoverflow.com/users/1747",
"pm_score": 5,
"selected": true,
"text": "<TreeViewItem Header=\"{Binding Path=Attribute[Title].Value}\"/>\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1747/"
] |
238,223
|
<p>I'm matching identifiers, but now I have a problem: my identifiers are allowed to contain unicode characters. Therefore the old way to do things is not enough:</p>
<pre><code>t_IDENTIFIER = r"[A-Za-z](\\.|[A-Za-z_0-9])*"
</code></pre>
<p>In <a href="http://freehg.org/u/cheery/aml/" rel="nofollow noreferrer">my markup language</a> parser I match unicode characters by allowing all the characters except those I explicitly use, because my markup language only has two or three of characters I need to escape that way.</p>
<p>How do I match all unicode characters with python regexs and ply? Also is this a good idea at all?</p>
<p>I'd want to let people use identifiers like Ω » « ° foo² väli π as an identifiers (variable names and such) in their programs. Heck! I want that people could write programs in their own language if it's practical! Anyway unicode is supported nowadays in wide variety of places, and it should spread.</p>
<p>Edit: POSIX character classes doesnt seem to be recognised by python regexes.</p>
<pre><code>>>> import re
>>> item = re.compile(r'[[:word:]]')
>>> print item.match('e')
None
</code></pre>
<p>Edit: To explain better what I need. I'd need a regex -thing that matches all the unicode printable characters but not ASCII characters at all.</p>
<p>Edit: r"\w" does a bit stuff what I want, but it does not match « », and I also need a regex that does not match numbers.</p>
|
[
{
"answer_id": 238293,
"author": "Cheery",
"author_id": 21711,
"author_profile": "https://Stackoverflow.com/users/21711",
"pm_score": 1,
"selected": false,
"text": "symbols = re.escape(''.join([chr(i) for i in xrange(33, 127) if not chr(i).isalnum()]))\nsymnums = re.escape(''.join([chr(i) for i in xrange(33, 127) if not chr(i).isalnum()]))\n\nt_IDENTIFIER = \"[^%s](\\\\.|[^%s])*\" % (symnums, symbols)\n"
},
{
"answer_id": 238646,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 4,
"selected": true,
"text": ">>> import re\n>>> m = re.compile('(?u)[^\\W0-9]\\w*')\n>>> m.match('a')\n<_sre.SRE_Match object at 0xb7d75410>\n>>> m.match('9')\n>>> m.match('ab')\n<_sre.SRE_Match object at 0xb7c258e0>\n>>> m.match('a9')\n<_sre.SRE_Match object at 0xb7d75410>\n>>> m.match('unicöde')\n<_sre.SRE_Match object at 0xb7c258e0>\n>>> m.match('ödipus')\n<_sre.SRE_Match object at 0xb7d75410>\n"
},
{
"answer_id": 8502908,
"author": "Stan",
"author_id": 471393,
"author_profile": "https://Stackoverflow.com/users/471393",
"pm_score": 2,
"selected": false,
"text": "lex.lex(reflags=re.UNICODE)\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21711/"
] |
238,260
|
<p>I have given a location defined by latitude and longitude.
Now i want to calculate a bounding box within e.g. 10 kilometers of that point.</p>
<p>The bounding box should be defined as latmin, lngmin and latmax, lngmax.</p>
<p>I need this stuff in order to use the <a href="http://www.panoramio.com/api/" rel="noreferrer">panoramio API</a>.</p>
<p>Does someone know the formula of how to get thos points?</p>
<p><strong>Edit:</strong> Guys i am looking for a formula/function which takes lat & lng as input and returns a bounding box as latmin & lngmin and latmax & latmin.
Mysql, php, c#, javascript is fine but also pseudocode should be okay.</p>
<p><strong>Edit:</strong> I am not looking for a solution which shows me the distance of 2 points</p>
|
[
{
"answer_id": 238278,
"author": "jcoby",
"author_id": 2884,
"author_profile": "https://Stackoverflow.com/users/2884",
"pm_score": 3,
"selected": false,
"text": "location"
},
{
"answer_id": 238558,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 7,
"selected": true,
"text": "# degrees to radians\ndef deg2rad(degrees):\n return math.pi*degrees/180.0\n# radians to degrees\ndef rad2deg(radians):\n return 180.0*radians/math.pi\n\n# Semi-axes of WGS-84 geoidal reference\nWGS84_a = 6378137.0 # Major semiaxis [m]\nWGS84_b = 6356752.3 # Minor semiaxis [m]\n\n# Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]\ndef WGS84EarthRadius(lat):\n # http://en.wikipedia.org/wiki/Earth_radius\n An = WGS84_a*WGS84_a * math.cos(lat)\n Bn = WGS84_b*WGS84_b * math.sin(lat)\n Ad = WGS84_a * math.cos(lat)\n Bd = WGS84_b * math.sin(lat)\n return math.sqrt( (An*An + Bn*Bn)/(Ad*Ad + Bd*Bd) )\n\n# Bounding box surrounding the point at given coordinates,\n# assuming local approximation of Earth surface as a sphere\n# of radius given by WGS84\ndef boundingBox(latitudeInDegrees, longitudeInDegrees, halfSideInKm):\n lat = deg2rad(latitudeInDegrees)\n lon = deg2rad(longitudeInDegrees)\n halfSide = 1000*halfSideInKm\n\n # Radius of Earth at given latitude\n radius = WGS84EarthRadius(lat)\n # Radius of the parallel at given latitude\n pradius = radius*math.cos(lat)\n\n latMin = lat - halfSide/radius\n latMax = lat + halfSide/radius\n lonMin = lon - halfSide/pradius\n lonMax = lon + halfSide/pradius\n\n return (rad2deg(latMin), rad2deg(lonMin), rad2deg(latMax), rad2deg(lonMax))\n def dps2deg(degrees, primes, seconds):\n return degrees + primes/60.0 + seconds/3600.0\n\ndef deg2dps(degrees):\n intdeg = math.floor(degrees)\n primes = (degrees - intdeg)*60.0\n intpri = math.floor(primes)\n seconds = (primes - intpri)*60.0\n intsec = round(seconds)\n return (int(intdeg), int(intpri), int(intsec))\n"
},
{
"answer_id": 14314146,
"author": "Ε Г И І И О",
"author_id": 687190,
"author_profile": "https://Stackoverflow.com/users/687190",
"pm_score": 5,
"selected": false,
"text": "public class MapPoint\n{\n public double Longitude { get; set; } // In Degrees\n public double Latitude { get; set; } // In Degrees\n}\n\npublic class BoundingBox\n{\n public MapPoint MinPoint { get; set; }\n public MapPoint MaxPoint { get; set; }\n} \n\n// Semi-axes of WGS-84 geoidal reference\nprivate const double WGS84_a = 6378137.0; // Major semiaxis [m]\nprivate const double WGS84_b = 6356752.3; // Minor semiaxis [m]\n\n// 'halfSideInKm' is the half length of the bounding box you want in kilometers.\npublic static BoundingBox GetBoundingBox(MapPoint point, double halfSideInKm)\n{ \n // Bounding box surrounding the point at given coordinates,\n // assuming local approximation of Earth surface as a sphere\n // of radius given by WGS84\n var lat = Deg2rad(point.Latitude);\n var lon = Deg2rad(point.Longitude);\n var halfSide = 1000 * halfSideInKm;\n\n // Radius of Earth at given latitude\n var radius = WGS84EarthRadius(lat);\n // Radius of the parallel at given latitude\n var pradius = radius * Math.Cos(lat);\n\n var latMin = lat - halfSide / radius;\n var latMax = lat + halfSide / radius;\n var lonMin = lon - halfSide / pradius;\n var lonMax = lon + halfSide / pradius;\n\n return new BoundingBox { \n MinPoint = new MapPoint { Latitude = Rad2deg(latMin), Longitude = Rad2deg(lonMin) },\n MaxPoint = new MapPoint { Latitude = Rad2deg(latMax), Longitude = Rad2deg(lonMax) }\n }; \n}\n\n// degrees to radians\nprivate static double Deg2rad(double degrees)\n{\n return Math.PI * degrees / 180.0;\n}\n\n// radians to degrees\nprivate static double Rad2deg(double radians)\n{\n return 180.0 * radians / Math.PI;\n}\n\n// Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]\nprivate static double WGS84EarthRadius(double lat)\n{\n // http://en.wikipedia.org/wiki/Earth_radius\n var An = WGS84_a * WGS84_a * Math.Cos(lat);\n var Bn = WGS84_b * WGS84_b * Math.Sin(lat);\n var Ad = WGS84_a * Math.Cos(lat);\n var Bd = WGS84_b * Math.Sin(lat);\n return Math.Sqrt((An*An + Bn*Bn) / (Ad*Ad + Bd*Bd));\n}\n"
},
{
"answer_id": 19489467,
"author": "kahna9",
"author_id": 2890967,
"author_profile": "https://Stackoverflow.com/users/2890967",
"pm_score": 0,
"selected": false,
"text": "<div dir=\"ltr\" style=\"text-align: center;\" trbidi=\"on\">\n<script src=\"https://ssl.panoramio.com/wapi/wapi.js?v=1&hl=en\"></script>\n<div id=\"wapiblock\" style=\"float: right; margin: 10px 15px\"></div>\n<script type=\"text/javascript\">\nvar myRequest = {\n 'tag': 'kahna',\n 'rect': {'sw': {'lat': -30, 'lng': 10.5}, 'ne': {'lat': 50.5, 'lng': 30}}\n};\n var myOptions = {\n 'width': 300,\n 'height': 200\n};\nvar wapiblock = document.getElementById('wapiblock');\nvar photo_widget = new panoramio.PhotoWidget('wapiblock', myRequest, myOptions);\nphoto_widget.setPosition(0);\n</script>\n</div>\n"
},
{
"answer_id": 19641738,
"author": "Greg Beck",
"author_id": 2929171,
"author_profile": "https://Stackoverflow.com/users/2929171",
"pm_score": 1,
"selected": false,
"text": "maxLon = $lon + rad2deg($rad/$R/cos(deg2rad($lat)));\nminLon = $lon - rad2deg($rad/$R/cos(deg2rad($lat)));\n (SrcRad/RadEarth)/cos(deg2rad(lat))\n -- GLOBAL Constants\ngc_pi CONSTANT REAL := 3.14159265359; -- Pi\n\n-- Conversion Factor Constants\ngc_rad_to_degs CONSTANT NUMBER := 180/gc_pi; -- Conversion for Radians to Degrees 180/pi\ngc_deg_to_rads CONSTANT NUMBER := gc_pi/180; --Conversion of Degrees to Radians\n\nlv_stat_lat -- The static latitude point that I am searching from \nlv_stat_long -- The static longitude point that I am searching from \n\n-- Angular radius ratio in radians\nlv_ang_radius := lv_search_radius / lv_earth_radius;\nlv_bb_maxlat := lv_stat_lat + (gc_rad_to_deg * lv_ang_radius);\nlv_bb_minlat := lv_stat_lat - (gc_rad_to_deg * lv_ang_radius);\n\n--Here's the tricky part, accounting for the Longitude getting smaller as we move up the latitiude scale\n-- I seperated the parts of the equation to make it easier to debug and understand\n-- I may not be a smart man but I know what the right answer is... :-)\n\nlv_int_calc := gc_deg_to_rads * lv_stat_lat;\nlv_int_calc := COS(lv_int_calc);\nlv_int_calc := lv_ang_radius/lv_int_calc;\nlv_int_calc := gc_rad_to_degs*lv_int_calc;\n\nlv_bb_maxlong := lv_stat_long + lv_int_calc;\nlv_bb_minlong := lv_stat_long - lv_int_calc;\n\n-- Now select the values from your location datatable \nSELECT * FROM (\nSELECT cityaliasname, city, state, zipcode, latitude, longitude, \n-- The actual distance in miles\nspherecos_pnttopntdist(lv_stat_lat, lv_stat_long, latitude, longitude, 'M') as miles_dist \nFROM Location_Table \nWHERE latitude between lv_bb_minlat AND lv_bb_maxlat\nAND longitude between lv_bb_minlong and lv_bb_maxlong)\nWHERE miles_dist <= lv_limit_distance_miles\norder by miles_dist\n;\n"
},
{
"answer_id": 25025590,
"author": "asalisbury",
"author_id": 1000482,
"author_profile": "https://Stackoverflow.com/users/1000482",
"pm_score": 4,
"selected": false,
"text": "'use strict';\n\n/**\n * @param {number} distance - distance (km) from the point represented by centerPoint\n * @param {array} centerPoint - two-dimensional array containing center coords [latitude, longitude]\n * @description\n * Computes the bounding coordinates of all points on the surface of a sphere\n * that has a great circle distance to the point represented by the centerPoint\n * argument that is less or equal to the distance argument.\n * Technique from: Jan Matuschek <http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates>\n * @author Alex Salisbury\n*/\n\ngetBoundingBox = function (centerPoint, distance) {\n var MIN_LAT, MAX_LAT, MIN_LON, MAX_LON, R, radDist, degLat, degLon, radLat, radLon, minLat, maxLat, minLon, maxLon, deltaLon;\n if (distance < 0) {\n return 'Illegal arguments';\n }\n // helper functions (degrees<–>radians)\n Number.prototype.degToRad = function () {\n return this * (Math.PI / 180);\n };\n Number.prototype.radToDeg = function () {\n return (180 * this) / Math.PI;\n };\n // coordinate limits\n MIN_LAT = (-90).degToRad();\n MAX_LAT = (90).degToRad();\n MIN_LON = (-180).degToRad();\n MAX_LON = (180).degToRad();\n // Earth's radius (km)\n R = 6378.1;\n // angular distance in radians on a great circle\n radDist = distance / R;\n // center point coordinates (deg)\n degLat = centerPoint[0];\n degLon = centerPoint[1];\n // center point coordinates (rad)\n radLat = degLat.degToRad();\n radLon = degLon.degToRad();\n // minimum and maximum latitudes for given distance\n minLat = radLat - radDist;\n maxLat = radLat + radDist;\n // minimum and maximum longitudes for given distance\n minLon = void 0;\n maxLon = void 0;\n // define deltaLon to help determine min and max longitudes\n deltaLon = Math.asin(Math.sin(radDist) / Math.cos(radLat));\n if (minLat > MIN_LAT && maxLat < MAX_LAT) {\n minLon = radLon - deltaLon;\n maxLon = radLon + deltaLon;\n if (minLon < MIN_LON) {\n minLon = minLon + 2 * Math.PI;\n }\n if (maxLon > MAX_LON) {\n maxLon = maxLon - 2 * Math.PI;\n }\n }\n // a pole is within the given distance\n else {\n minLat = Math.max(minLat, MIN_LAT);\n maxLat = Math.min(maxLat, MAX_LAT);\n minLon = MIN_LON;\n maxLon = MAX_LON;\n }\n return [\n minLon.radToDeg(),\n minLat.radToDeg(),\n maxLon.radToDeg(),\n maxLat.radToDeg()\n ];\n};\n"
},
{
"answer_id": 39037262,
"author": "Joe Black",
"author_id": 1208966,
"author_profile": "https://Stackoverflow.com/users/1208966",
"pm_score": 1,
"selected": false,
"text": "<?php\n# deg2rad and rad2deg are already within PHP\n\n# Semi-axes of WGS-84 geoidal reference\n$WGS84_a = 6378137.0; # Major semiaxis [m]\n$WGS84_b = 6356752.3; # Minor semiaxis [m]\n\n# Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]\nfunction WGS84EarthRadius($lat)\n{\n global $WGS84_a, $WGS84_b;\n\n $an = $WGS84_a * $WGS84_a * cos($lat);\n $bn = $WGS84_b * $WGS84_b * sin($lat);\n $ad = $WGS84_a * cos($lat);\n $bd = $WGS84_b * sin($lat);\n\n return sqrt(($an*$an + $bn*$bn)/($ad*$ad + $bd*$bd));\n}\n\n# Bounding box surrounding the point at given coordinates,\n# assuming local approximation of Earth surface as a sphere\n# of radius given by WGS84\nfunction boundingBox($latitudeInDegrees, $longitudeInDegrees, $halfSideInKm)\n{\n $lat = deg2rad($latitudeInDegrees);\n $lon = deg2rad($longitudeInDegrees);\n $halfSide = 1000 * $halfSideInKm;\n\n # Radius of Earth at given latitude\n $radius = WGS84EarthRadius($lat);\n # Radius of the parallel at given latitude\n $pradius = $radius*cos($lat);\n\n $latMin = $lat - $halfSide / $radius;\n $latMax = $lat + $halfSide / $radius;\n $lonMin = $lon - $halfSide / $pradius;\n $lonMax = $lon + $halfSide / $pradius;\n\n return array(rad2deg($latMin), rad2deg($lonMin), rad2deg($latMax), rad2deg($lonMax));\n}\n?>\n"
},
{
"answer_id": 39292616,
"author": "Ajay",
"author_id": 1621208,
"author_profile": "https://Stackoverflow.com/users/1621208",
"pm_score": 4,
"selected": false,
"text": "Min.lat = Given.Lat - (0.009 x N)\nMax.lat = Given.Lat + (0.009 x N)\nMin.lon = Given.lon - (0.009 x N)\nMax.lon = Given.lon + (0.009 x N)\n"
},
{
"answer_id": 41298946,
"author": "Noushad",
"author_id": 5466933,
"author_profile": "https://Stackoverflow.com/users/5466933",
"pm_score": 4,
"selected": false,
"text": "1 degree latitude ~ 111.2 km function getBoundsFromLatLng(lat, lng, radiusInKm){\n var lat_change = radiusInKm/111.2;\n var lon_change = Math.abs(Math.cos(lat*(Math.PI/180)));\n var bounds = { \n lat_min : lat - lat_change,\n lon_min : lng - lon_change,\n lat_max : lat + lat_change,\n lon_max : lng + lon_change\n };\n return bounds;\n}\n"
},
{
"answer_id": 45183958,
"author": "Jesuslg123",
"author_id": 1600491,
"author_profile": "https://Stackoverflow.com/users/1600491",
"pm_score": 1,
"selected": false,
"text": "#import \"LocationService+Bounds.h\"\n\n//Semi-axes of WGS-84 geoidal reference\nconst double WGS84_a = 6378137.0; //Major semiaxis [m]\nconst double WGS84_b = 6356752.3; //Minor semiaxis [m]\n\n@implementation LocationService (Bounds)\n\nstruct BoundsLocation {\n double maxLatitude;\n double minLatitude;\n double maxLongitude;\n double minLongitude;\n};\n\n+ (struct BoundsLocation)locationBoundsWithLatitude:(double)aLatitude longitude:(double)aLongitude maxDistanceKm:(NSInteger)aMaxKmDistance {\n return [self boundingBoxWithLatitude:aLatitude longitude:aLongitude halfDistanceKm:aMaxKmDistance/2];\n}\n\n#pragma mark - Algorithm \n\n+ (struct BoundsLocation)boundingBoxWithLatitude:(double)aLatitude longitude:(double)aLongitude halfDistanceKm:(double)aDistanceKm {\n double radianLatitude = [self degreesToRadians:aLatitude];\n double radianLongitude = [self degreesToRadians:aLongitude];\n double halfDistanceMeters = aDistanceKm*1000;\n\n\n double earthRadius = [self earthRadiusAtLatitude:radianLatitude];\n double parallelRadius = earthRadius*cosl(radianLatitude);\n\n double radianMinLatitude = radianLatitude - halfDistanceMeters/earthRadius;\n double radianMaxLatitude = radianLatitude + halfDistanceMeters/earthRadius;\n double radianMinLongitude = radianLongitude - halfDistanceMeters/parallelRadius;\n double radianMaxLongitude = radianLongitude + halfDistanceMeters/parallelRadius;\n\n struct BoundsLocation bounds;\n bounds.minLatitude = [self radiansToDegrees:radianMinLatitude];\n bounds.maxLatitude = [self radiansToDegrees:radianMaxLatitude];\n bounds.minLongitude = [self radiansToDegrees:radianMinLongitude];\n bounds.maxLongitude = [self radiansToDegrees:radianMaxLongitude];\n\n return bounds;\n}\n\n+ (double)earthRadiusAtLatitude:(double)aRadianLatitude {\n double An = WGS84_a * WGS84_a * cosl(aRadianLatitude);\n double Bn = WGS84_b * WGS84_b * sinl(aRadianLatitude);\n double Ad = WGS84_a * cosl(aRadianLatitude);\n double Bd = WGS84_b * sinl(aRadianLatitude);\n return sqrtl( ((An * An) + (Bn * Bn))/((Ad * Ad) + (Bd * Bd)) );\n}\n\n+ (double)degreesToRadians:(double)aDegrees {\n return M_PI*aDegrees/180.0;\n}\n\n+ (double)radiansToDegrees:(double)aRadians {\n return 180.0*aRadians/M_PI;\n}\n\n\n\n@end\n"
},
{
"answer_id": 45950371,
"author": "Sacky San",
"author_id": 5076414,
"author_profile": "https://Stackoverflow.com/users/5076414",
"pm_score": 0,
"selected": false,
"text": "earth_latitude_range earth_longitude_range SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;\n"
},
{
"answer_id": 47022562,
"author": "sma",
"author_id": 306999,
"author_profile": "https://Stackoverflow.com/users/306999",
"pm_score": 0,
"selected": false,
"text": "import (\n \"math\"\n)\n\n// Semi-axes of WGS-84 geoidal reference\nconst (\n // Major semiaxis (meters)\n WGS84A = 6378137.0\n // Minor semiaxis (meters)\n WGS84B = 6356752.3\n)\n\n// BoundingBox represents the geo-polygon that encompasses the given point and radius\ntype BoundingBox struct {\n LatMin float64\n LatMax float64\n LonMin float64\n LonMax float64\n}\n\n// Convert a degree value to radians\nfunc deg2Rad(deg float64) float64 {\n return math.Pi * deg / 180.0\n}\n\n// Convert a radian value to degrees\nfunc rad2Deg(rad float64) float64 {\n return 180.0 * rad / math.Pi\n}\n\n// Get the Earth's radius in meters at a given latitude based on the WGS84 ellipsoid\nfunc getWgs84EarthRadius(lat float64) float64 {\n an := WGS84A * WGS84A * math.Cos(lat)\n bn := WGS84B * WGS84B * math.Sin(lat)\n\n ad := WGS84A * math.Cos(lat)\n bd := WGS84B * math.Sin(lat)\n\n return math.Sqrt((an*an + bn*bn) / (ad*ad + bd*bd))\n}\n\n// GetBoundingBox returns a BoundingBox encompassing the given lat/long point and radius\nfunc GetBoundingBox(latDeg float64, longDeg float64, radiusKm float64) BoundingBox {\n lat := deg2Rad(latDeg)\n lon := deg2Rad(longDeg)\n halfSide := 1000 * radiusKm\n\n // Radius of Earth at given latitude\n radius := getWgs84EarthRadius(lat)\n\n pradius := radius * math.Cos(lat)\n\n latMin := lat - halfSide/radius\n latMax := lat + halfSide/radius\n lonMin := lon - halfSide/pradius\n lonMax := lon + halfSide/pradius\n\n return BoundingBox{\n LatMin: rad2Deg(latMin),\n LatMax: rad2Deg(latMax),\n LonMin: rad2Deg(lonMin),\n LonMax: rad2Deg(lonMax),\n }\n}\n"
},
{
"answer_id": 66816851,
"author": "Sujit Patel",
"author_id": 5694156,
"author_profile": "https://Stackoverflow.com/users/5694156",
"pm_score": 2,
"selected": false,
"text": "Number.prototype.degreeToRadius = function () {\n return this * (Math.PI / 180);\n};\n\nNumber.prototype.radiusToDegree = function () {\n return (180 * this) / Math.PI;\n};\n\nfunction getBoundingBox(fsLatitude, fsLongitude, fiDistanceInKM) {\n\n if (fiDistanceInKM == null || fiDistanceInKM == undefined || fiDistanceInKM == 0)\n fiDistanceInKM = 1;\n \n var MIN_LAT, MAX_LAT, MIN_LON, MAX_LON, ldEarthRadius, ldDistanceInRadius, lsLatitudeInDegree, lsLongitudeInDegree,\n lsLatitudeInRadius, lsLongitudeInRadius, lsMinLatitude, lsMaxLatitude, lsMinLongitude, lsMaxLongitude, deltaLon;\n \n // coordinate limits\n MIN_LAT = (-90).degreeToRadius();\n MAX_LAT = (90).degreeToRadius();\n MIN_LON = (-180).degreeToRadius();\n MAX_LON = (180).degreeToRadius();\n\n // Earth's radius (km)\n ldEarthRadius = 6378.1;\n\n // angular distance in radians on a great circle\n ldDistanceInRadius = fiDistanceInKM / ldEarthRadius;\n\n // center point coordinates (deg)\n lsLatitudeInDegree = fsLatitude;\n lsLongitudeInDegree = fsLongitude;\n\n // center point coordinates (rad)\n lsLatitudeInRadius = lsLatitudeInDegree.degreeToRadius();\n lsLongitudeInRadius = lsLongitudeInDegree.degreeToRadius();\n\n // minimum and maximum latitudes for given distance\n lsMinLatitude = lsLatitudeInRadius - ldDistanceInRadius;\n lsMaxLatitude = lsLatitudeInRadius + ldDistanceInRadius;\n\n // minimum and maximum longitudes for given distance\n lsMinLongitude = void 0;\n lsMaxLongitude = void 0;\n\n // define deltaLon to help determine min and max longitudes\n deltaLon = Math.asin(Math.sin(ldDistanceInRadius) / Math.cos(lsLatitudeInRadius));\n\n if (lsMinLatitude > MIN_LAT && lsMaxLatitude < MAX_LAT) {\n lsMinLongitude = lsLongitudeInRadius - deltaLon;\n lsMaxLongitude = lsLongitudeInRadius + deltaLon;\n if (lsMinLongitude < MIN_LON) {\n lsMinLongitude = lsMinLongitude + 2 * Math.PI;\n }\n if (lsMaxLongitude > MAX_LON) {\n lsMaxLongitude = lsMaxLongitude - 2 * Math.PI;\n }\n }\n\n // a pole is within the given distance\n else {\n lsMinLatitude = Math.max(lsMinLatitude, MIN_LAT);\n lsMaxLatitude = Math.min(lsMaxLatitude, MAX_LAT);\n lsMinLongitude = MIN_LON;\n lsMaxLongitude = MAX_LON;\n }\n\n return [\n lsMinLatitude.radiusToDegree(),\n lsMinLongitude.radiusToDegree(),\n lsMaxLatitude.radiusToDegree(),\n lsMaxLongitude.radiusToDegree()\n ];\n};\n var lsRectangleLatLong = getBoundingBox(parseFloat(latitude), parseFloat(longitude), lsDistance);\n if (lsRectangleLatLong != null && lsRectangleLatLong != undefined) {\n latLngArr.push({ lat: lsRectangleLatLong[0], lng: lsRectangleLatLong[1] });\n latLngArr.push({ lat: lsRectangleLatLong[0], lng: lsRectangleLatLong[3] });\n latLngArr.push({ lat: lsRectangleLatLong[2], lng: lsRectangleLatLong[3] });\n latLngArr.push({ lat: lsRectangleLatLong[2], lng: lsRectangleLatLong[1] });\n }\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21672/"
] |
238,267
|
<p>I have seen various rules for naming stored procedures. </p>
<p>Some people prefix the sproc name with usp_, others with an abbreviation for the app name, and still others with an owner name. You shouldn't use sp_ in SQL Server unless you really mean it.</p>
<p>Some start the proc name with a verb (Get, Add, Save, Remove). Others emphasize the entity name(s).</p>
<p>On a database with hundreds of sprocs, it can be very hard to scroll around and find a suitable sproc when you think one already exists. Naming conventions can make locating a sproc easier.</p>
<p>Do you use a naming convention? Please describe it, and explain why you prefer it over other choices.</p>
<p><strong>Summary of replies:</strong> </p>
<ul>
<li>Everybody seems to advocate consistency of naming, that it might be more important for everyone to use the same naming convention than which particular one is used.</li>
<li>Prefixes: While a lot of folks use usp_ or something similar (but rarely sp_), many others use database or app name. One clever DBA uses gen, rpt and tsk to distinguish general CRUD sprocs from those used for reporting or tasks.</li>
<li>Verb + Noun seems to be slightly more popular than Noun + Verb. Some people use the SQL keywords (Select, Insert, Update, Delete) for the verbs, while others use non-SQL verbs (or abbreviations for them) like Get and Add. Some distinguish between singluar and plural nouns to indicate whether one or many records are being retrieved.</li>
<li>An additional phrase is suggested at the end, where appropriate. GetCustomerById, GetCustomerBySaleDate.</li>
<li>Some people use underscores between the name segments, and some avoid underscores. app_ Get_Customer vs. appGetCustomer -- I guess it's a matter of readability.</li>
<li>Large collections of sprocs can be segregated into Oracle packages or Management Studio (SQL Server) solutions and projects, or SQL Server schemas.</li>
<li>Inscrutable abbreviations should be avoided.</li>
</ul>
<p><strong>Why I choose the answer I did:</strong> There are SO many good responses. Thank you all! As you can see, it would be very hard to choose just one. The one I chose resonated with me. I have followed the same path he describes -- trying to use Verb + Noun and then not being able to find all of the sprocs that apply to Customer. </p>
<p>Being able to locate an existing sproc, or to determine if one even exists, is very important. Serious problems can arise if someone inadvertently creates a duplicate sproc with another name. </p>
<p>Since I generally work on very large apps with hundreds of sprocs, I have a preference for the easiest-to-find naming method. For a smaller app, I might advocate Verb + Noun, as it follows the general coding convention for method names.</p>
<p>He also advocates prefixing with app name instead of the not very useful usp_. As several people pointed out, sometimes the database contains sprocs for multiple apps. So, prefixing with app name helps to segregate the sprocs AND helps DBAs and others to determine which app the sproc is used for.</p>
|
[
{
"answer_id": 238295,
"author": "driis",
"author_id": 13627,
"author_profile": "https://Stackoverflow.com/users/13627",
"pm_score": 1,
"selected": false,
"text": "shopGetCategories\nshopUpdateItem\n"
},
{
"answer_id": 238330,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 3,
"selected": false,
"text": "sp_ up_ sp_"
},
{
"answer_id": 238346,
"author": "dnolan",
"author_id": 29086,
"author_profile": "https://Stackoverflow.com/users/29086",
"pm_score": 7,
"selected": true,
"text": "[App]_[Object]_[Action][Process]\n\nApp_Tags_AddTag\nApp_Tags_AddTagRelations\nApp_Product_Add \nApp_Product_GetList\nApp_Product_GetSingle\n"
},
{
"answer_id": 238364,
"author": "computinglife",
"author_id": 17224,
"author_profile": "https://Stackoverflow.com/users/17224",
"pm_score": 1,
"selected": false,
"text": "Proc_Poll_Interface, Proc_Inv_Interface Proc_Order_Place\nProc_order_Delete\nProc_Order_Retrieve\nProc_Order_History\n"
},
{
"answer_id": 238435,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 3,
"selected": false,
"text": "Ins - INSERT\nSel - SELECT\nUpd - UPDATE\nDel - DELETE\n genInsOrderHeader\n\ngenSelCustomerByCustomerID\ngenSelCustomersBySaleDate\n\ngenUpdCommentText\n\ngenDelOrderDetailLine\n\nrptSelCustomersByState\nrptSelPaymentsByYear\n\ntskQueueAccountsForCollection\n"
},
{
"answer_id": 991670,
"author": "Gaurav Arora",
"author_id": 122574,
"author_profile": "https://Stackoverflow.com/users/122574",
"pm_score": 1,
"selected": false,
"text": "exec sMedicationInfo_G\nexec sMedicationInfo_D\nexec sMedicationInfo_I\nexec sMedicationInfo_U exec sp_MedicationInfoG\nexec sp_MedicationInfoD\nexec sp_MedicationInfoI\nexec sp_MedicationInfoU"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27637/"
] |
238,284
|
<p>I'm building an Android app and I want to copy the text value of an EditText widget. It's possible for the user to press <code>Menu+A</code> then <code>Menu+C</code> to copy the value, but how would I do this programmatically?</p>
|
[
{
"answer_id": 238297,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 10,
"selected": true,
"text": "ClipboardManager#setPrimaryClip import android.content.ClipboardManager;\n\n// ...\n\nClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); \nClipData clip = ClipData.newPlainText(\"label\", \"Text to copy\");\nclipboard.setPrimaryClip(clip);\n ClipboardManager"
},
{
"answer_id": 7953397,
"author": "ayrina",
"author_id": 1017908,
"author_profile": "https://Stackoverflow.com/users/1017908",
"pm_score": 4,
"selected": false,
"text": "public void onClick (View v) \n{\n switch (v.getId())\n {\n case R.id.ButtonCopy:\n copyToClipBoard();\n break;\n case R.id.ButtonPaste:\n pasteFromClipBoard();\n break;\n default:\n Log.d(TAG, \"OnClick: Unknown View Received!\");\n break;\n }\n}\n\n// Copy EditCopy text to the ClipBoard\nprivate void copyToClipBoard() \n{\n ClipboardManager clipMan = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\n clipMan.setPrimaryClip(editCopy.getText());\n}\n"
},
{
"answer_id": 9941666,
"author": "Viachaslau Tysianchuk",
"author_id": 74144,
"author_profile": "https://Stackoverflow.com/users/74144",
"pm_score": 4,
"selected": false,
"text": "ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);\n android.text.ClipboardManager android.content.ClipboardManager"
},
{
"answer_id": 11012443,
"author": "Warpzit",
"author_id": 969325,
"author_profile": "https://Stackoverflow.com/users/969325",
"pm_score": 8,
"selected": false,
"text": "int sdk = android.os.Build.VERSION.SDK_INT;\nif(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {\n android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\n clipboard.setText(\"text to clip\");\n} else {\n android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); \n android.content.ClipData clip = android.content.ClipData.newPlainText(\"text label\",\"text to clip\");\n clipboard.setPrimaryClip(clip);\n}\n <uses-sdk android:minSdkVersion=\"7\" android:targetSdkVersion=\"14\" />\n"
},
{
"answer_id": 26868729,
"author": "live-love",
"author_id": 436341,
"author_profile": "https://Stackoverflow.com/users/436341",
"pm_score": 3,
"selected": false,
"text": "public void copy(View v) { \n int startSelection = txtNotes.getSelectionStart();\n int endSelection = txtNotes.getSelectionEnd(); \n if ((txtNotes.getText() != null) && (endSelection > startSelection ))\n {\n String selectedText = txtNotes.getText().toString().substring(startSelection, endSelection); \n int sdk = android.os.Build.VERSION.SDK_INT;\n if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {\n android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\n clipboard.setText(selectedText);\n } else {\n android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); \n android.content.ClipData clip = android.content.ClipData.newPlainText(\"WordKeeper\",selectedText);\n clipboard.setPrimaryClip(clip);\n }\n }\n} \n\npublic void paste(View v) {\n int sdk = android.os.Build.VERSION.SDK_INT;\n if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {\n android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\n if (clipboard.getText() != null) {\n txtNotes.getText().insert(txtNotes.getSelectionStart(), clipboard.getText());\n }\n } else {\n android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\n android.content.ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);\n if (item.getText() != null) {\n txtNotes.getText().insert(txtNotes.getSelectionStart(), item.getText());\n }\n }\n}\n"
},
{
"answer_id": 38788513,
"author": "King of Masses",
"author_id": 3983054,
"author_profile": "https://Stackoverflow.com/users/3983054",
"pm_score": 3,
"selected": false,
"text": "android:textIsSelectable=\"true\"\n myTextView.setTextIsSelectable(true);"
},
{
"answer_id": 40837286,
"author": "Suragch",
"author_id": 3681880,
"author_profile": "https://Stackoverflow.com/users/3681880",
"pm_score": 4,
"selected": false,
"text": "ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\nClipData clip = ClipData.newPlainText(\"label\", selectedText);\nif (clipboard == null || clip == null) return;\nclipboard.setPrimaryClip(clip);\n ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\ntry {\n CharSequence text = clipboard.getPrimaryClip().getItemAt(0).getText();\n} catch (Exception e) {\n return;\n}\n android.content.ClipboardManager android.text.ClipboardManager ClipData context.getSystemService() null"
},
{
"answer_id": 43482476,
"author": "Agna JirKon Rx",
"author_id": 3183912,
"author_profile": "https://Stackoverflow.com/users/3183912",
"pm_score": 2,
"selected": false,
"text": "ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); \nClipData clip = ClipData.newPlainText(\"label\", \"Text to copy\");\nclipboard.setPrimaryClip(clip); \n label text import android.content.ClipboardManager;\n"
},
{
"answer_id": 53737565,
"author": "Mor2",
"author_id": 7523373,
"author_profile": "https://Stackoverflow.com/users/7523373",
"pm_score": 3,
"selected": false,
"text": "ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); \nClipData clip = ClipData.newPlainText(\"label\", \"Text to copy\");\nif (clipboard == null || clip == null)\n return;\nclipboard.setPrimaryClip(clip);\n import android.content.ClipboardManager;"
},
{
"answer_id": 60389093,
"author": "Mehul Boghra",
"author_id": 8968815,
"author_profile": "https://Stackoverflow.com/users/8968815",
"pm_score": 1,
"selected": false,
"text": "/**\n * Method to code text in clip board\n *\n * @param context context\n * @param text text what wan to copy in clipboard\n * @param label label what want to copied\n */\npublic static void copyCodeInClipBoard(Context context, String text, String label) {\n if (context != null) {\n ClipboardManager clipboard = (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);\n ClipData clip = ClipData.newPlainText(label, text);\n if (clipboard == null || clip == null)\n return;\n clipboard.setPrimaryClip(clip);\n\n }\n}\n"
},
{
"answer_id": 60720292,
"author": "Vijayakumar G",
"author_id": 13075633,
"author_profile": "https://Stackoverflow.com/users/13075633",
"pm_score": 2,
"selected": false,
"text": "fun copyToClipBoard(context: Context, message: String) {\n\n val clipBoard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager\n val clipData = ClipData.newPlainText(\"label\",message)\n clipBoard.setPrimaryClip(clipData)\n\n}\n"
},
{
"answer_id": 64720511,
"author": "Rajeev Shetty",
"author_id": 3932147,
"author_profile": "https://Stackoverflow.com/users/3932147",
"pm_score": 2,
"selected": false,
"text": "import android.content.ClipboardManager\n\n\n val clipBoard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager\n val clipData = ClipData.newPlainText(\"label\",\"Message to be Copied\")\n clipBoard.setPrimaryClip(clipData)\n"
},
{
"answer_id": 71312894,
"author": "jafar_aml",
"author_id": 6254352,
"author_profile": "https://Stackoverflow.com/users/6254352",
"pm_score": 0,
"selected": false,
"text": " private fun copyTextToClipboard(copyText: String) {\n\n val clipboardManager = requireActivity().\n getSystemService(CLIPBOARD_SERVICE) as \n android.content.ClipboardManager\n\n val clipData = ClipData.newPlainText(\"userLabel\" ,copyText.trim())\n\n clipboardManager.setPrimaryClip(clipData)\n\n }\n"
},
{
"answer_id": 73034626,
"author": "Alex Busuioc",
"author_id": 1147447,
"author_profile": "https://Stackoverflow.com/users/1147447",
"pm_score": 1,
"selected": false,
"text": " fun String.copyToClipboard(context: Context) {\n val clipBoard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager\n val clipData = ClipData.newPlainText(\"label\",this)\n clipBoard.setPrimaryClip(clipData)\n }\n \"stringToCopy\".copyToClipboard(requireContext())\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9128/"
] |
238,314
|
<p>Let's say I have the following ruby code :</p>
<pre><code>
def use_object(object)
puts object.some_method
end
</code></pre>
<p>and , this will work on any object that responds to <strong>some_method</strong>,right?</p>
<p>Assuming that the following java interface exists :</p>
<pre><code>
interface TestInterface {
public String some_method();
}
</code></pre>
<p>Am I right to presume that interfaces are java's way to achieving the same thing ( with the only difference that the parameter's type would be <strong>TestInterface</strong> ) ?</p>
|
[
{
"answer_id": 238327,
"author": "Fabian Buch",
"author_id": 28968,
"author_profile": "https://Stackoverflow.com/users/28968",
"pm_score": 1,
"selected": false,
"text": "interface TestInterface {\n public String some_method();\n}\n public class TestClass implements TestInterface {\n public String some_method() {\n return \"test\";\n }\n}\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31610/"
] |
238,317
|
<p>I have a route</p>
<pre><code>// Sample URL: /Fixtures/Team/id
routes.MapRoute(
"Fixtures-by-TeamID",
"Fixtures/Team/{teamId}",
new { controller = "Fixtures", action = "GetByTeamID", },
new { teamId = @"\d{1,3}" }
);
</code></pre>
<p>and I am trying to use ActionLink in ASP.net MVC p5. </p>
<pre><code><%= Html.ActionLink(g.HomeTeam.TeamName, "Team", new { teamId = g.HomeTeam.TeamID })%>
</code></pre>
<p>However it is not working and giving me </p>
<pre><code><a href="/Fixtures/Team?teamId=118">Team A</a>
</code></pre>
<p>If I use Url.RouteUrl i get the correct link.</p>
<pre><code><a href="<%=Url.RouteUrl("Fixtures-by-TeamID", new { teamId = g.HomeTeam.TeamID })%>"><%=g.HomeTeam.TeamName%></a>
<a href="/Fixtures/Team/118">Team A</a>
</code></pre>
<p>Any help would be great? Will this change in ASP.net MVC beta?</p>
<p>Thanks</p>
<p>Donald</p>
|
[
{
"answer_id": 238339,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 1,
"selected": false,
"text": "<a href=\"<%= Url.FixturesByTeam(g.HomeTeam.TeamID) %>\"><%= g.HomeTeam.TeamName %></a>\n <%= Html.LinkToFixturesByTeam(g.HomeTeam) %>\n"
},
{
"answer_id": 238433,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "// Sample URL: /Fixtures/Team/id\nroutes.MapRoute(\n \"Fixtures-by-TeamID\",\n \"Fixtures/Team/{teamId}\",\n new { controller = \"Fixtures\", action = \"Team\", teamId = -1 }\n);\n public class FixturesController : BaseController // or whatever \n{\n /*...*/\n public ActionResult Team(int teamId)\n {\n return View(\"Detail\", Team.GetTeamById(teamId)) // or whatever\n }\n /*...*/\n}\n <%= Html.ActionLink(\"Click here for the team details\", \"Team\", \"Fixtures\", new { teamId = ViewModel.Data.Id /*orwhateverlol*/ }) %>\n"
},
{
"answer_id": 241114,
"author": "Rob",
"author_id": 2595,
"author_profile": "https://Stackoverflow.com/users/2595",
"pm_score": 1,
"selected": false,
"text": "Html.ActionLink<FixturesController>(c => c.GetByTeamID(g.HomeTeam.TeamID), \"Team\")\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17584/"
] |
238,328
|
<p>I am trying to figure out the best way to model a spreadsheet (from the database point of view), taking into account :</p>
<ul>
<li>The spreadsheet can contain a variable number of rows.</li>
<li>The spreadsheet can contain a variable number of columns.</li>
<li>Each column can contain one single value, but its type is unknown (integer, date, string).</li>
<li>It has to be easy (and performant) to generate a CSV file containing the data.</li>
</ul>
<p>I am thinking about something like :</p>
<pre><code>class Cell(models.Model):
column = models.ForeignKey(Column)
row_number = models.IntegerField()
value = models.CharField(max_length=100)
class Column(models.Model):
spreadsheet = models.ForeignKey(Spreadsheet)
name = models.CharField(max_length=100)
type = models.CharField(max_length=100)
class Spreadsheet(models.Model):
name = models.CharField(max_length=100)
creation_date = models.DateField()
</code></pre>
<p>Can you think about a better way to model a spreadsheet ? My approach allows to store the data as a String. I am worried about it being too slow to generate the CSV file.</p>
|
[
{
"answer_id": 238397,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 2,
"selected": false,
"text": "Spreadsheet <-->> Cell : RowId, ColumnId, ValueType, Contents\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12388/"
] |
238,340
|
<p>I have a C# collection of strings. Each string is a sentence that can appear on a page. I also have a collection of page breaks which is a collection of int's. representing the index where the collection of strings are split to a new page.</p>
<p>Example: Each 10 items in the string collection is a page so the collection of page breaks would be a collection of int's with the values of 10, 20, 30. ...</p>
<p>So if there are 2 pages of strings then there will be 1 item in the page break collection and if there is 1 page then the page break collection would have zero items.</p>
<p>I am trying to create the following function:</p>
<pre><code>List<string> GetPage(List<string> docList, List<int> pageBreakList, int pageNum)
{
// This function returns a subset of docList - just the page requested
}
</code></pre>
<p>I've taken a few stabs at writing this function and keep on coming up with complex if and switch statements to take into account single and two page documents and page numbers being requested outside the range (e.g. last page should be returned if page number is greater than number of pages and first page if page number is 0 or less).</p>
<p>My struggle with this problem leads me to ask the question: Is there a well known pattern or algorithm to address this type of subset query?</p>
|
[
{
"answer_id": 238369,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "List<string> strings = ...\nint pageNum = ...\nint pageSze = ...\n\nif (pageNum < 1) pageNum = 1;\nif (pageSize < 1) pageSize = 1;\n\nList<string> pageOfStrings = strings.Skip( pageSize*(pageNum-1) ).Take( pageSize ).ToList();\n List<string> strings = ...\nList<int> sizes = ...\n\nint pageNum = ...\nint itemsToSkip = 0;\nint itemsToTake = 1;\n\nif (pageNum > 1)\n{\n sizes.Take( pageNum - 2).Sum();\n\n if (pageNum <= sizes.Count)\n {\n itemsToTake = sizes[pageNum-1]\n }\n{\n\nList<string> pageOfStrings = strings.Skip( itemsToSkip ).Take( itemsToTake );\n"
},
{
"answer_id": 238463,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": true,
"text": "//pageNum is zero-based.\nList<string> GetPage(List<string> docList, List<int> pageBreaks, int pageNum)\n{\n\n // 0 page case\n if (pageBreaks.Count != 0)\n {\n return docList;\n }\n\n int lastPage = pageBreaks.Count;\n\n //requestedPage is after the lastPage case\n if (requestedPage > lastPage)\n {\n requestedPage = lastPage;\n }\n\n\n int firstLine = requestedPage == 0 ? 0 :\n pageBreaks[requestedPage-1];\n int lastLine = requestedPage == lastPage ? docList.Count :\n pageBreaks[requestedPage];\n\n //lastLine is excluded. 6 - 3 = 3 - 3, 4, 5\n\n int howManyLines = lastLine - firstLine;\n\n return docList.GetRange(firstLine, howManyLines);\n}\n IEnumerable<Page> pages =\n Enumerable.Repeat(0, 1)\n .Concat(pageBreaks)\n .Select\n (\n (p, i) => new Page()\n {\n PageNumber = i,\n Lines = \n docList.GetRange(p, ((i != pageBreaks.Count) ? pageBreaks[i] : docList.Count) - p)\n }\n );\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
238,343
|
<p>I am trying to place a big number in a C++ variable. The number is 600851475143</p>
<p>I tried unsigned long long int but got an error saying it the constant was too big.
I then tried a bigInt library called BigInt -> <a href="http://mattmccutchen.net/bigint/" rel="nofollow noreferrer">http://mattmccutchen.net/bigint/</a></p>
<p>The problem is I can't compile the code as I get many errors regarding the lib.</p>
<p>undefined reference to `BigInteger::BigInteger(int)' <-- lot's of these.</p>
<p>Here is my code so far:</p>
<pre><code>#include "string"
#include "iostream"
#include "bigint/NumberlikeArray.hh"
#include "bigint/BigUnsigned.hh"
#include "bigint/BigInteger.hh"
#include "bigint/BigIntegerAlgorithms.hh"
#include "bigint/BigUnsignedInABase.hh"
#include "bigint/BigIntegerUtils.hh"
using namespace std;
int main() {
//unsigned long int num = 13195;
//unsigned long long int num = 600851475143;
BigInteger num = 13195;
int divider = 2;
//num = 600851475143;
while (1) {
if ((num % divider) == 0) {
cout << divider << '\n';
num /= divider;
}
else
divider++;
if (num == 1)
break;
}
}
</code></pre>
<p>If I put a smaller number and don't use the BigInt lib this program runs fine.
Any help will be appreciated :D</p>
|
[
{
"answer_id": 238345,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 6,
"selected": true,
"text": "#include <iostream>\n\nint main()\n{\n long long num = 600851475143LL;\n\n std::cout << num;\n}\n"
},
{
"answer_id": 238350,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": false,
"text": "unsigned long long int num = 600851475143ULL;\n"
},
{
"answer_id": 15887971,
"author": "Muricula",
"author_id": 1123789,
"author_profile": "https://Stackoverflow.com/users/1123789",
"pm_score": 0,
"selected": false,
"text": "g++ -c -O2 -Wall -Wextra -pedantic BigUnsigned.cc\ng++ -c -O2 -Wall -Wextra -pedantic BigInteger.cc\ng++ -c -O2 -Wall -Wextra -pedantic BigIntegerAlgorithms.cc\ng++ -c -O2 -Wall -Wextra -pedantic BigUnsignedInABase.cc\ng++ -c -O2 -Wall -Wextra -pedantic BigIntegerUtils.cc\ng++ -c -O2 -Wall -Wextra -pedantic sample.cc\ng++ sample.o BigUnsigned.o BigInteger.o BigIntegerAlgorithms.o BigUnsignedInABase.o BigIntegerUtils.o -o sample\n sample"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8715/"
] |
238,349
|
<p>Below is the code that i cannot get to work. I know i have established a connection to the database but this returns nothing. What am i doing wrong?</p>
<pre><code>$result = "SELECT * FROM images WHERE path = ?";
$params = array("blah");
$row = sqlsrv_query($conn, $result, $params);
$finished = sqlsrv_fetch_array($row);
if($finished)
{
echo "blach";
}
</code></pre>
|
[
{
"answer_id": 238502,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 0,
"selected": false,
"text": "$result = \"SELECT * FROM images WHERE path = ?\";\n$params = array(\"blah\");\n$row = sqlsrv_query($conn, $result, $params);\n\nif( $row === false ) {\n print_r(sqlsrv_errors());\n}\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
238,358
|
<p>I'm trying to get authentication working to my liking in a CakePHP app and running into a snag. </p>
<p>I want to let the user login from either the home page or from a dedicated login page. I'm using the Auth component to manage login and right now the login itself works. I am submitting the form on the home page to /Users/Login and it does log them in and create session. The problem is it then redirects the user back to the home page. I'd rather they redirect to the location specified in loginRedirect. </p>
<p>If i login from /users/login directly it does forward to loginRedirect. I think the problem has something to do with posting the form from one page to another page instead of to itself, auth automatically thinks you want to go back to the previous page. </p>
<p>Any thoughts?</p>
|
[
{
"answer_id": 374106,
"author": "nanoman",
"author_id": 46993,
"author_profile": "https://Stackoverflow.com/users/46993",
"pm_score": 0,
"selected": false,
"text": "$this->Session->del('Auth.redirect');\n"
},
{
"answer_id": 474358,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "public function beforeFilter( )\n{\n $this->Auth->autoRedirect = false;\n}\n public function login( )\n{\n if( $this->Auth->user( ) )\n {\n $this->redirect( array(\n 'controller' => 'users' ,\n 'action' => 'index' ,\n ));\n }\n}\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7018/"
] |
238,376
|
<p>I am writing my own Joomla component (MVC), its based heavily on the newsflash module, because I want to display the latest 5 content items in a sliding tabbed interface, all the hard work is done, but I am having real difficult getting content out of the for loop.</p>
<p>Here is the code I have so far
default.php</p>
<pre><code><ul id="handles" class="tabs">
<?php for ($i = 0, $n = count($list); $i < $n; $i ++) :
modSankeSlideHelper::getTabs($list[$i]);
endfor; ?>
<li class="end"></li>
</ul>
</code></pre>
<p>helper.php</p>
<pre><code>function getTabs(&$item)
{
global $mainframe;
$item->created = $item->created;
list($year, $month, $day) = split("-", $item->created);
$tabdate = date('d\/m\/y', mktime(0, 0, 0, $month, $day, $year));
require(JModuleHelper::getLayoutPath('mod_sankeslide', '_tab'));
}
</code></pre>
<p>_tab.php</p>
<pre><code><li><a href="#tab"><span><?php echo 'Shout ' . $tabdate; ?></span><b></b></a></li>
</code></pre>
<p>The first item needs to have different value and a class item added to the a: item, so I need to be able to identify which is the first item and do something during that loop.</p>
<p>I tried to use if $i = 0 else statement in the default.php, but it resulted in a page timeout for some reason!</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 238389,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 3,
"selected": true,
"text": "if $i = 0 == if ($i == 0){\n // First Item here...\n\n}else{\n // Other Items...\n\n} \n"
},
{
"answer_id": 238753,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 1,
"selected": false,
"text": "for doSomethingWithFirst($list[0]);\n\nfor ($i = 1; $i < count($list); $i++) {\n doSomethingWithTheRest($list[$i]);\n}\n foreach for $bFirstTime = true;\nforeach($list as $item) {\n if ($bFirstTime) {\n doSomethingWithFirst($item);\n $bFirstTime = false;\n } else {\n doSomethingWithTheRest($item);\n }\n}\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28241/"
] |
238,379
|
<p>How would I even go about forking a child process using Haskell in the first place?</p>
<p>Also, if pipes are an obvious solution to the data sharing question - is there any other way to do it besides using pipes? I'm familiar with the use of shared memory segments in C (the shmget, *shmat, shmdt and shmctl functions). Could Haskell be able to imitate this? If so, how?</p>
<p>I'd be very grateful for any help you could spare.</p>
<p>I must admit I'm very much new to functional programming languages, even more so when it comes to Haskell. So forgive me (and please correct me) if I said something silly.</p>
|
[
{
"answer_id": 21931154,
"author": "Edward Z. Yang",
"author_id": 23845,
"author_profile": "https://Stackoverflow.com/users/23845",
"pm_score": 0,
"selected": false,
"text": "forkProcess"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
238,380
|
<p>When there are one of more columns that reference another, I'm struggling for the best way to update that column while maintaining referential integrity. For example, if I have a table of labels and descriptions and two entries:</p>
<pre><code>Label | Description
------------------------------------
read | This item has been read
READ | You read this thing already
</code></pre>
<p>Now, I don't want these duplicates. I want to add a constraint to the column that doesn't allow values that are case-insensitively duplicates, as in the example. However, I have several rows of several other tables referencing 'READ', the one I want to drop.</p>
<p>I know Postgres knows which fields of other rows are referencing this, because I can't delete it as long as they are there. So, how could I get any field referencing this to update to 'read'? This is just an example, and I actually have a few places I want to do this. Another example is actually an int primary key for a few tables, where I want to add a new table as a sort of 'base table' that the existing ones extend and so they'll all need to have unique IDs now, which means updating the ones they have.</p>
<p>I am open to recipes for functions I can add to do this, tools I can utilize, or anything else.</p>
|
[
{
"answer_id": 238390,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": true,
"text": "select TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,\nREFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME from \nINFORMATION_SCHEMA.KEY_COLUMN_USAGE where\nREFERENCED_TABLE_NAME = '<table>' AND REFERENCED_COLUMN_NAME = '<column>'\n"
},
{
"answer_id": 238673,
"author": "Patryk Kordylewski",
"author_id": 30927,
"author_profile": "https://Stackoverflow.com/users/30927",
"pm_score": 0,
"selected": false,
"text": "CREATE UNIQUE INDEX index_name ON table ((lower(label)));\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19687/"
] |
238,413
|
<p>I am trying to use Lambda Expressions in a project to map to a third party query API. So, I'm parsing the Expression tree by hand.</p>
<p>If I pass in a lambda expression like:</p>
<pre><code>p => p.Title == "title"
</code></pre>
<p>everything works.</p>
<p>However, if my lambda expression looks like:</p>
<pre><code>p => p.Title == myaspdropdown.SelectedValue
</code></pre>
<p>Using the .NET debugger, I don't see the actual value of that funciton. Instead I see something like:</p>
<pre><code>p => p.Title = (value(ASP.usercontrols_myaspusercontrol_ascx).myaspdropdown.SelectedValue)
</code></pre>
<p>What gives? And when I try to grab the right side of the expression as a string, I get <code>(value(ASP.usercontrols_myaspusercontrol_ascx).myaspdropdown.SelectedValue)</code> instead of the actual value. <strong>How do I get the actual value?</strong></p>
|
[
{
"answer_id": 239359,
"author": "Bevan",
"author_id": 30280,
"author_profile": "https://Stackoverflow.com/users/30280",
"pm_score": 5,
"selected": true,
"text": "public class Class1\n{\n public string Selection { get; set; }\n\n public void Sample()\n {\n Selection = \"Example\";\n Example<Book, bool>(p => p.Title == Selection);\n }\n\n public void Example<T,TResult>(Expression<Func<T,TResult>> exp)\n {\n BinaryExpression equality = (BinaryExpression)exp.Body;\n Debug.Assert(equality.NodeType == ExpressionType.Equal);\n\n // Note that you need to know the type of the rhs of the equality\n var accessorExpression = Expression.Lambda<Func<string>>(equality.Right);\n Func<string> accessor = accessorExpression.Compile();\n var value = accessor();\n Debug.Assert(value == Selection);\n }\n}\n\npublic class Book\n{\n public string Title { get; set; }\n}\n"
},
{
"answer_id": 3726572,
"author": "squirrel",
"author_id": 213781,
"author_profile": "https://Stackoverflow.com/users/213781",
"pm_score": 0,
"selected": false,
"text": " [TestFixture]\npublic class TestClass\n{\n [Test]\n public void TEst()\n {\n var user = new User {Id = 123};\n var idToSearch = user.Id;\n var query = Creator.CreateQuery<User>()\n .Where(x => x.Id == idToSearch);\n }\n}\n\npublic class Query<T>\n{\n public Query<T> Where(Expression<Func<T, object>> filter)\n {\n var rightValue = GenericHelper.GetVariableValue(((BinaryExpression)((UnaryExpression)filter.Body).Operand).Right.Type, ((BinaryExpression)((UnaryExpression)filter.Body).Operand).Right);\n Console.WriteLine(rightValue);\n return this;\n }\n}\n\ninternal class GenericHelper\n{\n internal static object GetVariableValue(Type variableType, Expression expression)\n {\n var targetMethodInfo = typeof(InvokeGeneric).GetMethod(\"GetVariableValue\");\n var genericTargetCall = targetMethodInfo.MakeGenericMethod(variableType);\n return genericTargetCall.Invoke(new InvokeGeneric(), new[] { expression });\n }\n}\n\ninternal class InvokeGeneric\n{\n public T GetVariableValue<T>(Expression expression) where T : class\n {\n var accessorExpression = Expression.Lambda<Func<T>>(expression);\n var accessor = accessorExpression.Compile();\n return accessor();\n }\n}\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/49611/"
] |
238,430
|
<p>I think I know the answer, but I would like to bounce around some ideas.</p>
<p>I would like to pass several (in this instance 2) somewhat different pieces of data to a View. My initial thought is simply to wrap-up the various objects into a containing object and pass them along that way. Then from the View, I'd have something like </p>
<pre><code>var objContainer = ViewData.Model;
var thisObject = objContainer.ThisObject;
var thatObject = objContainer.ThatObject;
</code></pre>
<p>and these could be used independently in the Master Page and View Page.</p>
<p>Is that the "best" way?</p>
|
[
{
"answer_id": 238447,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "public class Duo<TFirst,TSecond> { /*...*/ }\npublic class Trio<TFirst,TSecond, TThird> { /*...*/ }\n public static class Group{\n\npublic static Duo<TFirst, TSecond> Duo(TFirst first, TSecond second) { \n return new Duo<TFirst, TSecond>(first, second);\n } \n/*...*/\n}\n"
},
{
"answer_id": 238448,
"author": "Tim Scott",
"author_id": 29493,
"author_profile": "https://Stackoverflow.com/users/29493",
"pm_score": 1,
"selected": false,
"text": "ViewData[\"foo\"] = myFoo;\nViewData[\"bar\"] = myBar;\n"
},
{
"answer_id": 238469,
"author": "David P",
"author_id": 13145,
"author_profile": "https://Stackoverflow.com/users/13145",
"pm_score": 5,
"selected": true,
"text": "namespace Core.Presentation\n{\n public class SearchPresentation\n {\n public IList<StateProvince> StateProvinces { get; set; }\n public IList<Country> Countries { get; set; }\n public IList<Gender> Genders { get; set; }\n public IList<AgeRange> AgeRanges { get; set; }\n }\n}\n public partial class Search : ViewPage<SearchPresentation>\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2017/"
] |
238,437
|
<p>In ASP.NET MVC, you can mark up a controller method with <code>AuthorizeAttribute</code>, like this:</p>
<pre><code>[Authorize(Roles = "CanDeleteTags")]
public void Delete(string tagName)
{
// ...
}
</code></pre>
<p>This means that, if the currently logged-in user is not in the "CanDeleteTags" role, the controller method will never be called.</p>
<p>Unfortunately, for failures, <code>AuthorizeAttribute</code> returns <code>HttpUnauthorizedResult</code>, which always returns HTTP status code 401. This causes a redirection to the login page.</p>
<p>If the user isn't logged in, this makes perfect sense. However, if the user is <em>already</em> logged in, but isn't in the required role, it's confusing to send them back to the login page.</p>
<p>It seems that <code>AuthorizeAttribute</code> conflates authentication and authorization.</p>
<p>This seems like a bit of an oversight in ASP.NET MVC, or am I missing something?</p>
<p>I've had to cook up a <code>DemandRoleAttribute</code> that separates the two. When the user isn't authenticated, it returns HTTP 401, sending them to the login page. When the user is logged in, but isn't in the required role, it creates a <code>NotAuthorizedResult</code> instead. Currently this redirects to an error page.</p>
<p>Surely I didn't have to do this?</p>
|
[
{
"answer_id": 705485,
"author": "Alan Jackson",
"author_id": 72995,
"author_profile": "https://Stackoverflow.com/users/72995",
"pm_score": 5,
"selected": false,
"text": "// User was redirected here because of authorization section\nif (User.Identity != null && User.Identity.IsAuthenticated)\n Response.Redirect(\"Unauthorized.aspx\");\n"
},
{
"answer_id": 5844884,
"author": "ShadowChaser",
"author_id": 497666,
"author_profile": "https://Stackoverflow.com/users/497666",
"pm_score": 9,
"selected": true,
"text": "AuthorizeAttribute [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]\npublic class AuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute\n{\n protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)\n {\n if (filterContext.HttpContext.Request.IsAuthenticated)\n {\n filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);\n }\n else\n {\n base.HandleUnauthorizedRequest(filterContext);\n }\n }\n}\n"
},
{
"answer_id": 27850037,
"author": "Kareem Cambridge",
"author_id": 4434720,
"author_profile": "https://Stackoverflow.com/users/4434720",
"pm_score": 0,
"selected": false,
"text": "if (HttpContext.Current.Response.Status.StartsWith(\"302\") && HttpContext.Current.Request.Url.ToString().Contains(\"/<restricted_path>/\"))\n{\n HttpContext.Current.Response.ClearContent();\n Response.Redirect(\"~/AccessDenied.aspx\");\n}\n"
},
{
"answer_id": 48797711,
"author": "Greg Gum",
"author_id": 425823,
"author_profile": "https://Stackoverflow.com/users/425823",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing Microsoft.AspNetCore.Mvc;\nusing Microsoft.AspNetCore.Mvc.Filters;\n\nnamespace Core\n{\n [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]\n public class AuthorizeApiAttribute : Microsoft.AspNetCore.Authorization.AuthorizeAttribute, IAuthorizationFilter\n {\n public void OnAuthorization(AuthorizationFilterContext context)\n {\n var user = context.HttpContext.User;\n\n if (!user.Identity.IsAuthenticated)\n {\n context.Result = new UnauthorizedResult();\n return;\n }\n }\n }\n}\n"
},
{
"answer_id": 55228016,
"author": "César León",
"author_id": 4905197,
"author_profile": "https://Stackoverflow.com/users/4905197",
"pm_score": 0,
"selected": false,
"text": "if (User != null && User.Identity.IsAuthenticated && Response.StatusCode == 401)\n{\n //Do whatever\n\n //In my case redirect to error page\n Response.RedirectToRoute(\"Default\", new { controller = \"Home\", action = \"ErrorUnauthorized\" });\n}\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446/"
] |
238,441
|
<p>I have worked on projects for embedded systems in the past where we have rearranged the order of declaration of stack variables to decrease the size of the resulting executable. For instance, if we had:</p>
<pre><code>void func()
{
char c;
int i;
short s;
...
}
</code></pre>
<p>We would reorder this to be:</p>
<pre><code>void func()
{
int i;
short s;
char c;
...
}
</code></pre>
<p>Because of alignment issues the first one resulted in 12 bytes of stack space being used and the second one resulted in only 8 bytes.</p>
<p>Is this standard behavior for C compilers or just a shortcoming of the compiler we were using? </p>
<p>It seems to me that a compiler should be able to reorder stack variables to favor smaller executable size if it wanted to. It has been suggested to me that some aspect of the C standard prevents this, but I haven't been able to find a reputable source either way.</p>
<p>As a bonus question, does this also apply to C++ compilers?</p>
<p><strong>Edit</strong></p>
<p>If the answer is yes, C/C++ compilers can rearrange stack variables, can you give an example of a compiler that definitely does this? I'd like to see compiler documentation or something similar that backs this up.</p>
<p><strong>Edit Again</strong></p>
<p>Thanks everybody for your help. For documentation, the best thing I've been able to find is the paper <a href="http://mirror-fpt-telecom.fpt.net/gcc/summit/2003/Optimal%20Stack%20Slot%20Assignment.pdf" rel="noreferrer">Optimal Stack Slot Assignment in GCC</a>(pdf), by Naveen Sharma and Sanjiv Kumar Gupta, which was presented at the GCC summit proceedings in 2003.</p>
<p>The project in question here was using the ADS compiler for ARM development. It is mentioned in the documentation for that compiler that ordering declarations like I've shown can improve performance, as well as stack size, because of how the ARM-Thumb architecture calculates addresses in the local stack frame. That compiler didn't automatically rearrange locals to take advantage of this. The paper linked here says that as of 2003 GCC also didn't rearrange the stack frame to improve locality of reference for ARM-Thumb processors, but it implies that you could.</p>
<p>I can't find anything that definitely says this was ever implemented in GCC, but I think this paper counts as proof that you're all correct. Thanks again.</p>
|
[
{
"answer_id": 243740,
"author": "Malkocoglu",
"author_id": 31152,
"author_profile": "https://Stackoverflow.com/users/31152",
"pm_score": 0,
"selected": false,
"text": "#pragma pack(push, 16)\n\ntypedef struct _S_speedy_struct{\n\n double fval[4];\n int64 lval[4];\n int32 ival[8];\n\n}S_speedy_struct;\n\n#pragma pack(pop)\n\nint function(...)\n{\n int i, t, rv;\n S_speedy_struct *ptr;\n char buff[112]; // sizeof(struct) + alignment\n\n // ugly , I know , but it works...\n t = (int)buff;\n t += 15; // alignment - 1\n t &= -16; // alignment\n ptr = (S_speedy_struct *)t;\n\n // speedy code goes on...\n}\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13728/"
] |
238,449
|
<p>How do I configure SSRS/Windows Server 2003, so that I can setup email delivery via a remote SMTP server that requires username and password.</p>
<p>I can configure SSRS with an SMTP address and other parameters, but nowhere is it possible to configure it with smtp username and password. </p>
<p>I have hunted around, but can only find vague reference to setting up some sort of relay, to cover up the bizarre lack of smtp functionality that SSRS has out of the box. </p>
<p>Any ideas?</p>
|
[
{
"answer_id": 511691,
"author": "Tom Willwerth",
"author_id": 3334,
"author_profile": "https://Stackoverflow.com/users/3334",
"pm_score": 3,
"selected": false,
"text": "<SMTPServer>x.x.x.x</SMTPServer> <From>you@yourwebserver.com</From> <SendEmailToUserAlias>False</SendEmailToUserAlias> <PermittedHosts> <HostName>yourwebsite.com</HostName> </PermittedHosts>"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1982/"
] |
238,451
|
<p>I'm trying to set up Eclipse for php web development. What I would like to do is preview a php web page from within Eclipse, but I cannot figure out how to do this. Is there an integrated web server of some sort that allows this, or do I have to set up IIS/Apache to do it? If so, do I have to have my php files in the web servers path, or does Eclipse auto deploy the files to the local web server? Any information or links would be very much appreciated.</p>
|
[
{
"answer_id": 238593,
"author": "acrosman",
"author_id": 24215,
"author_profile": "https://Stackoverflow.com/users/24215",
"pm_score": 2,
"selected": false,
"text": "http://localhost/project_name/file.php\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3291/"
] |
238,452
|
<p>I am familiar with C++ RTTI, and find the concept interesting.</p>
<p>Still there exist a lot of more ways to abuse it than to use it correctly (the RTTI-switch dread comes to mind). As a developer, I found (and used) only two viable uses for it (more exactly, one and a half).</p>
<p><strong>Could you share some of the ways RTTI is a viable solution to a problem, with example code/pseudo-code included?</strong></p>
<p>Note: The aim is to have a repository of viable examples a junior developer can consult, criticize and learn from.</p>
<p><strong>Edit:</strong> You'll find below code using C++ RTTI</p>
<pre><code>// A has a virtual destructor (i.e. is polymorphic)
// B has a virtual destructor (i.e. is polymorphic)
// B does (or does not ... pick your poison) inherits from A
void doSomething(A * a)
{
// typeid()::name() returns the "name" of the object (not portable)
std::cout << "a is [" << typeid(*a).name() << "]"<< std::endl ;
// the dynamic_cast of a pointer to another will return NULL is
// the conversion is not possible
if(B * b = dynamic_cast<B *>(a))
{
std::cout << "a is b" << std::endl ;
}
else
{
std::cout << "a is NOT b" << std::endl ;
}
}
</code></pre>
|
[
{
"answer_id": 238509,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 3,
"selected": false,
"text": "this class base\n{\n void foo(base *b) = 0; // dynamic on the parameter type as well\n};\n\nclass B : public base {...}\nclass B1 : public B {...}\nclass B2 : public B {...}\n\nclass A : public base\n{\n void foo(base *b)\n {\n if (B1 *b1=dynamic_cast<B1*>(b))\n doFoo(b1);\n else if (B2 *b2=dynamic_cast<B2*>(b))\n doFoo(b2);\n }\n};\n"
},
{
"answer_id": 238515,
"author": "KeyserSoze",
"author_id": 14116,
"author_profile": "https://Stackoverflow.com/users/14116",
"pm_score": 2,
"selected": false,
"text": "SimModel* SimDatabase::FindModel<type*>(char* name=\"\")\n{\n foreach(SimModel* mo in ModelList)\n if(name == \"\" || mo->name eq name)\n {\n if(dynamic_cast<type*>mo != NULL)\n {\n return dynamic_cast<type*>mo;\n }\n }\n return NULL;\n}\n class public SimModel\n{\n public:\n void RunModel()=0;\n};\n class EngineModelInterface : public SimModel\n{\n public:\n float RPM()=0;\n float FuelFlow()=0;\n void SetThrottle(float setting)=0; \n};\n class LycomingIO540 : public EngineModelInterface \n{\n public:\n float RPM()\n {\n return rpm;\n }\n float FuelFlow()\n {\n return throttleSetting * 10.0;\n }\n void SetThrottle(float setting) \n {\n throttleSetting = setting\n }\n void RunModel() // from SimModel base class\n {\n if(throttleSetting > 0.5)\n rpm += 1;\n else\n rpm -= 1;\n }\n private:\n float rpm, throttleSetting;\n};\nclass Continental350: public EngineModelInterface \n{\n public:\n float RPM()\n {\n return rand();\n }\n float FuelFlow()\n {\n return rand;\n }\n void SetThrottle(float setting) \n {\n }\n void RunModel() // from SimModel base class\n {\n }\n};\n .\n.\nEngineModelInterface * eng = simDB.FindModel<EngineModelInterface *>();\n.\n.\nfuel = fuel - deltaTime * eng->FuelFlow(); \n.\n.\n.\n qobject_cast dynamic_cast dynamic_cast"
},
{
"answer_id": 238685,
"author": "Zan Lynx",
"author_id": 13422,
"author_profile": "https://Stackoverflow.com/users/13422",
"pm_score": 3,
"selected": false,
"text": "D* obj = dynamic_cast<D*>(base);\nif (obj) {\n for(unsigned i=0; i<1000; ++i)\n f(obj->D::key(i));\n }\n} else {\n for(unsigned i=0; i<1000; ++i)\n f(base->key(i));\n }\n}\n"
},
{
"answer_id": 240155,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 2,
"selected": false,
"text": "static_cast dynamic_cast struct top {\n};\n\nstruct left : top { \n int i;\n left() : i(42) {}\n};\n\nstruct right : top {\n std::string name;\n right() : name(\"plonk\") { }\n};\n\nstruct bottom : left, right {\n};\n\nbottom b;\nleft* p = &b;\n\n//right* r = static_cast<right*>(p); // Compilation error!\n//right* r = (right*)p; // Gives bad pointer silently \nright* r = dynamic_cast<right*>(p); // OK\n"
},
{
"answer_id": 3277561,
"author": "Albert",
"author_id": 133374,
"author_profile": "https://Stackoverflow.com/users/133374",
"pm_score": 1,
"selected": false,
"text": "dynamic_cast operator== operator< boost::any Client std::set<Player*> NetPlayer LocalPlayer LocalPlayer LocalPlayer* Client::localPlayer() Client Variable Variable std::set<Variable*> vars BuiltinVar std::vector<BuiltinVar> builtins Variable* BuiltinVar* builtins dynamic_cast BuiltinVar GameObject Player GameObject bool GameObject::isPlayer() Player Object::isOfTypeXY() Object::checkScore_doThisActionOnlyIfIAmAPlayer() dynamic_cast TaskManager Task Task Task"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14089/"
] |
238,460
|
<p>When I use the default model binding to bind form parameters to a complex object which is a parameter to an action, the framework remembers the values passed to the first request, meaning that any subsequent request to that action gets the same data as the first. The parameter values and validation state are persisted between unrelated web requests.</p>
<p>Here is my controller code (<code>service</code> represents access to the back end of the app):</p>
<pre><code> [AcceptVerbs(HttpVerbs.Get)]
public ActionResult Create()
{
return View(RunTime.Default);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(RunTime newRunTime)
{
if (ModelState.IsValid)
{
service.CreateNewRun(newRunTime);
TempData["Message"] = "New run created";
return RedirectToAction("index");
}
return View(newRunTime);
}
</code></pre>
<p>My .aspx view (strongly typed as <code>ViewPage<RunTime</code>>) contains directives like: </p>
<pre><code><%= Html.TextBox("newRunTime.Time", ViewData.Model.Time) %>
</code></pre>
<p>This uses the <code>DefaultModelBinder</code> class, which is <a href="http://weblogs.asp.net/scottgu/archive/2008/10/16/asp-net-mvc-beta-released.aspx#three" rel="nofollow noreferrer">meant to autobind my model's properties</a>.</p>
<p>I hit the page, enter valid data (e.g. time = 1). The app correctly saves the new object with time = 1. I then hit it again, enter different valid data (e.g. time = 2). However the data that gets saved is the original (e.g. time = 1). This also affects validation, so if my original data was invalid, then all data I enter in the future is considered invalid. Restarting IIS or rebuilding my code flushes the persisted state.</p>
<p>I can fix the problem by writing my own hard-coded model binder, a basic naive example of which is shown below. </p>
<pre><code> [AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([ModelBinder(typeof (RunTimeBinder))] RunTime newRunTime)
{
if (ModelState.IsValid)
{
service.CreateNewRun(newRunTime);
TempData["Message"] = "New run created";
return RedirectToAction("index");
}
return View(newRunTime);
}
internal class RunTimeBinder : DefaultModelBinder
{
public override ModelBinderResult BindModel(ModelBindingContext bindingContext)
{
// Without this line, failed validation state persists between requests
bindingContext.ModelState.Clear();
double time = 0;
try
{
time = Convert.ToDouble(bindingContext.HttpContext.Request[bindingContext.ModelName + ".Time"]);
}
catch (FormatException)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName + ".Time", bindingContext.HttpContext.Request[bindingContext.ModelName + ".Time"] + "is not a valid number");
}
var model = new RunTime(time);
return new ModelBinderResult(model);
}
}
</code></pre>
<p>Am I missing something? I don't think it's a browser session problem as I can reproduce the problem if the first data is entered in one browser and the second in another.</p>
|
[
{
"answer_id": 240829,
"author": "Eilon",
"author_id": 31668,
"author_profile": "https://Stackoverflow.com/users/31668",
"pm_score": 2,
"selected": false,
"text": "[AcceptVerbs(HttpVerbs.Get)]\npublic ActionResult Create() {\n return View(RunTime.Default);\n}\n\n[AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult Create(RunTime newRunTime) {\n if (ModelState.IsValid) {\n //service.CreateNewRun(newRunTime);\n TempData[\"Message\"] = \"New run created\";\n TempData[\"value\"] = newRunTime.TheValue;\n return RedirectToAction(\"index\");\n }\n return View(newRunTime);\n}\n <% using (Html.BeginForm()) { %>\n<%= Html.TextBox(\"newRunTime.TheValue\", ViewData.Model.TheValue) %>\n<input type=\"submit\" value=\"Save\" />\n<% } %>\n public class RunTime {\n public static readonly RunTime Default = new RunTime(-1);\n\n public RunTime() {\n }\n\n public RunTime(int theValue) {\n TheValue = theValue;\n }\n\n public int TheValue {\n get;\n set;\n }\n }\n"
},
{
"answer_id": 240857,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 2,
"selected": false,
"text": "object htmlAttributes string value ViewData.Model.Time.ToString()"
},
{
"answer_id": 256821,
"author": "Alex Scordellis",
"author_id": 12006,
"author_profile": "https://Stackoverflow.com/users/12006",
"pm_score": 0,
"selected": false,
"text": "ModelState DefaultModelBinder ModelState"
},
{
"answer_id": 258188,
"author": "Jason",
"author_id": 7391,
"author_profile": "https://Stackoverflow.com/users/7391",
"pm_score": 0,
"selected": false,
"text": " if (_container == null) \n {\n _container = new WindsorContainer(\"config/castle.config\");\n ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(Container)); \n }\n return (IController)_container.Resolve(controllerType);\n <component \n id=\"home.controller\" \n type=\"DoYourStuff.Controllers.HomeController, DoYourStuff\" \n lifestyle=\"transient\" />\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12006/"
] |
238,465
|
<p>Back in the 90s when I first started out with MFC I used to dynamically link my apps and shipped the relevant MFC DLLs. This caused me a few issues (DLL hell!) and I switched to statically linking instead - not just for MFC, but for the CRT and ATL. Other than larger EXE files, statically linking has never caused me any problems at all - so are there any downsides that other people have come across? Is there a good reason for revisiting dynamic linking again? My apps are mainly STL/Boost nowadays FWIW.</p>
|
[
{
"answer_id": 238493,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 1,
"selected": false,
"text": "p = new LibClass() delete p;"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
238,466
|
<p>How do you access the items collection of a combo box in a specific row in a DataGridView?</p>
<p>I'm populating the combo as follows:</p>
<pre><code> Dim VATCombo As New DataGridViewComboBoxColumn
With VATCombo
.HeaderText = "VAT Rate"
.Name = .HeaderText
Dim VATCol As New JCVATRateCollection
VATCol.LoadAll(EntitySpaces.Interfaces.esSqlAccessType.StoredProcedure)
For Each Rate As JCVATRate In VATCol
.Items.Add(Rate.str.VATRate)
Next
.Sorted = True
VATCol = Nothing
.ToolTipText = "Select VAT Rate"
.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
.CellTemplate.Style.BackColor = Color.Honeydew
.DisplayIndex = 8
.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End With
.Columns.Add(VATCombo)
VATCombo = Nothing
</code></pre>
<p>I want to be able to set a default value for each new line added to the grid, I also want to be able to change the values in the combo based on other business logic. I realise I can just set the cell value directly but I want to avoid hard-coding the values into the system and rely on the database to populate.</p>
<p>I'm sure it must be straight-forward but it's eluding me.....</p>
|
[
{
"answer_id": 255989,
"author": "CestLaGalere",
"author_id": 6684,
"author_profile": "https://Stackoverflow.com/users/6684",
"pm_score": 2,
"selected": true,
"text": "Imports System.Collections.Generic\nImports System.Drawing\nImports System.Windows.Forms\n\nFriend Class ComboEditingControl\nInherits ComboBox\nImplements IDataGridViewEditingControl\n\nPrivate dataGridViewControl As DataGridView\nPrivate valueIsChanged As Boolean = False\nPrivate rowIndexNum As Integer\nPrivate ItemSelected As String\n\nPublic Sub New()\n Me.DropDownStyle = ComboBoxStyle.DropDownList\nEnd Sub\n\n\nPublic Property EditingControlFormattedValue() As Object _\n Implements IDataGridViewEditingControl.EditingControlFormattedValue\n\n Get\n Return ItemSelected\n End Get\n\n Set(ByVal value As Object)\n If TypeOf value Is Decimal Then\n Me.SelectedItem = value.ToString()\n End If\n End Set\nEnd Property\n\n\nPublic Function GetEditingControlFormattedValue(ByVal context As DataGridViewDataErrorContexts) As Object _\n Implements IDataGridViewEditingControl.GetEditingControlFormattedValue\n Return ItemSelected\nEnd Function\n\nPublic ReadOnly Property EditingControlCursor() As Cursor _\n Implements IDataGridViewEditingControl.EditingPanelCursor\n Get\n Return MyBase.Cursor\n End Get\nEnd Property\n\nPublic Sub ApplyCellStyleToEditingControl(ByVal dataGridViewCellStyle As DataGridViewCellStyle) _\n Implements IDataGridViewEditingControl.ApplyCellStyleToEditingControl\n\n Me.Font = dataGridViewCellStyle.Font\n Me.ForeColor = dataGridViewCellStyle.ForeColor\n Me.BackColor = dataGridViewCellStyle.BackColor\n\nEnd Sub\n\nPublic Property EditingControlRowIndex() As Integer _\n Implements IDataGridViewEditingControl.EditingControlRowIndex\n\n Get\n Return rowIndexNum\n End Get\n Set(ByVal value As Integer)\n rowIndexNum = value\n End Set\n\nEnd Property\n\nPublic Function EditingControlWantsInputKey(ByVal key As Keys, ByVal dataGridViewWantsInputKey As Boolean) As Boolean _\n Implements IDataGridViewEditingControl.EditingControlWantsInputKey\n\n ' Let the DateTimePicker handle the keys listed.\n Select Case key And Keys.KeyCode\n Case Keys.Up, Keys.Down, Keys.Home, Keys.End, Keys.PageDown, Keys.PageUp\n Return True\n Case Else\n Return False\n End Select\nEnd Function\n\nPublic Sub PrepareEditingControlForEdit(ByVal selectAll As Boolean) _\n Implements IDataGridViewEditingControl.PrepareEditingControlForEdit\n ' No preparation needs to be done.\nEnd Sub\n\nPublic ReadOnly Property RepositionEditingControlOnValueChange() As Boolean Implements _\n IDataGridViewEditingControl.RepositionEditingControlOnValueChange\n Get\n Return False\n End Get\nEnd Property\n\nPublic Property EditingControlDataGridView() As DataGridView _\n Implements IDataGridViewEditingControl.EditingControlDataGridView\n\n Get\n Return dataGridViewControl\n End Get\n Set(ByVal value As DataGridView)\n dataGridViewControl = value\n End Set\n\nEnd Property\n\nPublic Property EditingControlValueChanged() As Boolean _\n Implements IDataGridViewEditingControl.EditingControlValueChanged\n\n Get\n Return valueIsChanged\n End Get\n Set(ByVal value As Boolean)\n valueIsChanged = value\n End Set\nEnd Property\n\n\n''' <summary>\n''' Notify the DataGridView that the contents of the cell have changed.\n''' </summary>\n''' <param name=\"eventargs\"></param>\n''' <remarks></remarks>\nProtected Overrides Sub OnSelectedIndexChanged(ByVal eventargs As EventArgs)\n valueIsChanged = True\n dataGridViewControl.NotifyCurrentCellDirty(True)\n MyBase.OnSelectedItemChanged(eventargs)\n ItemSelected = SelectedItem.ToString()\nEnd Sub\nEnd Class\n Friend Class ComboColumn\n Inherits DataGridViewColumn\n\n Public Sub New()\n MyBase.New(New ComboCell())\n End Sub\n\n Public Overrides Property CellTemplate() As DataGridViewCell\n Get\n Return MyBase.CellTemplate\n End Get\n Set(ByVal value As DataGridViewCell)\n ' Ensure that the cell used for the template is a ComboCell.\n If Not (value Is Nothing) AndAlso Not value.GetType().IsAssignableFrom(GetType(ComboCell)) Then\n Throw New InvalidCastException(\"Must be a ComboCell\")\n End If\n MyBase.CellTemplate = value\n End Set\n End Property\nEnd Class\n\nFriend Class ComboCell\n Inherits DataGridViewTextBoxCell\n\n Public Sub New()\n End Sub\n\n Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, ByVal initialFormattedValue As Object, ByVal dataGridViewCellStyle As DataGridViewCellStyle)\n ' Set the value of the editing control to the current cell value.\n MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle)\n\n Dim ctl As ComboEditingControl = CType(DataGridView.EditingControl, ComboEditingControl)\n\n Dim GetValueFromRowToUseForBuildingCombo As String = Me.DataGridView.Rows(rowIndex).Cells(0).Value.ToString()\n\n ctl.Items.Clear()\n For Each thing As String In ACollection\n ctl.Items.Add(Sheet)\n Next\n\n\n If Me.Value Is Nothing Then\n ctl.SelectedIndex = -1\n Else\n ctl.SelectedItem = Me.Value\n End If\n End Sub\n\n Public Overrides ReadOnly Property EditType() As Type\n Get\n Return GetType(ComboEditingControl)\n End Get\n End Property\n\n Public Overrides ReadOnly Property ValueType() As Type\n Get\n Return GetType(String)\n End Get\n End Property\n\n Public Overrides ReadOnly Property FormattedValueType() As System.Type\n Get\n Return GetType(String)\n End Get\n End Property\n\n Public Overrides ReadOnly Property DefaultNewRowValue() As Object\n Get\n Return \"\"\n End Get\n End Property\nEnd Class\n Dim c As New ComboColumn\nc.HeaderText = \"Sheet\"\nc.DataPropertyName = \"My Combo\"\nc.ToolTipText = \"Select something from my combo\"\nMyDataGridView.Columns.Add(c)\n ThisRow.Cells(ComboCol).Value"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20048/"
] |
238,473
|
<p>I want to make a really simple iphone app: one screen with a single button... when the button is tapped a new screen appears. That's it. No animations, nothing,</p>
<p>I've tried endlessly to make the NavBar sample project do this... and it works but only if I use a UINavigationController with a table that I can tap etc. I've tried all the skeleton projects in XCode too.</p>
<p>I thought I was done when I did this:</p>
<pre><code>[[self navigationController] presentModalViewController:myViewController animated:YES];
</code></pre>
<p>But I couldn't do it without the UINavigationController. I just want a simple example.</p>
<p>Thanks so much!</p>
|
[
{
"answer_id": 238477,
"author": "kdbdallas",
"author_id": 26728,
"author_profile": "https://Stackoverflow.com/users/26728",
"pm_score": 4,
"selected": true,
"text": "LoginView *login = [[LoginView alloc] initWithFrame: rect];\n[mainView addSubview: login];\n"
},
{
"answer_id": 238795,
"author": "Colin Barrett",
"author_id": 23106,
"author_profile": "https://Stackoverflow.com/users/23106",
"pm_score": 1,
"selected": false,
"text": "UINavigationController viewDidLoad UIControlEventTouchUpInside [self.navigationController pushViewController:[[[SecondViewControllerClass alloc] initWithNib:nibName bundle:nil] autorelease]];\n"
},
{
"answer_id": 762952,
"author": "Isaac Waller",
"author_id": 764272,
"author_profile": "https://Stackoverflow.com/users/764272",
"pm_score": 3,
"selected": false,
"text": "[self presentModalViewController:myViewController animated:NO];\n [self dismissModalViewControllerAnimated:NO];\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22471/"
] |
238,504
|
<p>Is it possible to load child entities in a <strong><em>single</em></strong> query without using DataLoadOptions?</p>
<p>I am using one data context per request in an asp.net web application and trying to get around the linq to sql limitation of not being able to change dataloadoptions once a query has been executed.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 238696,
"author": "bh213",
"author_id": 28912,
"author_profile": "https://Stackoverflow.com/users/28912",
"pm_score": 0,
"selected": false,
"text": "from a in Albums join o in Users on a.Owner equals o select new {a, o}\n"
},
{
"answer_id": 238761,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 0,
"selected": false,
"text": "Person p = ctx.Persons.First();\np.Addresses.Load();\n"
},
{
"answer_id": 245402,
"author": "user24358",
"author_id": 24358,
"author_profile": "https://Stackoverflow.com/users/24358",
"pm_score": 1,
"selected": false,
"text": " Public Function GetSubjectsWithBooks() As List(Of Subject)\n Dim results As IMultipleResults = Me.GetSubjectAndBooks\n Dim Subjects = results.GetResult(Of Subject).ToList\n Dim Books = results.GetResult(Of Book).ToList\n For Each s In Subjects\n Dim thisId As Guid = s.ID\n s.FetchedBooks = (From b In Books Where b.SubjectId = thisId).ToList\n Next\n Return Subjects\n End Function\n"
},
{
"answer_id": 245451,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 1,
"selected": false,
"text": "LazyList<T> var categories = (from c in _db.Categories\n select new Category\n {\n CategoryID = c.CategoryID,\n CategoryName = c.CategoryName,\n ParentCategoryID = c.ParentCategoryID,\n SubCategories = new LazyList<Category>(\n from sc in _db.Categories\n where sc.ParentCategoryID == c.CategoryID\n select new Category\n {\n CategoryID = sc.CategoryID,\n CategoryName = sc.CategoryName,\n ParentCategoryID = sc.ParentCategoryID\n })\n });\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24358/"
] |
238,517
|
<p>I have intermittent crashes occurring in my ActiveMQ libraries due to the way I'm using the activemq-cpp API. It'd be much easier to debug the issue if I could observe every function being called leading up to the crash. Are there any quick ways to trace the entry and exit of functions in a Visual Studio 2005 c++ multithreaded program?</p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 238522,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 3,
"selected": true,
"text": "\nclass Tracer\n{\npublic:\n Tracer(const char *functionName) : functionName_(functionName)\n {\n cout << \"Entering function \" << functionName_ << endl;\n }\n\n ~Tracer()\n {\n cout << \"Exiting function \" << functionName_ << endl;\n }\n\n const char *functionName_;\n};\n \nvoid foo()\n{\n Tracer t(\"foo\");\n ...\n}\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191808/"
] |
238,523
|
<p>If I want to move to C++ and SDL in the future, is Python and pygame a good way to learn SDL?</p>
|
[
{
"answer_id": 239464,
"author": "ulukyn",
"author_id": 31748,
"author_profile": "https://Stackoverflow.com/users/31748",
"pm_score": 2,
"selected": false,
"text": "import pygame, sys,os\nfrom pygame.locals import * \n\npygame.init() \n\nwindow = pygame.display.set_mode((468, 60)) \npygame.display.set_caption('Monkey Fever') \nscreen = pygame.display.get_surface() \n\nmonkey_head_file_name = os.path.join(\"data\",\"chimp.bmp\")\n\nmonkey_surface = pygame.image.load(monkey_head_file_name)\n\nscreen.blit(monkey_surface, (0,0)) \npygame.display.flip() \n\ndef input(events): \n for event in events: \n if event.type == QUIT: \n sys.exit(0) \n else: \n print event \n\nwhile True: \n input(pygame.event.get())\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
238,525
|
<p>I've been running the built-in <a href="http://ant.apache.org/" rel="nofollow noreferrer">Ant</a> from the command line on a Macintosh (10.5.5) and have run into some trouble with the <strong>Mail</strong> task. Running the Mail task produces the following message:</p>
<pre><code>[mail] Failed to initialise MIME mail: org.apache.tools.ant.taskdefs.email.MimeMailer
</code></pre>
<p>This is most likely due to a missing ant-javamail.jar file in the /usr/share/ant/lib directory. I see a "ant-javamail-1.7.0.pom" file in this directory but not the appropriate jar file. Anyone know why this jar file might be missing and what the best way to resolve the problem is?</p>
|
[
{
"answer_id": 239516,
"author": "npellow",
"author_id": 2767300,
"author_profile": "https://Stackoverflow.com/users/2767300",
"pm_score": 1,
"selected": false,
"text": "ant -f fetch all\n all load all the libraries\n antlr load antlr libraries\n bcel load bcel libraries\n beanshell load beanshell support\n bsf load bsf libraries\n debugging internal ant debugging\n get-m2 Download the Maven2 Ant tasks\n jdepend load jdepend libraries\n jruby load jruby\n junit load junit libraries\n jython load jython\n logging load logging libraries\n networking load networking libraries (commons-net; jsch)\n regexp load regexp libraries\n rhino load rhino\n script load script languages\n xerces load an updated version of Xerces\n xml load full XML libraries (xalan, resolver)\n"
},
{
"answer_id": 265270,
"author": "Ken",
"author_id": 31629,
"author_profile": "https://Stackoverflow.com/users/31629",
"pm_score": 3,
"selected": true,
"text": "ln -s /usr/local/share/apache-ant-1.7.1/bin/ant /usr/bin/ant ln -s /usr/share/ant/bin/ant /usr/bin/ant"
},
{
"answer_id": 859744,
"author": "benzado",
"author_id": 10947,
"author_profile": "https://Stackoverflow.com/users/10947",
"pm_score": 0,
"selected": false,
"text": "~/.ant/lib apache-ant-1.7.0/lib/ant-javamail.jar"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31629/"
] |
238,535
|
<p>Is it more efficient for a class to access member variables or local variables? For example, suppose you have a (callback) method whose sole responsibility is to receive data, perform calculations on it, then pass it off to other classes. Performance-wise, would it make more sense to have a list of member variables that the method populates as it receives data? Or just declare local variables each time the callback method is called?</p>
<p>Assume this method would be called hundreds of times a second...</p>
<p>In case I'm not being clear, here's some quick examples:</p>
<pre><code>// use local variables
class thisClass {
public:
void callback( msg& msg )
{
int varA;
double varB;
std::string varC;
varA = msg.getInt();
varB = msg.getDouble();
varC = msg.getString();
// do a bunch of calculations
}
};
// use member variables
class thisClass {
public:
void callback( msg& msg )
{
m_varA = msg.getInt();
m_varB = msg.getDouble();
m_varC = msg.getString();
// do a bunch of calculations
}
private:
int m_varA;
double m_varB;
std::string m_varC;
};
</code></pre>
|
[
{
"answer_id": 238568,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 7,
"selected": true,
"text": "// stack variable: load into eax\nmov eax, [esp+10]\n\n// member variable: load into eax\nmov ecx, [adress of object]\nmov eax, [ecx+4]\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
238,537
|
<p>I am new to Access. I have a table full of records. I want to write a function to check if any id is null or empty. If so, I want to update it with xxxxx.
The check for id must be run through all tables in a database.
Can anyone provide some sample code?</p>
|
[
{
"answer_id": 238551,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 1,
"selected": false,
"text": "update TABLE set FIELD = 'xxxxxx' where ID is null\n"
},
{
"answer_id": 238709,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": -1,
"selected": false,
"text": "Function UpdateFieldWhereNull(DbPath As String, fieldName as String, newFieldValue as String) As Boolean\n 'This links to all the tables that reside in DbPath,\n ' whether or not they already reside in this database.\n 'This works when linking to an Access .mdb file, not to ODBC.\n 'This keeps the same table name on the front end as on the back end.\n Dim rs As Recordset\n\n On Error Resume Next\n\n 'get tables in back end database\n Set rs = CurrentDb.OpenRecordset(\"SELECT Name \" & _\n \"FROM MSysObjects IN '\" & DbPath & \"' \" & _\n \"WHERE Type=1 AND Flags=0\")\n If Err <> 0 Then Exit Function\n\n 'update field in tables\n While Not rs.EOF\n If DbPath <> Nz(DLookup(\"Database\", \"MSysObjects\", \"Name='\" & rs!Name & \"' And Type=6\")) Then\n\n 'UPDATE the field with new value if null\n DoCmd.RunSQL \"UPDATE \" & acTable & \" SET [\" & fieldName & \"] = '\" & newFieldValue & \"' WHERE [\" & fieldName & \"] IS NULL\"\n\n End If\n rs.MoveNext\n Wend\n rs.Close\n\n UpdateFieldWhereNull = True\nEnd Function\n\n\nSub CallUpdateFieldWhereNull()\n Dim Result As Boolean\n\n 'Sample call:\n Result = UpdateFieldWhereNull(\"C:\\Program Files\\Microsoft Office\\Office\\Samples\\Northwind.mdb\", \"ID\", \"xxxxxx\")\n Debug.Print Result\nEnd Sub\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
238,547
|
<p>I would like to be able to fetch a web page's html and save it to a <code>String</code>, so I can do some processing on it. Also, how could I handle various types of compression.</p>
<p>How would I go about doing that using Java?</p>
|
[
{
"answer_id": 238634,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 8,
"selected": true,
"text": "public static void main(String[] args) {\n URL url;\n InputStream is = null;\n BufferedReader br;\n String line;\n\n try {\n url = new URL(\"http://stackoverflow.com/\");\n is = url.openStream(); // throws an IOException\n br = new BufferedReader(new InputStreamReader(is));\n\n while ((line = br.readLine()) != null) {\n System.out.println(line);\n }\n } catch (MalformedURLException mue) {\n mue.printStackTrace();\n } catch (IOException ioe) {\n ioe.printStackTrace();\n } finally {\n try {\n if (is != null) is.close();\n } catch (IOException ioe) {\n // nothing to see here\n }\n }\n}\n"
},
{
"answer_id": 2582771,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 5,
"selected": false,
"text": "URL url = new URL(urlStr);\nHttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Cast shouldn't fail\nHttpURLConnection.setFollowRedirects(true);\n// allow both GZip and Deflate (ZLib) encodings\nconn.setRequestProperty(\"Accept-Encoding\", \"gzip, deflate\");\nString encoding = conn.getContentEncoding();\nInputStream inStr = null;\n\n// create the appropriate stream wrapper based on\n// the encoding type\nif (encoding != null && encoding.equalsIgnoreCase(\"gzip\")) {\n inStr = new GZIPInputStream(conn.getInputStream());\n} else if (encoding != null && encoding.equalsIgnoreCase(\"deflate\")) {\n inStr = new InflaterInputStream(conn.getInputStream(),\n new Inflater(true));\n} else {\n inStr = conn.getInputStream();\n}\n conn.setRequestProperty ( \"User-agent\", \"my agent name\");\n"
},
{
"answer_id": 4571551,
"author": "BalusC",
"author_id": 157882,
"author_profile": "https://Stackoverflow.com/users/157882",
"pm_score": 8,
"selected": false,
"text": "String html = Jsoup.connect(\"http://stackoverflow.com\").get().html();\n Document String Document document = Jsoup.connect(\"http://google.com\").get();\n"
},
{
"answer_id": 39023500,
"author": "Jan Bodnar",
"author_id": 2008247,
"author_profile": "https://Stackoverflow.com/users/2008247",
"pm_score": 0,
"selected": false,
"text": "package com.zetcode;\n\nimport org.eclipse.jetty.client.HttpClient;\nimport org.eclipse.jetty.client.api.ContentResponse;\n\npublic class ReadWebPageEx5 {\n\n public static void main(String[] args) throws Exception {\n\n HttpClient client = null;\n\n try {\n\n client = new HttpClient();\n client.start();\n \n String url = \"http://example.com\";\n\n ContentResponse res = client.GET(url);\n\n System.out.println(res.getContentAsString());\n\n } finally {\n\n if (client != null) {\n\n client.stop();\n }\n }\n }\n}\n"
},
{
"answer_id": 46949580,
"author": "A_01",
"author_id": 2683452,
"author_profile": "https://Stackoverflow.com/users/2683452",
"pm_score": -1,
"selected": false,
"text": "package test;\n\nimport java.net.*;\nimport java.io.*;\n\npublic class PDFTest {\n public static void main(String[] args) throws Exception {\n try {\n URL oracle = new URL(\"http://www.fetagracollege.org\");\n BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));\n\n String fileName = \"D:\\\\a_01\\\\output.txt\";\n\n PrintWriter writer = new PrintWriter(fileName, \"UTF-8\");\n OutputStream outputStream = new FileOutputStream(fileName);\n String inputLine;\n\n while ((inputLine = in.readLine()) != null) {\n System.out.println(inputLine);\n writer.println(inputLine);\n }\n in.close();\n } catch(Exception e) {\n\n }\n\n }\n}\n"
},
{
"answer_id": 47848212,
"author": "Sohaib Aslam",
"author_id": 8660085,
"author_profile": "https://Stackoverflow.com/users/8660085",
"pm_score": 0,
"selected": false,
"text": "public class MainActivity extends AppCompatActivity {\n\n EditText url;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate( savedInstanceState );\n setContentView( R.layout.activity_main );\n\n url = ((EditText)findViewById( R.id.editText));\n DownloadCode obj = new DownloadCode();\n\n try {\n String des=\" \";\n\n String tag1= \"<div class=\\\"description\\\">\";\n String l = obj.execute( \"http://www.nu.edu.pk/Campus/Chiniot-Faisalabad/Faculty\" ).get();\n\n url.setText( l );\n url.setText( \" \" );\n\n String[] t1 = l.split(tag1);\n String[] t2 = t1[0].split( \"</div>\" );\n url.setText( t2[0] );\n\n }\n catch (Exception e)\n {\n Toast.makeText( this,e.toString(),Toast.LENGTH_SHORT ).show();\n }\n\n }\n // input, extrafunctionrunparallel, output\n class DownloadCode extends AsyncTask<String,Void,String>\n {\n @Override\n protected String doInBackground(String... WebAddress) // string of webAddress separate by ','\n {\n String htmlcontent = \" \";\n try {\n URL url = new URL( WebAddress[0] );\n HttpURLConnection c = (HttpURLConnection) url.openConnection();\n c.connect();\n InputStream input = c.getInputStream();\n int data;\n InputStreamReader reader = new InputStreamReader( input );\n\n data = reader.read();\n\n while (data != -1)\n {\n char content = (char) data;\n htmlcontent+=content;\n data = reader.read();\n }\n }\n catch (Exception e)\n {\n Log.i(\"Status : \",e.toString());\n }\n return htmlcontent;\n }\n }\n}\n"
},
{
"answer_id": 53024745,
"author": "Supercoder",
"author_id": 9486645,
"author_profile": "https://Stackoverflow.com/users/9486645",
"pm_score": 2,
"selected": false,
"text": "import java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.URL;\n\nimport javax.net.ssl.HttpsURLConnection;\n\n/**\n * <b>Get the Html source from the secure url </b>\n */\npublic class HttpsClientUtil {\n public static void main(String[] args) throws Exception {\n String httpsURL = \"https://stackoverflow.com\";\n String FILENAME = \"c:\\\\temp\\\\filename.html\";\n BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME));\n URL myurl = new URL(httpsURL);\n HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();\n con.setRequestProperty ( \"User-Agent\", \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0\" );\n InputStream ins = con.getInputStream();\n InputStreamReader isr = new InputStreamReader(ins, \"Windows-1252\");\n BufferedReader in = new BufferedReader(isr);\n String inputLine;\n\n // Write each line into the file\n while ((inputLine = in.readLine()) != null) {\n System.out.println(inputLine);\n bw.write(inputLine);\n }\n in.close(); \n bw.close();\n }\n}\n"
},
{
"answer_id": 62395467,
"author": "Jan Tibar",
"author_id": 11820594,
"author_profile": "https://Stackoverflow.com/users/11820594",
"pm_score": 1,
"selected": false,
"text": "URL url = new URL( \"http://download.me/\" );\nFiles.copy( url.openStream(), Paths.get(\"downloaded.html\" ) );\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
] |
238,555
|
<p>How do I get the value of a <code>MemberInfo</code> object? <code>.Name</code> returns the name of the variable, but I need the value. </p>
<p>I think you can do this with <code>FieldInfo</code> but I don't have a snippet, if you know how to do this can you provide a snippet??</p>
<p>Thanks!</p>
|
[
{
"answer_id": 238562,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": false,
"text": "using System;\nusing System.Reflection;\n\npublic class Test\n{\n // public just for the sake of a short example.\n public int x;\n\n static void Main()\n {\n FieldInfo field = typeof(Test).GetField(\"x\");\n Test t = new Test();\n t.x = 10;\n\n Console.WriteLine(field.GetValue(t));\n }\n}\n"
},
{
"answer_id": 238663,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": "PropertyInfo prop.GetValue(obj, null); System.ComponentModel foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj))\n {\n Console.WriteLine(\"{0}={1}\", prop.Name, prop.GetValue(obj));\n }\n PropertyDescriptor prop = TypeDescriptor.GetProperties(obj)[\"SomeProperty\"];\n Console.WriteLine(\"{0}={1}\", prop.Name, prop.GetValue(obj));\n System.ComponentModel DataView"
},
{
"answer_id": 33446914,
"author": "EJHewy",
"author_id": 4736631,
"author_profile": "https://Stackoverflow.com/users/4736631",
"pm_score": 6,
"selected": false,
"text": " public static object GetValue(this MemberInfo memberInfo, object forObject)\n {\n switch (memberInfo.MemberType)\n {\n case MemberTypes.Field:\n return ((FieldInfo)memberInfo).GetValue(forObject);\n case MemberTypes.Property:\n return ((PropertyInfo)memberInfo).GetValue(forObject);\n default:\n throw new NotImplementedException();\n }\n } \n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/49611/"
] |
238,603
|
<p>How can I find out the size of a file I opened with an application written in C ?
I would like to know the size, because I want to put the content of the loaded file into a string, which I allocate using <code>malloc()</code>. Just writing <code>malloc(10000*sizeof(char));</code> is IMHO a bad idea. </p>
|
[
{
"answer_id": 238607,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 10,
"selected": true,
"text": "fseek(fp, 0L, SEEK_END);\nsz = ftell(fp);\n fseek(fp, 0L, SEEK_SET);\n rewind(fp);\n"
},
{
"answer_id": 238609,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 9,
"selected": false,
"text": "fseek(f, 0, SEEK_END); // seek to end of file\nsize = ftell(f); // get current file pointer\nfseek(f, 0, SEEK_SET); // seek back to beginning of file\n// proceed with allocating memory and reading the file\n stat fstat #include <sys/stat.h>\nstruct stat st;\nstat(filename, &st);\nsize = st.st_size;\n"
},
{
"answer_id": 238644,
"author": "PiedPiper",
"author_id": 19315,
"author_profile": "https://Stackoverflow.com/users/19315",
"pm_score": 7,
"selected": false,
"text": "fstat() #include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n\n// fd = fileno(f); //if you have a stream (e.g. from fopen), not a file descriptor.\nstruct stat buf;\nfstat(fd, &buf);\noff_t size = buf.st_size;\n"
},
{
"answer_id": 246855,
"author": "plan9assembler",
"author_id": 1710672,
"author_profile": "https://Stackoverflow.com/users/1710672",
"pm_score": -1,
"selected": false,
"text": "#include <stdio.h>\n\n#define MAXNUMBER 1024\n\nint main()\n{\n int i;\n char a[MAXNUMBER];\n\n FILE *fp = popen(\"du -b /bin/bash\", \"r\");\n\n while((a[i++] = getc(fp))!= 9)\n ;\n\n a[i] ='\\0';\n\n printf(\" a is %s\\n\", a);\n\n pclose(fp);\n return 0;\n} \n"
},
{
"answer_id": 1643801,
"author": "Pat Morin",
"author_id": 198911,
"author_profile": "https://Stackoverflow.com/users/198911",
"pm_score": 3,
"selected": false,
"text": "#define CHUNK 1024\n\n/* Read the contents of a file into a buffer. Return the size of the file \n * and set buf to point to a buffer allocated with malloc that contains \n * the file contents.\n */\nint read_file(FILE *fp, char **buf) \n{\n int n, np;\n char *b, *b2;\n\n n = CHUNK;\n np = n;\n b = malloc(sizeof(char)*n);\n while ((r = fread(b, sizeof(char), CHUNK, fp)) > 0) {\n n += r;\n if (np - n < CHUNK) { \n np *= 2; // buffer is too small, the next read could overflow!\n b2 = malloc(np*sizeof(char));\n memcpy(b2, b, n * sizeof(char));\n free(b);\n b = b2;\n }\n }\n *buf = b;\n return n;\n}\n"
},
{
"answer_id": 2003824,
"author": "lezard",
"author_id": 243621,
"author_profile": "https://Stackoverflow.com/users/243621",
"pm_score": 4,
"selected": false,
"text": "#include <fcntl.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/stat.h>\n\nvoid\nfseek_filesize(const char *filename)\n{\n FILE *fp = NULL;\n long off;\n\n fp = fopen(filename, \"r\");\n if (fp == NULL)\n {\n printf(\"failed to fopen %s\\n\", filename);\n exit(EXIT_FAILURE);\n }\n\n if (fseek(fp, 0, SEEK_END) == -1)\n {\n printf(\"failed to fseek %s\\n\", filename);\n exit(EXIT_FAILURE);\n }\n\n off = ftell(fp);\n if (off == -1)\n {\n printf(\"failed to ftell %s\\n\", filename);\n exit(EXIT_FAILURE);\n }\n\n printf(\"[*] fseek_filesize - file: %s, size: %ld\\n\", filename, off);\n\n if (fclose(fp) != 0)\n {\n printf(\"failed to fclose %s\\n\", filename);\n exit(EXIT_FAILURE);\n }\n}\n\nvoid\nfstat_filesize(const char *filename)\n{\n int fd;\n struct stat statbuf;\n\n fd = open(filename, O_RDONLY, S_IRUSR | S_IRGRP);\n if (fd == -1)\n {\n printf(\"failed to open %s\\n\", filename);\n exit(EXIT_FAILURE);\n }\n\n if (fstat(fd, &statbuf) == -1)\n {\n printf(\"failed to fstat %s\\n\", filename);\n exit(EXIT_FAILURE);\n }\n\n printf(\"[*] fstat_filesize - file: %s, size: %lld\\n\", filename, statbuf.st_size);\n\n if (close(fd) == -1)\n {\n printf(\"failed to fclose %s\\n\", filename);\n exit(EXIT_FAILURE);\n }\n}\n\nvoid\nstat_filesize(const char *filename)\n{\n struct stat statbuf;\n\n if (stat(filename, &statbuf) == -1)\n {\n printf(\"failed to stat %s\\n\", filename);\n exit(EXIT_FAILURE);\n }\n\n printf(\"[*] stat_filesize - file: %s, size: %lld\\n\", filename, statbuf.st_size);\n\n}\n\nvoid\nseek_filesize(const char *filename)\n{\n int fd;\n off_t off;\n\n if (filename == NULL)\n {\n printf(\"invalid filename\\n\");\n exit(EXIT_FAILURE);\n }\n\n fd = open(filename, O_RDONLY, S_IRUSR | S_IRGRP);\n if (fd == -1)\n {\n printf(\"failed to open %s\\n\", filename);\n exit(EXIT_FAILURE);\n }\n\n off = lseek(fd, 0, SEEK_END);\n if (off == -1)\n {\n printf(\"failed to lseek %s\\n\", filename);\n exit(EXIT_FAILURE);\n }\n\n printf(\"[*] seek_filesize - file: %s, size: %lld\\n\", filename, (long long) off);\n\n if (close(fd) == -1)\n {\n printf(\"failed to close %s\\n\", filename);\n exit(EXIT_FAILURE);\n }\n}\n\nint\nmain(int argc, const char *argv[])\n{\n int i;\n\n if (argc < 2)\n {\n printf(\"%s <file1> <file2>...\\n\", argv[0]);\n exit(0);\n }\n\n for(i = 1; i < argc; i++)\n {\n seek_filesize(argv[i]);\n stat_filesize(argv[i]);\n fstat_filesize(argv[i]);\n fseek_filesize(argv[i]);\n }\n\n return 0;\n}\n"
},
{
"answer_id": 5446759,
"author": "Earlz",
"author_id": 69742,
"author_profile": "https://Stackoverflow.com/users/69742",
"pm_score": 5,
"selected": false,
"text": "fsize int fsize(FILE *fp){\n int prev=ftell(fp);\n fseek(fp, 0L, SEEK_END);\n int sz=ftell(fp);\n fseek(fp,prev,SEEK_SET); //go back to where we were\n return sz;\n}\n /dev/null"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25017/"
] |
238,606
|
<p>I'm trying to make a simple C# web server that, at this stage, you can access via your browser and will just do a "Hello World". </p>
<p>The problem I'm having is that the server can receive data fine - I get the browser's header information - but the browser doesn't receive anything I send. Furthermore, I can only connect to the server by going to localhost (or 127.0.0.1). I can't get to it by going to my IP and it's not a network setting because Apache works fine if I run that instead. Also, I'm using a port monitoring program and after I attempt a connection from a browser, the process's port gets stuck in a TIME_WAIT state even though I told the connection to close and it should be back to LISTEN.</p>
<p>Here's the relevant code. A couple calls might not make sense but this is a piece of a larger program.</p>
<pre><code>class ConnectionHandler
{
private Server server;
private TcpListener tcp;
private ArrayList connections;
private bool listening;
private Thread listeningThread;
public Server getServer()
{
return server;
}
private void log(String s, bool e)
{
server.log("Connection Manager: " + s, e);
}
private void threadedListen()
{
while (listening)
{
try
{
TcpClient t = tcp.AcceptTcpClient();
Connection conn = new Connection(this, t);
}
catch (NullReferenceException)
{
log("unable to accept connections!", true);
}
}
log("Stopped listening", false);
}
public void listen()
{
log("Listening for new connections", false);
tcp.Start();
listening = true;
if (listeningThread != null && listeningThread.IsAlive)
{
listeningThread.Abort();
}
listeningThread = new Thread(new ThreadStart(
this.threadedListen));
listeningThread.Start();
}
public void stop()
{
listening = false;
if (listeningThread != null)
{
listeningThread.Abort();
log("Forced stop", false);
}
log("Stopped listening", false);
}
public ConnectionHandler(Server server)
{
this.server = server;
tcp = new TcpListener(new IPEndPoint(
IPAddress.Parse("127.0.0.1"), 80));
connections = new ArrayList();
}
}
class Connection
{
private Socket socket;
private TcpClient tcp;
private ConnectionHandler ch;
public Connection(ConnectionHandler ch, TcpClient t)
{
try
{
this.ch = ch;
this.tcp = t;
ch.getServer().log("new tcp connection to "
+ this.tcp.Client.RemoteEndPoint.ToString(), false);
NetworkStream ns = t.GetStream();
String responseString;
Byte[] response;
Int32 bytes;
responseString = String.Empty;
response = new Byte[512];
bytes = ns.Read(response, 0, response.Length);
responseString =
System.Text.Encoding.ASCII.GetString(response, 0, bytes);
ch.getServer().log("Received: " + responseString);
String msg = "<html>Hello World</html>";
String fullMsg = "HTTP/1.x 200 OK\r\n"
+ "Server: Test Server\r\n"
+ "Content-Type: text/html; "
+ "charset=UTF-8\r\n"
+ "Content-Length: " + msg.Length + "\r\n"
+ "Date: Sun, 10 Aug 2008 22:59:59 GMT"
+ "\r\n";
nsSend(fullMsg, ns);
nsSend(msg, ns);
ns.Close();
tcp.Close();
}
catch (ArgumentNullException e)
{
ch.getServer().log("connection error: argument null exception: " + e);
}
catch (SocketException e)
{
ch.getServer().log("connection error: socket exception: " + e);
}
}
private void nsSend(String s, NetworkStream ns)
{
Byte[] data = System.Text.Encoding.ASCII.GetBytes(s);
ns.Write(data, 0, data.Length);
ns.Flush();
ch.getServer().log("Sent: " + s);
}
}
</code></pre>
<p>Does anyone have any ideas? It feels like it's gotta be something stupid on my part but I just don't know what. I'd really appreciate any insight</p>
|
[
{
"answer_id": 238640,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": true,
"text": "HttpListener httpcfg netsh"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19696/"
] |
238,608
|
<p>I'm using TortoiseHg 0.5 (which includes Mercurial 1.0.2) on Vista64. My understanding from the <a href="http://hgbook.red-bean.com/hgbookch7.html#x11-1530007.7" rel="noreferrer">Mercurial Book</a> is that Mercurial should handle filenames in a case-insensitive manner on a case-insensitive filesystem (such as NTFS, which is what I'm on). However I find that my installation of Mercurial is in fact sensitive to case:</p>
<pre><code>>hg status -A foo
C foo
>hg status -A FOO
? FOO
</code></pre>
<p>Could this be a bug in Mercurial, a bug in the TortoiseHg build of Mercurial, or is it something else? How can I achieve case-insensitive filename handling from Mercurial on Windows?</p>
|
[
{
"answer_id": 245867,
"author": "Ry4an Brase",
"author_id": 8992,
"author_profile": "https://Stackoverflow.com/users/8992",
"pm_score": 3,
"selected": false,
"text": "hg status -A FOO ! Foo\n? FOO\n"
},
{
"answer_id": 529728,
"author": "Mentat",
"author_id": 30198,
"author_profile": "https://Stackoverflow.com/users/30198",
"pm_score": 4,
"selected": true,
"text": ">hg status -A foo\nC foo\n>hg status -A FOO\nC foo\n >ren foo FOO\n>hg status -A fOO\nC foo\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30198/"
] |
238,615
|
<p>I have a quite old templating system written on top of ERB. It relies on ERB templates stored in database. Those are read and rendered. When I want to pass data from one template to another I use the :locals parameter to Rails render method. For setting default variables of those variables in some templates I use the defined? method which simply tells me if local variable has been defined and if not I initialize it with default value like this: </p>
<pre><code>unless defined?(perex)
perex = true
end
</code></pre>
<p>I am upgrading the app to latest Rails and I see some weird behavior. Basically this sometimes works (sometimes perex is undefined) and sometimes it does not (perex is defined and set to nil). This happens without anything else changing.</p>
<p>I have two questions:
Is there any better way other than using defined? which is proving unreliable (was reliable for several years on top Rails 1.6)? Such a way should not result in me rewriting all the templates.
I have been going through Ruby docs and was not able to find anything about defined? method. Was it deprecated or am I just plain blind?</p>
<p><em>Edit:</em> The actual issue was caused by what seems to be a Ruby/eRB bug. Sometimes the <em>unless</em> statement would work, but sometimes not. The weird thing is that even if the second line got executed <em>perex</em> stil stayed nil to the rest of the world. Removing defined? resolved that.</p>
|
[
{
"answer_id": 238715,
"author": "Rômulo Ceccon",
"author_id": 23193,
"author_profile": "https://Stackoverflow.com/users/23193",
"pm_score": 6,
"selected": true,
"text": "defined? perex ||= true\n perex nil nil perex false perex ||= perex.nil? # Assign true only when perex is undefined or nil\n"
},
{
"answer_id": 633927,
"author": "mislav",
"author_id": 11687,
"author_profile": "https://Stackoverflow.com/users/11687",
"pm_score": 5,
"selected": false,
"text": "local_assigns[:perex]\n defined?"
},
{
"answer_id": 1924195,
"author": "KenB",
"author_id": 234077,
"author_profile": "https://Stackoverflow.com/users/234077",
"pm_score": 4,
"selected": false,
"text": "if local_assigns.has_key? :perex\n"
},
{
"answer_id": 11616785,
"author": "Matt Huggins",
"author_id": 107277,
"author_profile": "https://Stackoverflow.com/users/107277",
"pm_score": 3,
"selected": false,
"text": "perex = local_assigns.fetch(:perex, true)\n ||= false false perex = local_assigns[:perex] || true\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8621/"
] |
238,620
|
<p>I have a subclass "s" of UIView. I want to put some buttons and labels on s. How do I associate my UIView subclass with a nib file?</p>
|
[
{
"answer_id": 238806,
"author": "Colin Barrett",
"author_id": 23106,
"author_profile": "https://Stackoverflow.com/users/23106",
"pm_score": 6,
"selected": true,
"text": "-[NSBundle loadNibNamed:owner:options:]"
},
{
"answer_id": 18748065,
"author": "djibouti33",
"author_id": 607876,
"author_profile": "https://Stackoverflow.com/users/607876",
"pm_score": 2,
"selected": false,
"text": "initWithNibName: initWithNibName: - (instancetype)initWithNibName:(NSString *)nibName\n{\n NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil];\n if (arrayOfViews.count < 1) {\n return nil;\n }\n\n self = arrayOfViews[0];\n\n return self;\n}\n owner:self"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22471/"
] |
238,625
|
<p>I have a Visual Studio 2008 solution with two projects (a Word-Template project and a VB.Net console application for testing). Both projects reference a database project which opens a connection to an MS-Access 2007 database file and have references to System.Data.OleDb. In the database project I have a function which retrieves a data table as follows</p>
<pre><code> private class AdminDatabase
' stores the connection string which is set in the New() method
dim strAdminConnection as string
public sub New()
...
adminName = dlgopen.FileName
conAdminDB = New OleDbConnection
conAdminDB.ConnectionString = "Data Source='" + adminName + "';" + _
"Provider=Microsoft.ACE.OLEDB.12.0"
' store the connection string in strAdminConnection
strAdminConnection = conAdminDB.ConnectionString.ToString()
My.Settings.SetUserOverride("AdminConnectionString", strAdminConnection)
...
End Sub
' retrieves data from the database
Public Function getDataTable(ByVal sqlStatement As String) As DataTable
Dim ds As New DataSet
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
Dim localCon As New OleDbConnection
localCon.ConnectionString = strAdminConnection
Using localCon
Dim command As OleDbCommand = localCon.CreateCommand()
command.CommandText = sqlStatement
localCon.Open()
da.SelectCommand = command
da.Fill(dt)
getDataTable = dt
End Using
End Function
End Class
</code></pre>
<p>When I call this function from my Word 2007 Template project everything works fine; no errors. But when I run it from the console application it throws the following exception</p>
<blockquote>
<p>ex = {"The 'Microsoft.ACE.OLEDB.12.0'
provider is not registered on the
local machine."}</p>
</blockquote>
<p>Both projects have the same reference and the console application did work when I first wrote it (a while ago) but now it has stopped work. I must be missing something but I don't know what. Any ideas?</p>
|
[
{
"answer_id": 1894000,
"author": "Pescadore",
"author_id": 230087,
"author_profile": "https://Stackoverflow.com/users/230087",
"pm_score": 3,
"selected": false,
"text": "VC# Express VC# Express Configuration Manager Tools -> Options \"Show all settings\" \"Projects and Solutions\" \"Show advanced build configuraions.\" OK Build -> Configuration Manager \"<New...>\" \"New platform\" setting, choose \"x86\" OK Close Configuration Manager"
},
{
"answer_id": 21455784,
"author": "TechSpud",
"author_id": 1368849,
"author_profile": "https://Stackoverflow.com/users/1368849",
"pm_score": 2,
"selected": false,
"text": "(New-Object system.data.oledb.oledbenumerator).GetElements() | select SOURCES_NAME, SOURCES_DESCRIPTION\n SOURCES_NAME SOURCES_DESCRIPTION \n------------ ------------------- \nMicrosoft.ACE.OLEDB.15.0 Microsoft Office 15.0 Access Database Engine OLE DB Provider\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4612/"
] |
238,631
|
<p>I have Visual Studio 2008 and the Windows SDK for Windows Server 2008 and .NET Framework 3.5
installed. I believe that is the latest platform SDK.</p>
<p>I'm trying to build a signed dll to be installed in SxS.
All the tutorials explain to use a tool called pktextract.exe which is part of the SDK, but I can't seem to find the tool. All the other tools such as makecert, mt, makecat exist.</p>
<p>Was pktextract replaced by some other tool in the latest version of the sdk?</p>
<p>Thanks for the help.</p>
|
[
{
"answer_id": 1894000,
"author": "Pescadore",
"author_id": 230087,
"author_profile": "https://Stackoverflow.com/users/230087",
"pm_score": 3,
"selected": false,
"text": "VC# Express VC# Express Configuration Manager Tools -> Options \"Show all settings\" \"Projects and Solutions\" \"Show advanced build configuraions.\" OK Build -> Configuration Manager \"<New...>\" \"New platform\" setting, choose \"x86\" OK Close Configuration Manager"
},
{
"answer_id": 21455784,
"author": "TechSpud",
"author_id": 1368849,
"author_profile": "https://Stackoverflow.com/users/1368849",
"pm_score": 2,
"selected": false,
"text": "(New-Object system.data.oledb.oledbenumerator).GetElements() | select SOURCES_NAME, SOURCES_DESCRIPTION\n SOURCES_NAME SOURCES_DESCRIPTION \n------------ ------------------- \nMicrosoft.ACE.OLEDB.15.0 Microsoft Office 15.0 Access Database Engine OLE DB Provider\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4697/"
] |
238,660
|
<p>When you attempt to declare an unsigned variable in C#.NET with a value outside its value range it is flagged as a compiler error, but if you produce a negative value at runtime and assign it to that variable at runtime the value wraps.</p>
<pre><code>uint z = -1; // Will not compile
uint a = 5;
uint b = 6;
uint c = a - b; // Will result in uint.MaxValue
</code></pre>
<p>Is there a good reason why unsigned variables wrap in such a situation instead of throwing an exception?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 238669,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": "uint z;\n int.MaxValue int.MinValue class Test\n{\n static void Main()\n {\n checked\n {\n uint a = 5;\n uint b = 6;\n uint c = a - b;\n }\n }\n}\n OverflowException /checked+ csc c"
},
{
"answer_id": 238672,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": " uint a = 3, b = 4;\n checked\n {\n uint c = a - b; // throws an overflow\n }\n"
},
{
"answer_id": 238680,
"author": "Dave Cluderay",
"author_id": 30933,
"author_profile": "https://Stackoverflow.com/users/30933",
"pm_score": 2,
"selected": false,
"text": "uint c = checked(a - b);\n"
},
{
"answer_id": 238701,
"author": "Andrew Watt",
"author_id": 31650,
"author_profile": "https://Stackoverflow.com/users/31650",
"pm_score": 0,
"selected": false,
"text": "uint"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27765/"
] |
238,662
|
<pre><code>string[] filesOfType1 = GetFileList1();
string[] filesOfType2 = GetFileList2();
var cookieMap = new Dictionary<string, CookieContainer>();
Action<string, Func<string, KeyValuePair<string, CookieContainer>>> addToMap = (filename, pairGetter) =>
{
KeyValuePair<string, CookieContainer> cookiePair;
try
{
cookiePair = pairGetter(filename);
}
catch
{
Console.WriteLine("An error was encountered while trying to read " + file + ".");
return;
}
if (cookieMap.ContainsKey(cookiePair.Key))
{
if (cookiePair.Value.Count > cookieMap[cookiePair.Key].Count)
{
cookieMap[cookiePair.Key] = cookiePair.Value;
}
}
else
{
cookieMap.Add(cookiePair.Key, cookiePair.Value);
}
};
foreach (string file in filesOfType1)
{
addToMap(file, GetType1FileCookiePair);
}
foreach (string file in filesOfType2)
{
addToMap(file, GetType2FileCookiePair);
}
</code></pre>
<p>Salient features that must be preserved:</p>
<ul>
<li>Files of type 1 are more important than files of type 2; i.e. if a file of type 1 maps to a (key, value1) combination and a file of type 2 maps to a (key, value2) combination, then we add (key, value1) to cookieMap and <em>not</em> (key, value2). <strong>Edit: as pointed out by Bevan, this is not satisfied by my original procedural code.</strong></li>
<li>Secondarily, <code>CookieContainer</code>s with a higher <code>Count</code> have higher priority, i.e. if there are two (key, value) combos for the same key and both from the same filetype, we choose the one with higher <code>value.Count</code>.</li>
<li>Per-case exception handling is a must; screwing up a single file-reading should just allows us to note that and continue.</li>
</ul>
<p>My best attempt started like this:</p>
<pre><code>var cookieMap = (filesOfType1.Select(file => GetType1FileCookiePair(file))
.Concat(filesOfType2.Select(file => GetType2FileCookiePair(file))))
.GroupBy(pair => pair.Key)
.Select(/* some way of selecting per the above bullets */)
.ToDictionary(pair => pair.Key, pair => pair.Value);
</code></pre>
<p>But it's inelegant and filling in that comment block seems like a bitch. Right now I'm happy to stay procedural, but I thought that it might be a fun challenge to see if people can come up with something really clever.</p>
|
[
{
"answer_id": 238729,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 1,
"selected": false,
"text": "var cookieMap = (from pair in\n (from f1 in filesOfType1\n select Swallow(() => GetType1FileCookiePair(f1)))\n .Concat(from f2 in filesOfType2\n select Swallow(() => GetType2FileCookiePair(f2)))\n .SelectMany(dict => dict)\n group pair by pair.Key into g\n select g)\n .ToDictionary(g => g.Key, g => g.Select(pair => pair.Value)\n .OrderByDescending(value => value.Count)\n .First());\n Swallow private static T Swallow<T>(Func<T> getT)\n{\n try { return getT(); } catch { }\n\n return default(T);\n}\n Swallow Swallow"
},
{
"answer_id": 238861,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 2,
"selected": false,
"text": "using CookiePair = KeyValuePair<string, CookieContainer>;\nusing CookieDictionary = Dictionary<string, CookieContainer>;\n\nFunc<string[], Func<string, CookiePair>, IEnumerable<CookiePair>> getCookies =\n ( files, pairGetter ) =>\n files.SelectMany( filename => {\n try { return new[] { pairGetter( filename ) }; }\n catch { Console.WriteLine( \"...\" ); return new CookiePair[0]; }\n } );\n\nvar type1Cookies = getCookies( filesOfType1, GetType1FileCookiePair ).ToArray( );\nvar type1CookieNames = type1Cookies.Select( p => p.Key ).ToArray( );\nvar type2Cookies = getCookies( filesOfType2, GetType2FileCookiePair )\n .Where( p => !type1CookieNames.Contains( p.Key ) );\n\nvar cookieMap = type1Cookies.Concat( type2Cookies )\n .Aggregate( new CookieDictionary( ), ( d, p ) => {\n if( !d.ContainsKey( p.Key ) || p.Value.Count > d[p.Key].Count )\n d[p.Key] = p.Value;\n return d;\n } );\n"
},
{
"answer_id": 239325,
"author": "Bevan",
"author_id": 30280,
"author_profile": "https://Stackoverflow.com/users/30280",
"pm_score": 3,
"selected": true,
"text": "// Handle all files of type 1\nvar pairsOfType1 = \n filesOfType1\n .Select( file => Swallow( pairGetter(file)))\n .Where( pair => pair != null);\n\n// Handle files of type 2 and filter out those with keys already provided by type 1\nvar pairsOfType2 =\n filesOfType2\n .Select( file => Swallow( pairGetter(file)))\n .Where( pair => pair != null);\n .Where( pair => !pairsOfType1.Contains(p => p.Key == pair.Key));\n\n// Merge the two sets, keeping only the pairs with the highest count\nvar cookies =\n pairsOfType1\n .Union( pairsOfType2)\n .GroupBy( pair => pair.Key)\n .Select( group => group.OrderBy( pair => pair.Value.Count).Last());\n .ToDictionary( pair => pair.Key);\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3191/"
] |
238,665
|
<p>Is there a mechanism to inject dependencies into Linq to Sql or entity framework entities? If so would it be a sensible approach?</p>
|
[
{
"answer_id": 238689,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "XmlMappingSource"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29547/"
] |
238,675
|
<p>Im looking to build a thread manager for an application.</p>
<p>I have already started threading and it works entirely fine but I would like to be able to programatically kill them or get information on them.</p>
<p>Does anyone have ideas?</p>
|
[
{
"answer_id": 238681,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "Thread.Abort"
},
{
"answer_id": 239018,
"author": "Jon B",
"author_id": 27414,
"author_profile": "https://Stackoverflow.com/users/27414",
"pm_score": 2,
"selected": true,
"text": "Thread.ThreadState Thread.Interrupt() Thread.Abort() System.Diagnostics.Process.GetCurrentProcess().Threads"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31642/"
] |
238,684
|
<p>I have a Ruby DateTime which gets filled from a form. Additionally I have n hours from the form as well. I'd like to subtract those n hours from the previous DateTime. (To get a time range).</p>
<p>DateTime has two methods "-" and "<<" to subtract day and month, but not hour. (<a href="https://ruby-doc.org/stdlib-2.5.1/libdoc/date/rdoc/DateTime.html" rel="noreferrer">API</a>). Any suggestions how I can do that?</p>
|
[
{
"answer_id": 238690,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 3,
"selected": false,
"text": "> Time.now - 12.hours\n=> 2019-08-19 05:50:43 +0200\n DateTime Time t = Time.now\nt = t - (hours*60**2)\n Time DateTime DateTime.commercial(date.year,date.month,date.day,date.hour-x,date.minute,date.second)\n DateTime - <<"
},
{
"answer_id": 238718,
"author": "Mike Spross",
"author_id": 17862,
"author_profile": "https://Stackoverflow.com/users/17862",
"pm_score": 2,
"selected": false,
"text": "DateTime Fixnum require 'date'\n\n# A placeholder class for holding a set number of hours.\n# Used so we can know when to change the behavior\n# of DateTime#-() by recognizing when hours are explicitly passed in.\n\nclass Hours\n attr_reader :value\n\n def initialize(value)\n @value = value\n end\nend\n\n# Patch the #-() method to handle subtracting hours\n# in addition to what it normally does\n\nclass DateTime\n\n alias old_subtract -\n\n def -(x) \n case x\n when Hours; return DateTime.new(year, month, day, hour-x.value, min, sec)\n else; return self.old_subtract(x)\n end\n end\n\nend\n\n# Add an #hours attribute to Fixnum that returns an Hours object. \n# This is for syntactic sugar, allowing you to write \"someDate - 4.hours\" for example\n\nclass Fixnum\n def hours\n Hours.new(self)\n end\nend\n some_date = some_date - n.hours\n n some_date"
},
{
"answer_id": 238822,
"author": "glenn mcdonald",
"author_id": 7919,
"author_profile": "https://Stackoverflow.com/users/7919",
"pm_score": 3,
"selected": false,
"text": "mydatetime = DateTime.parse(formvalue)\nnhoursbefore = mydatetime - n / 24.0\n"
},
{
"answer_id": 239119,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 7,
"selected": true,
"text": "adjusted_datetime = (datetime_from_form.to_time - n.hours).to_datetime\n"
},
{
"answer_id": 251832,
"author": "danmayer",
"author_id": 27738,
"author_profile": "https://Stackoverflow.com/users/27738",
"pm_score": 2,
"selected": false,
"text": "require 'active_support'\n\nlast_accessed = 2.hours.ago\nlast_accessed = 2.weeks.ago\nlast_accessed = 1.days.ago\n"
},
{
"answer_id": 343860,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "two_hours_ago = DateTime.now - (2/24.0)\n hours = 10\nminutes = 5\nseconds = 64\n\nhours = DateTime.now - (hours/24.0) #<DateTime: 2015-03-11T07:27:17+02:00 ((2457093j,19637s,608393383n),+7200s,2299161j)>\nminutes = DateTime.now - (minutes/1440.0) #<DateTime: 2015-03-11T17:22:17+02:00 ((2457093j,55337s,614303598n),+7200s,2299161j)>\nseconds = DateTime.now - (seconds/86400.0) #<DateTime: 2015-03-11T17:26:14+02:00 ((2457093j,55574s,785701811n),+7200s,2299161j)>\n Rational"
},
{
"answer_id": 1274391,
"author": "Mladen Jablanović",
"author_id": 82592,
"author_profile": "https://Stackoverflow.com/users/82592",
"pm_score": 4,
"selected": false,
"text": "n/24.0 >> DateTime.parse('2009-06-04 02:00:00').step(DateTime.parse('2009-06-04 05:00:00'),1.0/24){|d| puts d}\n2009-06-04T02:00:00+00:00\n2009-06-04T03:00:00+00:00\n2009-06-04T03:59:59+00:00\n2009-06-04T04:59:59+00:00\n >> DateTime.parse('2009-06-04 02:00:00').step(DateTime.parse('2009-06-04 05:00:00'),Rational(1,24)){|d| puts d}\n2009-06-04T02:00:00+00:00\n2009-06-04T03:00:00+00:00\n2009-06-04T04:00:00+00:00\n2009-06-04T05:00:00+00:00\n"
},
{
"answer_id": 6012178,
"author": "Joe Kelley",
"author_id": 754944,
"author_profile": "https://Stackoverflow.com/users/754944",
"pm_score": 4,
"selected": false,
"text": "adjusted = time_from_form.advance(:hours => -n)\n"
},
{
"answer_id": 8574397,
"author": "Anu",
"author_id": 1107663,
"author_profile": "https://Stackoverflow.com/users/1107663",
"pm_score": -1,
"selected": false,
"text": "Time.now.ago(n*60*60)\n Time.now.ago(7200)"
},
{
"answer_id": 25311144,
"author": "fguillen",
"author_id": 316700,
"author_profile": "https://Stackoverflow.com/users/316700",
"pm_score": 2,
"selected": false,
"text": "Time DateTime # Just remove the number of seconds from the Time object\nTime.now - (6 * 60 * 60) # 6 hours ago\n"
},
{
"answer_id": 31447415,
"author": "Nigel Thorne",
"author_id": 23963,
"author_profile": "https://Stackoverflow.com/users/23963",
"pm_score": 4,
"selected": false,
"text": "two_hours_ago = DateTime.now - (2.0/24)\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31644/"
] |
238,702
|
<p>In my database, Concessions have a many-to-one relationship with Firms (each Concession has a FirmID). SqlMetal has captured this relationship and generated the appropriate classes, so that each Concession has a Firm element. I'm binding against a query (simplified here) that returns a list of Concessions along with information about the corresponding Firm:</p>
<pre><code>From c as Concession in Db.Concessions _
Select _
c.ConcessionID, _
c.Title, _
c.Firm.Title
</code></pre>
<p>The problem is that in some cases a Concession has not been assigned to a Firm (c.FirmID is null), so c.Firm is nothing and I get <code>Object not set to an instance</code> etc.</p>
<p>I can get around this by doing a join as follows:</p>
<pre><code>From c As Concession In Db.Concessions _
Join f As Firm In Db.Firms On f.FirmID Equals c.FirmID _
Select _
c.ConcessionID, _
c.Title, _
Firm_Title = f.Title
</code></pre>
<p>This doesn't throw an error when FirmID is null (Firm_Title is just an empty string), but it's not elegant: it's not object-oriented, and it doesn't leverage all of the relational intelligence that Linq to SQL has already captured. </p>
<p>Is there a more graceful way to deal with this situation?</p>
|
[
{
"answer_id": 238717,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "from c in Db.Concessions\nselect \n{ \n c.ConcessionID, \n c.Title, \n Title = c.Firm.Title ?? \"\"\n}\n"
},
{
"answer_id": 238873,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 2,
"selected": true,
"text": ".ToList From c As Concession In db.Concessions _\nSelect _\n c.ConcessionID, _\n c.Title, _\n Firm_Title = If(c.Firm IsNot Nothing, c.Firm.Title, String.Empty) _\n"
},
{
"answer_id": 886541,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Public Property office() As String\n Get\n Return _office\n End Get\n Set(ByVal value As String)\n If value IsNot Nothing Then\n _office = value\n Else\n _office = String.Empty\n End If\n End Set\n End Property\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
] |
238,724
|
<p>I need advice for rendering an undirected graph with 178,000 nodes and 500,000 edges. I've tried Neato, Tulip, and Cytoscape. Neato doesn't even come remotely close, and Tulip and Cytoscape claim they can handle it but don't seem to be able to. (Tulip does nothing and Cytoscape claims to be working, and then just stops.)</p>
<p>I'd just like a vector format file (ps or pdf) with a remotely reasonable layout of the nodes.</p>
|
[
{
"answer_id": 5093458,
"author": "Anthony Liekens",
"author_id": 361178,
"author_profile": "https://Stackoverflow.com/users/361178",
"pm_score": 5,
"selected": false,
"text": "sfdp"
},
{
"answer_id": 11093000,
"author": "MRocklin",
"author_id": 616616,
"author_profile": "https://Stackoverflow.com/users/616616",
"pm_score": 0,
"selected": false,
"text": "L"
},
{
"answer_id": 26245864,
"author": "dranxo",
"author_id": 424631,
"author_profile": "https://Stackoverflow.com/users/424631",
"pm_score": 4,
"selected": false,
"text": "import graph_tool.all as gt\nimport math\n\ng = gt.collection.data[\"polblogs\"] # http://www2.scedu.unibo.it/roversi/SocioNet/AdamicGlanceBlogWWW.pdf\nprint(g.num_vertices(), g.num_edges())\n\n#reduce to only connected nodes\ng = gt.GraphView(g,vfilt=lambda v: (v.out_degree() > 0) and (v.in_degree() > 0) )\ng.purge_vertices()\n\nprint(g.num_vertices(), g.num_edges())\n\n#use 1->Republican, 2->Democrat\nred_blue_map = {1:(1,0,0,1),0:(0,0,1,1)}\nplot_color = g.new_vertex_property('vector<double>')\ng.vertex_properties['plot_color'] = plot_color\nfor v in g.vertices():\n plot_color[v] = red_blue_map[g.vertex_properties['value'][v]]\n\n#edge colors\nalpha=0.15\nedge_color = g.new_edge_property('vector<double>')\ng.edge_properties['edge_color']=edge_color\nfor e in g.edges():\n if plot_color[e.source()] != plot_color[e.target()]:\n if plot_color[e.source()] == (0,0,1,1):\n #orange on dem -> rep\n edge_color[e] = (255.0/255.0, 102/255.0, 0/255.0, alpha)\n else:\n edge_color[e] = (102.0/255.0, 51/255.0, 153/255.0, alpha) \n #red on rep-rep edges\n elif plot_color[e.source()] == (1,0,0,1):\n edge_color[e] = (1,0,0, alpha)\n #blue on dem-dem edges\n else:\n edge_color[e] = (0,0,1, alpha)\n\nstate = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)\nbstack = state.get_bstack()\nt = gt.get_hierarchy_tree(bstack)[0]\ntpos = pos = gt.radial_tree_layout(t, t.vertex(t.num_vertices() - 1), weighted=True)\ncts = gt.get_hierarchy_control_points(g, t, tpos)\npos = g.own_property(tpos)\nb = bstack[0].vp[\"b\"]\n\n#labels\ntext_rot = g.new_vertex_property('double')\ng.vertex_properties['text_rot'] = text_rot\nfor v in g.vertices():\n if pos[v][0] >0:\n text_rot[v] = math.atan(pos[v][1]/pos[v][0])\n else:\n text_rot[v] = math.pi + math.atan(pos[v][1]/pos[v][0])\n\ngt.graph_draw(g, pos=pos, vertex_fill_color=g.vertex_properties['plot_color'], \n vertex_color=g.vertex_properties['plot_color'],\n edge_control_points=cts,\n vertex_size=10,\n vertex_text=g.vertex_properties['label'],\n vertex_text_rotation=g.vertex_properties['text_rot'],\n vertex_text_position=1,\n vertex_font_size=9,\n edge_color=g.edge_properties['edge_color'],\n vertex_anchor=0,\n bg_color=[0,0,0,1],\n output_size=[4024,4024],\n output='polblogs_blockmodel.png')\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
238,733
|
<p>I want to "remove" a UIView from a superview and add it again at the end... but at the "bottom" of the rest of the UIviews that belong to the superview. </p>
<p>Is this possible?</p>
<p>Any help is very appreciated!</p>
|
[
{
"answer_id": 238758,
"author": "Max Stewart",
"author_id": 18338,
"author_profile": "https://Stackoverflow.com/users/18338",
"pm_score": 5,
"selected": true,
"text": "- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index;\n - (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview;\n - (void)sendSubviewToBack:(UIView *)view;\n"
},
{
"answer_id": 238796,
"author": "Gu1234",
"author_id": 407138,
"author_profile": "https://Stackoverflow.com/users/407138",
"pm_score": 1,
"selected": false,
"text": "[view removeFromSuperview]; retain [view retain]; release [view release]; zPosition view.layer.zPosition = X; zPosition zPosition"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23695/"
] |
238,738
|
<p>I'm not sure how to look for this online... I think they might be called something different in C++</p>
<p>I want to have a simple event system, somthing like</p>
<pre><code>event myCustomEvent;
myCustomEvent.subscribe( void myHandler(string) );
myCustomEvent.fire("a custom argument");
// myHandler prints out the string passed in the first argument
event myNewCustomEvent;
myNewCustomEvent.subscribe( void myNewHandler(int) );
myNewCustomEvent.fire(10);
// myHandler prints 10
</code></pre>
<p>I can do this pretty easily with a simple class -- but when i want to have an event that passes a different type or amount of arguments to the subscriber i have to write, and define an entirely new event class.. I figure there has to be some library, or maybe even something native in Visual C++ 2008 that will work something similar to this. It's basicly just an implementation of the Observer pattern, so it can't be too impossible to do in C++</p>
<p>This really makes me appreciate how nice it is in JavaScript not to have to worry about the arguments you are passing.</p>
<p>Tell me if this is a stupid question.</p>
|
[
{
"answer_id": 238963,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 3,
"selected": false,
"text": "[event_source(native)]\nclass CSource {\npublic:\n __event void MyEvent(int nValue);\n};\n\n[event_receiver(native)]\nclass CReceiver {\npublic:\n void MyHandler1(int nValue) {\n printf_s(\"MyHandler1 was called with value %d.\\n\", nValue);\n }\n\n void MyHandler2(int nValue) {\n printf_s(\"MyHandler2 was called with value %d.\\n\", nValue);\n }\n\n void hookEvent(CSource* pSource) {\n __hook(&CSource::MyEvent, pSource, &CReceiver::MyHandler1);\n __hook(&CSource::MyEvent, pSource, &CReceiver::MyHandler2);\n }\n\n void unhookEvent(CSource* pSource) {\n __unhook(&CSource::MyEvent, pSource, &CReceiver::MyHandler1);\n __unhook(&CSource::MyEvent, pSource, &CReceiver::MyHandler2);\n }\n};\n\nint main() {\n CSource source;\n CReceiver receiver;\n\n receiver.hookEvent(&source);\n __raise source.MyEvent(123);\n receiver.unhookEvent(&source);\n}\n"
},
{
"answer_id": 242488,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "#include <iostream>\n#include <sigc++/sigc++.h>\n\nusing namespace std;\n\nclass AlienDetector {\npublic:\n void run ();\n sigc::signal<void> signal_detected;\n};\n\nvoid warn_people () {\n cout << \"There are aliens in the carpark!\" << endl;\n}\n\nvoid AlienDetector::run () {\n signal_detected.emit ();\n}\n\nint main () {\n AlienDetector mydetector;\n mydetector.signal_detected.connect (sigc::ptr_fun (warn_people));\n mydetector.run ();\n}\n sigc::mem_fun (someobject, &SomeClass::some_method);\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1825034/"
] |
238,748
|
<p>We have a 3D application that retrieves keyboard presses via the IDirectInputDevice8. Is there any way, when we retrive keyboard events via the win32 API winproc loop back that we can send these commands to the DirectInputDevice?</p>
|
[
{
"answer_id": 238774,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 0,
"selected": false,
"text": "WM_SYSKEYDOWN\nWM_SYSKEYUP\nWM_KEYDOWN\nWM_KEYUP \nWM_CHAR \n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
238,765
|
<p>I am parsing an Expression Tree. Given a NodeType of ExpressionType.MemberAccess, how do I get the value of that Field? </p>
<p>From C# MSDN docs:
MemberAccess is A node that represents reading from a field or property. </p>
<p>A code snippet would be incredibly, incredibly helpful. Thanks in advance!!!</p>
<p>My code looks something like this: </p>
<pre><code>public static List<T> Filter(Expression<Func<T, bool>> filterExp)
{
//the expression is indeed a binary expression in this case
BinaryExpression expBody = filterExp.Body as BinaryExpression;
if (expBody.Left.NodeType == ExpressionType.MemberAccess)
//do something with ((MemberExpressionexpBody.Left).Name
//right hand side is indeed member access. in fact, the value comes from //aspdroplist.selectedvalue
if (expBody.Right.NodeType == ExpressionType.MemberAccess)
{
//how do i get the value of aspdroplist.selected value?? note: it's non-static
}
//return a list
}
</code></pre>
|
[
{
"answer_id": 238798,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 7,
"selected": true,
"text": "Expression MemberExpression MemberExpression PropertyInfo FieldInfo .Expression .Member FieldInfo .GetValue(obj) FieldInfo PropertyInfo .Expression ConstantExpression ParameterExpression Expression .Compile() using System;\nusing System.Linq.Expressions;\nusing System.Reflection;\nclass Foo\n{\n public string Bar { get; set; }\n}\n\nstatic class Program\n{\n static void Main()\n {\n Foo foo = new Foo {Bar = \"abc\"};\n Expression<Func<string>> func = () => foo.Bar;\n\n MemberExpression outerMember = (MemberExpression)func.Body;\n PropertyInfo outerProp = (PropertyInfo) outerMember.Member;\n MemberExpression innerMember = (MemberExpression)outerMember.Expression;\n FieldInfo innerField = (FieldInfo)innerMember.Member;\n ConstantExpression ce = (ConstantExpression) innerMember.Expression;\n object innerObj = ce.Value;\n object outerObj = innerField.GetValue(innerObj);\n string value = (string) outerProp.GetValue(outerObj, null); \n }\n\n}\n"
},
{
"answer_id": 238945,
"author": "Keith Fitzgerald",
"author_id": 49611,
"author_profile": "https://Stackoverflow.com/users/49611",
"pm_score": 5,
"selected": false,
"text": "object value = Expression.Lambda(expBody.Right).Compile().DynamicInvoke();\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/49611/"
] |
238,768
|
<p>I would to change the menuitems in the default context menu provided in the Web Browser Control. I have already tried: webbrowser.contextmenu = mycontextmenu.
Nothing changed. Is there a way to do this?</p>
|
[
{
"answer_id": 1151160,
"author": "Marco Luglio",
"author_id": 14263,
"author_profile": "https://Stackoverflow.com/users/14263",
"pm_score": 1,
"selected": false,
"text": "using System.Windows;\nusing System.Runtime.InteropServices;\nusing mshtml;\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
238,784
|
<p>I wrote a class/function to send xml over https via PHP4/cURL, just wondering if this is the correct approach, or if there's a better one.</p>
<p>Note that PHP5 is not an option at present.</p>
<pre><code>/**
* Send XML via http(s) post
*
* curl --header "Content-Type: text/xml" --data "<?xml version="1.0"?>...." http://www.foo.com/
*
*/
function sendXmlOverPost($url, $xml) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// For xml, change the content-type.
curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // ask for results to be returned
if(CurlHelper::checkHttpsURL($url)) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
}
// Send to remote and return data to caller.
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
</code></pre>
<p>cheers!</p>
|
[
{
"answer_id": 238790,
"author": "Nick Stinemates",
"author_id": 4960,
"author_profile": "https://Stackoverflow.com/users/4960",
"pm_score": -1,
"selected": false,
"text": "$soap = new SoapClient(\"http://some.url/service/some.wsdl\");\n$args = array(\"someTypeName\" => \"someTypeValue\"\n \"someOtherTypeName\" => \"someOtherTypeValue\");\n\n$response = $soap->executeSomeService($args);\n\nprint_r($response);\n"
},
{
"answer_id": 1973950,
"author": "Dr. Rajesh Rolen",
"author_id": 201387,
"author_profile": "https://Stackoverflow.com/users/201387",
"pm_score": 2,
"selected": false,
"text": " if( $this -> usingHTTPS() )\n {\n curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);\n curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $this->sslVerifyHost);\n\n }\n\n curl_setopt($ch,CURLOPT_POST,TRUE);\n curl_setopt($ch, CURLOPT_HEADER, FALSE); \n curl_setopt ($ch, CURLOPT_POSTFIELDS, \"OTA_request=\".urlencode($this->xmlMessage));\n\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);\n\n $this->xmlResponse = curl_exec ($ch); \n\n $this -> callerFactory -> dbgMsg('xmlResponse: <hr><pre>'.htmlentities($this->xmlResponse).'</pre><hr>'. curl_error($ch));\n curl_close ($ch);\n\n $this->checkResponse();\n"
},
{
"answer_id": 8314845,
"author": "jhon",
"author_id": 1071808,
"author_profile": "https://Stackoverflow.com/users/1071808",
"pm_score": 2,
"selected": false,
"text": "// here you can have all the required business checks\nif ( $_SERVER['REQUEST_METHOD'] === 'POST' ){\n $postText = file_get_contents('php://input');\n}\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29854/"
] |
238,792
|
<p>I cannot seem to programmatcally scroll in WPF
in a normal Windows Form I would use the code below
but that property does not exist in WPF.</p>
<pre><code>HtmlDocument doc = this.webBrowser1.Document;
doc.Body.ScrollTop = 800;
return;
</code></pre>
<p>Is there an alternative to doing this? </p>
|
[
{
"answer_id": 50808320,
"author": "Kyle Delaney",
"author_id": 2122672,
"author_profile": "https://Stackoverflow.com/users/2122672",
"pm_score": 0,
"selected": false,
"text": "if (wb.Document is mshtml.HTMLDocument htmlDoc)\n{\n htmlDoc.parentWindow.scrollTo(0, 0);\n}\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
238,800
|
<p>I have a query:</p>
<p>UPDATE choices SET votes = votes + 1 WHERE choice_id = '$user_choice'</p>
<p>But when I execute it in my script, the votes field is updated twice, so the votes will go from 4 to 6 instead to 5. It doesn't seem that it is getting called twice because I echo out stuff to test this and only get one echo. Is there a way to have it so PHP will only execute this query once per page "refresh"?</p>
<p><strong>EDIT</strong>: Thanks for the responses, I'm using regular MySQL, no MySQLi or PDO. Another thing I found is that when doing the query, it works when you start out with 0 and update to 1, but then after that it goes 3, 5, 7, ...</p>
|
[
{
"answer_id": 238808,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "$pdo = new PDO(...options...);\n$stmt = $pdo->query('UPDATE ...'); // executes once\n$stmt->execute(); // executes a second time\n"
},
{
"answer_id": 239189,
"author": "Kirill Titov",
"author_id": 25705,
"author_profile": "https://Stackoverflow.com/users/25705",
"pm_score": 1,
"selected": false,
"text": "UPDATE `choices` SET `votes` = `votes` + 1 WHERE `choice_id` = '$user_choice'\n"
},
{
"answer_id": 239203,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 1,
"selected": false,
"text": "votes + 1 UPDATE choices SET votes = (votes + 1) WHERE choice_id = '$user_choice';\n LIMIT 1"
},
{
"answer_id": 242441,
"author": "Ronald Conco",
"author_id": 16092,
"author_profile": "https://Stackoverflow.com/users/16092",
"pm_score": 0,
"selected": false,
"text": "choices votes choice_id"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
238,812
|
<p>I have a server dropdownlist in an <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a> updatepanel. When I use the mouse to click on an item it fires the postback but when I click the up/down arrow to change entries, this is not firing. What could be reason?</p>
|
[
{
"answer_id": 238864,
"author": "Paul Prewett",
"author_id": 15751,
"author_profile": "https://Stackoverflow.com/users/15751",
"pm_score": 0,
"selected": false,
"text": "onKeyDown"
},
{
"answer_id": 238934,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 4,
"selected": true,
"text": "<asp:DropDownList ID=\"DropDownList1\" runat=\"server\" AutoPostBack=\"True\" \nOnSelectedIndexChanged=\"DropDownList1_SelectedIndexChanged\" onKeyUp=\"this.blur();\">\n"
},
{
"answer_id": 238950,
"author": "Dhaust",
"author_id": 242,
"author_profile": "https://Stackoverflow.com/users/242",
"pm_score": 3,
"selected": false,
"text": "<asp:DropDownList ID=\"DropDownList1\" runat=\"server\" AutoPostBack=\"true\">\n</asp:DropDownList>\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
238,814
|
<p>I'm trying to build an in-game Tell A Friend form like in AppStore. Does anybody know if it can be found anywhere in the SDK? I wouldn't like to reinvent the sliced bread.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 239375,
"author": "Chris Samuels",
"author_id": 30342,
"author_profile": "https://Stackoverflow.com/users/30342",
"pm_score": 3,
"selected": false,
"text": "NSURL *url = [[NSURL alloc] initWithString: @\"mailto:gilm@myopenid.com?subject=subject&body=body\"];\n[[UIApplication sharedApplication] openURL:url];\n"
},
{
"answer_id": 8884907,
"author": "Sam Baumgarten",
"author_id": 800336,
"author_profile": "https://Stackoverflow.com/users/800336",
"pm_score": 2,
"selected": false,
"text": "#import <MessageUI/MessageUI.h> #import <MessageUI/MFMailComposeViewController.h> <MFMailComposeViewControllerDelegate> @interface tellAFriend : UIViewController <MFMailComposeViewControllerDelegate> {\n -(IBAction)tellAFriend; -(IBAction)tellAFriendViaSMS; -(IBAction)tellAFriend {\n\nif ([MFMailComposeViewController canSendMail]) {\n\nMFMailComposeViewController *mailView = [[MFMailComposeViewController alloc] init];\nmailView.mailComposeDelegate = self;\n[mailView setSubject:@\"Check Out your_app_name_here\"];\n[mailView setMessageBody:@\"Check out your_app_name_here <br> It's really cool and I think you would like it.\" isHTML:YES];\n\n[self presentModalViewController:mailView animated:YES];\n[mailView release];\n\n}\n\nelse {\n\nNSLog(@”Mail Not Supported”);\n\n}\n\n}\n\n-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult MFMailComposeResult)result error NSError*)error {\n\n[self dismissModalViewControllerAnimated:YES];\n\n}\n -(IBAction)tellAFriendViaSMS {\nMFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];\nif([MFMessageComposeViewController canSendText])\n{\n controller.body = @\"Check Out your_app_name_here, itunes_link_here\";\n controller.recipients = [NSArray arrayWithObjects:@\"phoneNumbersHere\", @\"PhoneNumberTwo\", nil]; // Optional\n controller.messageComposeDelegate = self;\n [self presentModalViewController:controller animated:YES];\n}\n}\n"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31515/"
] |
238,815
|
<p>I currently have a couple of SVN repositories hosted at Unfuddle and I'd like to have a local copy of the repositories as a backup. Ideally, it would be a "live" backup so my local repository would "ping" the remote repository, and if any changes were detected, the changes would be applied to my local repository.</p>
<p>Has anyone tried this before? If so, what tools were used to accomplish the job?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 238853,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "svnadmin dump svnadmin hotcopy"
},
{
"answer_id": 238866,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 3,
"selected": true,
"text": "svnsync svnsync sync svn-mirror git-svn svnsync git-svn"
}
] |
2008/10/26
|
[
"https://Stackoverflow.com/questions/238815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3440/"
] |
238,824
|
<p>How do I call a url in order to process the results?</p>
<p>I have a stand-alone reporting servlet which I link to for reports. I want to email these reports now, if I were doing this in the browser, I could just use an xhttprequest, and process the results - I basically want to do the same thing in Java, but I'm not sure how to go about it.</p>
<p><strong>UPDATE</strong>: I'm looking to get a file back from the url (whether that be a pdf or html etc).</p>
<p><strong>UPDATE</strong>: This will be running purely on the server - there is no request that triggers the emailing, rather it is a scheduled email.</p>
|
[
{
"answer_id": 238845,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 1,
"selected": false,
"text": "RequestDispatcher dispatcher =\n getServletContext().getRequestDispatcher(\"/url of other resource\");\nif (dispatcher != null)\n dispatcher.include(request, response);\n} \n"
},
{
"answer_id": 238850,
"author": "albertb",
"author_id": 26715,
"author_profile": "https://Stackoverflow.com/users/26715",
"pm_score": 4,
"selected": true,
"text": "public byte[] download(URL url) throws IOException {\n URLConnection uc = url.openConnection();\n int len = uc.getContentLength();\n InputStream is = new BufferedInputStream(uc.getInputStream());\n try {\n byte[] data = new byte[len];\n int offset = 0;\n while (offset < len) {\n int read = is.read(data, offset, data.length - offset);\n if (read < 0) {\n break;\n }\n offset += read;\n }\n if (offset < len) {\n throw new IOException(\n String.format(\"Read %d bytes; expected %d\", offset, len));\n }\n return data;\n } finally {\n is.close();\n }\n}\n"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/238824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/943/"
] |
238,878
|
<p>I am still very new to Ruby (reading through the Pickaxe and spending most of my time in <code>irb</code>), and now that I know it's possible to patch classes in Ruby, I'm wondering when it's acceptable to do so, specifically whether it's acceptable to patch Ruby's base classes. For example: I answered another Ruby question <a href="https://stackoverflow.com/questions/238684/subtract-n-hours-from-a-datetime-in-ruby#238718">here</a> where the poster wanted to know how to subtract hours from a <code>DateTime</code>. Since the <code>DateTime</code> class doesn't seem to provide this functionality, I posted an answer that patches the <code>DateTime</code> and <code>Fixnum</code> classes as a possible solution. This is the code I submitted:</p>
<pre><code>require 'date'
# A placeholder class for holding a set number of hours.
# Used so we can know when to change the behavior
# of DateTime#-() by recognizing when hours are explicitly passed in.
class Hours
attr_reader :value
def initialize(value)
@value = value
end
end
# Patch the #-() method to handle subtracting hours
# in addition to what it normally does
class DateTime
alias old_subtract -
def -(x)
case x
when Hours; return DateTime.new(year, month, day, hour-x.value, min, sec)
else; return self.old_subtract(x)
end
end
end
# Add an #hours attribute to Fixnum that returns an Hours object.
# This is for syntactic sugar, allowing you to write "someDate - 4.hours" for example
class Fixnum
def hours
Hours.new(self)
end
end
</code></pre>
<p>I patched the classes because I thought in this instance it would result in a clear, concise syntax for subtracting a fixed number of hours from a <code>DateTime</code>. Specifically, you could do something like this as a result of the above code:</p>
<pre><code>five_hours_ago = DateTime.now - 5.hours
</code></pre>
<p>Which seems to be fairly nice to look at and easy to understand; however, I'm not sure whether it's a good idea to be messing with the functionality of <code>DateTime</code>'s <code>-</code> operator.</p>
<p>The only alternatives that I can think of for this situation would be:</p>
<p><strong>1. Simply create a new <code>DateTime</code> object on-the-fly, computing the new hour value in the call to <code>new</code></strong>
<br/></p>
<pre><code>new_date = DateTime.new(old_date.year, old_date.year, old_date.month, old_date.year.day, old_date.hour - hours_to_subtract, date.min, date.sec)
</code></pre>
<p><br/>
<strong>2. Write a utility method that accepts a <code>DateTime</code> and the number of hours to subtract from it</strong>
<br/></p>
<p>Basically, just a wrapper around method (1):</p>
<pre><code>def subtract_hours(date, hours)
return DateTime.new(date.year, date.month, date.day, date.hour - hours, date.min, date.sec)
end
</code></pre>
<p><br/>
<strong>3. Add a new method to <code>DateTime</code> instead of changing the existing behavior of <code>#-()</code></strong></p>
<p>Perhaps a new <code>DateTime#less</code> method that could work together with the <code>Fixnum#hours</code> patch, to allow syntax like this:</p>
<pre><code>date.less(5.hours)
</code></pre>
<hr/>
<p>However, as I already mentioned, I took the patching approach because I thought it resulted in a much more expressive syntax.</p>
<p>Is there anything wrong with my approach, or should I be using one of the 3 alternatives (or another one I haven't thought of) in order to do this? I have the feeling that patching is becoming my new 'hammer' for problems in Ruby, so I'd like to get some feedback on whether I'm doing things the "Ruby way" or not.</p>
|
[
{
"answer_id": 238917,
"author": "glenn mcdonald",
"author_id": 7919,
"author_profile": "https://Stackoverflow.com/users/7919",
"pm_score": 3,
"selected": false,
"text": "class MyDateTime < DateTime\n alias...\n def...\n"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/238878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17862/"
] |
238,894
|
<p>I am trying to design a 4-bit adder subtracter in verilog. This is only the second thing I have ever written in verilog, and I don't know all the correct syntax yet. This is the module I have so far:</p>
<pre><code>module Question3(carryin, X, Y, Z, S, carryout, overflow);
parameter n = 4;
input carryin, Z;
input [n-1:0]X, Y;
output reg [n-1:0]S;
output reg carryout, overflow;
if(Z==0)
begin
Y = not(y) + 4'b0001;
end
always @(X, Y, carryin)
begin
{carryout, S} = X + Y + carryin;
overflow = carryout ^ X[n-1]^Y[n-1]^S[n-1];
end
endmodule
</code></pre>
<p>My compiler (xilinx 10.1), keeps saying "Syntax error near if." I have tried many different ways of doing the conversion, including just using a Case that takes Y as an argument, then checks all the possible 4-bit combinations, and converts them to two's complement.</p>
<p>Z is what determines if the adder does subtraction or addition. If it's 0, it means subtraction, and I want to convert y to two's complement, then just do regular addition. I'm sure the rest of the adder is correct, I just do not know what is wrong with the part where I'm trying to convert.</p>
|
[
{
"answer_id": 1005430,
"author": "Steve K",
"author_id": 121394,
"author_profile": "https://Stackoverflow.com/users/121394",
"pm_score": 4,
"selected": true,
"text": "reg [n-1:0] Y_compl;\n\nalways @( Z, Y, X, carryin ) begin\n Y_ = ( ~Y + 4'b0001 );\n if ( Z == 1'b0 ) begin\n {carryout, S} = X + Y_compl + carryin;\n overflow = carryout ^ X[n-1] ^ Y_compl[n-1] ^ S[n-1];\n end\n else begin\n {carryout, S} = X + Y + carryin;\n overflow = carryout ^ X[n-1] ^ Y[n-1] ^ S[n-1];\n end\n\nend\n"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/238894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23323/"
] |
238,898
|
<p>Has anyone noticed that if you retrieve HTML from the clipboard, it gets the encoding wrong and injects weird characters?</p>
<p>For example, executing a command like this:</p>
<pre><code>string s = (string) Clipboard.GetData(DataFormats.Html)
</code></pre>
<p>Results in stuff like:</p>
<pre><code><FONT size=-2>Â Â <A href="/advanced_search?hl=en">Advanced
Search</A><BR>Â Â <A href="/preferences?hl=en">Preferences</A><BR>Â Â <A
href="/language_tools?hl=en">Language
Tools</A></FONT>
</code></pre>
<p><em>Not sure how MarkDown will process this, but there are weird characters in the resulting markup above.</em></p>
<p>It appears that the bug is with the .NET framework. What do you think is the best way to get correctly-encoded HTML from the clipboard?</p>
|
[
{
"answer_id": 19068371,
"author": "Julo",
"author_id": 2826535,
"author_profile": "https://Stackoverflow.com/users/2826535",
"pm_score": 2,
"selected": false,
"text": "byte[] data = Encoding.Default.GetBytes(text);\ntext = Encoding.UTF8.GetString(data);\n public static bool FixMisencodedUTF8(ref string text, Encoding encoding)\n{\n if (string.IsNullOrEmpty(text))\n return false;\n byte[] data = encoding.GetBytes(text);\n // there should not be any character outside source encoding\n string newStr = encoding.GetString(data);\n if (!string.Equals(text, newStr)) // if there is any character \"outside\"\n return false; // leave, the input is in a different encoding\n if (IsValidUtf8(data) == 0) // test data to be valid UTF-8 byte sequence\n return false; // if not, can not convert to UTF-8\n text = Encoding.UTF8.GetString(data);\n return true;\n}\n"
},
{
"answer_id": 29662404,
"author": "Огњен Шобајић",
"author_id": 638041,
"author_profile": "https://Stackoverflow.com/users/638041",
"pm_score": 0,
"selected": false,
"text": "System.Windows.Forms.Clipboard.GetText(System.Windows.Forms.TextDataFormat.Html);\n"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/238898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31015/"
] |
238,915
|
<p>I've got a UserControl that contains an UpdatePanel. When I put that on a page, it throws the following error:</p>
<blockquote>
<p>Cannot unregister UpdatePanel with ID
'ReviewContentUpdatePanel' since it
was not registered with the
ScriptManager. This might occur if the
UpdatePanel was removed from the
control tree and later added again,
which is not supported. Parameter
name: updatePanel</p>
</blockquote>
<p><code>ReviewContentUpdatePanel</code> is the name of the update panel & it's not being removed or added in code, it exists in the aspx page and isn't removed. Has anyone come across this before?</p>
|
[
{
"answer_id": 19006245,
"author": "Steve",
"author_id": 1571391,
"author_profile": "https://Stackoverflow.com/users/1571391",
"pm_score": 2,
"selected": false,
"text": "protected override void OnInit(EventArgs e)\n{\n ScriptManager sm = ScriptManager.GetCurrent(this.Page);\n MethodInfo m = (\n from methods in typeof(ScriptManager).GetMethods(\n BindingFlags.NonPublic | BindingFlags.Instance\n )\n where methods.Name.Equals(\"System.Web.UI.IScriptManagerInternal.RegisterUpdatePanel\")\n select methods).First<MethodInfo>();\n\n m.Invoke(sm, new object[] { updatePanel });\n base.OnInit(e);\n}\n"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/238915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
] |
238,918
|
<p>I have been having some problems trying to get my PHP running. When I try and run any scripts they appear in the source and do not run properly. This is the htaccess file:</p>
<pre><code># Use PHP5 as default
AddHandler application/x-httpd-php5 .php
AddType x-mapp-php5 .php
AddHandler x-mapp-php5 .php
</code></pre>
<p>Could this be the error?</p>
|
[
{
"answer_id": 238926,
"author": "noob source",
"author_id": 29838,
"author_profile": "https://Stackoverflow.com/users/29838",
"pm_score": 3,
"selected": true,
"text": "AddHandler application/x-httpd-php5 .php AddHandler application/x-httpd-php .php AddType AddHandler x-mapp-* LoadModule php5_module /usr/lib/apache2/modules/libphp5.so"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/238918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31677/"
] |
238,920
|
<p>What's a simple/easy way to access the system clock using Java, so that I can calculate the elapsed time of an event?</p>
|
[
{
"answer_id": 238924,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": false,
"text": "java.lang.System.currentTimeMillis() java.lang.System.nanoTime()"
},
{
"answer_id": 238943,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 5,
"selected": false,
"text": "long startTime = System.currentTimeMillis();\n// Run some code;\nlong stopTime = System.currentTimeMillis();\n\nSystem.out.println(\"Elapsed time was \" + (stopTime - startTime) + \" miliseconds.\");\n"
},
{
"answer_id": 239661,
"author": "Leigh",
"author_id": 26061,
"author_profile": "https://Stackoverflow.com/users/26061",
"pm_score": 7,
"selected": true,
"text": "System.currentTimeMillis() currentTimeMillis() System.nanoTime()"
},
{
"answer_id": 13477989,
"author": "Wilhem Meignan",
"author_id": 1812722,
"author_profile": "https://Stackoverflow.com/users/1812722",
"pm_score": 2,
"selected": false,
"text": "public class StopWatch {\n // Constructor\n public StopWatch() {\n }\n\n // Public API\n public void start() {\n if (!_isRunning) {\n _startTime = System.nanoTime();\n _isRunning = true;\n }\n }\n\n public void stop() {\n if (_isRunning) {\n _elapsedTime += System.nanoTime() - _startTime;\n _isRunning = false;\n }\n }\n\n public void reset() {\n _elapsedTime = 0;\n if (_isRunning) {\n _startTime = System.nanoTime();\n }\n }\n\n public boolean isRunning() {\n return _isRunning;\n }\n\n public long getElapsedTimeNanos() {\n if (_isRunning) {\n return System.nanoTime() - _startTime;\n }\n return _elapsedTime;\n }\n\n public long getElapsedTimeMillis() {\n return getElapsedTimeNanos() / 1000000L;\n }\n\n // Private Members\n private boolean _isRunning = false;\n private long _startTime = 0;\n private long _elapsedTime = 0;\n}\n"
},
{
"answer_id": 36049046,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 3,
"selected": false,
"text": "Instant now Instant now = Instant.now();\n Instant Duration Duration duration = Duration.between( startInstant , stopInstant );\n Duration::toString toNanos toMillis Clock System.currentTimeMillis() Clock"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/238920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22371/"
] |
238,931
|
<p>I am developing some client side Javascript that is using some JSON web services on a different domain. I have read that some browsers do not allow cross-domain scripting and that I should create a proxy on my local server to serve the data.</p>
<p>Can someone please point me to a simple example of how to do this in ASP.Net?</p>
|
[
{
"answer_id": 238953,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 0,
"selected": false,
"text": "SomeAjaxAbstraction.Request('proxyScript', {\n parameters: {\n address: 'http://somewhere.com/someapi?some=query'\n }\n});\n var address = GET['address'];\nif(ValidUrl(address) && ConnectionAllowed(address)) {\n // Validating address and whitelisting services is an exercise to the reader\n var response = SomeHttpGetFunction(address);\n echo XssAndBadStuffFilter(response);\n} else {\n // Handle errors\n}\n"
},
{
"answer_id": 239068,
"author": "Matt Ephraim",
"author_id": 22291,
"author_profile": "https://Stackoverflow.com/users/22291",
"pm_score": 3,
"selected": true,
"text": "jQuery.getJSON(\"http://www.someothersite.com/webservice?callback=?\", function(result)\n{\n doStuffWithResult(result);\n});\n jsonp2342342({key: value, key2: value});\n"
},
{
"answer_id": 3199434,
"author": "chapmanjw",
"author_id": 385835,
"author_profile": "https://Stackoverflow.com/users/385835",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Net;\nusing System.IO;\n\nnamespace Proxy\n{\n public partial class _Proxy : System.Web.UI.Page\n {\n protected void Page_Load(object sender, EventArgs e)\n {\n string proxyURL = string.Empty;\n try\n {\n proxyURL = HttpUtility.UrlDecode(Request.QueryString[\"u\"].ToString());\n }\n catch { }\n\n if (proxyURL != string.Empty)\n {\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(proxyURL);\n request.Method = \"GET\";\n HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n\n if (response.StatusCode.ToString().ToLower() == \"ok\")\n {\n string contentType = response.ContentType;\n Stream content = response.GetResponseStream();\n StreamReader contentReader = new StreamReader(content);\n Response.ContentType = contentType;\n Response.Write(contentReader.ReadToEnd());\n }\n }\n }\n }\n}\n"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/238931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10589/"
] |
238,941
|
<p><strong>UPDATE:</strong> Thanks to everyone for the responses. I didn't realize document.write() was deprecated. Add a another notch to the learning column. I'll be taking the advice posted here, but leave the original question so that the answers given make sense in context of the original question.</p>
<hr>
<p>I'm in the process of coding some rather long write() arguments and am trying to decide which of the following examples would be the best to follow, considering syntax, readability and performance. Should I</p>
<p>a. Keep them all on one line:</p>
<pre><code><script>
var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)";
document.write("<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>" + someVariable + "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>" + someVariable);
</script>
</code></pre>
<p>b. Break them up by adding line breaks for somewhat improved readability:</p>
<pre><code><script>
var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)";
document.write("<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>"
+ someVariable
+ "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>"
+ someVariable);
</script>
</code></pre>
<p>c. Break them up by using multiple variables:</p>
<pre><code><script>
var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)";
var partOne = "<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>";
var partTwo = "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>";
document.write(partOne + someVariable + partTwo + someVariable);
</script>
</code></pre>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 238957,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 3,
"selected": true,
"text": "var longVar = 'asdfasdf asdf asdf asdfasdf asdfasdf asdf asdfasdf' +\n ' fasdf s9d0af asdf asdf0s,dv z-xcfva-sdfmwaert ' +\n 'qersdfasdfasdfasdfasdf';\ndocument.write(longVar);\n var longVar = [\n 'asdfasdf asdf asdf asdfasdf asdfasdf asdf asdfasdf',\n ' fasdf s9d0af asdf asdf0s,dv z-xcfva-sdfmwaert ',\n 'qersdfasdfasdfasdfasdf'\n].join('');\ndocument.write(longVar);\n"
},
{
"answer_id": 239022,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": 0,
"selected": false,
"text": "document.write() <script type=\"text/javascript\">\n window.onload = function(){\n var newD = document.createElement(\"div\");\n newD.appendChild(document.createTextNode(\"Hello World\"));\n document.getElementsByTagName(\"body\")[0].appendChild(newD);\n }\n</script>\n"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/238941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
238,949
|
<p>If this is possible, please provide a sample query or two so I can see how it would work. Both tables will be in the same database.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 238952,
"author": "Andrew",
"author_id": 826,
"author_profile": "https://Stackoverflow.com/users/826",
"pm_score": 5,
"selected": true,
"text": "insert into <target-table>\n( <column-list> )\nselect <columns>\n from <source-table>\n"
},
{
"answer_id": 239003,
"author": "Rob",
"author_id": 3542,
"author_profile": "https://Stackoverflow.com/users/3542",
"pm_score": 2,
"selected": false,
"text": "INSERT...SELECT INSERT INTO names\nSELECT last_name, first_name\nFROM people\n"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/238949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1572436/"
] |
238,956
|
<p>On the latest Ubuntu, I have a functioning PHP 5.2.4 installation. I want to use a remote Oracle server from PHP using OCI.</p>
<p>I've downloaded the <em>"Instant Client Package - Basic Lite"</em> (<a href="http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/linuxsoft.html" rel="nofollow noreferrer">Link</a>). I've unzipped the package containing the OCI libraries to a dir but I have no idea how to tell PHP that I want to use these libraries. Predictably, I get</p>
<blockquote>
<p>Fatal error: Call to undefined function oci_connect() in...</p>
</blockquote>
<p>when running this code:</p>
<pre><code><?php
$conn = oci_connect('hr', 'hrpw', 'someremotehost');
?>
</code></pre>
<p>I don't want to recompile PHP with Oracle support. What's the fastest way to wire up PHP so that I can use Oracle? Do I need any other libaries, like the Oracle client if I want to connect to a remote Oracle instance?</p>
|
[
{
"answer_id": 238979,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 2,
"selected": false,
"text": "(sudo) pecl install oci8\n extension=oci8.so <?php phpinfo(); ?>"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/238956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3401/"
] |
238,977
|
<p>How do i take a HTML site that currently has no doctype declaration and make it W3C compliant?</p>
|
[
{
"answer_id": 240021,
"author": "Mr. Shiny and New 安宇",
"author_id": 7867,
"author_profile": "https://Stackoverflow.com/users/7867",
"pm_score": 0,
"selected": false,
"text": "<div height=\"100\" width=\"100\" style=\"border: 1px solid red\"></div>\n <head>\n <style> .adbox { height: 100px; width: 100px; border: 1px solid red; } </style>\n</head>\n<body>\n <div class=\"adbox\"></div>\n</body>\n"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/238977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
238,980
|
<p>I began an iPhone project the other day with a silly development code name, and now I want to change the name of the project since it's nearly finished. </p>
<p>But I'm not sure how to do this with Xcode, trying the obvious of changing the application's name in the info.plist file, causes the signing process to go wrong (I think...) and my app won't launch giving me a Launcher error.</p>
<p>I guess I could make a new project and copy paste everything over, but it seems so primitive that I'm hoping for a more civilized solution.</p>
|
[
{
"answer_id": 239006,
"author": "Giao",
"author_id": 14099,
"author_profile": "https://Stackoverflow.com/users/14099",
"pm_score": 11,
"selected": true,
"text": "Targets Xcode Build Settings Product Name Packaging"
},
{
"answer_id": 27418699,
"author": "Jeffrey Neo",
"author_id": 1856717,
"author_profile": "https://Stackoverflow.com/users/1856717",
"pm_score": 3,
"selected": false,
"text": "Product Name Project Name"
},
{
"answer_id": 34370505,
"author": "surfrider",
"author_id": 667483,
"author_profile": "https://Stackoverflow.com/users/667483",
"pm_score": 3,
"selected": false,
"text": ".plist plist $(TARGET_NAME)"
},
{
"answer_id": 40885997,
"author": "onmyway133",
"author_id": 1418457,
"author_profile": "https://Stackoverflow.com/users/1418457",
"pm_score": 3,
"selected": false,
"text": "Product name $(PRODUCT_NAME) Target name scheme Bundle display name CFBundleDisplayName Product name"
},
{
"answer_id": 56841093,
"author": "Sudhanshu Vohra",
"author_id": 6726650,
"author_profile": "https://Stackoverflow.com/users/6726650",
"pm_score": 4,
"selected": false,
"text": "A target specifies a product to build and contains the instructions for building the product from a set of files in a project or workspace. $(PRODUCT_NAME) $(TARGET_NAME)"
},
{
"answer_id": 58380264,
"author": "Muhammad Nayab",
"author_id": 6743228,
"author_profile": "https://Stackoverflow.com/users/6743228",
"pm_score": 4,
"selected": false,
"text": "CFBundleDisplayName <key>CFBundleDisplayName</key>\n<string>Your App Name</string>\n"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/238980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] |
238,996
|
<p>I've never had a reason to put a label element inside of a legend element (never really thought about it or seen it done). But with the design I'm implementing, it's tempting to do so.</p>
<p>Here's what I'm tempted to do:</p>
<pre><code><fieldset>
<legend><label for="formInfo">I would like information on</label></legend>
<select id="formInfo">
<option value="Cats">Cats</option>
<option value="Dogs">Dogs</option>
<option value="Lolz">Lolz</option>
</select>
</fieldset>
</code></pre>
<p>It works as expected (clicking the label focuses the corresponding input) in Firefox3, Safari, Opera, and IE6/7 and it passes validation, but I'm just wondering if there are any known reasons (accessibility? semantics? browser issues) why this shouldn't be done</p>
|
[
{
"answer_id": 239011,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "legend"
},
{
"answer_id": 239190,
"author": "joelhardi",
"author_id": 11438,
"author_profile": "https://Stackoverflow.com/users/11438",
"pm_score": 5,
"selected": true,
"text": "</fieldset> legend fieldset label div span div span select"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/238996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17252/"
] |
239,002
|
<p>Is there a simple way to duplicate all child components under parent component, including their published properties?</p>
<p>For example:</p>
<ul>
<li>TPanel
<ul>
<li>TLabel</li>
<li>TEdit</li>
<li>TListView</li>
<li>TSpecialClassX</li>
</ul></li>
</ul>
<p>Of course the most important factor, it should duplicate any new component which I drop on the TPanel without modifying the code under normal circumstances.</p>
<p>I've heard of the RTTI, but never used it actually. Any ideas?</p>
|
[
{
"answer_id": 239056,
"author": "Kluge",
"author_id": 8752,
"author_profile": "https://Stackoverflow.com/users/8752",
"pm_score": 0,
"selected": false,
"text": "for (i = 0; i < ComponentCount; ++i) {\n TControl *Comp = dynamic_cast<TControl *>(Components[i]);\n if (Comp) {\n if (Comp->ClassNameIs(\"TLabel\")) {\n TLabel *OldLabel = dynamic_cast<TDBEdit *>(Components[i]);\n TLabel *NewLabel = new TLabel(this); // new label\n // copy properties from old to new\n NewLabel->Top = OldLabel->Top;\n NewLabel->Left = OldLabel->Left;\n NewLabel->Caption = Oldlabel->Caption\n // and so on...\n } else if (Comp->ClassNameIs(\"TPanel\")) {\n // copy a TPanel object\n }\n"
},
{
"answer_id": 239148,
"author": "Christopher Chase",
"author_id": 11016,
"author_profile": "https://Stackoverflow.com/users/11016",
"pm_score": 4,
"selected": true,
"text": "procedure CopyObject(ObjFrom, ObjTo: TObject); \n var\nPropInfos: PPropList;\nPropInfo: PPropInfo;\nCount, Loop: Integer;\nOrdVal: Longint;\nStrVal: String;\nFloatVal: Extended; \nMethodVal: TMethod;\nbegin\n//{ Iterate thru all published fields and properties of source }\n//{ copying them to target }\n\n//{ Find out how many properties we'll be considering }\nCount := GetPropList(ObjFrom.ClassInfo, tkAny, nil);\n//{ Allocate memory to hold their RTTI data }\nGetMem(PropInfos, Count * SizeOf(PPropInfo));\ntry\n//{ Get hold of the property list in our new buffer }\nGetPropList(ObjFrom.ClassInfo, tkAny, PropInfos);\n//{ Loop through all the selected properties }\nfor Loop := 0 to Count - 1 do\nbegin\n PropInfo := GetPropInfo(ObjTo.ClassInfo, PropInfos^[Loop]^.Name);\n // { Check the general type of the property }\n //{ and read/write it in an appropriate way }\n case PropInfos^[Loop]^.PropType^.Kind of\n tkInteger, tkChar, tkEnumeration,\n tkSet, tkClass{$ifdef Win32}, tkWChar{$endif}:\n begin\n OrdVal := GetOrdProp(ObjFrom, PropInfos^[Loop]);\n if Assigned(PropInfo) then\n SetOrdProp(ObjTo, PropInfo, OrdVal);\n end;\n tkFloat:\n begin\n FloatVal := GetFloatProp(ObjFrom, PropInfos^[Loop]);\n if Assigned(PropInfo) then\n SetFloatProp(ObjTo, PropInfo, FloatVal);\n end;\n {$ifndef DelphiLessThan3}\n tkWString,\n {$endif}\n {$ifdef Win32}\n tkLString,\n {$endif}\n tkString:\n begin\n { Avoid copying 'Name' - components must have unique names }\n if UpperCase(PropInfos^[Loop]^.Name) = 'NAME' then\n Continue;\n StrVal := GetStrProp(ObjFrom, PropInfos^[Loop]);\n if Assigned(PropInfo) then\n SetStrProp(ObjTo, PropInfo, StrVal);\n end;\n tkMethod:\n begin\n MethodVal := GetMethodProp(ObjFrom, PropInfos^[Loop]);\n if Assigned(PropInfo) then\n SetMethodProp(ObjTo, PropInfo, MethodVal);\n end\n end\nend\nfinally\n FreeMem(PropInfos, Count * SizeOf(PPropInfo));\nend;\nend;\n"
},
{
"answer_id": 239321,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 3,
"selected": false,
"text": "uses\n TypInfo;\n\nprocedure CloneProperties(const Source: TControl; const Dest: TControl);\nvar\n ms: TMemoryStream;\n OldName: string;\nbegin\n OldName := Source.Name;\n Source.Name := ''; // needed to avoid Name collision\n try\n ms := TMemoryStream.Create;\n try\n ms.WriteComponent(Source);\n ms.Position := 0;\n ms.ReadComponent(Dest);\n finally\n ms.Free;\n end;\n finally\n Source.Name := OldName;\n end;\nend;\n\nprocedure CloneEvents(Source, Dest: TControl);\nvar\n I: Integer;\n PropList: TPropList;\nbegin\n for I := 0 to GetPropList(Source.ClassInfo, [tkMethod], @PropList) - 1 do\n SetMethodProp(Dest, PropList[I], GetMethodProp(Source, PropList[I]));\nend;\n\nprocedure DuplicateChildren(const ParentSource: TWinControl;\n const WithEvents: Boolean = True);\nvar\n I: Integer;\n CurrentControl, ClonedControl: TControl;\nbegin\n for I := ParentSource.ControlCount - 1 downto 0 do\n begin\n CurrentControl := ParentSource.Controls[I];\n ClonedControl := TControlClass(CurrentControl.ClassType).Create(CurrentControl.Owner);\n ClonedControl.Parent := ParentSource;\n CloneProperties(CurrentControl, ClonedControl);\n ClonedControl.Name := CurrentControl.Name + '_';\n if WithEvents then\n CloneEvents(CurrentControl, ClonedControl);\n end;\nend;\n\nprocedure TForm1.Button1Click(Sender: TObject);\nbegin\n DuplicateChildren(Panel1);\nend;\n"
},
{
"answer_id": 241415,
"author": "Uwe Raabe",
"author_id": 26833,
"author_profile": "https://Stackoverflow.com/users/26833",
"pm_score": 3,
"selected": false,
"text": "MemStream := TMemoryStream.Create;\ntry\n MemStream.WriteComponent(Source);\n MemStream.Position := 0;\n MemStream.ReadComponent(Target);\nfinally\n MemStream.Free;\nend;\n"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/239002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30787/"
] |
239,004
|
<p>We use GNU Make for our system. At the end of our makefiles, we have an include called Makedepends which generates a bunch of .d files using -MM switch on gcc. We then include the .d file for each .cc file using an include $(CXXFILES:.cc=.d) line. But when we delete file or move files, the dependancies step breaks and we have to manually delete the .d files (even a make clean doesn't work because the dependencies fail)</p>
<p>Is there a way to generate these dependency .d files or include these dependency .d files which will gracefully handle a file deletion or relocation?</p>
<p>EDIT: For example: I have serial.cc and the makefiles generate a serial.d file which has a dependency on buffer.h but then I change it so I don't need buffer.h any more and I delete buffer.h. Next time I run make, it will choke because it includes the .d file which still makes serial.o depend on buffer.h.</p>
|
[
{
"answer_id": 239024,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 0,
"selected": false,
"text": ".SUFFIXES: .d\n\n%.d::\n makedepend_command_here\n Last Resort info %::\n touch $@\n .d"
},
{
"answer_id": 16016596,
"author": "Daniel",
"author_id": 1122011,
"author_profile": "https://Stackoverflow.com/users/1122011",
"pm_score": 0,
"selected": false,
"text": "--rm-stale .makepprc gcc -MM"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/239004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20889/"
] |
239,009
|
<p>I need to update data to a mssql 2005 database so I have decided to use adodbapi, which is supposed to come built into the standard installation of python 2.1.1 and greater.</p>
<p>It needs pywin32 to work correctly and the open office python 2.3 installation does not have pywin32 built into it. It also seems like this built int python installation does not have adodbapi, as I get an error when I go import adodbapi. </p>
<p>Any suggestions on how to get both pywin32 and adodbapi installed into this open office 2.4 python installation?</p>
<p>thanks </p>
<hr>
<p>oh yeah I tried those ways. annoyingly nothing. So i have reverted to jython, that way I can access Open Office for its conversion capabilities along with decent database access.</p>
<p>Thanks for the help.</p>
|
[
{
"answer_id": 239179,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 0,
"selected": false,
"text": "tools / COM Makepy utility makepy Microsoft ActiveX Data Objects 2.8 Library (2.8)\nMicrosoft ActiveX Data Objects Recordset 2.8 Library (2.8)\n makepy COM ADODB from win32com import client\nconn=client.Dispatch('adodb.connection')\nconn.Open(connection_string)\nresultset,x=e.Execute('select * from mytable')\nresultset.MoveFirst()\nrecord_fields=resultset.Fields\n(etc.)\n"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/239009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21537/"
] |
239,020
|
<p>I have a third-party product, a terminal emulator, which provides a DLL that can be linked to a C program to basically automate the driving of this product (send keystrokes, detect what's on the screen and so forth).</p>
<p>I want to drive it from a scripting language (I'm comfortable with Python and slightly less so with Perl) so that we don't have to compile and send out executables to our customers whenever there's a problem found.</p>
<p>We also want the customers to be able to write their own scripts using ours as baselines and they won't entertain the idea of writing and compiling C code.</p>
<p>What's a good way of getting Python/Perl to interface to a Windows DLL. My first thought was to write a server program and have a Python script communicate with it via TCP but there's got to be an easier solution.</p>
|
[
{
"answer_id": 239041,
"author": "albertb",
"author_id": 26715,
"author_profile": "https://Stackoverflow.com/users/26715",
"pm_score": 5,
"selected": true,
"text": ">>> from ctypes import *\n>>> windll.user32.MessageBoxA(None, \"Hello world\", \"ctypes\", 0);\n"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/239020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14860/"
] |
239,023
|
<p>I have a dependency that I need to inject into one of my classes. This dependency will be lifestyle of <code>Transient</code>. It in-turn has a dependency of type <code>Type</code>. This type should be the type of the original class. I was just wondering if anyone has any idea how I might go about conducting this registration.</p>
<p>See example:</p>
<pre><code>public interface ICustomer
{
.....
}
public class Customer : ICustomer
{
public Customer(IRegister register)
{ .... }
}
public interface IRegister
{
.....
}
public class Register
{
public Register(Type partentType)
{ .... }
}
public class TestExample
{
public static void TestMe()
{
//If i was creating all this manually it would look
// something like this
IRegister myRegister = new Register(typeof(Customer));
ICustomer myCustomer = new Customer(myRegister);
}
}
</code></pre>
<p>Now I know I could call <code>Container.Resolve</code> when ever I want a <code>Customer</code> and then inject <code>Register</code> manually. But I need to inject <code>Register</code> into most of my classes so this isn't really that feasible. Hence I need a way of doing it via the config or via <code>container.Register</code>.</p>
|
[
{
"answer_id": 239033,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 0,
"selected": false,
"text": "public interface IRegister{\n RegisterResult MyMethod(object thing);\n}\n"
},
{
"answer_id": 329420,
"author": "Andrey Shchekin",
"author_id": 39068,
"author_profile": "https://Stackoverflow.com/users/39068",
"pm_score": 1,
"selected": false,
"text": "public interface IRegister<TParent> { ... }\npublic class Register<TParent> : IRegister<TParent>\n{\n public Register() { ... }\n}\n\npublic class Customer : ICustomer\n{\n public Customer(IRegister<Customer> register) { .... }\n}\n"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/239023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30572/"
] |
239,059
|
<p>I am trying to mock out HttpContext so that I can unit test my controller's Request.IsAuthenicated call. I am using the <a href="http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx" rel="noreferrer">code that I found at Scott Hanselman's</a> blog to simulate HttpContext using rhino.mocks.
so i have this unit test piece:</p>
<pre><code>PostsController postsController = new PostsController(postDL);
mocks.SetFakeControllerContext(postsController);
Expect.Call(postsController.Request.IsAuthenticated).Return(true);
</code></pre>
<p>In my controller action, I have something like
<code>if(Request.IsAuthenticated)....</code>
when I try to run the unit test, the test fails throwing a null exception, and when I try to debug the unit test, I see that the HttpContext is never assigned to the controller.
any ideas?</p>
|
[
{
"answer_id": 239418,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "interface IAuthenticationChecker\n{\n bool IsAuthenticated { get; }\n}\n\npublic class MockAuthenticationChecker : IAuthenticationChecker\n{\n static bool _authenticated = false;\n\n public static void SetAuthenticated(bool value)\n {\n _authenticated = value;\n }\n #region IAuthenticationChecker Members\n\n public bool IsAuthenticated\n {\n get { return _authenticated; }\n }\n\n #endregion\n}\n\npublic class RequestAuthenticationChecker : IAuthenticationChecker\n{\n\n #region IAuthenticationChecker Members\n\n public bool IsAuthenticated\n {\n get {\n if (HttpContext.Current == null)\n throw new ApplicationException(\n \"Unable to Retrieve IsAuthenticated for Request becuse there is no current HttpContext.\");\n\n return HttpContext.Current.Request.IsAuthenticated;\n }\n }\n\n #endregion\n}\n"
},
{
"answer_id": 239955,
"author": "Tim Scott",
"author_id": 29493,
"author_profile": "https://Stackoverflow.com/users/29493",
"pm_score": 3,
"selected": false,
"text": "PostsController postsController = new PostsController(postDL);\nvar context = mocks.Stub<HttpContextBase>();\nvar request = mocks.Stub<HttpRequestBase>();\nSetupResult.For(request.IsAuthenticated).Return(true);\nSetupResult.For(context.Request).Return(request); \npostsController.ControllerContext = new ControllerContext(context, new RouteData(), postsController);\n"
},
{
"answer_id": 7500053,
"author": "Lauri I",
"author_id": 824931,
"author_profile": "https://Stackoverflow.com/users/824931",
"pm_score": 0,
"selected": false,
"text": " TextWriter tw = new StringWriter();\n HttpWorkerRequest wr = new SimpleWorkerRequest(\"/webapp\", \"c:\\\\inetpub\\\\wwwroot\\\\webapp\\\\\", \"default.aspx\", \"\", tw);\n HttpContext.Current = new HttpContext(wr);\n"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/239059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31699/"
] |
239,063
|
<p>I came across an article about Car remote entry system at <a href="http://auto.howstuffworks.com/remote-entry2.htm" rel="nofollow noreferrer">http://auto.howstuffworks.com/remote-entry2.htm</a> In the third bullet, author says,</p>
<blockquote>
<p>Both the transmitter and the receiver use the same pseudo-random number generator. When the transmitter sends a 40-bit code, it uses the pseudo-random number generator to pick a new code, which it stores in memory. On the other end, when the receiver receives a valid code, it uses the same pseudo-random number generator to pick a new one. In this way, the transmitter and the receiver are synchronized. The receiver only opens the door if it receives the code it expects.</p>
</blockquote>
<p>Is it possible to have two PRNG functions producing same random numbers at the same time? </p>
|
[
{
"answer_id": 239066,
"author": "Erik Forbes",
"author_id": 16942,
"author_profile": "https://Stackoverflow.com/users/16942",
"pm_score": 5,
"selected": true,
"text": "// Provide the same seed value for both generators:\nSystem.Random r1 = new System.Random(1);\nSystem.Random r2 = new System.Random(1);\n\n// Will output 'True'\nConsole.WriteLine(r1.Next() == r2.Next());\n"
},
{
"answer_id": 239079,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 2,
"selected": false,
"text": "nextNumber = function(seed);\nseed = nextNumber;\n function(seed)"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/239063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15474/"
] |
239,082
|
<p>I'm working on a simple javascript login for a site, and have come up with this:</p>
<pre><code><form id="loginwindow">
<strong>Login to view!</strong>
<p><strong>User ID:</strong>
<input type="text" name="text2">
</p>
<p><strong>Password:</strong>
<input type="password" name="text1"><br>
<input type="button" value="Check In" name="Submit" onclick=javascript:validate(text2.value,"username",text1.value,"password") />
</p>
</form>
<script language = "javascript">
function validate(text1,text2,text3,text4)
{
if (text1==text2 && text3==text4)
load('album.html');
else
{
load('failure.html');
}
}
function load(url)
{
location.href=url;
}
</script>
</code></pre>
<p>...which works except for one thing: hitting enter to submit the form doesn't do anything. I have a feeling it's cause I've used "onclick" but I'm not sure what to use instead. Thoughts?</p>
<hr>
<p>Okay yeah so I'm well aware of how flimsy this is security-wise. It's not for anything particularly top secret, so it's not a huge issue, but if you guys could elaborate on your thoughts with code, I'd love to see your ideas. the code i listed is literally all I'm working with at this point, so I can start from scratch if need be.</p>
|
[
{
"answer_id": 239086,
"author": "keparo",
"author_id": 19468,
"author_profile": "https://Stackoverflow.com/users/19468",
"pm_score": 6,
"selected": true,
"text": "<input type=\"submit\".../> \n <input type=\"button\".../>\n <form action=\"/post.php\" method=\"post\">\n <!-- \n ...\n -->\n <input type=\"submit\" value=\"go\"/>\n</form>\n <form action=\"#\" method=\"post\" id=\"loginwindow\">\n <h3>Login to view!</h3>\n <label>User ID: <input type=\"text\" id=\"userid\"></label>\n <label>Password: <input type=\"password\" id=\"pass\"></label>\n <input type=\"submit\" value=\"Check In\" />\n</form>\n\n<script type=\"text/javascript\">\nwindow.onload = function () {\n var loginForm = document.getElementById('loginwindow');\n if ( loginwindow ) {\n loginwindow.onsubmit = function () {\n\n var userid = document.getElementById('userid');\n var pass = document.getElementById('pass');\n\n // Make sure javascript found the nodes:\n if (!userid || !pass ) {\n return false;\n }\n\n // Actually check values, however you'd like this to be done:\n if (pass.value !== \"secret\") {\n location.href = 'failure.html';\n }\n\n location.href = 'album.html';\n return false;\n };\n }\n};\n</script>\n"
},
{
"answer_id": 239092,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 0,
"selected": false,
"text": "<form id=\"loginwindow\" onsubmit='validate(text2.value,\"username\",text1.value,\"password\")'>\n<strong>Login to view!</strong>\n<p><strong>User ID:</strong>\n <input type=\"text\" name=\"text2\">\n</p>\n<p><strong>Password:</strong>\n<input type=\"password\" name=\"text1\"><br>\n <input type=\"submit\" value=\"Check In\"/>\n</p>\n\n</form>\n"
},
{
"answer_id": 239095,
"author": "Elle H",
"author_id": 23666,
"author_profile": "https://Stackoverflow.com/users/23666",
"pm_score": 1,
"selected": false,
"text": "<input type=\"password\" name=\"text1\" onkeypress=\"detectKey(event)\">\n"
},
{
"answer_id": 239104,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": 0,
"selected": false,
"text": "<form action=\"http://www.mySite.com/\" method=\"post\" onsubmit=\"this.action+=this.theName.value+this.thePassword.value;\">\n Name: <input type=\"text\" name=\"theName\"><br>\n Password: <input type=\"password\" name=\"thePassword\"><br>\n <input type=\"submit\" value=\"Login now\">\n</form>\n"
},
{
"answer_id": 43979442,
"author": "csandreas1",
"author_id": 6041389,
"author_profile": "https://Stackoverflow.com/users/6041389",
"pm_score": 2,
"selected": false,
"text": " <form id=\"Form-v2\" action=\"#\">\n\n<input type=\"text\" name=\"search_field\" placeholder=\"Enter a movie\" value=\"\" \nid=\"search_field\" title=\"Enter a movie here\" class=\"blink search-field\" />\n<input type=\"submit\" onclick=\"\" value=\"GO!\" class=\"search-button\" /> \n </form>\n\n <script>\n //submit the form\n $( \"#Form-v2\" ).submit(function( event ) {\n event.preventDefault();\n });\n </script>\n"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/239082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27171/"
] |
239,103
|
<p>I have a char in c#:</p>
<pre><code>char foo = '2';
</code></pre>
<p>Now I want to get the 2 into an int. I find that Convert.ToInt32 returns the actual decimal value of the char and not the number 2. The following will work:</p>
<pre><code>int bar = Convert.ToInt32(new string(foo, 1));
</code></pre>
<p>int.parse only works on strings as well. </p>
<p>Is there no native function in C# to go from a char to int without making it a string? I know this is trivial but it just seems odd that there's nothing native to directly make the conversion.</p>
|
[
{
"answer_id": 239107,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 8,
"selected": false,
"text": "int char foo = '2';\nint bar = foo - '0';\n '0' '9' '0' '2'"
},
{
"answer_id": 239109,
"author": "sontek",
"author_id": 17176,
"author_profile": "https://Stackoverflow.com/users/17176",
"pm_score": 5,
"selected": false,
"text": "char c = '1';\nint i = (int)(c - '0');\n static int ToInt(this char c)\n{\n return (int)(c - '0');\n}\n"
},
{
"answer_id": 239159,
"author": "faulty",
"author_id": 20007,
"author_profile": "https://Stackoverflow.com/users/20007",
"pm_score": 7,
"selected": false,
"text": "int.Parse() int.TryParse() int bar = int.Parse(foo.ToString());\n int bar;\nif (!int.TryParse(foo.ToString(), out bar))\n{\n //Do something to correct the problem\n}\n"
},
{
"answer_id": 795991,
"author": "Chad Grant",
"author_id": 1385845,
"author_profile": "https://Stackoverflow.com/users/1385845",
"pm_score": 9,
"selected": true,
"text": "GetNumericValue Char Parse TryParse Char ToString Char String"
},
{
"answer_id": 8677050,
"author": "RollerCosta",
"author_id": 1016228,
"author_profile": "https://Stackoverflow.com/users/1016228",
"pm_score": 4,
"selected": false,
"text": "char x = '9'; // '9' = ASCII 57\n\nint b = x - '0'; //That is '9' - '0' = 57 - 48 = 9\n"
},
{
"answer_id": 13082249,
"author": "Nikolay",
"author_id": 1679627,
"author_profile": "https://Stackoverflow.com/users/1679627",
"pm_score": 3,
"selected": false,
"text": "int bar = int.Parse(foo.ToString());"
},
{
"answer_id": 18435669,
"author": "Renán Díaz",
"author_id": 2716612,
"author_profile": "https://Stackoverflow.com/users/2716612",
"pm_score": -1,
"selected": false,
"text": "int bar = int.Parse(\"\" + foo);\n"
},
{
"answer_id": 29712248,
"author": "Dan Friedman",
"author_id": 1152054,
"author_profile": "https://Stackoverflow.com/users/1152054",
"pm_score": 3,
"selected": false,
"text": "CharUnicodeInfo.GetDecimalDigitValue('2')"
},
{
"answer_id": 31981205,
"author": "antonio",
"author_id": 1024754,
"author_profile": "https://Stackoverflow.com/users/1024754",
"pm_score": 2,
"selected": false,
"text": "char letterA = Convert.ToChar(65);\nConsole.WriteLine(letterA);\nletterA = 'あ';\nushort valueA = Convert.ToUInt16(letterA);\nConsole.WriteLine(valueA);\nchar japaneseA = Convert.ToChar(valueA);\nConsole.WriteLine(japaneseA);\n"
},
{
"answer_id": 41655385,
"author": "Slai",
"author_id": 1383168,
"author_profile": "https://Stackoverflow.com/users/1383168",
"pm_score": 2,
"selected": false,
"text": "char c1 = (char)('0' - 1), c2 = (char)('9' + 1); \n\nDebug.Print($\"{c1 & 15}, {c2 & 15}\"); // 15, 10\nDebug.Print($\"{c1 ^ '0'}, {c2 ^ '0'}\"); // 31, 10\nDebug.Print($\"{c1 - '0'}, {c2 - '0'}\"); // -1, 10\nDebug.Print($\"{(uint)c1 - '0'}, {(uint)c2 - '0'}\"); // 4294967295, 10\nDebug.Print($\"{char.GetNumericValue(c1)}, {char.GetNumericValue(c2)}\"); // -1, -1\n"
},
{
"answer_id": 44248498,
"author": "gamerdev",
"author_id": 8082890,
"author_profile": "https://Stackoverflow.com/users/8082890",
"pm_score": -1,
"selected": false,
"text": "int s;\nchar i= '2';\ns = (int) i;\n"
},
{
"answer_id": 47975935,
"author": "Tomer Wolberg",
"author_id": 8271180,
"author_profile": "https://Stackoverflow.com/users/8271180",
"pm_score": 3,
"selected": false,
"text": "char foo = '2';\nint bar = foo & 15;\n 0 - 0011 0000\n1 - 0011 0001\n2 - 0011 0010\n3 - 0011 0011\n4 - 0011 0100\n5 - 0011 0101\n6 - 0011 0110\n7 - 0011 0111\n8 - 0011 1000\n9 - 0011 1001\n public static int CharToInt(char c)\n{\n return 0b0000_1111 & (byte) c;\n}\n"
},
{
"answer_id": 56634031,
"author": "Hamit YILDIRIM",
"author_id": 914284,
"author_profile": "https://Stackoverflow.com/users/914284",
"pm_score": 3,
"selected": false,
"text": "int bar = Convert.ToInt32(new string(foo, 1)); // => gives bar=2\n char v = '1';\nint vv = (int)char.GetNumericValue(v); \n int[] values = \"41234\".ToArray().Select(c=> (int)char.GetNumericValue(c)).ToArray();\n"
},
{
"answer_id": 67908779,
"author": "Akhila Babu",
"author_id": 16131219,
"author_profile": "https://Stackoverflow.com/users/16131219",
"pm_score": 2,
"selected": false,
"text": "var character = '1';\nvar integerValue = int.Parse(character.ToString());\n"
},
{
"answer_id": 67955420,
"author": "Amir",
"author_id": 3782535,
"author_profile": "https://Stackoverflow.com/users/3782535",
"pm_score": 0,
"selected": false,
"text": "public static string NormalizeNumbers(this string text)\n{\n if (string.IsNullOrWhiteSpace(text)) return text;\n\n string normalized = text;\n\n char[] allNumbers = text.Where(char.IsNumber).Distinct().ToArray();\n\n foreach (char ch in allNumbers)\n {\n char equalNumber = char.Parse(char.GetNumericValue(ch).ToString(\"N0\"));\n normalized = normalized.Replace(ch, equalNumber);\n }\n\n return normalized;\n}\n"
},
{
"answer_id": 69089437,
"author": "ElVit",
"author_id": 13211180,
"author_profile": "https://Stackoverflow.com/users/13211180",
"pm_score": 0,
"selected": false,
"text": "char testChar = 'e';\nint result = Uri.IsHexDigit(testChar) \n ? Uri.FromHex(testChar)\n : -1;\n"
},
{
"answer_id": 72253729,
"author": "Титан",
"author_id": 14871509,
"author_profile": "https://Stackoverflow.com/users/14871509",
"pm_score": 1,
"selected": false,
"text": "public static int ToIntT(this char c) =>\n c is >= '0' and <= '9'?\n c-'0' : -1;\n c-'0' //current\nswitch //about 25% slower, no method with disabled isnum check (it is but performance is same as with enabled)\n0b0000_1111 & (byte) c; //same speed\nUri.FromHex(c) /*2 times slower; about 20% slower if use my isnum check*/ (c is >= '0' and <= '9') /*instead of*/ Uri.IsHexDigit(testChar)\n(int)char.GetNumericValue(c); // about 20% slower. I expected it will be much more slower.\nConvert.ToInt32(new string(c, 1)) //3-4 times slower\n c"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/239103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26854/"
] |
239,122
|
<p>Just to clarify, I'm running Sybase 12.5.3, but I am lead to believe that this holds true for SQL Server 2005 too. Basically, I'm trying to write a query that looks a little like this, I've simplified it as much as possible to highlight the problem:</p>
<pre><code>DECLARE @a int, @b int, @c int
SELECT
@a = huzzah.a
,@b = huzzah.b
,@c = huzzah.c
FROM (
SELECT
1 a
,2 b
,3 c
) huzzah
</code></pre>
<p>This query gives me the following error: <em>"Error:141 A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations."</em></p>
<p>The only work around that I've got for this so far, is to insert the derived-table data into a temporary table and then select it right back out again. Which works fine, but the fact that this doesn't work irks me. Is there a better way to do this?</p>
|
[
{
"answer_id": 239407,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "DECLARE @a int, @b int, @c int\n\nSELECT\n @a = huzzah.a\n ,@b = huzzah.b\n ,@c = huzzah.c\nFROM (\n SELECT\n 1 a\n ,2 b\n ,3 c\n) huzzah\n\nselect @a\nselect @b\nselect @c\n"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/239122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] |
239,127
|
<p>What is the exact use of an Abstract class? Is not possible to do the same things in an ordinary class as it is an an abstract class? </p>
|
[
{
"answer_id": 239156,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 1,
"selected": false,
"text": "abstract abstract"
}
] |
2008/10/27
|
[
"https://Stackoverflow.com/questions/239127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.