qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
26,205,066
I have a large JSON formatted file (254MB) which I am trying to import into MongoDB in Cloud9 IDE using mongoimport. Json file consists of mongodb documents each on its own row using newline character. The file looks like this: ``` ... {"t":"1358836264","p":"1.33470"} {"t":"1358836265","p":"1.33475"} {"t":"1358836271","p":"1.33477"} {"t":"1358836272","p":"1.33481"} {"t":"1358836274","p":"1.33475"} {"t":"1358836275","p":"1.33478"} {"t":"1358836288","p":"1.33480"} {"t":"1358836291","p":"1.33481"} {"t":"1358836294","p":"1.33481"} {"t":"1358836295","p":"1.33478"} ... ``` I have tried: ``` mongoimport -d woption -c eurusd eurusddata.json ``` This gave me the following output with error: ``` connected to: 127.0.0.1 Sun Oct 5 16:51:15.094 Progress: 1636800/26345472 6% Sun Oct 5 16:51:15.094 49600 16533/second Sun Oct 5 16:51:18.088 Progress: 3375900/26345472 12% Sun Oct 5 16:51:18.088 102300 17050/second Sun Oct 5 16:51:21.089 Progress: 4867500/26345472 18% Sun Oct 5 16:51:21.089 147500 16388/second Sun Oct 5 16:51:24.103 Progress: 7728600/26345472 29% Sun Oct 5 16:51:24.103 234200 19516/second Sun Oct 5 16:51:27.093 Progress: 10467600/26345472 39% Sun Oct 5 16:51:27.093 317200 21146/second Sun Oct 5 16:51:30.094 Progress: 13312200/26345472 50% Sun Oct 5 16:51:30.094 403400 22411/second Sun Oct 5 16:51:33.302 Progress: 16038000/26345472 60% Sun Oct 5 16:51:33.303 486000 23142/second Sun Oct 5 16:51:36.088 Progress: 17341500/26345472 65% Sun Oct 5 16:51:36.088 525500 21895/second Sun Oct 5 16:51:39.004 Progress: 18526200/26345472 70% Sun Oct 5 16:51:39.004 561400 20792/second Sun Oct 5 16:51:42.032 Progress: 19067400/26345472 72% Sun Oct 5 16:51:42.032 577800 19260/second Sun Oct 5 16:51:45.088 Progress: 20829600/26345472 79% Sun Oct 5 16:51:45.088 631200 19127/second Sun Oct 5 16:51:48.071 Progress: 23007600/26345472 87% Sun Oct 5 16:51:48.071 697200 19366/second Sun Oct 5 16:51:51.914 Progress: 23443200/26345472 88% Sun Oct 5 16:51:51.914 710400 18215/second Sun Oct 5 16:51:54.103 Progress: 23611500/26345472 89% Sun Oct 5 16:51:54.104 715500 17035/second Sun Oct 5 16:51:57.709 Progress: 23967900/26345472 90% Sun Oct 5 16:51:57.709 726300 16140/second Sun Oct 5 16:52:00.096 Progress: 24538800/26345472 93% Sun Oct 5 16:52:00.096 743600 15491/second Sun Oct 5 16:52:03.088 Progress: 25548600/26345472 96% Sun Oct 5 16:52:03.088 774200 15180/second Sun Oct 5 16:52:04.644 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Expecting ':': offset:21 Sun Oct 5 16:52:04.644 Sun Oct 5 16:52:04.644 check 9 798347 Sun Oct 5 16:52:05.061 imported 798347 objects Sun Oct 5 16:52:05.061 ERROR: encountered 1 error(s) ``` Then I tried using --jsonArray at the end of previous command: ``` mongoimport -d woption -c eurusd eurusddata.json --jsonArray ``` This gave me the following output with error: ``` connected to: 127.0.0.1 Sun Oct 5 16:54:20.343 exception:JSONArray file too large Sun Oct 5 16:54:20.444 warning: log line attempted (16384k) over max size(10k), printing beginning and end ... {"t":"1357070402","p":"1.32041"} {"t":"1357070424","p":"1.32040"} {"t":"1357070447","p":"1.32038"} {"t":"1357070457","p":"1.32034"} {"t":"1357070463","p":"1.32039"} {"t":"1357070464","p":"1.32038"} {"t":"1357070470","p":"1.32034"} {"t":"1357070485","p":"1.32035"} {"t":"1357070491","p":"1.32046"} {"t":"1357070520","p":"1.32050"} {"t":"1357070522","p":"1.32049"} {"t":"1357070535","p":"1.32050"} {"t":"1357070581","p":"1.32049"} {"t":"1357070582","p":"1.32050"} {"t":"1357070587","p":"1.32035"} {"t":"1357070589","p":"1.32034"} {"t":"1357070593","p":"1.32033"} {"t":"1357070594","p":"1.32024"} {"t":"1357070595","p":"1.32025"} {"t":"1357070599","p":"1.32009"} {"t":"1357070602","p":"1.32024"} {"t":"1357070630","p":"1.32023"} {"t":"1357070637","p":"1.32025"} {"t":"1357070656","p":"1.32023"} {"t":"1357070691","p":"1.32025"} {"t":"1357070702","p":"1.32027"} {"t":"1357070703","p":"1.32028"} {"t":"1357070706","p":"1.32027"} {"t":"1357070707","p":"1.32026"} {"t":"1357070709","p":"1.32027"} {"t":"1357070710","p":"1.32026"} {"t":"1357070721","p":"1.32027"} {"t":"1357070723","p":"1.32026"} {"t":"1357070761","p":"1.32025"} {"t":"1357070767","p":"1.32027"} {"t":"1357070768","p":"1.32025"} {"t":"1357070784","p":"1.32026"} {"t":"1357070798","p":"1.32027"} {"t":"1357070799","p":"1.32026"} {"t":"1357070804","p":"1.32036"} {"t":"1357070819","p":"1.32034"} {"t":"1357070842","p":"1.32035"} {"t":"1357070880","p":"1.32030"} {"t":"1357070881","p":"1.32035"} {"t":"1357070966","p":"1.32053"} {"t":"1357070967","p":"1.32063"} {"t":"1357070973","p":"1.32048"} {"t":"1357070974","p":"1.32046"} {"t":"1357070977","p":"1.32066"} {"t":"1357070978","p":"1.32065"} {"t":"1357070984","p":"1.32064"} {"t":"1357070987","p":"1.32063"} {"t":"1357070988","p":"1.32064"} {"t":"1357070993","p":"1.32065"} {"t":"1357070997","p":"1.32065"} {"t":"1357070998","p":"1.32063"} {"t":"1357071000","p":"1.32064"} {"t":"1357071003","p":"1.32064"} {"t":"1357071011","p":"1.32065"} {"t":"1357071012","p":"1.32069"} {"t":"1357071013","p":"1.32069"} {"t":"1357071023","p":"1.32068"} {"t":"1357071024","p":"1.32068"} {"t":"1357071026","p":"1.32072"} {"t":"1357071027","p":"1.32070"} {"t":"1357071028","p":"1.32069"} {"t":"1357071047","p":"1.32068"} {"t":"1357071048","p":"1.32069"} {"t":"1357071070","p":"1.32072"} {"t":"1357071071","p":"1.32069"} {"t":"1357071077","p":"1.32068"} {"t":"1357071078","p":"1.32069"} {"t":"1357071085","p":"1.32068"} {"t":"1357071086","p":"1.32069"} {"t":"1357071095","p":"1.32072"} {"t":"1357071096","p":"1.32069"} {"t":"1357071097","p":"1.32070"} {"t":"1357071104","p":"1.32069"} {"t":"1357071105","p":"1.32069"} {"t":"1357071114","p":"1.32068"} {"t":"1357071125","p":"1.32068"} {"t":"1357071132","p":"1.32072"} {"t":"1357071133","p":"1.32068"} {"t":"1357071134","p":"1.32069"} {"t":"1357071136","p":"1.32043"} {"t":"1357071137","p":"1.32049"} {"t":"1357071139","p":"1.32052"} {"t":"1357071140","p":"1.32058"} {"t":"1357071156","p":"1.32052"} {"t":"1357071163","p":"1.32050"} {"t":"1357071174","p":"1.32052"} {"t":"1357071176","p":"1.32055"} {"t":"1357071178","p":"1.32053"} {"t":"1357071185","p":"1.32054"} {"t":"1357071187","p":"1.32053"} {"t":"1357071189","p":"1.32025"} {"t":"1357071190","p":"1.32023"} {"t":"1357071191","p":"1.32045"} {"t":"1357071192","p":"1.32044"} {"t":"1357071193","p":"1.32045"} {"t":"1357071197","p":"1.32044"} {"t":"1357071198","p":"1.32043"} {"t":"1357071199","p":"1.32004"} {"t":"13570712 .......... ":"1358836127","p":"1.33455"} {"t":"1358836128","p":"1.33454"} {"t":"1358836129","p":"1.33455"} {"t":"1358836130","p":"1.33458"} {"t":"1358836131","p":"1.33463"} {"t":"1358836132","p":"1.33462"} {"t":"1358836133","p":"1.33460"} {"t":"1358836134","p":"1.33459"} {"t":"1358836135","p":"1.33464"} {"t":"1358836137","p":"1.33463"} {"t":"1358836139","p":"1.33461"} {"t":"1358836140","p":"1.33462"} {"t":"1358836142","p":"1.33463"} {"t":"1358836143","p":"1.33459"} {"t":"1358836144","p":"1.33461"} {"t":"1358836146","p":"1.33462"} {"t":"1358836147","p":"1.33466"} {"t":"1358836148","p":"1.33473"} {"t":"1358836149","p":"1.33475"} {"t":"1358836151","p":"1.33479"} {"t":"1358836152","p":"1.33484"} {"t":"1358836153","p":"1.33492"} {"t":"1358836154","p":"1.33488"} {"t":"1358836155","p":"1.33492"} {"t":"1358836156","p":"1.33489"} {"t":"1358836157","p":"1.33482"} {"t":"1358836158","p":"1.33483"} {"t":"1358836159","p":"1.33480"} {"t":"1358836160","p":"1.33479"} {"t":"1358836161","p":"1.33482"} {"t":"1358836162","p":"1.33481"} {"t":"1358836163","p":"1.33481"} {"t":"1358836166","p":"1.33480"} {"t":"1358836167","p":"1.33480"} {"t":"1358836168","p":"1.33475"} {"t":"1358836169","p":"1.33454"} {"t":"1358836170","p":"1.33454"} {"t":"1358836172","p":"1.33459"} {"t":"1358836173","p":"1.33456"} {"t":"1358836174","p":"1.33455"} {"t":"1358836175","p":"1.33457"} {"t":"1358836176","p":"1.33459"} {"t":"1358836177","p":"1.33460"} {"t":"1358836178","p":"1.33462"} {"t":"1358836179","p":"1.33458"} {"t":"1358836180","p":"1.33459"} {"t":"1358836181","p":"1.33456"} {"t":"1358836182","p":"1.33458"} {"t":"1358836183","p":"1.33457"} {"t":"1358836184","p":"1.33459"} {"t":"1358836185","p":"1.33460"} {"t":"1358836186","p":"1.33467"} {"t":"1358836189","p":"1.33466"} {"t":"1358836190","p":"1.33472"} {"t":"1358836191","p":"1.33470"} {"t":"1358836192","p":"1.33470"} {"t":"1358836193","p":"1.33469"} {"t":"1358836194","p":"1.33465"} {"t":"1358836195","p":"1.33466"} {"t":"1358836196","p":"1.33461"} {"t":"1358836197","p":"1.33460"} {"t":"1358836198","p":"1.33466"} {"t":"1358836199","p":"1.33465"} {"t":"1358836200","p":"1.33466"} {"t":"1358836201","p":"1.33458"} {"t":"1358836202","p":"1.33457"} {"t":"1358836203","p":"1.33453"} {"t":"1358836204","p":"1.33454"} {"t":"1358836205","p":"1.33456"} {"t":"1358836210","p":"1.33455"} {"t":"1358836211","p":"1.33450"} {"t":"1358836214","p":"1.33449"} {"t":"1358836216","p":"1.33451"} {"t":"1358836217","p":"1.33452"} {"t":"1358836218","p":"1.33457"} {"t":"1358836220","p":"1.33458"} {"t":"1358836221","p":"1.33457"} {"t":"1358836222","p":"1.33456"} {"t":"1358836223","p":"1.33457"} {"t":"1358836226","p":"1.33460"} {"t":"1358836229","p":"1.33459"} {"t":"1358836230","p":"1.33458"} {"t":"1358836236","p":"1.33461"} {"t":"1358836237","p":"1.33466"} {"t":"1358836240","p":"1.33467"} {"t":"1358836241","p":"1.33467"} {"t":"1358836242","p":"1.33463"} {"t":"1358836243","p":"1.33466"} {"t":"1358836244","p":"1.33467"} {"t":"1358836245","p":"1.33468"} {"t":"1358836250","p":"1.33468"} {"t":"1358836256","p":"1.33469"} {"t":"1358836263","p":"1.33472"} {"t":"1358836264","p":"1.33470"} {"t":"1358836265","p":"1.33475"} {"t":"1358836271","p":"1.33477"} {"t":"1358836272","p":"1.33481"} {"t":"1358836274","p":"1.33475"} {"t":"1358836275","p":"1.33478"} {"t":"1358836288","p":"1.33480"} {"t":"1358836291","p":"1.33481"} {"t":"1358836294","p":"1.33481"} {"t":"1358836295","p":"1.33478"} {"t":"1358836296 Sun Oct 5 16:54:20.445 check 0 0 Sun Oct 5 16:54:20.445 imported 0 objects Sun Oct 5 16:54:20.445 ERROR: encountered 1 error(s) ``` I then tried using something like this: ``` mongoimport -d woption -c eurusd < /home/ubuntu/workspace/eurusddata.json ``` This gave me the following output with error: ``` connected to: 127.0.0.1 Sun Oct 5 16:58:08.107 77400 25800/second Sun Oct 5 16:58:11.096 136300 22716/second Sun Oct 5 16:58:14.107 177700 19744/second Sun Oct 5 16:58:17.093 232900 19408/second Sun Oct 5 16:58:20.125 280400 18693/second Sun Oct 5 16:58:23.103 343500 19083/second Sun Oct 5 16:58:26.091 424800 20228/second Sun Oct 5 16:58:29.095 482800 20116/second Sun Oct 5 16:58:32.097 517900 19181/second Sun Oct 5 16:58:35.088 566700 18890/second Sun Oct 5 16:58:38.091 608700 18445/second Sun Oct 5 16:58:41.098 664700 18463/second Sun Oct 5 16:58:44.088 718300 18417/second Sun Oct 5 16:58:47.089 776800 18495/second Sun Oct 5 16:58:47.848 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Expecting ':': offset:21 Sun Oct 5 16:58:47.848 Sun Oct 5 16:58:47.848 check 9 798347 Sun Oct 5 16:58:48.852 imported 798347 objects Sun Oct 5 16:58:48.852 ERROR: encountered 1 error(s) ``` Also tried using previous command with --jsonArray: ``` mongoimport -d woption -c eurusd < /home/ubuntu/workspace/eurusddata.json --jsonArray ``` This gave me the following output with error: ``` connected to: 127.0.0.1 Sun Oct 5 16:59:35.063 exception:JSONArray file too large Sun Oct 5 16:59:35.101 warning: log line attempted (16384k) over max size(10k), printing beginning and end ... {"t":"1357070402","p":"1.32041"} {"t":"1357070424","p":"1.32040"} {"t":"1357070447","p":"1.32038"} {"t":"1357070457","p":"1.32034"} {"t":"1357070463","p":"1.32039"} {"t":"1357070464","p":"1.32038"} {"t":"1357070470","p":"1.32034"} {"t":"1357070485","p":"1.32035"} {"t":"1357070491","p":"1.32046"} {"t":"1357070520","p":"1.32050"} {"t":"1357070522","p":"1.32049"} {"t":"1357070535","p":"1.32050"} {"t":"1357070581","p":"1.32049"} {"t":"1357070582","p":"1.32050"} {"t":"1357070587","p":"1.32035"} {"t":"1357070589","p":"1.32034"} {"t":"1357070593","p":"1.32033"} {"t":"1357070594","p":"1.32024"} {"t":"1357070595","p":"1.32025"} {"t":"1357070599","p":"1.32009"} {"t":"1357070602","p":"1.32024"} {"t":"1357070630","p":"1.32023"} {"t":"1357070637","p":"1.32025"} {"t":"1357070656","p":"1.32023"} {"t":"1357070691","p":"1.32025"} {"t":"1357070702","p":"1.32027"} {"t":"1357070703","p":"1.32028"} {"t":"1357070706","p":"1.32027"} {"t":"1357070707","p":"1.32026"} {"t":"1357070709","p":"1.32027"} {"t":"1357070710","p":"1.32026"} {"t":"1357070721","p":"1.32027"} {"t":"1357070723","p":"1.32026"} {"t":"1357070761","p":"1.32025"} {"t":"1357070767","p":"1.32027"} {"t":"1357070768","p":"1.32025"} {"t":"1357070784","p":"1.32026"} {"t":"1357070798","p":"1.32027"} {"t":"1357070799","p":"1.32026"} {"t":"1357070804","p":"1.32036"} {"t":"1357070819","p":"1.32034"} {"t":"1357070842","p":"1.32035"} {"t":"1357070880","p":"1.32030"} {"t":"1357070881","p":"1.32035"} {"t":"1357070966","p":"1.32053"} {"t":"1357070967","p":"1.32063"} {"t":"1357070973","p":"1.32048"} {"t":"1357070974","p":"1.32046"} {"t":"1357070977","p":"1.32066"} {"t":"1357070978","p":"1.32065"} {"t":"1357070984","p":"1.32064"} {"t":"1357070987","p":"1.32063"} {"t":"1357070988","p":"1.32064"} {"t":"1357070993","p":"1.32065"} {"t":"1357070997","p":"1.32065"} {"t":"1357070998","p":"1.32063"} {"t":"1357071000","p":"1.32064"} {"t":"1357071003","p":"1.32064"} {"t":"1357071011","p":"1.32065"} {"t":"1357071012","p":"1.32069"} {"t":"1357071013","p":"1.32069"} {"t":"1357071023","p":"1.32068"} {"t":"1357071024","p":"1.32068"} {"t":"1357071026","p":"1.32072"} {"t":"1357071027","p":"1.32070"} {"t":"1357071028","p":"1.32069"} {"t":"1357071047","p":"1.32068"} {"t":"1357071048","p":"1.32069"} {"t":"1357071070","p":"1.32072"} {"t":"1357071071","p":"1.32069"} {"t":"1357071077","p":"1.32068"} {"t":"1357071078","p":"1.32069"} {"t":"1357071085","p":"1.32068"} {"t":"1357071086","p":"1.32069"} {"t":"1357071095","p":"1.32072"} {"t":"1357071096","p":"1.32069"} {"t":"1357071097","p":"1.32070"} {"t":"1357071104","p":"1.32069"} {"t":"1357071105","p":"1.32069"} {"t":"1357071114","p":"1.32068"} {"t":"1357071125","p":"1.32068"} {"t":"1357071132","p":"1.32072"} {"t":"1357071133","p":"1.32068"} {"t":"1357071134","p":"1.32069"} {"t":"1357071136","p":"1.32043"} {"t":"1357071137","p":"1.32049"} {"t":"1357071139","p":"1.32052"} {"t":"1357071140","p":"1.32058"} {"t":"1357071156","p":"1.32052"} {"t":"1357071163","p":"1.32050"} {"t":"1357071174","p":"1.32052"} {"t":"1357071176","p":"1.32055"} {"t":"1357071178","p":"1.32053"} {"t":"1357071185","p":"1.32054"} {"t":"1357071187","p":"1.32053"} {"t":"1357071189","p":"1.32025"} {"t":"1357071190","p":"1.32023"} {"t":"1357071191","p":"1.32045"} {"t":"1357071192","p":"1.32044"} {"t":"1357071193","p":"1.32045"} {"t":"1357071197","p":"1.32044"} {"t":"1357071198","p":"1.32043"} {"t":"1357071199","p":"1.32004"} {"t":"13570712 .......... ":"1358836127","p":"1.33455"} {"t":"1358836128","p":"1.33454"} {"t":"1358836129","p":"1.33455"} {"t":"1358836130","p":"1.33458"} {"t":"1358836131","p":"1.33463"} {"t":"1358836132","p":"1.33462"} {"t":"1358836133","p":"1.33460"} {"t":"1358836134","p":"1.33459"} {"t":"1358836135","p":"1.33464"} {"t":"1358836137","p":"1.33463"} {"t":"1358836139","p":"1.33461"} {"t":"1358836140","p":"1.33462"} {"t":"1358836142","p":"1.33463"} {"t":"1358836143","p":"1.33459"} {"t":"1358836144","p":"1.33461"} {"t":"1358836146","p":"1.33462"} {"t":"1358836147","p":"1.33466"} {"t":"1358836148","p":"1.33473"} {"t":"1358836149","p":"1.33475"} {"t":"1358836151","p":"1.33479"} {"t":"1358836152","p":"1.33484"} {"t":"1358836153","p":"1.33492"} {"t":"1358836154","p":"1.33488"} {"t":"1358836155","p":"1.33492"} {"t":"1358836156","p":"1.33489"} {"t":"1358836157","p":"1.33482"} {"t":"1358836158","p":"1.33483"} {"t":"1358836159","p":"1.33480"} {"t":"1358836160","p":"1.33479"} {"t":"1358836161","p":"1.33482"} {"t":"1358836162","p":"1.33481"} {"t":"1358836163","p":"1.33481"} {"t":"1358836166","p":"1.33480"} {"t":"1358836167","p":"1.33480"} {"t":"1358836168","p":"1.33475"} {"t":"1358836169","p":"1.33454"} {"t":"1358836170","p":"1.33454"} {"t":"1358836172","p":"1.33459"} {"t":"1358836173","p":"1.33456"} {"t":"1358836174","p":"1.33455"} {"t":"1358836175","p":"1.33457"} {"t":"1358836176","p":"1.33459"} {"t":"1358836177","p":"1.33460"} {"t":"1358836178","p":"1.33462"} {"t":"1358836179","p":"1.33458"} {"t":"1358836180","p":"1.33459"} {"t":"1358836181","p":"1.33456"} {"t":"1358836182","p":"1.33458"} {"t":"1358836183","p":"1.33457"} {"t":"1358836184","p":"1.33459"} {"t":"1358836185","p":"1.33460"} {"t":"1358836186","p":"1.33467"} {"t":"1358836189","p":"1.33466"} {"t":"1358836190","p":"1.33472"} {"t":"1358836191","p":"1.33470"} {"t":"1358836192","p":"1.33470"} {"t":"1358836193","p":"1.33469"} {"t":"1358836194","p":"1.33465"} {"t":"1358836195","p":"1.33466"} {"t":"1358836196","p":"1.33461"} {"t":"1358836197","p":"1.33460"} {"t":"1358836198","p":"1.33466"} {"t":"1358836199","p":"1.33465"} {"t":"1358836200","p":"1.33466"} {"t":"1358836201","p":"1.33458"} {"t":"1358836202","p":"1.33457"} {"t":"1358836203","p":"1.33453"} {"t":"1358836204","p":"1.33454"} {"t":"1358836205","p":"1.33456"} {"t":"1358836210","p":"1.33455"} {"t":"1358836211","p":"1.33450"} {"t":"1358836214","p":"1.33449"} {"t":"1358836216","p":"1.33451"} {"t":"1358836217","p":"1.33452"} {"t":"1358836218","p":"1.33457"} {"t":"1358836220","p":"1.33458"} {"t":"1358836221","p":"1.33457"} {"t":"1358836222","p":"1.33456"} {"t":"1358836223","p":"1.33457"} {"t":"1358836226","p":"1.33460"} {"t":"1358836229","p":"1.33459"} {"t":"1358836230","p":"1.33458"} {"t":"1358836236","p":"1.33461"} {"t":"1358836237","p":"1.33466"} {"t":"1358836240","p":"1.33467"} {"t":"1358836241","p":"1.33467"} {"t":"1358836242","p":"1.33463"} {"t":"1358836243","p":"1.33466"} {"t":"1358836244","p":"1.33467"} {"t":"1358836245","p":"1.33468"} {"t":"1358836250","p":"1.33468"} {"t":"1358836256","p":"1.33469"} {"t":"1358836263","p":"1.33472"} {"t":"1358836264","p":"1.33470"} {"t":"1358836265","p":"1.33475"} {"t":"1358836271","p":"1.33477"} {"t":"1358836272","p":"1.33481"} {"t":"1358836274","p":"1.33475"} {"t":"1358836275","p":"1.33478"} {"t":"1358836288","p":"1.33480"} {"t":"1358836291","p":"1.33481"} {"t":"1358836294","p":"1.33481"} {"t":"1358836295","p":"1.33478"} {"t":"1358836296 Sun Oct 5 16:59:35.101 check 0 0 Sun Oct 5 16:59:35.102 imported 0 objects Sun Oct 5 16:59:35.102 ERROR: encountered 1 error(s) ``` What am I doing wrong or what am I missing here? How can I import large json files to MongoDB?
2014/10/05
[ "https://Stackoverflow.com/questions/26205066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312286/" ]
According to the message: ``` Sun Oct 5 16:52:03.088 Progress: 25548600/26345472 96% Sun Oct 5 16:52:03.088 774200 15180/second Sun Oct 5 16:52:04.644 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Expecting ':': offset:21 ``` **I think there are some mistakes near the end of your imported file.** For `{"t":"1358836291","p":"1.33481"}`, the offset of second `:` is 21. So, please check syntax of documents near the end (96% ~ 100%) of imported file. By the way, `--jsonArray` is improper to use here because it has a limit of 16MB.
Try this option: --batchSize 1 Like: ``` mongoimport -d woption -c eurusd eurusddata.json --batchSize 1 ```
41,305,378
I am new to android and trying to update the `gridlayout` in popular movies popular movies app of udacity nanodegree project. I am downloading the data using `AsyncTask` and parsing the data, updating the `recyclerview` and setting adapter in `onPostExecute`. **This is my AsyncTask class** ``` private class getJson extends AsyncTask<String, Void, String>{ @Override protected String doInBackground(String... strings) { String result = ""; URL url; HttpURLConnection httpURLConnection = null; try { url = new URL(strings[0]); httpURLConnection = (HttpURLConnection) url.openConnection(); InputStream in = httpURLConnection.getInputStream(); InputStreamReader reader = new InputStreamReader(in); int data = reader.read(); while ( data != -1 ){ char current = (char) data; result += current; data = reader.read(); } } catch (java.io.IOException e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); jsonString = s; Log.i("result", jsonString); JSONObject jsonObject = null; if(!list.isEmpty()) list.clear(); try { jsonObject = new JSONObject(jsonString); JSONArray jsonArray = jsonObject.getJSONArray("results"); for( int i = 0; i < jsonArray.length() && i < 10; i++ ){ JSONObject currObject = jsonArray.getJSONObject(i); String posterurl = preUrl + currObject.getString("backdrop_path"); Log.i("poster", posterurl); String url = preUrl + currObject.getString("poster_path"); String overview = currObject.getString("overview"); String title = currObject.getString("original_title"); String release_date = (currObject.getString("release_date")); String votes = (currObject.getString("vote_average")); list.add(new MovieDetails(url,overview, title, release_date, votes, posterurl)); } } catch (JSONException e) { e.printStackTrace(); } } } ``` **This is my adapter class** ``` public class MainRecyclerViewAdapter extends RecyclerView.Adapter<MainRecyclerViewAdapter.ViewHolder> { ArrayList<MovieDetails> data; Context context; public MainRecyclerViewAdapter(Context context, ArrayList<MovieDetails> data ){ this.data = data; this.context = context; } @Override public MainRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_item, parent, false); MainRecyclerViewAdapter.ViewHolder viewHolder = new MainRecyclerViewAdapter.ViewHolder(v); return viewHolder; } @Override public void onBindViewHolder(MainRecyclerViewAdapter.ViewHolder holder, int position) { Picasso.with(context).load(data.get(position).getImageUrl()).into(holder.movie_thumbnail); //holder.movie_thumbnail.setImageResource(R.mipmap.ic_launcher); } @Override public int getItemCount() { return data.size(); } public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ ImageView movie_thumbnail; private Context context; @Override public void onClick(View view) { Toast.makeText(context,data.get(getPosition()).getTitle(),Toast.LENGTH_LONG).show(); Intent intent = new Intent(context, DetailsActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable("list", (Serializable) data); intent.putExtras(bundle); intent.putExtra("index", getAdapterPosition()); context.startActivity(intent); } public ViewHolder(View itemView) { super(itemView); context = itemView.getContext(); itemView.setOnClickListener(this); movie_thumbnail = (ImageView) itemView.findViewById(R.id.movies_item_thumbnail); } } } ``` This is how I am handling *sorting* based on voting or popularity ``` @Override public boolean onOptionsItemSelected(MenuItem item) { getJson gJson = new getJson(); switch (item.getItemId()){ case R.id.rating : gJson.execute(top_rated); return true; case R.id.popularity : gJson.execute(popular); return true; default: return super.onOptionsItemSelected(item); } } ``` onCreate ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar myToolbar = (Toolbar) findViewById(R.id.main_toolbar); setSupportActionBar(myToolbar); getJson getJson = new getJson(); getJson.execute(popular); recyclerView = (RecyclerView)findViewById(R.id.main_recyclerview); recyclerView.setHasFixedSize(true); layoutManager = new GridLayoutManager(MainActivity.this,2); recyclerView.setLayoutManager(layoutManager); adapter = new MainRecyclerViewAdapter(MainActivity.this, list); recyclerView.setAdapter(adapter); } ``` I figured out to use `notifydatasetchanged()`, but I am not able to figure *where* to use that. Also please tell me *better* way to handle the sorting. This is what I did : 1. I moved the instantiating of adapter and setting of adapter of to onCreate 2. calling `notfiydatasetchanged()` in `onPostexeute()` 3. Everytime I call the `AsyncTask`, my arraylist is being populated with new elements and so the adapter is filling all images. I am **`list.clear()`** before parsing the json in `onPostexecute()`
2016/12/23
[ "https://Stackoverflow.com/questions/41305378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7316349/" ]
Basically arrow functions will help with this and since React-Native doesnt have to deal with browser compatibility you can define you're functions like this: ``` handleData = (data) => { this.setState({ data }); } ``` You won't ever have to .bind or that=this if you use this.
`this` is already bound because of the arrow function you've used. ``` // ... componentDidMount() { this.props.myService.listensTo( 'action', (data) => this.handleData(data) ); } handleData(data) { // handle data } // ... ```
27,988,603
As the title states, what is the purpose of appending `(0);` rather than just `();` in this code snippit ([found here](https://github.com/thomseddon/node-oauth2-server/blob/master/lib/runner.js)): ``` function runner (fns, context, next) { var last = fns.length - 1; (function run(pos) { fns[pos].call(context, function (err) { if (err || pos === last) return next(err); run(++pos); }); })(0); } ```
2015/01/16
[ "https://Stackoverflow.com/questions/27988603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/334695/" ]
It is approximately equivalent to: ``` function runner (fns, context, next) { var last = fns.length - 1; function run(pos) { fns[pos].call(context, function (err) { if (err || pos === last) return next(err); run(++pos); }); } run(0); } ``` `0` is just what’s passed to `run()` as the first value of `pos` – same as in the recursive `run(++pos);` (which would be better written as `run(pos + 1)`).
The purpose is that you're passing 0 as the value to the *pos* argument.
2,450,560
in a right triangle, the side $a = 3$ and the subtraction the sides $b - c =\sqrt{3}$, What is the value of the hypotenuse? Can someone help me? I need understand how to arrive at the answer.
2017/09/29
[ "https://math.stackexchange.com/questions/2450560", "https://math.stackexchange.com", "https://math.stackexchange.com/users/485848/" ]
$c$ can not be the hypotenuse. Let $a$ be the hypotenuse. Thus, $$c^2+(c+\sqrt3)^2=3^2,$$ which gives $c=\frac{\sqrt3}{2}$, which is possible. Let $b$ be the hypotenuse. Thus, $$(c+\sqrt3)^2=3^2+c^2,$$ which gives $c=\sqrt3$ and $b=2\sqrt3$ and it's possible again.
The sides are $3, c, c+\sqrt{3}$. Now consider possible pythagorean pairs. Either $3$ can be hypotenuse, or $c+\sqrt{3}$ 1. Using 3 as hypotenuse, we get: $$9 = 2c^2 + 2c\sqrt{3} +3\\ c^2 + c\sqrt{3} -3=0\\ c = \frac{\sqrt 3}{2}$$ 2. Using $c+\sqrt{3}$ as hypotenuse, you have: $$c^2 + 2c\sqrt 3+3=c^2+9 \\ c = \frac{1}{\sqrt{3}}$$
2,450,560
in a right triangle, the side $a = 3$ and the subtraction the sides $b - c =\sqrt{3}$, What is the value of the hypotenuse? Can someone help me? I need understand how to arrive at the answer.
2017/09/29
[ "https://math.stackexchange.com/questions/2450560", "https://math.stackexchange.com", "https://math.stackexchange.com/users/485848/" ]
The sides are $3, c, c+\sqrt{3}$. Now consider possible pythagorean pairs. Either $3$ can be hypotenuse, or $c+\sqrt{3}$ 1. Using 3 as hypotenuse, we get: $$9 = 2c^2 + 2c\sqrt{3} +3\\ c^2 + c\sqrt{3} -3=0\\ c = \frac{\sqrt 3}{2}$$ 2. Using $c+\sqrt{3}$ as hypotenuse, you have: $$c^2 + 2c\sqrt 3+3=c^2+9 \\ c = \frac{1}{\sqrt{3}}$$
Hint: if $b$ is the hypotenuse then $(b+c)(b-c)=b^2-c^2=9$. So what is $b+c$?
2,450,560
in a right triangle, the side $a = 3$ and the subtraction the sides $b - c =\sqrt{3}$, What is the value of the hypotenuse? Can someone help me? I need understand how to arrive at the answer.
2017/09/29
[ "https://math.stackexchange.com/questions/2450560", "https://math.stackexchange.com", "https://math.stackexchange.com/users/485848/" ]
The sides are $3, c, c+\sqrt{3}$. Now consider possible pythagorean pairs. Either $3$ can be hypotenuse, or $c+\sqrt{3}$ 1. Using 3 as hypotenuse, we get: $$9 = 2c^2 + 2c\sqrt{3} +3\\ c^2 + c\sqrt{3} -3=0\\ c = \frac{\sqrt 3}{2}$$ 2. Using $c+\sqrt{3}$ as hypotenuse, you have: $$c^2 + 2c\sqrt 3+3=c^2+9 \\ c = \frac{1}{\sqrt{3}}$$
As we assue $a,b,c>0$: We know $b=\sqrt{3}+c>c$, hence we know that $c$ cannot be the hypothenuse (= longes side). There are only two possibilities left. $b$ is the hypotenuse or $a$ is the hypotenuse. A) $a^2+c^2=b^2=(c+\sqrt{3})^2 \implies 9 +c^2=c^2+2\sqrt 3c + 3 \implies c = \frac{6}{2\sqrt{3}}$ B) $c^2+(c+\sqrt{3})^2=a^2 \implies c^2+c^2+2\sqrt 3 c+3=9 \implies 2c^2+2\sqrt 3 c-6=0$ From $2c^2+2\sqrt 3 c-6=0 \implies c^2+\sqrt 3 c-3=0 \implies c\_{1,2}=\frac{-\sqrt{3}\pm\sqrt{3-4(-3)}}{2}$
2,450,560
in a right triangle, the side $a = 3$ and the subtraction the sides $b - c =\sqrt{3}$, What is the value of the hypotenuse? Can someone help me? I need understand how to arrive at the answer.
2017/09/29
[ "https://math.stackexchange.com/questions/2450560", "https://math.stackexchange.com", "https://math.stackexchange.com/users/485848/" ]
The sides are $3, c, c+\sqrt{3}$. Now consider possible pythagorean pairs. Either $3$ can be hypotenuse, or $c+\sqrt{3}$ 1. Using 3 as hypotenuse, we get: $$9 = 2c^2 + 2c\sqrt{3} +3\\ c^2 + c\sqrt{3} -3=0\\ c = \frac{\sqrt 3}{2}$$ 2. Using $c+\sqrt{3}$ as hypotenuse, you have: $$c^2 + 2c\sqrt 3+3=c^2+9 \\ c = \frac{1}{\sqrt{3}}$$
Since $b=c+\sqrt{3}$ it cannot be the hypotenuse. So we have two possibilities: $$ c^2+a^2=b^2 \iff c^2+9=(c+\sqrt{3})^2 $$ or $$ c^2+b^2=a^2 \iff c^2+(c+\sqrt{3})^2 = 9 $$ solve for $c$ and in the first case $b$ is the hypotenuse, in the second it is $a$.
2,450,560
in a right triangle, the side $a = 3$ and the subtraction the sides $b - c =\sqrt{3}$, What is the value of the hypotenuse? Can someone help me? I need understand how to arrive at the answer.
2017/09/29
[ "https://math.stackexchange.com/questions/2450560", "https://math.stackexchange.com", "https://math.stackexchange.com/users/485848/" ]
$c$ can not be the hypotenuse. Let $a$ be the hypotenuse. Thus, $$c^2+(c+\sqrt3)^2=3^2,$$ which gives $c=\frac{\sqrt3}{2}$, which is possible. Let $b$ be the hypotenuse. Thus, $$(c+\sqrt3)^2=3^2+c^2,$$ which gives $c=\sqrt3$ and $b=2\sqrt3$ and it's possible again.
Hint: if $b$ is the hypotenuse then $(b+c)(b-c)=b^2-c^2=9$. So what is $b+c$?
2,450,560
in a right triangle, the side $a = 3$ and the subtraction the sides $b - c =\sqrt{3}$, What is the value of the hypotenuse? Can someone help me? I need understand how to arrive at the answer.
2017/09/29
[ "https://math.stackexchange.com/questions/2450560", "https://math.stackexchange.com", "https://math.stackexchange.com/users/485848/" ]
$c$ can not be the hypotenuse. Let $a$ be the hypotenuse. Thus, $$c^2+(c+\sqrt3)^2=3^2,$$ which gives $c=\frac{\sqrt3}{2}$, which is possible. Let $b$ be the hypotenuse. Thus, $$(c+\sqrt3)^2=3^2+c^2,$$ which gives $c=\sqrt3$ and $b=2\sqrt3$ and it's possible again.
As we assue $a,b,c>0$: We know $b=\sqrt{3}+c>c$, hence we know that $c$ cannot be the hypothenuse (= longes side). There are only two possibilities left. $b$ is the hypotenuse or $a$ is the hypotenuse. A) $a^2+c^2=b^2=(c+\sqrt{3})^2 \implies 9 +c^2=c^2+2\sqrt 3c + 3 \implies c = \frac{6}{2\sqrt{3}}$ B) $c^2+(c+\sqrt{3})^2=a^2 \implies c^2+c^2+2\sqrt 3 c+3=9 \implies 2c^2+2\sqrt 3 c-6=0$ From $2c^2+2\sqrt 3 c-6=0 \implies c^2+\sqrt 3 c-3=0 \implies c\_{1,2}=\frac{-\sqrt{3}\pm\sqrt{3-4(-3)}}{2}$
2,450,560
in a right triangle, the side $a = 3$ and the subtraction the sides $b - c =\sqrt{3}$, What is the value of the hypotenuse? Can someone help me? I need understand how to arrive at the answer.
2017/09/29
[ "https://math.stackexchange.com/questions/2450560", "https://math.stackexchange.com", "https://math.stackexchange.com/users/485848/" ]
$c$ can not be the hypotenuse. Let $a$ be the hypotenuse. Thus, $$c^2+(c+\sqrt3)^2=3^2,$$ which gives $c=\frac{\sqrt3}{2}$, which is possible. Let $b$ be the hypotenuse. Thus, $$(c+\sqrt3)^2=3^2+c^2,$$ which gives $c=\sqrt3$ and $b=2\sqrt3$ and it's possible again.
Since $b=c+\sqrt{3}$ it cannot be the hypotenuse. So we have two possibilities: $$ c^2+a^2=b^2 \iff c^2+9=(c+\sqrt{3})^2 $$ or $$ c^2+b^2=a^2 \iff c^2+(c+\sqrt{3})^2 = 9 $$ solve for $c$ and in the first case $b$ is the hypotenuse, in the second it is $a$.
2,450,560
in a right triangle, the side $a = 3$ and the subtraction the sides $b - c =\sqrt{3}$, What is the value of the hypotenuse? Can someone help me? I need understand how to arrive at the answer.
2017/09/29
[ "https://math.stackexchange.com/questions/2450560", "https://math.stackexchange.com", "https://math.stackexchange.com/users/485848/" ]
Hint: if $b$ is the hypotenuse then $(b+c)(b-c)=b^2-c^2=9$. So what is $b+c$?
Since $b=c+\sqrt{3}$ it cannot be the hypotenuse. So we have two possibilities: $$ c^2+a^2=b^2 \iff c^2+9=(c+\sqrt{3})^2 $$ or $$ c^2+b^2=a^2 \iff c^2+(c+\sqrt{3})^2 = 9 $$ solve for $c$ and in the first case $b$ is the hypotenuse, in the second it is $a$.
2,450,560
in a right triangle, the side $a = 3$ and the subtraction the sides $b - c =\sqrt{3}$, What is the value of the hypotenuse? Can someone help me? I need understand how to arrive at the answer.
2017/09/29
[ "https://math.stackexchange.com/questions/2450560", "https://math.stackexchange.com", "https://math.stackexchange.com/users/485848/" ]
As we assue $a,b,c>0$: We know $b=\sqrt{3}+c>c$, hence we know that $c$ cannot be the hypothenuse (= longes side). There are only two possibilities left. $b$ is the hypotenuse or $a$ is the hypotenuse. A) $a^2+c^2=b^2=(c+\sqrt{3})^2 \implies 9 +c^2=c^2+2\sqrt 3c + 3 \implies c = \frac{6}{2\sqrt{3}}$ B) $c^2+(c+\sqrt{3})^2=a^2 \implies c^2+c^2+2\sqrt 3 c+3=9 \implies 2c^2+2\sqrt 3 c-6=0$ From $2c^2+2\sqrt 3 c-6=0 \implies c^2+\sqrt 3 c-3=0 \implies c\_{1,2}=\frac{-\sqrt{3}\pm\sqrt{3-4(-3)}}{2}$
Since $b=c+\sqrt{3}$ it cannot be the hypotenuse. So we have two possibilities: $$ c^2+a^2=b^2 \iff c^2+9=(c+\sqrt{3})^2 $$ or $$ c^2+b^2=a^2 \iff c^2+(c+\sqrt{3})^2 = 9 $$ solve for $c$ and in the first case $b$ is the hypotenuse, in the second it is $a$.
43,749,166
So lets say that I have these two arrays with different sizes [![values](https://i.stack.imgur.com/gxCYs.png)](https://i.stack.imgur.com/gxCYs.png) And I'd like to perform a levene test with the function leveneTest() However, the way I have been taught converts these to a dataframe and then calls the function melt to make a data structure readable by the function. This ends up repopulating the smallest array so that both arrays have the same size. ``` dataServers <- as.data.frame(cbind(down25,down27)) #dataServers is 124*2 now dataServers <- melt(dataServers,variable.name="Server",value.name="DownTimes") leveneTest(DownTimes~Server,dataServers,center=mean) ``` What would be the easiest way around this?
2017/05/03
[ "https://Stackoverflow.com/questions/43749166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5583899/" ]
You can simply `stack` your two samples, of different sizes, into one data frame and perform the `leveneTest`: ``` stacked <- stack(list(down25=down25,down27=down27)) car::leveneTest(values~ind,data=stacked,center=mean) ```
Could you not just make them independent dataframes add an identifier column to each and then do an R bind and run the test? I can make up a full example if that helps that is reproducible. make dataframe1 with id and value dataframe2 with id and value rbind the two together and skip the melt step
14,021,347
I have been trying to send packets using raw socket in following code.This code I found somewhere in the internet. I created my own ipheader and udp header. The whole data packet is sent using sendto() function on raw socket. sendto() returns 0. Which means a packet of 0 length is sent out of it and hence even wireshark doesnt detect any packet. Where is my mistake? ``` // Must be run by root lol! Just datagram, no payload/data #include <unistd.h> #include <stdio.h> #include <string.h> #include <cstdlib> #include <arpa/inet.h> #include <sys/socket.h> #include <netinet/ip.h> #include <netinet/udp.h> // The packet length #define PCKT_LEN 35 // Can create separate header file (.h) for all headers' structure // The IP header's structure struct ipheader { unsigned char iph_ihl:4, iph_ver:4; unsigned char iph_tos; unsigned short int iph_len; unsigned short int iph_ident; unsigned char iph_flag; unsigned short int iph_offset; unsigned char iph_ttl; unsigned char iph_protocol; unsigned short int iph_chksum; unsigned int iph_sourceip; unsigned int iph_destip; }; // UDP header's structure struct udpheader { unsigned short int udph_srcport; unsigned short int udph_destport; unsigned short int udph_len; unsigned short int udph_chksum; }; // total udp header length: 8 bytes (=64 bits) // Function for checksum calculation. From the RFC, // the checksum algorithm is: // "The checksum field is the 16 bit one's complement of the one's // complement sum of all 16 bit words in the header. For purposes of // computing the checksum, the value of the checksum field is zero." unsigned short csum(unsigned short *buf, int nwords) { // unsigned long sum; for(sum=0; nwords>0; nwords--) sum += *buf++; sum = (sum >> 16) + (sum &0xffff); sum += (sum >> 16); return (unsigned short)(~sum); } // Source IP, source port, target IP, target port from the command line arguments int main(int argc, char *argv[]) { int sd; // No data/payload just datagram char buffer[PCKT_LEN]; // Our own headers' structures struct ipheader *ip = (struct ipheader *) buffer; struct udpheader *udp = (struct udpheader *) (buffer + sizeof(struct ipheader)); // Source and destination addresses: IP and port struct sockaddr_in sin, din; int one = 1; const int *val = &one; memset(buffer, 0, PCKT_LEN); if(argc != 5) { printf("- Invalid parameters!!!\n"); printf("- Usage %s <source hostname/IP> <source port> <target hostname/IP> <target port>\n", argv[0]); exit(-1); } // Create a raw socket with UDP protocol sd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP); if(sd < 0) { perror("socket() error"); // If something wrong just exit exit(-1); } else printf("socket() - Using SOCK_RAW socket and UDP protocol is OK.\n"); // The source is redundant, may be used later if needed // The address family sin.sin_family = AF_INET; din.sin_family = AF_INET; // Port numbers sin.sin_port = htons(atoi(argv[2])); din.sin_port = htons(atoi(argv[4])); // IP addresses sin.sin_addr.s_addr = inet_addr(argv[1]); din.sin_addr.s_addr = inet_addr(argv[3]); // Fabricate the IP header or we can use the // standard header structures but assign our own values. ip->iph_ihl = 5; ip->iph_ver = 4; ip->iph_tos = 16; // Low delay ip->iph_len = sizeof(struct ipheader) + sizeof(struct udpheader); ip->iph_ident = htons(54321); ip->iph_ttl = 64; // hops ip->iph_protocol = 17; // UDP // Source IP address, can use spoofed address here!!! ip->iph_sourceip = inet_addr(argv[1]); // The destination IP address ip->iph_destip = inet_addr(argv[3]); // Fabricate the UDP header. Source port number, redundant udp->udph_srcport = htons(atoi(argv[2])); // Destination port number udp->udph_destport = htons(atoi(argv[4])); udp->udph_len = htons(sizeof(struct udpheader)); // Calculate the checksum for integrity ip->iph_chksum = csum((unsigned short *)buffer, sizeof(struct ipheader) + sizeof(struct udpheader)); // Inform the kernel do not fill up the packet structure. we will build our own... if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < 0) { perror("setsockopt() error"); exit(-1); } else printf("setsockopt() is OK.\n"); // Send loop, send for every 2 second for 100 count printf("Trying...\n"); printf("Using raw socket and UDP protocol\n"); printf("Using Source IP: %s port: %u, Target IP: %s port: %u.\n", argv[1], atoi(argv[2]), argv[3], atoi(argv[4])); int count; int i; for(count = 1; count <=20; count++) { if(i = sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0) // Verify { perror("sendto() error"); exit(-1); } else { printf("Count #%u - sendto() is OK. Data Length#%d\n", count,i); sleep(2); } } close(sd); return 0; } ```
2012/12/24
[ "https://Stackoverflow.com/questions/14021347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665884/" ]
Aha! I've got at least part of it. `i = sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0` is the same as `i = (sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0)` you probably want: `(i = sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin))) < 0` You may want to: 1. Turn on warnings in your compiler - at least if you use gcc, that should give you a warning for comparing and assigning in the same if-statement. 2. Retry with the fixed code. I'm sure there may be other problems in your code too - I'm no network expert.
It is really hard to read this piece of code and to understand what and why you're doing. So I can recoomend you look at my piece of code: [dhcp client implementation](https://github.com/fycth/DHCP-server-scanner/blob/master/src/dhcpd-detector.c) Look at function getSock() to see how socket is created, and on function talker() on how to form and send completed packet.
14,021,347
I have been trying to send packets using raw socket in following code.This code I found somewhere in the internet. I created my own ipheader and udp header. The whole data packet is sent using sendto() function on raw socket. sendto() returns 0. Which means a packet of 0 length is sent out of it and hence even wireshark doesnt detect any packet. Where is my mistake? ``` // Must be run by root lol! Just datagram, no payload/data #include <unistd.h> #include <stdio.h> #include <string.h> #include <cstdlib> #include <arpa/inet.h> #include <sys/socket.h> #include <netinet/ip.h> #include <netinet/udp.h> // The packet length #define PCKT_LEN 35 // Can create separate header file (.h) for all headers' structure // The IP header's structure struct ipheader { unsigned char iph_ihl:4, iph_ver:4; unsigned char iph_tos; unsigned short int iph_len; unsigned short int iph_ident; unsigned char iph_flag; unsigned short int iph_offset; unsigned char iph_ttl; unsigned char iph_protocol; unsigned short int iph_chksum; unsigned int iph_sourceip; unsigned int iph_destip; }; // UDP header's structure struct udpheader { unsigned short int udph_srcport; unsigned short int udph_destport; unsigned short int udph_len; unsigned short int udph_chksum; }; // total udp header length: 8 bytes (=64 bits) // Function for checksum calculation. From the RFC, // the checksum algorithm is: // "The checksum field is the 16 bit one's complement of the one's // complement sum of all 16 bit words in the header. For purposes of // computing the checksum, the value of the checksum field is zero." unsigned short csum(unsigned short *buf, int nwords) { // unsigned long sum; for(sum=0; nwords>0; nwords--) sum += *buf++; sum = (sum >> 16) + (sum &0xffff); sum += (sum >> 16); return (unsigned short)(~sum); } // Source IP, source port, target IP, target port from the command line arguments int main(int argc, char *argv[]) { int sd; // No data/payload just datagram char buffer[PCKT_LEN]; // Our own headers' structures struct ipheader *ip = (struct ipheader *) buffer; struct udpheader *udp = (struct udpheader *) (buffer + sizeof(struct ipheader)); // Source and destination addresses: IP and port struct sockaddr_in sin, din; int one = 1; const int *val = &one; memset(buffer, 0, PCKT_LEN); if(argc != 5) { printf("- Invalid parameters!!!\n"); printf("- Usage %s <source hostname/IP> <source port> <target hostname/IP> <target port>\n", argv[0]); exit(-1); } // Create a raw socket with UDP protocol sd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP); if(sd < 0) { perror("socket() error"); // If something wrong just exit exit(-1); } else printf("socket() - Using SOCK_RAW socket and UDP protocol is OK.\n"); // The source is redundant, may be used later if needed // The address family sin.sin_family = AF_INET; din.sin_family = AF_INET; // Port numbers sin.sin_port = htons(atoi(argv[2])); din.sin_port = htons(atoi(argv[4])); // IP addresses sin.sin_addr.s_addr = inet_addr(argv[1]); din.sin_addr.s_addr = inet_addr(argv[3]); // Fabricate the IP header or we can use the // standard header structures but assign our own values. ip->iph_ihl = 5; ip->iph_ver = 4; ip->iph_tos = 16; // Low delay ip->iph_len = sizeof(struct ipheader) + sizeof(struct udpheader); ip->iph_ident = htons(54321); ip->iph_ttl = 64; // hops ip->iph_protocol = 17; // UDP // Source IP address, can use spoofed address here!!! ip->iph_sourceip = inet_addr(argv[1]); // The destination IP address ip->iph_destip = inet_addr(argv[3]); // Fabricate the UDP header. Source port number, redundant udp->udph_srcport = htons(atoi(argv[2])); // Destination port number udp->udph_destport = htons(atoi(argv[4])); udp->udph_len = htons(sizeof(struct udpheader)); // Calculate the checksum for integrity ip->iph_chksum = csum((unsigned short *)buffer, sizeof(struct ipheader) + sizeof(struct udpheader)); // Inform the kernel do not fill up the packet structure. we will build our own... if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < 0) { perror("setsockopt() error"); exit(-1); } else printf("setsockopt() is OK.\n"); // Send loop, send for every 2 second for 100 count printf("Trying...\n"); printf("Using raw socket and UDP protocol\n"); printf("Using Source IP: %s port: %u, Target IP: %s port: %u.\n", argv[1], atoi(argv[2]), argv[3], atoi(argv[4])); int count; int i; for(count = 1; count <=20; count++) { if(i = sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0) // Verify { perror("sendto() error"); exit(-1); } else { printf("Count #%u - sendto() is OK. Data Length#%d\n", count,i); sleep(2); } } close(sd); return 0; } ```
2012/12/24
[ "https://Stackoverflow.com/questions/14021347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665884/" ]
It is really hard to read this piece of code and to understand what and why you're doing. So I can recoomend you look at my piece of code: [dhcp client implementation](https://github.com/fycth/DHCP-server-scanner/blob/master/src/dhcpd-detector.c) Look at function getSock() to see how socket is created, and on function talker() on how to form and send completed packet.
Local IP header structure is wrong... my suggestion is to include the IP header provided with your distro (are you using linux? don't you?). What i did is just include linux/ip.h, rename ipheader structure reference to iphdr, and rename the ip header fields according to the structure described in the latter file. I tried to sniff packets with tcpdump and it works now (i didn't try with wireshark but it must work too) Try this fixed code: ``` // Must be run by root lol! Just datagram, no payload/data #include <unistd.h> #include <stdio.h> #include <string.h> #include <arpa/inet.h> #include <sys/socket.h> #include <netinet/udp.h> #include <linux/ip.h> // The packet length #define PCKT_LEN 35 // UDP header's structure struct udpheader { unsigned short int udph_srcport; unsigned short int udph_destport; unsigned short int udph_len; unsigned short int udph_chksum; }; // total udp header length: 8 bytes (=64 bits) // Function for checksum calculation. From the RFC, // the checksum algorithm is: // "The checksum field is the 16 bit one's complement of the one's // complement sum of all 16 bit words in the header. For purposes of // computing the checksum, the value of the checksum field is zero." unsigned short csum(unsigned short *buf, int nwords) { // unsigned long sum; for(sum=0; nwords>0; nwords--) sum += *buf++; sum = (sum >> 16) + (sum &0xffff); sum += (sum >> 16); return (unsigned short)(~sum); } // Source IP, source port, target IP, target port from the command line arguments int main(int argc, char *argv[]) { int sd; // No data/payload just datagram char buffer[PCKT_LEN]; // Our own headers' structures struct iphdr *ip = (struct iphdr *) buffer; struct udpheader *udp = (struct udpheader *) (buffer + sizeof(struct iphdr)); // Source and destination addresses: IP and port struct sockaddr_in sin, din; int one = 1; const int *val = &one; memset(buffer, 0, PCKT_LEN); if(argc != 5) { printf("- Invalid parameters!!!\n"); printf("- Usage %s <source hostname/IP> <source port> <target hostname/IP> <target port>\n", argv[0]); exit(-1); } // Create a raw socket with UDP protocol sd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP); if(sd < 0) { perror("socket() error"); // If something wrong just exit exit(-1); } else printf("socket() - Using SOCK_RAW socket and UDP protocol is OK.\n"); // The source is redundant, may be used later if needed // The address family sin.sin_family = AF_INET; din.sin_family = AF_INET; // Port numbers sin.sin_port = htons(atoi(argv[2])); din.sin_port = htons(atoi(argv[4])); // IP addresses sin.sin_addr.s_addr = inet_addr(argv[1]); din.sin_addr.s_addr = inet_addr(argv[3]); // Fabricate the IP header or we can use the // standard header structures but assign our own values. ip->ihl = 5; ip->version = 4; ip->tos = 16; // Low delay ip->tot_len = sizeof(struct iphdr) + sizeof(struct udpheader); ip->id = htons(54321); ip->ttl = 64; // hops ip->protocol = 17; // UDP // Source IP address, can use spoofed address here!!! ip->saddr = inet_addr(argv[1]); // The destination IP address ip->daddr = inet_addr(argv[3]); // Fabricate the UDP header. Source port number, redundant udp->udph_srcport = htons(atoi(argv[2])); // Destination port number udp->udph_destport = htons(atoi(argv[4])); udp->udph_len = htons(sizeof(struct udpheader)); // Calculate the checksum for integrity ip->check = csum((unsigned short *)buffer, sizeof(struct iphdr) + sizeof(struct udpheader)); // Inform the kernel do not fill up the packet structure. we will build our own... if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < 0) { perror("setsockopt() error"); exit(-1); } else printf("setsockopt() is OK.\n"); // Send loop, send for every 2 second for 100 count printf("Trying...\n"); printf("Using raw socket and UDP protocol\n"); printf("Using Source IP: %s port: %u, Target IP: %s port: %u.\n", argv[1], atoi(argv[2]), argv[3], atoi(argv[4])); int count; int i; for(count = 1; count <=20; count++) { if((i = sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin))) < 0) // Verify { perror("sendto() error"); exit(-1); } else { printf("Count #%u - sendto() is OK. Data Length# %d\n", count,i); sleep(2); } } close(sd); return 0; } ```
14,021,347
I have been trying to send packets using raw socket in following code.This code I found somewhere in the internet. I created my own ipheader and udp header. The whole data packet is sent using sendto() function on raw socket. sendto() returns 0. Which means a packet of 0 length is sent out of it and hence even wireshark doesnt detect any packet. Where is my mistake? ``` // Must be run by root lol! Just datagram, no payload/data #include <unistd.h> #include <stdio.h> #include <string.h> #include <cstdlib> #include <arpa/inet.h> #include <sys/socket.h> #include <netinet/ip.h> #include <netinet/udp.h> // The packet length #define PCKT_LEN 35 // Can create separate header file (.h) for all headers' structure // The IP header's structure struct ipheader { unsigned char iph_ihl:4, iph_ver:4; unsigned char iph_tos; unsigned short int iph_len; unsigned short int iph_ident; unsigned char iph_flag; unsigned short int iph_offset; unsigned char iph_ttl; unsigned char iph_protocol; unsigned short int iph_chksum; unsigned int iph_sourceip; unsigned int iph_destip; }; // UDP header's structure struct udpheader { unsigned short int udph_srcport; unsigned short int udph_destport; unsigned short int udph_len; unsigned short int udph_chksum; }; // total udp header length: 8 bytes (=64 bits) // Function for checksum calculation. From the RFC, // the checksum algorithm is: // "The checksum field is the 16 bit one's complement of the one's // complement sum of all 16 bit words in the header. For purposes of // computing the checksum, the value of the checksum field is zero." unsigned short csum(unsigned short *buf, int nwords) { // unsigned long sum; for(sum=0; nwords>0; nwords--) sum += *buf++; sum = (sum >> 16) + (sum &0xffff); sum += (sum >> 16); return (unsigned short)(~sum); } // Source IP, source port, target IP, target port from the command line arguments int main(int argc, char *argv[]) { int sd; // No data/payload just datagram char buffer[PCKT_LEN]; // Our own headers' structures struct ipheader *ip = (struct ipheader *) buffer; struct udpheader *udp = (struct udpheader *) (buffer + sizeof(struct ipheader)); // Source and destination addresses: IP and port struct sockaddr_in sin, din; int one = 1; const int *val = &one; memset(buffer, 0, PCKT_LEN); if(argc != 5) { printf("- Invalid parameters!!!\n"); printf("- Usage %s <source hostname/IP> <source port> <target hostname/IP> <target port>\n", argv[0]); exit(-1); } // Create a raw socket with UDP protocol sd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP); if(sd < 0) { perror("socket() error"); // If something wrong just exit exit(-1); } else printf("socket() - Using SOCK_RAW socket and UDP protocol is OK.\n"); // The source is redundant, may be used later if needed // The address family sin.sin_family = AF_INET; din.sin_family = AF_INET; // Port numbers sin.sin_port = htons(atoi(argv[2])); din.sin_port = htons(atoi(argv[4])); // IP addresses sin.sin_addr.s_addr = inet_addr(argv[1]); din.sin_addr.s_addr = inet_addr(argv[3]); // Fabricate the IP header or we can use the // standard header structures but assign our own values. ip->iph_ihl = 5; ip->iph_ver = 4; ip->iph_tos = 16; // Low delay ip->iph_len = sizeof(struct ipheader) + sizeof(struct udpheader); ip->iph_ident = htons(54321); ip->iph_ttl = 64; // hops ip->iph_protocol = 17; // UDP // Source IP address, can use spoofed address here!!! ip->iph_sourceip = inet_addr(argv[1]); // The destination IP address ip->iph_destip = inet_addr(argv[3]); // Fabricate the UDP header. Source port number, redundant udp->udph_srcport = htons(atoi(argv[2])); // Destination port number udp->udph_destport = htons(atoi(argv[4])); udp->udph_len = htons(sizeof(struct udpheader)); // Calculate the checksum for integrity ip->iph_chksum = csum((unsigned short *)buffer, sizeof(struct ipheader) + sizeof(struct udpheader)); // Inform the kernel do not fill up the packet structure. we will build our own... if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < 0) { perror("setsockopt() error"); exit(-1); } else printf("setsockopt() is OK.\n"); // Send loop, send for every 2 second for 100 count printf("Trying...\n"); printf("Using raw socket and UDP protocol\n"); printf("Using Source IP: %s port: %u, Target IP: %s port: %u.\n", argv[1], atoi(argv[2]), argv[3], atoi(argv[4])); int count; int i; for(count = 1; count <=20; count++) { if(i = sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0) // Verify { perror("sendto() error"); exit(-1); } else { printf("Count #%u - sendto() is OK. Data Length#%d\n", count,i); sleep(2); } } close(sd); return 0; } ```
2012/12/24
[ "https://Stackoverflow.com/questions/14021347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665884/" ]
It is really hard to read this piece of code and to understand what and why you're doing. So I can recoomend you look at my piece of code: [dhcp client implementation](https://github.com/fycth/DHCP-server-scanner/blob/master/src/dhcpd-detector.c) Look at function getSock() to see how socket is created, and on function talker() on how to form and send completed packet.
I'm guessing you based that on [this example code](https://www.tenouk.com/Module43a.html), which has multiple fatal bugs. It has wasted many hours of my life. But to answer this specific question (and to help anyone else who is unfortunate enough to try to use that code), the bug that prevents you from seeing the packets in wireshark is here: ```c sin.sin_addr.s_addr = inet_addr(argv[1]); ``` This sets the address used for sending the packet in `sentdo()` to the *source* address. Therefore, the packet is sent over the loopback interface, and it goes nowhere. (Wireshark or other capture tools *will* be able to see the packet if you capture the `lo`/loopback interface, fwiw.) So the corrected line for this particular program is: ```c sin.sin_addr.s_addr = inet_addr(argv[3]); ```
14,021,347
I have been trying to send packets using raw socket in following code.This code I found somewhere in the internet. I created my own ipheader and udp header. The whole data packet is sent using sendto() function on raw socket. sendto() returns 0. Which means a packet of 0 length is sent out of it and hence even wireshark doesnt detect any packet. Where is my mistake? ``` // Must be run by root lol! Just datagram, no payload/data #include <unistd.h> #include <stdio.h> #include <string.h> #include <cstdlib> #include <arpa/inet.h> #include <sys/socket.h> #include <netinet/ip.h> #include <netinet/udp.h> // The packet length #define PCKT_LEN 35 // Can create separate header file (.h) for all headers' structure // The IP header's structure struct ipheader { unsigned char iph_ihl:4, iph_ver:4; unsigned char iph_tos; unsigned short int iph_len; unsigned short int iph_ident; unsigned char iph_flag; unsigned short int iph_offset; unsigned char iph_ttl; unsigned char iph_protocol; unsigned short int iph_chksum; unsigned int iph_sourceip; unsigned int iph_destip; }; // UDP header's structure struct udpheader { unsigned short int udph_srcport; unsigned short int udph_destport; unsigned short int udph_len; unsigned short int udph_chksum; }; // total udp header length: 8 bytes (=64 bits) // Function for checksum calculation. From the RFC, // the checksum algorithm is: // "The checksum field is the 16 bit one's complement of the one's // complement sum of all 16 bit words in the header. For purposes of // computing the checksum, the value of the checksum field is zero." unsigned short csum(unsigned short *buf, int nwords) { // unsigned long sum; for(sum=0; nwords>0; nwords--) sum += *buf++; sum = (sum >> 16) + (sum &0xffff); sum += (sum >> 16); return (unsigned short)(~sum); } // Source IP, source port, target IP, target port from the command line arguments int main(int argc, char *argv[]) { int sd; // No data/payload just datagram char buffer[PCKT_LEN]; // Our own headers' structures struct ipheader *ip = (struct ipheader *) buffer; struct udpheader *udp = (struct udpheader *) (buffer + sizeof(struct ipheader)); // Source and destination addresses: IP and port struct sockaddr_in sin, din; int one = 1; const int *val = &one; memset(buffer, 0, PCKT_LEN); if(argc != 5) { printf("- Invalid parameters!!!\n"); printf("- Usage %s <source hostname/IP> <source port> <target hostname/IP> <target port>\n", argv[0]); exit(-1); } // Create a raw socket with UDP protocol sd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP); if(sd < 0) { perror("socket() error"); // If something wrong just exit exit(-1); } else printf("socket() - Using SOCK_RAW socket and UDP protocol is OK.\n"); // The source is redundant, may be used later if needed // The address family sin.sin_family = AF_INET; din.sin_family = AF_INET; // Port numbers sin.sin_port = htons(atoi(argv[2])); din.sin_port = htons(atoi(argv[4])); // IP addresses sin.sin_addr.s_addr = inet_addr(argv[1]); din.sin_addr.s_addr = inet_addr(argv[3]); // Fabricate the IP header or we can use the // standard header structures but assign our own values. ip->iph_ihl = 5; ip->iph_ver = 4; ip->iph_tos = 16; // Low delay ip->iph_len = sizeof(struct ipheader) + sizeof(struct udpheader); ip->iph_ident = htons(54321); ip->iph_ttl = 64; // hops ip->iph_protocol = 17; // UDP // Source IP address, can use spoofed address here!!! ip->iph_sourceip = inet_addr(argv[1]); // The destination IP address ip->iph_destip = inet_addr(argv[3]); // Fabricate the UDP header. Source port number, redundant udp->udph_srcport = htons(atoi(argv[2])); // Destination port number udp->udph_destport = htons(atoi(argv[4])); udp->udph_len = htons(sizeof(struct udpheader)); // Calculate the checksum for integrity ip->iph_chksum = csum((unsigned short *)buffer, sizeof(struct ipheader) + sizeof(struct udpheader)); // Inform the kernel do not fill up the packet structure. we will build our own... if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < 0) { perror("setsockopt() error"); exit(-1); } else printf("setsockopt() is OK.\n"); // Send loop, send for every 2 second for 100 count printf("Trying...\n"); printf("Using raw socket and UDP protocol\n"); printf("Using Source IP: %s port: %u, Target IP: %s port: %u.\n", argv[1], atoi(argv[2]), argv[3], atoi(argv[4])); int count; int i; for(count = 1; count <=20; count++) { if(i = sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0) // Verify { perror("sendto() error"); exit(-1); } else { printf("Count #%u - sendto() is OK. Data Length#%d\n", count,i); sleep(2); } } close(sd); return 0; } ```
2012/12/24
[ "https://Stackoverflow.com/questions/14021347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665884/" ]
Aha! I've got at least part of it. `i = sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0` is the same as `i = (sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0)` you probably want: `(i = sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin))) < 0` You may want to: 1. Turn on warnings in your compiler - at least if you use gcc, that should give you a warning for comparing and assigning in the same if-statement. 2. Retry with the fixed code. I'm sure there may be other problems in your code too - I'm no network expert.
Local IP header structure is wrong... my suggestion is to include the IP header provided with your distro (are you using linux? don't you?). What i did is just include linux/ip.h, rename ipheader structure reference to iphdr, and rename the ip header fields according to the structure described in the latter file. I tried to sniff packets with tcpdump and it works now (i didn't try with wireshark but it must work too) Try this fixed code: ``` // Must be run by root lol! Just datagram, no payload/data #include <unistd.h> #include <stdio.h> #include <string.h> #include <arpa/inet.h> #include <sys/socket.h> #include <netinet/udp.h> #include <linux/ip.h> // The packet length #define PCKT_LEN 35 // UDP header's structure struct udpheader { unsigned short int udph_srcport; unsigned short int udph_destport; unsigned short int udph_len; unsigned short int udph_chksum; }; // total udp header length: 8 bytes (=64 bits) // Function for checksum calculation. From the RFC, // the checksum algorithm is: // "The checksum field is the 16 bit one's complement of the one's // complement sum of all 16 bit words in the header. For purposes of // computing the checksum, the value of the checksum field is zero." unsigned short csum(unsigned short *buf, int nwords) { // unsigned long sum; for(sum=0; nwords>0; nwords--) sum += *buf++; sum = (sum >> 16) + (sum &0xffff); sum += (sum >> 16); return (unsigned short)(~sum); } // Source IP, source port, target IP, target port from the command line arguments int main(int argc, char *argv[]) { int sd; // No data/payload just datagram char buffer[PCKT_LEN]; // Our own headers' structures struct iphdr *ip = (struct iphdr *) buffer; struct udpheader *udp = (struct udpheader *) (buffer + sizeof(struct iphdr)); // Source and destination addresses: IP and port struct sockaddr_in sin, din; int one = 1; const int *val = &one; memset(buffer, 0, PCKT_LEN); if(argc != 5) { printf("- Invalid parameters!!!\n"); printf("- Usage %s <source hostname/IP> <source port> <target hostname/IP> <target port>\n", argv[0]); exit(-1); } // Create a raw socket with UDP protocol sd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP); if(sd < 0) { perror("socket() error"); // If something wrong just exit exit(-1); } else printf("socket() - Using SOCK_RAW socket and UDP protocol is OK.\n"); // The source is redundant, may be used later if needed // The address family sin.sin_family = AF_INET; din.sin_family = AF_INET; // Port numbers sin.sin_port = htons(atoi(argv[2])); din.sin_port = htons(atoi(argv[4])); // IP addresses sin.sin_addr.s_addr = inet_addr(argv[1]); din.sin_addr.s_addr = inet_addr(argv[3]); // Fabricate the IP header or we can use the // standard header structures but assign our own values. ip->ihl = 5; ip->version = 4; ip->tos = 16; // Low delay ip->tot_len = sizeof(struct iphdr) + sizeof(struct udpheader); ip->id = htons(54321); ip->ttl = 64; // hops ip->protocol = 17; // UDP // Source IP address, can use spoofed address here!!! ip->saddr = inet_addr(argv[1]); // The destination IP address ip->daddr = inet_addr(argv[3]); // Fabricate the UDP header. Source port number, redundant udp->udph_srcport = htons(atoi(argv[2])); // Destination port number udp->udph_destport = htons(atoi(argv[4])); udp->udph_len = htons(sizeof(struct udpheader)); // Calculate the checksum for integrity ip->check = csum((unsigned short *)buffer, sizeof(struct iphdr) + sizeof(struct udpheader)); // Inform the kernel do not fill up the packet structure. we will build our own... if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < 0) { perror("setsockopt() error"); exit(-1); } else printf("setsockopt() is OK.\n"); // Send loop, send for every 2 second for 100 count printf("Trying...\n"); printf("Using raw socket and UDP protocol\n"); printf("Using Source IP: %s port: %u, Target IP: %s port: %u.\n", argv[1], atoi(argv[2]), argv[3], atoi(argv[4])); int count; int i; for(count = 1; count <=20; count++) { if((i = sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin))) < 0) // Verify { perror("sendto() error"); exit(-1); } else { printf("Count #%u - sendto() is OK. Data Length# %d\n", count,i); sleep(2); } } close(sd); return 0; } ```
14,021,347
I have been trying to send packets using raw socket in following code.This code I found somewhere in the internet. I created my own ipheader and udp header. The whole data packet is sent using sendto() function on raw socket. sendto() returns 0. Which means a packet of 0 length is sent out of it and hence even wireshark doesnt detect any packet. Where is my mistake? ``` // Must be run by root lol! Just datagram, no payload/data #include <unistd.h> #include <stdio.h> #include <string.h> #include <cstdlib> #include <arpa/inet.h> #include <sys/socket.h> #include <netinet/ip.h> #include <netinet/udp.h> // The packet length #define PCKT_LEN 35 // Can create separate header file (.h) for all headers' structure // The IP header's structure struct ipheader { unsigned char iph_ihl:4, iph_ver:4; unsigned char iph_tos; unsigned short int iph_len; unsigned short int iph_ident; unsigned char iph_flag; unsigned short int iph_offset; unsigned char iph_ttl; unsigned char iph_protocol; unsigned short int iph_chksum; unsigned int iph_sourceip; unsigned int iph_destip; }; // UDP header's structure struct udpheader { unsigned short int udph_srcport; unsigned short int udph_destport; unsigned short int udph_len; unsigned short int udph_chksum; }; // total udp header length: 8 bytes (=64 bits) // Function for checksum calculation. From the RFC, // the checksum algorithm is: // "The checksum field is the 16 bit one's complement of the one's // complement sum of all 16 bit words in the header. For purposes of // computing the checksum, the value of the checksum field is zero." unsigned short csum(unsigned short *buf, int nwords) { // unsigned long sum; for(sum=0; nwords>0; nwords--) sum += *buf++; sum = (sum >> 16) + (sum &0xffff); sum += (sum >> 16); return (unsigned short)(~sum); } // Source IP, source port, target IP, target port from the command line arguments int main(int argc, char *argv[]) { int sd; // No data/payload just datagram char buffer[PCKT_LEN]; // Our own headers' structures struct ipheader *ip = (struct ipheader *) buffer; struct udpheader *udp = (struct udpheader *) (buffer + sizeof(struct ipheader)); // Source and destination addresses: IP and port struct sockaddr_in sin, din; int one = 1; const int *val = &one; memset(buffer, 0, PCKT_LEN); if(argc != 5) { printf("- Invalid parameters!!!\n"); printf("- Usage %s <source hostname/IP> <source port> <target hostname/IP> <target port>\n", argv[0]); exit(-1); } // Create a raw socket with UDP protocol sd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP); if(sd < 0) { perror("socket() error"); // If something wrong just exit exit(-1); } else printf("socket() - Using SOCK_RAW socket and UDP protocol is OK.\n"); // The source is redundant, may be used later if needed // The address family sin.sin_family = AF_INET; din.sin_family = AF_INET; // Port numbers sin.sin_port = htons(atoi(argv[2])); din.sin_port = htons(atoi(argv[4])); // IP addresses sin.sin_addr.s_addr = inet_addr(argv[1]); din.sin_addr.s_addr = inet_addr(argv[3]); // Fabricate the IP header or we can use the // standard header structures but assign our own values. ip->iph_ihl = 5; ip->iph_ver = 4; ip->iph_tos = 16; // Low delay ip->iph_len = sizeof(struct ipheader) + sizeof(struct udpheader); ip->iph_ident = htons(54321); ip->iph_ttl = 64; // hops ip->iph_protocol = 17; // UDP // Source IP address, can use spoofed address here!!! ip->iph_sourceip = inet_addr(argv[1]); // The destination IP address ip->iph_destip = inet_addr(argv[3]); // Fabricate the UDP header. Source port number, redundant udp->udph_srcport = htons(atoi(argv[2])); // Destination port number udp->udph_destport = htons(atoi(argv[4])); udp->udph_len = htons(sizeof(struct udpheader)); // Calculate the checksum for integrity ip->iph_chksum = csum((unsigned short *)buffer, sizeof(struct ipheader) + sizeof(struct udpheader)); // Inform the kernel do not fill up the packet structure. we will build our own... if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < 0) { perror("setsockopt() error"); exit(-1); } else printf("setsockopt() is OK.\n"); // Send loop, send for every 2 second for 100 count printf("Trying...\n"); printf("Using raw socket and UDP protocol\n"); printf("Using Source IP: %s port: %u, Target IP: %s port: %u.\n", argv[1], atoi(argv[2]), argv[3], atoi(argv[4])); int count; int i; for(count = 1; count <=20; count++) { if(i = sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0) // Verify { perror("sendto() error"); exit(-1); } else { printf("Count #%u - sendto() is OK. Data Length#%d\n", count,i); sleep(2); } } close(sd); return 0; } ```
2012/12/24
[ "https://Stackoverflow.com/questions/14021347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665884/" ]
Aha! I've got at least part of it. `i = sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0` is the same as `i = (sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0)` you probably want: `(i = sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin))) < 0` You may want to: 1. Turn on warnings in your compiler - at least if you use gcc, that should give you a warning for comparing and assigning in the same if-statement. 2. Retry with the fixed code. I'm sure there may be other problems in your code too - I'm no network expert.
I'm guessing you based that on [this example code](https://www.tenouk.com/Module43a.html), which has multiple fatal bugs. It has wasted many hours of my life. But to answer this specific question (and to help anyone else who is unfortunate enough to try to use that code), the bug that prevents you from seeing the packets in wireshark is here: ```c sin.sin_addr.s_addr = inet_addr(argv[1]); ``` This sets the address used for sending the packet in `sentdo()` to the *source* address. Therefore, the packet is sent over the loopback interface, and it goes nowhere. (Wireshark or other capture tools *will* be able to see the packet if you capture the `lo`/loopback interface, fwiw.) So the corrected line for this particular program is: ```c sin.sin_addr.s_addr = inet_addr(argv[3]); ```
57,421,973
I'm trying to my setting names be unique for each user id ```sql Table: Settings Cols: ID, Name, Value, UserID Row1: 1, 'Database', 'shop', 1 Row2: 2, 'DBLogin' , 'admin', 1 Row3: 3, 'DBPass' , 'hash', 1 Row4: 4, 'Database', 'lol', 2 --this is ok Row5: 5, 'Database', 'shop', 3 --this is ok Row6: 6, 'Database', 'lol', 3 --this shoud be rejected ``` In "Check Constraint Expression" window of MS SQL Server MS, table creation I've tried such example ```sql Name NOT IN (SELECT Name WHERE UserID = 3) ``` But even this causes error "Subqueries are not allowed in this context. Only scalar expressions are allowed. Incorrect syntax near ')'" Is there a way to achieve my goal? BTW. Is there a MS's equivalent of Oracle's :NEW.field? This would be useful: ```sql Name NOT IN (SELECT Name WHERE UserID = :NEW.UserID) ``` ...but it's stil a subquery The main goal is to create a Dictionary of settings for each user(C#)
2019/08/08
[ "https://Stackoverflow.com/questions/57421973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9150149/" ]
**Unfortunately**.From [Xamarin.Forms - Xaminals](https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/userinterface-xaminals/) sample , also occurs this phenomenon. **This should be a limit of Shell FlyoutItem in Current version of XF**. ``` <Shell.ItemTemplate> <DataTemplate > <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="0.2*" /> <ColumnDefinition Width="0.8*" /> </Grid.ColumnDefinitions> <Image Source="{Binding FlyoutIcon}" Margin="5" HeightRequest="45" /> <Label Grid.Column="1" Text="{Binding Title}" FontAttributes="Italic" VerticalTextAlignment="Center" /> </Grid> </DataTemplate> </Shell.ItemTemplate> ``` If not using `Shell.ItemTemplate` , selectitem is marked: [![enter image description here](https://i.stack.imgur.com/5I6zW.png)](https://i.stack.imgur.com/5I6zW.png) Else selectitem is not marked : [![enter image description here](https://i.stack.imgur.com/GfpIN.png)](https://i.stack.imgur.com/GfpIN.png) ===================================**UPDATE**================================ **Solution**: If adding style to the template , can hold the selected state after selecting. **Shell.Resources**: adding a *FloutItemStyle*. ``` <Style x:Key="FloutItemStyle" TargetType="Grid"> <Setter Property="VisualStateManager.VisualStateGroups"> <VisualStateGroupList> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal" /> <VisualState x:Name="Selected"> <VisualState.Setters> <Setter Property="BackgroundColor" Value="Accent"/> </VisualState.Setters> </VisualState> </VisualStateGroup> </VisualStateGroupList> </Setter> </Style> ``` Using in **Shell.ItemTemplate** as follow: ``` <Shell.ItemTemplate> <DataTemplate > <Grid Style="{StaticResource FloutItemStyle}"> <Grid.ColumnDefinitions> <ColumnDefinition Width="0.2*" /> <ColumnDefinition Width="0.8*" /> </Grid.ColumnDefinitions> <Image Source="{Binding FlyoutIcon}" Margin="5" HeightRequest="45" /> <Label Grid.Column="1" Text="{Binding Title}" FontAttributes="Italic" VerticalTextAlignment="Center" /> </Grid> </DataTemplate> </Shell.ItemTemplate> ``` Finally showing the effect: [![enter image description here](https://i.stack.imgur.com/1gIay.png)](https://i.stack.imgur.com/1gIay.png)
You can use a binding property. Create a custom grid ``` public class ShellItemGrid : Grid { public static readonly BindableProperty SelectedColorProperty = BindableProperty.Create("SelectedColor", typeof(Color), typeof(ShellItemGrid),Color.Transparent); public Color SelectedColor { get { return (Color)GetValue(SelectedColorProperty); } set { SetValue(SelectedColorProperty, value); } } } ``` Define the style for the grid ``` <Shell.Resources> <Style x:Key="FlyoutItemStyle" TargetType="controls:ShellItemGrid"> <Setter Property="VisualStateManager.VisualStateGroups"> <VisualStateGroupList> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Selected"> <VisualState.Setters> <Setter Property="SelectedColor" Value="Red"/> </VisualState.Setters> </VisualState> <VisualState x:Name="Normal"> <VisualState.Setters> <Setter Property="SelectedColor" Value="White"/> </VisualState.Setters> </VisualState> </VisualStateGroup> </VisualStateGroupList> </Setter> </Style> ``` Define the item template and bind the TextColor of the Label to the SelectedColor of the grid ``` <Shell.ItemTemplate> <DataTemplate> <controls:ShellItemGrid x:Name="mGrid" Style="{StaticResource FlyoutItemStyle}" > <Label HorizontalTextAlignment="Start" VerticalTextAlignment="Center" Margin="20,10,0,10" Text="{Binding Title}" TextColor="{Binding Source={x:Reference mGrid},Path=SelectedColor}" FontSize="18" /> </controls:ShellItemGrid > </DataTemplate> </Shell.ItemTemplate> ```
63,315,991
I don't fully understand the concept of Singleton class in Java. For example I have singleton class like this: ``` private int i = 0; private static Singleton INSTANCE = new Singleton(); public static Singleton getInstance() { return INSTANCE; } public int getI() { return i; } public void setI(int i) { this.i = i; } ``` So every time I call getInstance() isn't it creating a new Object of Singleton because of this: `new Singleton()` ? Then why if I initializes it like this : ``` Singleton s = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); s.setI(5); System.out.println(s.getI()); System.out.println(s2.getI()); ``` I'm getting '5' two times. Shouldn't it write 0 to me the second time? I'm truly missing something but no idea what.
2020/08/08
[ "https://Stackoverflow.com/questions/63315991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14071194/" ]
``` INSTANCE = new Singleton(); ``` would only get called once as it is static. Thereafter: ``` getInstance() ``` only ever returns that static instance
Singleton is a just pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class. and to Implement that u should : 1. Private constructor to restrict instantiation of the class from other classes. 2. Private static variable of the same class that is the only instance of the class. 3. Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class. public class SingleObject { ``` private int i = 0; //create an object of SingleObject private static SingleObject instance = new SingleObject(); //make the constructor private so that this class cannot be //instantiated private SingleObject() {} //Get the only object available public static SingleObject getInstance() { return instance; } public int getI() { return i; } public void setI(int i) { this.i = i; } ``` }
39,496,251
I am trying to copy/move one text file to the zip. I don't want to unzip it, copy the file and zip it back. Is there any way we can directly copy or move text file to the zip in powershell. When i am doing it in powershell, it's doing after that when i try to look inside the zip it's saying invalid path. Powershell commands: ``` $A = "20160914.4" New-Item "C:\test\VersionLabel.txt" -ItemType file $A | Set-Content "C:\test\VersionLabel.txt" Copy-Item "C:\test\VersionLabel.txt" "C:\test\Abc.zip" -Force ``` > > Error: The compressed folder is invalid > > >
2016/09/14
[ "https://Stackoverflow.com/questions/39496251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6553195/" ]
**>= PowerShell 5.0** Per @SonnyPuijk's answer above, use `Compress-Archive`. ``` clear-host [string]$zipFN = 'c:\temp\myZipFile.zip' [string]$fileToZip = 'c:\temp\myTestFile.dat' Compress-Archive -Path $fileToZip -Update -DestinationPath $zipFN ``` **< PowerShell 5.0** ***To add a single file to an existing zip:*** ``` clear-host Add-Type -assembly 'System.IO.Compression' Add-Type -assembly 'System.IO.Compression.FileSystem' [string]$zipFN = 'c:\temp\myZipFile.zip' [string]$fileToZip = 'c:\temp\myTestFile.dat' [System.IO.Compression.ZipArchive]$ZipFile = [System.IO.Compression.ZipFile]::Open($zipFN, ([System.IO.Compression.ZipArchiveMode]::Update)) [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($ZipFile, $fileToZip, (Split-Path $fileToZip -Leaf)) $ZipFile.Dispose() ``` ***To create a single file zip file from scratch:*** Same as above, only replace: `[System.IO.Compression.ZipArchiveMode]::Update` With: `[System.IO.Compression.ZipArchiveMode]::Create` **Related Documentation:** * `Compress-Archive`: <https://technet.microsoft.com/en-us/library/dn841358.aspx> * `CreateEntryFromFile`: <https://msdn.microsoft.com/en-us/library/hh485720(v=vs.110).aspx>
You can use [`Compress-Archive`](https://technet.microsoft.com/en-us/library/dn841358.aspx) for this. `Copy-Item` doesn't support zip files. If you don't have PowerShell v5 you can use either 7Zip command line or .Net
7,523,763
Convert the url in CONENT to be clickable and make it shorter. For example: Convert the content ``` Balabala The link is http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff ``` to ``` Balabala The link is <a href=http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff>http://www.google.com/?aa...</a> ```
2011/09/23
[ "https://Stackoverflow.com/questions/7523763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192223/" ]
Something like this may help: ``` <div id='result'> </div> <script> var content = "The link is http://www.google.com/?q=hello visit it!"; var result = content.replace(/(http:\/\/(www\.)?([^(\s)]+))/, "<a href='$1'>$3</a>"); document.getElementById('result').innerHTML = result; </script> ```
Something like: ``` len = 15; //set how long of a string you would like to show url = "http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff"; //if the original url is smaller than or equal to the length than do nothing //otherwise take the len number of chars and append ... after shorturl = (url.length <= len) ? url : url.substr(0,len) + "..."; link = "<a href='" + url + "'>" + shorturl + "</a>"; ```
7,523,763
Convert the url in CONENT to be clickable and make it shorter. For example: Convert the content ``` Balabala The link is http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff ``` to ``` Balabala The link is <a href=http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff>http://www.google.com/?aa...</a> ```
2011/09/23
[ "https://Stackoverflow.com/questions/7523763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192223/" ]
Here is a function that replaces any URLs inside a string with an anchor: ``` function linkify(str){ var url = 'http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff'; return str.replace(/https?\:\/\/\S+/, function(url){ var shortUrl = url.substring(0, 20) + '...'; return shortUrl.link(url) }) } linkify("Balabala The link is http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff") // "Balabala The link is <a href="http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff">http://www.google.com/?aaaaabe...</a>" ``` The "cut" length can be passed as the second argument.
Something like: ``` len = 15; //set how long of a string you would like to show url = "http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff"; //if the original url is smaller than or equal to the length than do nothing //otherwise take the len number of chars and append ... after shorturl = (url.length <= len) ? url : url.substr(0,len) + "..."; link = "<a href='" + url + "'>" + shorturl + "</a>"; ```
24,837,716
I want to enter the text and specific character. After that i want to count how many those characters contain in the text. **My code** ``` #include <stdio.h> #include <stdlib.h> int counting(char text[], char character); int main() { char text[20]; char character; int a; printf("Enter text!\n"); scanf("%s", text); printf("Enter character!\n"); scanf("%s", character); a= counting(text, character); printf("Text contain %d character!\n", a); } ``` **And the counting function** ``` int counting(char text[], char character) { int i=0; int counter=0; while(text[i] != '\0') { if (text[i]==character) { counter++; } } i++; return counter; } ``` **Error:** ![enter image description here](https://i.stack.imgur.com/nE7hC.jpg)
2014/07/19
[ "https://Stackoverflow.com/questions/24837716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3772600/" ]
The line for reading the character needs to be: ``` scanf(" %c", &character); ``` Also, ``` scanf("%s", text); ``` is not safe. If the user enter a string that is longer than 19 characters, you will be writing over unauthorized memory, which will lead to undefined behavior. Use ``` scanf("%19s", text); ```
In function `int counting(...)` ``` while(text[i] != '\0') { if (text[i]==character) { counter++; } } i++; ``` Need `i++` inside your `while..loop`.
24,837,716
I want to enter the text and specific character. After that i want to count how many those characters contain in the text. **My code** ``` #include <stdio.h> #include <stdlib.h> int counting(char text[], char character); int main() { char text[20]; char character; int a; printf("Enter text!\n"); scanf("%s", text); printf("Enter character!\n"); scanf("%s", character); a= counting(text, character); printf("Text contain %d character!\n", a); } ``` **And the counting function** ``` int counting(char text[], char character) { int i=0; int counter=0; while(text[i] != '\0') { if (text[i]==character) { counter++; } } i++; return counter; } ``` **Error:** ![enter image description here](https://i.stack.imgur.com/nE7hC.jpg)
2014/07/19
[ "https://Stackoverflow.com/questions/24837716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3772600/" ]
The line for reading the character needs to be: ``` scanf(" %c", &character); ``` Also, ``` scanf("%s", text); ``` is not safe. If the user enter a string that is longer than 19 characters, you will be writing over unauthorized memory, which will lead to undefined behavior. Use ``` scanf("%19s", text); ```
You have two problems. 1)You are reading the specific character as a string so you have to change `scanf("%s", character);` to `scanf(" %c", character);` 2)In function `counting()` `i++` needs to be in while loop so you don't enter an infinite loop.
24,837,716
I want to enter the text and specific character. After that i want to count how many those characters contain in the text. **My code** ``` #include <stdio.h> #include <stdlib.h> int counting(char text[], char character); int main() { char text[20]; char character; int a; printf("Enter text!\n"); scanf("%s", text); printf("Enter character!\n"); scanf("%s", character); a= counting(text, character); printf("Text contain %d character!\n", a); } ``` **And the counting function** ``` int counting(char text[], char character) { int i=0; int counter=0; while(text[i] != '\0') { if (text[i]==character) { counter++; } } i++; return counter; } ``` **Error:** ![enter image description here](https://i.stack.imgur.com/nE7hC.jpg)
2014/07/19
[ "https://Stackoverflow.com/questions/24837716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3772600/" ]
In function `int counting(...)` ``` while(text[i] != '\0') { if (text[i]==character) { counter++; } } i++; ``` Need `i++` inside your `while..loop`.
You have two problems. 1)You are reading the specific character as a string so you have to change `scanf("%s", character);` to `scanf(" %c", character);` 2)In function `counting()` `i++` needs to be in while loop so you don't enter an infinite loop.
37,711,261
``` <add key="DBconnection" value="USER=harc, PASSWORD=imp, FOR_USER=ra005" /> ``` I have this line of config in my `web.config`. I am getting this value in my C# code as ``` string connect = System.Configuration.ConfigurationManager.AppSettings["DBconnection"]; ``` How do I get the USER and PASSWORD values individually from this configuration?
2016/06/08
[ "https://Stackoverflow.com/questions/37711261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6287696/" ]
Assuming this is a SQL Server connection string, pass it to a [`SqlConnectionStringBuilder`](https://msdn.microsoft.com/library/system.data.sqlclient.sqlconnectionstringbuilder): ``` var builder = new SqlConnectionStringBuilder( ConfigurationManager.AppSettings["DBconnection"] ); // use builder.UserID and builder.Password here ``` If it's a connection string for another database, you'll have to know the proper provider -- or store it as a `<connectionString>` so the provider is included. Note that actually including a user ID and password as plain text in a configuration setting is not recommended. See [Connection Strings and Configuration Files](https://msdn.microsoft.com/library/ms254494), especially the section "Encrypting Configuration File Sections Using Protected Configuration".
You can add key value pair in webconfig file ``` <add key="UserName" value="test" /> <add key="Password" value="test" /> ``` and read it like `System.Web.Configuration.WebConfigurationManager.AppSettings["UserName"]`
34,324,407
I'm getting an error in my program saying: > > Lyrics.java:11: error: cannot find symbol > > > > ``` > Cube(b); > ^ > > ``` > > symbol: method Cube(int) > > > location: class Lyrics > > > Lyrics.java:15: error: incompatible types: possible lossy conversion from double to int > > > > ``` > return Math.pow (b, 3); > ^ > > ``` > > 2 errors > > > I looked around on the website and it turns out other people also had this issue but i looked at the comments and i still dont understand the problem, theres no double in my code why would it say this. And i also dont undestand the error saying cannot find symbol. Please help ive really been stuck on this for a while. ``` import static java.lang.Math.pow; import java.util.Scanner; public class Lyrics { public static void main(String []args) { int b; Scanner scan = new Scanner(System.in); System.out.println ("Enter a number: "); b = scan.nextInt(); Cube(b); } public static int cube (int b) { return Math.pow (b, 3); } } ```
2015/12/17
[ "https://Stackoverflow.com/questions/34324407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5407820/" ]
The first problem is a simple typo. Java is case sensitive, so `cube` and `Cube` mean different things. Solution: 1) be consistent, and 2) use names starting with lowercase letters for method names ... as per the Java style guides. --- The second problem is due to the method signature for `Math.pow`; see the [javadoc](http://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#pow-double-double-). It returns the result as a `double`. You then attempte to return the `double` as an `int`, and *that* is a lossy conversion. The solutions include: ``` return b * b * b; // i.e. don't use `pow`. ``` or ``` return (int) Math.pow(b, 3); ``` The second one directly addresses your compilation error by *casting* the `double` return to an `int`. This is the way you tell the compiler that the lossy conversion is actually OK. The lossy conversion error message you are seeing refers to that fact for large enough values of `b`, the result of `Math.pow(b, 3)` will be too large to be represented as an `int`1. With the type cast in place, Java will convert a floating point number that is "too large" into `Integer.MAX_VALUE`. The first solution is faster and simpler code, but if `b` is too large, the calculations will silently overflow and you will get a nonsense answer. --- **UPDATE** - If you wanted overflow to always be treated as an error then: ``` return Math.multiplyExact(b, Math.multiplyExact(b, b)); ``` or ``` return Math.toIntExact((long) Math.pow(b, 3)); ``` or variations on the above. --- 1 - Actually, the compiler doesn't know about the semantics of `pow`, so it doesn't know about *"... for large enough values of `b` ..."*. But it does know that if the method call *did* return a large enough value, then the conversion *would* be lossy. That's why the message says *"**possible** lossy conversion"*.
Two problems: 1. Letter case is important: `Cube` is not the same as `cube`. 2. Your function `cube(int)` returns an integer, but the output of `Math.pow` is a `double`. You should probably change `cube()` to return a `double`. Then you have more code to write in the `main` method to use the results of calling `cube`.
4,348,382
While investigating counterexamples for certain conjectures in matrix analysis, I stumbled across the following calculus problem. > > I need to show (rigorously) that for $1<p<2$, > $$\left\lVert\begin{pmatrix}\sqrt 2 + 1 \\ \sqrt 2 - 1 \end{pmatrix}\right\rVert^2\_p < \left\lVert\begin{pmatrix}2 \\ 0 \end{pmatrix}\right\rVert^2\_p + \left\lVert\begin{pmatrix}1 \\ 1 \end{pmatrix}\right\rVert^2\_p $$ > where $\left\lVert \begin{pmatrix} x \\ y \end{pmatrix} \right\rVert\_p =(|x|^p + |y|^p)^{\frac{1}{p}}.$ > > > Here is the graph of LHS - RHS. [![enter image description here](https://i.stack.imgur.com/BZYh2m.png)](https://i.stack.imgur.com/BZYh2m.png) --- I could proceed in the following direction with some simple and possibly helpful observations. * Take $a = \sqrt 2 + 1$, then $\sqrt 2 - 1 = \dfrac{1}{a}$. * Using some norm inequalities the above problem can be "reduced" to proving the following inequality. $$a^p + a^{-p} < (2 \sqrt 2)^p \left[\dfrac{1}{2} + \dfrac{1}{2^p} \right] $$ The following is the graph of LHS - RHS of the above function. [![enter image description here](https://i.stack.imgur.com/BfsOhm.png)](https://i.stack.imgur.com/BfsOhm.png) * In both the equations, as you can see in the graph, at $p = 1$ and $2$, the LHS = RHS. So I have tried to show that the difference as a function of $p$ is convex in the interval $(1,2)$. But that involves a more complicated equation than the one we started with. * I am also trying a slight variant of the above argument. That is, to show that the LHS $\neq$ RHS as a function of $p$ in the interval $(1,2)$, and LHS - RHS takes a negative value for some $p$ in that interval. I have been unsuccesful in all my attempts so far, and any help would be highly appreciated.
2022/01/04
[ "https://math.stackexchange.com/questions/4348382", "https://math.stackexchange.com", "https://math.stackexchange.com/users/714494/" ]
**Sketch of a proof**: For convenience, denote $a = \sqrt2 - 1$. We need to prove that $$a^{-2}(1 + a^{2p})^{2/p} < 4 + 2^{2/p}. \tag{1}$$ $\phantom{2}$ **Fact 1**: Let $u > 0$ and $v \in [0, 1]$. Then $u^v \ge \frac{u}{u + v - uv}$. **Fact 2**: Let $0 \le r \le 1$ and $0 \le x < 1$. Then $(1 - x)^r \le 1 - rx - \frac12 (r - r^2)x^2$. **Fact 3**: Let $0\le s \le 1$. Then $2^s \ge \frac{1}{24}(s^4 - 2s^3 + 11s^2 + 14s + 24)$. $\phantom{2}$ Using Fact 1, letting $u = 1 + a^{2p}$ and $v = 2 - 2/p$, we have $$(1 + a^{2p})^{2 - 2/p} \ge \frac{1 + a^{2p}}{1 + a^{2p} + 2 - 2/p - (1 + a^{2p})(2 - 2/p)}$$ which results in $$(1 + a^{2p})^{2/p} = \frac{(1 + a^{2p})^2}{(1 + a^{2p})^{2 - 2/p}} \le (1 + a^{2p})^2(2/p - 1) + (1 + a^{2p})(2 - 2/p). \tag{2}$$ Using Fact 2, letting $r = p - 1$ and $x = 1 - a$, we have $$a^{p - 1} \le 1 - (p - 1)(1 - a) - \frac12 (p - 1)(2 - p)(1 - a)^2$$ which results in $$a^{2p} = a^2(a^{p - 1})^2 \le a^2A^2 \tag{3}$$ where $$A = 1 - (p - 1)(1 - a) - \frac12(p - 1)(2 - p)(1 - a)^2.$$ Using (2) and (3), we have $$(1 + a^{2p})^{2/p} \le (1 + a^2A^2)^2(2/p - 1) + (1 + a^2A^2)(2 - 2/p). \tag{4}$$ Using Fact 3, letting $s = 2/p - 1$, we have $$2^{2/p - 1} \ge \frac{(2/p - 1)^4 - 2(2/p - 1)^3 + 11(2/p - 1)^2 + 14(2/p - 1) + 24}{24}$$ which results in $$2^{2/p} = 2\cdot 2^{2/p - 1} \ge \frac{6p^4 - 9p^3 + 23p^2 - 12p + 4}{3p^4}. \tag{5}$$ Using (4) and (5), it suffices to prove that \begin{align\*} &a^{-2}\Big[(1 + a^2A^2)^2(2/p - 1) + (1 + a^2A^2)(2 - 2/p)\Big]\\ <\,& 4 + \frac{6p^4 - 9p^3 + 23p^2 - 12p + 4}{3p^4} \tag{6} \end{align\*} or (after clearing the denominators) \begin{align\*} &(-10089 + 7134\sqrt{2})p^{10} + (-95190\sqrt{2} + 134619)p^9 + (533862\sqrt{2} - 754995)p^8\\ &\qquad + (-1628238\sqrt{2} + 2302677)p^7 + (2911752\sqrt{2} - 4117842)p^6\\ &\qquad + (-3050004\sqrt{2} + 4313364)p^5 + (1733064\sqrt{2} - 2450934)p^4\\ &\qquad + (-412656\sqrt{2} + 583596)p^3 - 6p^2 + 3p - 2 > 0 \end{align\*} or (letting $p = 1 + \frac{1}{1 + t}$ for $t > 0$, clearing the denominators) \begin{align\*} &(-276\sqrt{2} + 391)t^{10} + (-120\sqrt{2} + 181)t^9 + (-2676\sqrt{2} + 3858)t^8\\ &\quad + (-27546\sqrt{2} + 39219)t^7 + (-24480\sqrt{2} + 35208)t^6 + (154908\sqrt{2} - 218202)t^5\\ &\quad + (372192\sqrt{2} - 525486)t^4 + (313200\sqrt{2} - 442344)t^3\\ &\quad + (125472\sqrt{2} - 177189)t^2 + (24576\sqrt{2} - 34691)t + 1920\sqrt{2} - 2708 > 0. \end{align\*} Note that $\mathrm{LHS}$ is a polynomial with non-negative coefficients and positive constant term. So, the inequality is true. We are done.
We want to prove that for $1<p<2$, $$ \left((\sqrt{2}+1)^p + (\sqrt{2}-1)^p\right)^{\frac 1 p} < 2^{\frac 1 p} + 2. $$ Note that whenever $a, b \ge 0$ and $\gamma > 1$, we have $a^\gamma + b^\gamma < (a + b)^{\gamma}$. Indeed, for $t > 0$, $$t^{\gamma - 1} < (a + t)^{\gamma -1 }$$ and integrating from $0$ to $b$ gives the desired result. Now put $a = \sqrt{2}+1, b=\sqrt{2}-1$, and $\gamma = p$. Then we have $$ \left((\sqrt{2}+1)^p + (\sqrt{2}-1)^p\right)^{\frac 1 p} < 2\sqrt{2} < 2\cdot 2^{\frac 1p} < 2^{\frac 1 p} + 2, $$ since $1 < p < 2$.
26,854
Im in the process of trying to 'wake up' I made a grievous error with a colleague recently. I sent a nasty email about something she was involved in. I was trying to manipulate her-even perhaps bully her with my views I was drinking a lot at the time. I have since realized the error of trying to control anybody or not to take the views of others to heart. I have realized my error after reading various guides to Buddhism. I have offered an apology but now a considerable amount of my colleagues hate me.I see it in their eyes and way they communicate with me. How does a novice Buddhist deal with this?
2018/06/13
[ "https://buddhism.stackexchange.com/questions/26854", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/13640/" ]
Answer given by dhamma 4life is very nice arisen out of real and genuine concern/compassion about the questioner.It is very appreciable and important that you have developed an interest in buddhism ,which is a very true and gives guarantee of attaining liberation if followed ardently and honestly giving stress of 10% to the codes of conduct and 90% to the practice. First of all whatever you have done to your colleague ,was it not out of deep interest of wellbeing of her? if yes then dont bother at all ,howsoever others may have whatever look in their eyes. Afterall we are surrounded by mundane people controlled by their ego,jealousy,hatred. And as we have these things in us it will not be proper to think that why they behave with you like this. As long as you are true in your intention ,forget about everything happening to you or whatever you have done.Whenever we commit mistake ,our so called built up image of a goody person gets little bit shattered . That image building is part of the running of ego.(here i mean running of a machine) . So our mind convince us that say sorry ,by doing so the shattered image again rebuilds itself by assuming that i have said sorry. okay i have done wrong but i am so good that i have said sorry also for it. this assumption makes us again ready for commiting mistakes. So saying sorry is of no use . Now as pointed out by dhamma 4 life , you are very much engrossed in thoughts about the things happened . I do not know what you are trying to practice ,but if it is vipassana then observe the sensations rising on arising of thoughts and be equinimous ,dont react to them with aversion,be neutral. It is the sensations produced and the reaction of us towards them is the root cause of whatever we do ,feel happy or sad . So make use of the situation. In buddhism dukkha is the base from where to move further. Our father/mother sometimes speak harsh words/beat us but never feels guilty about it bcs he is very sure of his good intention behind it. Your action is immaterial, your intention behind it is important .As buddha quotes "intention is kamma". Go in some 10 day retreat to practice vipassana available and convenient to you. Afterall we are not that which we see in the eye of people. people's eyes see very superficially. Pl bear in mind that the interest developed in buddhism /your starting of the practice let it be in crude way , is of very very importance and of top priority, So don not waste time in this senseless,foolish things of engrossing in those thoughts again and again. Wish you practice/study buddhism ardently and genuinely to go further and further on the path. heartily best luck.
There is nothing you can do about the past, and Buddhist deals with it in a way that avoids clinging to the past. Let it go for that is what makes you suffer. Also, all memories can be transformed if done skilfully, it just takes time and they will flourish in their own way. But that requires non-violence towards your thoughts and memories, no matter the content, good or bad. As for present, try mindfulness. Be mindful, keeping *right view* in mind so you do not act wrongly (through wrong view), that is right mindfulness. Let it get you to the shore. If you find yourself lost in thoughts and guilt, or feeling being despised of, again, be *gently* mindful of it. I stress gently, as such is the way of non-violence, as opposed to violence that is being harsh on yourself and your thoughts. > > **183.** Avoid all evil, cultivate the good, purify your mind: this sums up the teaching of the Buddhas. > > > **281.** Guard your thoughts, words and deeds. These three disciplines will spend you along the path to pure wisdom. > > > *(Dhammapada)* > > > Be compassionate towards those who hate, as hate does not bring happiness. Be compassionate towards yourself. I advise plenty of Metta (Loving-kindness) meditation throughout that hard time you are having. It will definitely help to purify the mind.
26,854
Im in the process of trying to 'wake up' I made a grievous error with a colleague recently. I sent a nasty email about something she was involved in. I was trying to manipulate her-even perhaps bully her with my views I was drinking a lot at the time. I have since realized the error of trying to control anybody or not to take the views of others to heart. I have realized my error after reading various guides to Buddhism. I have offered an apology but now a considerable amount of my colleagues hate me.I see it in their eyes and way they communicate with me. How does a novice Buddhist deal with this?
2018/06/13
[ "https://buddhism.stackexchange.com/questions/26854", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/13640/" ]
You are not going to become any better if you are just looking for a way to escape from the consequences of your mistakes. You need to put forth an honest effort to become better. Here are some steps that will help you in doing that. 1. If you haven't already done it, send another mail to all those who received the original mail, correcting the previous mail and apologizing for it. Mention that you have realized your mistakes after getting guidance from Buddhism. 2. Go to the Buddha and take the [Triple Refuge and the five precepts](https://refuge.sirimangalo.org/). When you take the 4th precept, make sure to promise to refrain from all 4 forms of wrong speech: **lying, hateful/vulgar speech, divisive speech, idle speech**. 3. Practice on-the-go-Metta meditation towards your friends and colleagues regardless of the way they look at you. Meaning, you have to chant in your mind "may you(other) be happy, may you be well, may you be successful, may you be free from suffering" as you interact with them. 4. Whenever the thoughts of regret come to the mind, simply discard them as impermanent, suffering and non-self. Later as the mind becomes more matured and capable, try to observe these thoughts to see the 3 characteristics.
There is nothing you can do about the past, and Buddhist deals with it in a way that avoids clinging to the past. Let it go for that is what makes you suffer. Also, all memories can be transformed if done skilfully, it just takes time and they will flourish in their own way. But that requires non-violence towards your thoughts and memories, no matter the content, good or bad. As for present, try mindfulness. Be mindful, keeping *right view* in mind so you do not act wrongly (through wrong view), that is right mindfulness. Let it get you to the shore. If you find yourself lost in thoughts and guilt, or feeling being despised of, again, be *gently* mindful of it. I stress gently, as such is the way of non-violence, as opposed to violence that is being harsh on yourself and your thoughts. > > **183.** Avoid all evil, cultivate the good, purify your mind: this sums up the teaching of the Buddhas. > > > **281.** Guard your thoughts, words and deeds. These three disciplines will spend you along the path to pure wisdom. > > > *(Dhammapada)* > > > Be compassionate towards those who hate, as hate does not bring happiness. Be compassionate towards yourself. I advise plenty of Metta (Loving-kindness) meditation throughout that hard time you are having. It will definitely help to purify the mind.
26,854
Im in the process of trying to 'wake up' I made a grievous error with a colleague recently. I sent a nasty email about something she was involved in. I was trying to manipulate her-even perhaps bully her with my views I was drinking a lot at the time. I have since realized the error of trying to control anybody or not to take the views of others to heart. I have realized my error after reading various guides to Buddhism. I have offered an apology but now a considerable amount of my colleagues hate me.I see it in their eyes and way they communicate with me. How does a novice Buddhist deal with this?
2018/06/13
[ "https://buddhism.stackexchange.com/questions/26854", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/13640/" ]
In addition to all the good answers here's some solution from my experience. 1. One of the problems you have dealing with this situation is Guilt that you are still feeling about sending that email in the first place. This guilt can be dealt with skillfully. Now that you have already accepted the problem that's the first step. As you have already said that you were drinking at that time, sit for meditation and contemplate on the following. You didn't have had a real choice to make at that time as you were not mindful and aware of your action in that moment of anger, your brain/mind reacted to something she did. In that moment limbic system of your brain completely took over the neo-cortex and you acted out of emotions of anger and hatred. In part, it was also your biology so have forgiveness for your self for what got done through you. 2. You are saying, *I see it in their eyes and way they communicate with me*, you have to trust me on this, it is largely made up by your mind. At the most you can say, your colleagues don't have a good opinion of you. What happens is we are filled with some expectations from people, based on our past mind projects these expectations, and you end up experiencing what you were looking for in the first place. Think about this, if they are filled with hate over an email, every time they see you, it is really their problem, not yours. Contemplate on these words of Buddha. > > “By doing this (*holding on to anger*) you are like a man who wants to hit another and picks up a burning ember or excrement in his hand and so first burns himself or makes himself stink.” > Visuddhimagga IX, 23. > > > So, in effect don't think about the hateful eyes of your friends. 3. As pointed out by other answers, practice *metta* meditation. The best place to start is Ajahn Brahm's youtube videos of guided *metta* meditations. No matter what has happened to give *metta* and loving kindness to your friends. *Dukkha* is an inevitable consequence of human life. Maybe your friends need *metta* too. 4. Also, contemplate the following verse from *Dhammapada* > > One should not consider the faults of others, nor their doing or not doing good or bad deeds. One should consider only whether one has done or not done good or bad deeds. --- Dhammapada Verse 50. > > > The point is you cultivate the pure mind by following the 10 paramitas. Don't focus on others, like everything else, others will change. Hope this helps. *Metta* to you.
There is nothing you can do about the past, and Buddhist deals with it in a way that avoids clinging to the past. Let it go for that is what makes you suffer. Also, all memories can be transformed if done skilfully, it just takes time and they will flourish in their own way. But that requires non-violence towards your thoughts and memories, no matter the content, good or bad. As for present, try mindfulness. Be mindful, keeping *right view* in mind so you do not act wrongly (through wrong view), that is right mindfulness. Let it get you to the shore. If you find yourself lost in thoughts and guilt, or feeling being despised of, again, be *gently* mindful of it. I stress gently, as such is the way of non-violence, as opposed to violence that is being harsh on yourself and your thoughts. > > **183.** Avoid all evil, cultivate the good, purify your mind: this sums up the teaching of the Buddhas. > > > **281.** Guard your thoughts, words and deeds. These three disciplines will spend you along the path to pure wisdom. > > > *(Dhammapada)* > > > Be compassionate towards those who hate, as hate does not bring happiness. Be compassionate towards yourself. I advise plenty of Metta (Loving-kindness) meditation throughout that hard time you are having. It will definitely help to purify the mind.
26,854
Im in the process of trying to 'wake up' I made a grievous error with a colleague recently. I sent a nasty email about something she was involved in. I was trying to manipulate her-even perhaps bully her with my views I was drinking a lot at the time. I have since realized the error of trying to control anybody or not to take the views of others to heart. I have realized my error after reading various guides to Buddhism. I have offered an apology but now a considerable amount of my colleagues hate me.I see it in their eyes and way they communicate with me. How does a novice Buddhist deal with this?
2018/06/13
[ "https://buddhism.stackexchange.com/questions/26854", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/13640/" ]
You are not going to become any better if you are just looking for a way to escape from the consequences of your mistakes. You need to put forth an honest effort to become better. Here are some steps that will help you in doing that. 1. If you haven't already done it, send another mail to all those who received the original mail, correcting the previous mail and apologizing for it. Mention that you have realized your mistakes after getting guidance from Buddhism. 2. Go to the Buddha and take the [Triple Refuge and the five precepts](https://refuge.sirimangalo.org/). When you take the 4th precept, make sure to promise to refrain from all 4 forms of wrong speech: **lying, hateful/vulgar speech, divisive speech, idle speech**. 3. Practice on-the-go-Metta meditation towards your friends and colleagues regardless of the way they look at you. Meaning, you have to chant in your mind "may you(other) be happy, may you be well, may you be successful, may you be free from suffering" as you interact with them. 4. Whenever the thoughts of regret come to the mind, simply discard them as impermanent, suffering and non-self. Later as the mind becomes more matured and capable, try to observe these thoughts to see the 3 characteristics.
Answer given by dhamma 4life is very nice arisen out of real and genuine concern/compassion about the questioner.It is very appreciable and important that you have developed an interest in buddhism ,which is a very true and gives guarantee of attaining liberation if followed ardently and honestly giving stress of 10% to the codes of conduct and 90% to the practice. First of all whatever you have done to your colleague ,was it not out of deep interest of wellbeing of her? if yes then dont bother at all ,howsoever others may have whatever look in their eyes. Afterall we are surrounded by mundane people controlled by their ego,jealousy,hatred. And as we have these things in us it will not be proper to think that why they behave with you like this. As long as you are true in your intention ,forget about everything happening to you or whatever you have done.Whenever we commit mistake ,our so called built up image of a goody person gets little bit shattered . That image building is part of the running of ego.(here i mean running of a machine) . So our mind convince us that say sorry ,by doing so the shattered image again rebuilds itself by assuming that i have said sorry. okay i have done wrong but i am so good that i have said sorry also for it. this assumption makes us again ready for commiting mistakes. So saying sorry is of no use . Now as pointed out by dhamma 4 life , you are very much engrossed in thoughts about the things happened . I do not know what you are trying to practice ,but if it is vipassana then observe the sensations rising on arising of thoughts and be equinimous ,dont react to them with aversion,be neutral. It is the sensations produced and the reaction of us towards them is the root cause of whatever we do ,feel happy or sad . So make use of the situation. In buddhism dukkha is the base from where to move further. Our father/mother sometimes speak harsh words/beat us but never feels guilty about it bcs he is very sure of his good intention behind it. Your action is immaterial, your intention behind it is important .As buddha quotes "intention is kamma". Go in some 10 day retreat to practice vipassana available and convenient to you. Afterall we are not that which we see in the eye of people. people's eyes see very superficially. Pl bear in mind that the interest developed in buddhism /your starting of the practice let it be in crude way , is of very very importance and of top priority, So don not waste time in this senseless,foolish things of engrossing in those thoughts again and again. Wish you practice/study buddhism ardently and genuinely to go further and further on the path. heartily best luck.
26,854
Im in the process of trying to 'wake up' I made a grievous error with a colleague recently. I sent a nasty email about something she was involved in. I was trying to manipulate her-even perhaps bully her with my views I was drinking a lot at the time. I have since realized the error of trying to control anybody or not to take the views of others to heart. I have realized my error after reading various guides to Buddhism. I have offered an apology but now a considerable amount of my colleagues hate me.I see it in their eyes and way they communicate with me. How does a novice Buddhist deal with this?
2018/06/13
[ "https://buddhism.stackexchange.com/questions/26854", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/13640/" ]
Answer given by dhamma 4life is very nice arisen out of real and genuine concern/compassion about the questioner.It is very appreciable and important that you have developed an interest in buddhism ,which is a very true and gives guarantee of attaining liberation if followed ardently and honestly giving stress of 10% to the codes of conduct and 90% to the practice. First of all whatever you have done to your colleague ,was it not out of deep interest of wellbeing of her? if yes then dont bother at all ,howsoever others may have whatever look in their eyes. Afterall we are surrounded by mundane people controlled by their ego,jealousy,hatred. And as we have these things in us it will not be proper to think that why they behave with you like this. As long as you are true in your intention ,forget about everything happening to you or whatever you have done.Whenever we commit mistake ,our so called built up image of a goody person gets little bit shattered . That image building is part of the running of ego.(here i mean running of a machine) . So our mind convince us that say sorry ,by doing so the shattered image again rebuilds itself by assuming that i have said sorry. okay i have done wrong but i am so good that i have said sorry also for it. this assumption makes us again ready for commiting mistakes. So saying sorry is of no use . Now as pointed out by dhamma 4 life , you are very much engrossed in thoughts about the things happened . I do not know what you are trying to practice ,but if it is vipassana then observe the sensations rising on arising of thoughts and be equinimous ,dont react to them with aversion,be neutral. It is the sensations produced and the reaction of us towards them is the root cause of whatever we do ,feel happy or sad . So make use of the situation. In buddhism dukkha is the base from where to move further. Our father/mother sometimes speak harsh words/beat us but never feels guilty about it bcs he is very sure of his good intention behind it. Your action is immaterial, your intention behind it is important .As buddha quotes "intention is kamma". Go in some 10 day retreat to practice vipassana available and convenient to you. Afterall we are not that which we see in the eye of people. people's eyes see very superficially. Pl bear in mind that the interest developed in buddhism /your starting of the practice let it be in crude way , is of very very importance and of top priority, So don not waste time in this senseless,foolish things of engrossing in those thoughts again and again. Wish you practice/study buddhism ardently and genuinely to go further and further on the path. heartily best luck.
You might know this already but here's some advice. It's appropriate to apologise (people do apologise, in the Suttas; and apology or confession is prescribed in the Vinaya). I think that elements of an apology include: * Saying, "I understand that action was wrong" * Saying, "Understanding it (and having understood it) as wrong, I will not do it again" * And then, in fact, not doing it again I think that part of the reason for an apology is that, without it, the victim of your offence might live in fear that you'll do it (hurt them) again. --- You said "I have offered an apology", but it's not clear how clear (nor how public) your apology was, nor whether it was "accepted" and if not why not. Anyway, maybe if it's not accepted that's out of your hands? You said "I have since realized the error of trying to control anybody" -- and maybe this is an example, i.e. you can't force people to accept the apology. The "second noble truth" associates suffering with craving -- craving is wanting things to be other than they are -- perhaps part of your suffering is your wanting your colleagues' action to be other than they are. --- There's a saying that "people are heir to their own kamma". If colleagues are unhappy maybe that's a result of your actions, not their fault, i.e. you shouldn't blame them for being unhappy. Blaming them will only perpetuate your own suffering. --- Some people talk of "body, speech, and mind". The body permits experience (e.g. of pain and pleasure); and speech help people understand what you say, and what you say might be kind or unkind. Your mind is important because it determines what you say (and what you experience). --- If you're successfully avoiding alcohol now, well done. Drinking is against the [fifth precept](https://en.wikipedia.org/wiki/Five_Precepts). In the West some people are alcoholic addicts, which is difficult to resolve. One of the (non-Buddhist) methods or programs that people try is a "twelve step program". If you are or were alcoholic you might find [this description of its Process](https://en.wikipedia.org/wiki/Twelve-step_program#Process) informative, and perhaps steps 8, 9, and 10 of the 12 steps. I don't know, some people (non-Buddhists) find a 12-step program more helpful than nothing and continuing with addiction as before; but it is non-Buddhist. Instead you might want to explore some Buddhist resources such as <http://5th-precept.org/> --- You might want to learn to practice the [Brahmaviharas](https://accesstoinsight.org/search_results.html?q=brahmaviharas&sa=Search): > > These four attitudes are said to be excellent or sublime because they are the right or ideal way of conduct towards living beings (sattesu samma patipatti). They provide, in fact, the answer to all situations arising from social contact. > > > and: > > The Brahma-viharas are incompatible with a hating state of mind > > > --- There's a bit of discussion in comments under [Sankha's answer](https://buddhism.stackexchange.com/a/26863/254), continued in [this chat room](https://chat.stackexchange.com/rooms/78924). If I can try to summarise: * There are different states of mind (including emotions, views, perceptions); which may be categorised as wholesome or skilful (they lead towards non-suffering), or as unwholesome or unskillful (their result is suffering). * Craving (e.g. "I wish things were other than they are") is unwholesome. * Desire (e.g. "I want to follow the wholesome Buddhist path) can be wholesome. * Aversion (e.g. "I don't like this") is form of craving and unwholesome. * Skilful variants of aversion are called something other than "aversion": e.g. not wanting to hurt people is called "compassion" (not called "aversion to hurting people"), and knowing the difference between wholesome and unwholesome might be called "wisdom" (not called "aversion to the unwholesome"). Maybe "aversion" is always associated with an unwholesome state of mind. * A sense of "shame" (i.e. [*Hiri*](https://en.wikipedia.org/wiki/Hri_(Buddhism))) might be defined as wholesome (see also those alternative translations: "self-respect, conscientiousness, moral self-dignity, dignity"). Conversely a lack of shame (being "shameless") might make a person untrainable (immoral or amoral). * A sense of "guilt" (i.e. [*Kukkucca*](https://en.wikipedia.org/wiki/Kaukritya)) might be defined as unwholesome (also translated "regret, worry, remorse"). That might seem odd, or a subtle difference, because I guess that "shame" and "guilt" imply something similar in English, but there's an important distinction in the Pali. I think that the difference between *Hiri* and *Kukkucca* is that *Hiri* results in virtuous behaviour and non-suffering, and *Kukkucca* is associated with non-virtuous behaviour and suffering. A result of skilful/virtuous behaviour is meant to be "absence of remorse": which results in joy and so on ... i.e. it's the absence of remorse that's wholesome and is a foundation for peace of mind. I suppose an example might be: 1. I used to have a bad habit 2. I later eventually understood the error (and associated suffering), and eradicated the habit 3. Now I don't (and shouldn't) feel remorse (about a bad habit which is in the past and no longer exists), instead feel a lack of remorse as a result of having stopped the habit (conditioned by the non-existence or eradication of the habit). --- I think (I can't find a reference) that even a desire for fame or for people to hold you in high esteem, caring about reputation, might be a form of greed of craving (and "conceit") and unwholesome. --- If you're looking for suggestions about how to communicate, you might get (non-Buddhist) answers if you post on [InterpersonalSkills.SE](https://interpersonal.stackexchange.com/) or [Workplace.SE](https://workplace.stackexchange.com/). I guess the Buddhist answer (even about how to communicate) is to be clear about your mind state. I recommend the [first few verses](https://www.accesstoinsight.org/tipitaka/kn/dhp/dhp.01.budd.html) of the Dhammapada, for example: > > 1. Mind precedes all mental states. Mind is their chief; they are all mind-wrought. If with an impure mind a person speaks or acts suffering follows him like the wheel that follows the foot of the ox. > 2. Mind precedes all mental states. Mind is their chief; they are all mind-wrought. If with a pure mind a person speaks or acts happiness follows him like his never-departing shadow. > 3. "He abused me, he struck me, he overpowered me, he robbed me." Those who harbor such thoughts do not still their hatred. > 4. "He abused me, he struck me, he overpowered me, he robbed me." Those who do not harbor such thoughts still their hatred. > 5. Hatred is never appeased by hatred in this world. By non-hatred alone is hatred appeased. This is a law eternal. > > >
26,854
Im in the process of trying to 'wake up' I made a grievous error with a colleague recently. I sent a nasty email about something she was involved in. I was trying to manipulate her-even perhaps bully her with my views I was drinking a lot at the time. I have since realized the error of trying to control anybody or not to take the views of others to heart. I have realized my error after reading various guides to Buddhism. I have offered an apology but now a considerable amount of my colleagues hate me.I see it in their eyes and way they communicate with me. How does a novice Buddhist deal with this?
2018/06/13
[ "https://buddhism.stackexchange.com/questions/26854", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/13640/" ]
You are not going to become any better if you are just looking for a way to escape from the consequences of your mistakes. You need to put forth an honest effort to become better. Here are some steps that will help you in doing that. 1. If you haven't already done it, send another mail to all those who received the original mail, correcting the previous mail and apologizing for it. Mention that you have realized your mistakes after getting guidance from Buddhism. 2. Go to the Buddha and take the [Triple Refuge and the five precepts](https://refuge.sirimangalo.org/). When you take the 4th precept, make sure to promise to refrain from all 4 forms of wrong speech: **lying, hateful/vulgar speech, divisive speech, idle speech**. 3. Practice on-the-go-Metta meditation towards your friends and colleagues regardless of the way they look at you. Meaning, you have to chant in your mind "may you(other) be happy, may you be well, may you be successful, may you be free from suffering" as you interact with them. 4. Whenever the thoughts of regret come to the mind, simply discard them as impermanent, suffering and non-self. Later as the mind becomes more matured and capable, try to observe these thoughts to see the 3 characteristics.
In addition to all the good answers here's some solution from my experience. 1. One of the problems you have dealing with this situation is Guilt that you are still feeling about sending that email in the first place. This guilt can be dealt with skillfully. Now that you have already accepted the problem that's the first step. As you have already said that you were drinking at that time, sit for meditation and contemplate on the following. You didn't have had a real choice to make at that time as you were not mindful and aware of your action in that moment of anger, your brain/mind reacted to something she did. In that moment limbic system of your brain completely took over the neo-cortex and you acted out of emotions of anger and hatred. In part, it was also your biology so have forgiveness for your self for what got done through you. 2. You are saying, *I see it in their eyes and way they communicate with me*, you have to trust me on this, it is largely made up by your mind. At the most you can say, your colleagues don't have a good opinion of you. What happens is we are filled with some expectations from people, based on our past mind projects these expectations, and you end up experiencing what you were looking for in the first place. Think about this, if they are filled with hate over an email, every time they see you, it is really their problem, not yours. Contemplate on these words of Buddha. > > “By doing this (*holding on to anger*) you are like a man who wants to hit another and picks up a burning ember or excrement in his hand and so first burns himself or makes himself stink.” > Visuddhimagga IX, 23. > > > So, in effect don't think about the hateful eyes of your friends. 3. As pointed out by other answers, practice *metta* meditation. The best place to start is Ajahn Brahm's youtube videos of guided *metta* meditations. No matter what has happened to give *metta* and loving kindness to your friends. *Dukkha* is an inevitable consequence of human life. Maybe your friends need *metta* too. 4. Also, contemplate the following verse from *Dhammapada* > > One should not consider the faults of others, nor their doing or not doing good or bad deeds. One should consider only whether one has done or not done good or bad deeds. --- Dhammapada Verse 50. > > > The point is you cultivate the pure mind by following the 10 paramitas. Don't focus on others, like everything else, others will change. Hope this helps. *Metta* to you.
26,854
Im in the process of trying to 'wake up' I made a grievous error with a colleague recently. I sent a nasty email about something she was involved in. I was trying to manipulate her-even perhaps bully her with my views I was drinking a lot at the time. I have since realized the error of trying to control anybody or not to take the views of others to heart. I have realized my error after reading various guides to Buddhism. I have offered an apology but now a considerable amount of my colleagues hate me.I see it in their eyes and way they communicate with me. How does a novice Buddhist deal with this?
2018/06/13
[ "https://buddhism.stackexchange.com/questions/26854", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/13640/" ]
You are not going to become any better if you are just looking for a way to escape from the consequences of your mistakes. You need to put forth an honest effort to become better. Here are some steps that will help you in doing that. 1. If you haven't already done it, send another mail to all those who received the original mail, correcting the previous mail and apologizing for it. Mention that you have realized your mistakes after getting guidance from Buddhism. 2. Go to the Buddha and take the [Triple Refuge and the five precepts](https://refuge.sirimangalo.org/). When you take the 4th precept, make sure to promise to refrain from all 4 forms of wrong speech: **lying, hateful/vulgar speech, divisive speech, idle speech**. 3. Practice on-the-go-Metta meditation towards your friends and colleagues regardless of the way they look at you. Meaning, you have to chant in your mind "may you(other) be happy, may you be well, may you be successful, may you be free from suffering" as you interact with them. 4. Whenever the thoughts of regret come to the mind, simply discard them as impermanent, suffering and non-self. Later as the mind becomes more matured and capable, try to observe these thoughts to see the 3 characteristics.
You might know this already but here's some advice. It's appropriate to apologise (people do apologise, in the Suttas; and apology or confession is prescribed in the Vinaya). I think that elements of an apology include: * Saying, "I understand that action was wrong" * Saying, "Understanding it (and having understood it) as wrong, I will not do it again" * And then, in fact, not doing it again I think that part of the reason for an apology is that, without it, the victim of your offence might live in fear that you'll do it (hurt them) again. --- You said "I have offered an apology", but it's not clear how clear (nor how public) your apology was, nor whether it was "accepted" and if not why not. Anyway, maybe if it's not accepted that's out of your hands? You said "I have since realized the error of trying to control anybody" -- and maybe this is an example, i.e. you can't force people to accept the apology. The "second noble truth" associates suffering with craving -- craving is wanting things to be other than they are -- perhaps part of your suffering is your wanting your colleagues' action to be other than they are. --- There's a saying that "people are heir to their own kamma". If colleagues are unhappy maybe that's a result of your actions, not their fault, i.e. you shouldn't blame them for being unhappy. Blaming them will only perpetuate your own suffering. --- Some people talk of "body, speech, and mind". The body permits experience (e.g. of pain and pleasure); and speech help people understand what you say, and what you say might be kind or unkind. Your mind is important because it determines what you say (and what you experience). --- If you're successfully avoiding alcohol now, well done. Drinking is against the [fifth precept](https://en.wikipedia.org/wiki/Five_Precepts). In the West some people are alcoholic addicts, which is difficult to resolve. One of the (non-Buddhist) methods or programs that people try is a "twelve step program". If you are or were alcoholic you might find [this description of its Process](https://en.wikipedia.org/wiki/Twelve-step_program#Process) informative, and perhaps steps 8, 9, and 10 of the 12 steps. I don't know, some people (non-Buddhists) find a 12-step program more helpful than nothing and continuing with addiction as before; but it is non-Buddhist. Instead you might want to explore some Buddhist resources such as <http://5th-precept.org/> --- You might want to learn to practice the [Brahmaviharas](https://accesstoinsight.org/search_results.html?q=brahmaviharas&sa=Search): > > These four attitudes are said to be excellent or sublime because they are the right or ideal way of conduct towards living beings (sattesu samma patipatti). They provide, in fact, the answer to all situations arising from social contact. > > > and: > > The Brahma-viharas are incompatible with a hating state of mind > > > --- There's a bit of discussion in comments under [Sankha's answer](https://buddhism.stackexchange.com/a/26863/254), continued in [this chat room](https://chat.stackexchange.com/rooms/78924). If I can try to summarise: * There are different states of mind (including emotions, views, perceptions); which may be categorised as wholesome or skilful (they lead towards non-suffering), or as unwholesome or unskillful (their result is suffering). * Craving (e.g. "I wish things were other than they are") is unwholesome. * Desire (e.g. "I want to follow the wholesome Buddhist path) can be wholesome. * Aversion (e.g. "I don't like this") is form of craving and unwholesome. * Skilful variants of aversion are called something other than "aversion": e.g. not wanting to hurt people is called "compassion" (not called "aversion to hurting people"), and knowing the difference between wholesome and unwholesome might be called "wisdom" (not called "aversion to the unwholesome"). Maybe "aversion" is always associated with an unwholesome state of mind. * A sense of "shame" (i.e. [*Hiri*](https://en.wikipedia.org/wiki/Hri_(Buddhism))) might be defined as wholesome (see also those alternative translations: "self-respect, conscientiousness, moral self-dignity, dignity"). Conversely a lack of shame (being "shameless") might make a person untrainable (immoral or amoral). * A sense of "guilt" (i.e. [*Kukkucca*](https://en.wikipedia.org/wiki/Kaukritya)) might be defined as unwholesome (also translated "regret, worry, remorse"). That might seem odd, or a subtle difference, because I guess that "shame" and "guilt" imply something similar in English, but there's an important distinction in the Pali. I think that the difference between *Hiri* and *Kukkucca* is that *Hiri* results in virtuous behaviour and non-suffering, and *Kukkucca* is associated with non-virtuous behaviour and suffering. A result of skilful/virtuous behaviour is meant to be "absence of remorse": which results in joy and so on ... i.e. it's the absence of remorse that's wholesome and is a foundation for peace of mind. I suppose an example might be: 1. I used to have a bad habit 2. I later eventually understood the error (and associated suffering), and eradicated the habit 3. Now I don't (and shouldn't) feel remorse (about a bad habit which is in the past and no longer exists), instead feel a lack of remorse as a result of having stopped the habit (conditioned by the non-existence or eradication of the habit). --- I think (I can't find a reference) that even a desire for fame or for people to hold you in high esteem, caring about reputation, might be a form of greed of craving (and "conceit") and unwholesome. --- If you're looking for suggestions about how to communicate, you might get (non-Buddhist) answers if you post on [InterpersonalSkills.SE](https://interpersonal.stackexchange.com/) or [Workplace.SE](https://workplace.stackexchange.com/). I guess the Buddhist answer (even about how to communicate) is to be clear about your mind state. I recommend the [first few verses](https://www.accesstoinsight.org/tipitaka/kn/dhp/dhp.01.budd.html) of the Dhammapada, for example: > > 1. Mind precedes all mental states. Mind is their chief; they are all mind-wrought. If with an impure mind a person speaks or acts suffering follows him like the wheel that follows the foot of the ox. > 2. Mind precedes all mental states. Mind is their chief; they are all mind-wrought. If with a pure mind a person speaks or acts happiness follows him like his never-departing shadow. > 3. "He abused me, he struck me, he overpowered me, he robbed me." Those who harbor such thoughts do not still their hatred. > 4. "He abused me, he struck me, he overpowered me, he robbed me." Those who do not harbor such thoughts still their hatred. > 5. Hatred is never appeased by hatred in this world. By non-hatred alone is hatred appeased. This is a law eternal. > > >
26,854
Im in the process of trying to 'wake up' I made a grievous error with a colleague recently. I sent a nasty email about something she was involved in. I was trying to manipulate her-even perhaps bully her with my views I was drinking a lot at the time. I have since realized the error of trying to control anybody or not to take the views of others to heart. I have realized my error after reading various guides to Buddhism. I have offered an apology but now a considerable amount of my colleagues hate me.I see it in their eyes and way they communicate with me. How does a novice Buddhist deal with this?
2018/06/13
[ "https://buddhism.stackexchange.com/questions/26854", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/13640/" ]
In addition to all the good answers here's some solution from my experience. 1. One of the problems you have dealing with this situation is Guilt that you are still feeling about sending that email in the first place. This guilt can be dealt with skillfully. Now that you have already accepted the problem that's the first step. As you have already said that you were drinking at that time, sit for meditation and contemplate on the following. You didn't have had a real choice to make at that time as you were not mindful and aware of your action in that moment of anger, your brain/mind reacted to something she did. In that moment limbic system of your brain completely took over the neo-cortex and you acted out of emotions of anger and hatred. In part, it was also your biology so have forgiveness for your self for what got done through you. 2. You are saying, *I see it in their eyes and way they communicate with me*, you have to trust me on this, it is largely made up by your mind. At the most you can say, your colleagues don't have a good opinion of you. What happens is we are filled with some expectations from people, based on our past mind projects these expectations, and you end up experiencing what you were looking for in the first place. Think about this, if they are filled with hate over an email, every time they see you, it is really their problem, not yours. Contemplate on these words of Buddha. > > “By doing this (*holding on to anger*) you are like a man who wants to hit another and picks up a burning ember or excrement in his hand and so first burns himself or makes himself stink.” > Visuddhimagga IX, 23. > > > So, in effect don't think about the hateful eyes of your friends. 3. As pointed out by other answers, practice *metta* meditation. The best place to start is Ajahn Brahm's youtube videos of guided *metta* meditations. No matter what has happened to give *metta* and loving kindness to your friends. *Dukkha* is an inevitable consequence of human life. Maybe your friends need *metta* too. 4. Also, contemplate the following verse from *Dhammapada* > > One should not consider the faults of others, nor their doing or not doing good or bad deeds. One should consider only whether one has done or not done good or bad deeds. --- Dhammapada Verse 50. > > > The point is you cultivate the pure mind by following the 10 paramitas. Don't focus on others, like everything else, others will change. Hope this helps. *Metta* to you.
You might know this already but here's some advice. It's appropriate to apologise (people do apologise, in the Suttas; and apology or confession is prescribed in the Vinaya). I think that elements of an apology include: * Saying, "I understand that action was wrong" * Saying, "Understanding it (and having understood it) as wrong, I will not do it again" * And then, in fact, not doing it again I think that part of the reason for an apology is that, without it, the victim of your offence might live in fear that you'll do it (hurt them) again. --- You said "I have offered an apology", but it's not clear how clear (nor how public) your apology was, nor whether it was "accepted" and if not why not. Anyway, maybe if it's not accepted that's out of your hands? You said "I have since realized the error of trying to control anybody" -- and maybe this is an example, i.e. you can't force people to accept the apology. The "second noble truth" associates suffering with craving -- craving is wanting things to be other than they are -- perhaps part of your suffering is your wanting your colleagues' action to be other than they are. --- There's a saying that "people are heir to their own kamma". If colleagues are unhappy maybe that's a result of your actions, not their fault, i.e. you shouldn't blame them for being unhappy. Blaming them will only perpetuate your own suffering. --- Some people talk of "body, speech, and mind". The body permits experience (e.g. of pain and pleasure); and speech help people understand what you say, and what you say might be kind or unkind. Your mind is important because it determines what you say (and what you experience). --- If you're successfully avoiding alcohol now, well done. Drinking is against the [fifth precept](https://en.wikipedia.org/wiki/Five_Precepts). In the West some people are alcoholic addicts, which is difficult to resolve. One of the (non-Buddhist) methods or programs that people try is a "twelve step program". If you are or were alcoholic you might find [this description of its Process](https://en.wikipedia.org/wiki/Twelve-step_program#Process) informative, and perhaps steps 8, 9, and 10 of the 12 steps. I don't know, some people (non-Buddhists) find a 12-step program more helpful than nothing and continuing with addiction as before; but it is non-Buddhist. Instead you might want to explore some Buddhist resources such as <http://5th-precept.org/> --- You might want to learn to practice the [Brahmaviharas](https://accesstoinsight.org/search_results.html?q=brahmaviharas&sa=Search): > > These four attitudes are said to be excellent or sublime because they are the right or ideal way of conduct towards living beings (sattesu samma patipatti). They provide, in fact, the answer to all situations arising from social contact. > > > and: > > The Brahma-viharas are incompatible with a hating state of mind > > > --- There's a bit of discussion in comments under [Sankha's answer](https://buddhism.stackexchange.com/a/26863/254), continued in [this chat room](https://chat.stackexchange.com/rooms/78924). If I can try to summarise: * There are different states of mind (including emotions, views, perceptions); which may be categorised as wholesome or skilful (they lead towards non-suffering), or as unwholesome or unskillful (their result is suffering). * Craving (e.g. "I wish things were other than they are") is unwholesome. * Desire (e.g. "I want to follow the wholesome Buddhist path) can be wholesome. * Aversion (e.g. "I don't like this") is form of craving and unwholesome. * Skilful variants of aversion are called something other than "aversion": e.g. not wanting to hurt people is called "compassion" (not called "aversion to hurting people"), and knowing the difference between wholesome and unwholesome might be called "wisdom" (not called "aversion to the unwholesome"). Maybe "aversion" is always associated with an unwholesome state of mind. * A sense of "shame" (i.e. [*Hiri*](https://en.wikipedia.org/wiki/Hri_(Buddhism))) might be defined as wholesome (see also those alternative translations: "self-respect, conscientiousness, moral self-dignity, dignity"). Conversely a lack of shame (being "shameless") might make a person untrainable (immoral or amoral). * A sense of "guilt" (i.e. [*Kukkucca*](https://en.wikipedia.org/wiki/Kaukritya)) might be defined as unwholesome (also translated "regret, worry, remorse"). That might seem odd, or a subtle difference, because I guess that "shame" and "guilt" imply something similar in English, but there's an important distinction in the Pali. I think that the difference between *Hiri* and *Kukkucca* is that *Hiri* results in virtuous behaviour and non-suffering, and *Kukkucca* is associated with non-virtuous behaviour and suffering. A result of skilful/virtuous behaviour is meant to be "absence of remorse": which results in joy and so on ... i.e. it's the absence of remorse that's wholesome and is a foundation for peace of mind. I suppose an example might be: 1. I used to have a bad habit 2. I later eventually understood the error (and associated suffering), and eradicated the habit 3. Now I don't (and shouldn't) feel remorse (about a bad habit which is in the past and no longer exists), instead feel a lack of remorse as a result of having stopped the habit (conditioned by the non-existence or eradication of the habit). --- I think (I can't find a reference) that even a desire for fame or for people to hold you in high esteem, caring about reputation, might be a form of greed of craving (and "conceit") and unwholesome. --- If you're looking for suggestions about how to communicate, you might get (non-Buddhist) answers if you post on [InterpersonalSkills.SE](https://interpersonal.stackexchange.com/) or [Workplace.SE](https://workplace.stackexchange.com/). I guess the Buddhist answer (even about how to communicate) is to be clear about your mind state. I recommend the [first few verses](https://www.accesstoinsight.org/tipitaka/kn/dhp/dhp.01.budd.html) of the Dhammapada, for example: > > 1. Mind precedes all mental states. Mind is their chief; they are all mind-wrought. If with an impure mind a person speaks or acts suffering follows him like the wheel that follows the foot of the ox. > 2. Mind precedes all mental states. Mind is their chief; they are all mind-wrought. If with a pure mind a person speaks or acts happiness follows him like his never-departing shadow. > 3. "He abused me, he struck me, he overpowered me, he robbed me." Those who harbor such thoughts do not still their hatred. > 4. "He abused me, he struck me, he overpowered me, he robbed me." Those who do not harbor such thoughts still their hatred. > 5. Hatred is never appeased by hatred in this world. By non-hatred alone is hatred appeased. This is a law eternal. > > >
41,347,474
### Background I'm trying to create two instances of a `struct`. One of them will not change and is therefore declared `const`, but the other may be changed asynchronously, therefore I'd like to make it `volatile`. ### Problem I'm trying to use the `const` instance of the structure to initialise the `volatile` one. However, if I use the `volatile` keyword the compiler throws this error: ``` passing 'volatile rect' as 'this' argument of 'rect& rect::operator=(rect&&)' discards qualifiers [-fpermissive]at line 15 col 8 ``` ### Reproducible example ``` #include <Arduino.h> struct rect { int x0; int y0; int width; int height; }; const rect outer = {0, 0, 10, 5}; volatile rect inner; void setup() { inner = {outer.x0 + 1, outer.y0 + 1, outer.width - 2, outer.height - 2}; } void loop() { ; } ``` Omitting `volatile` compiles fine: ``` rect inner = {outer.x0 + 1, outer.y0 + 1, outer.width - 2, outer.height - 2}; ``` Initialising one-by-one also works, but this is exactly what I'm trying to avoid: ``` inner.x0 = outer.x0 + 1; inner.y0 = outer.y0 + 1; inner.width = 0; inner.height = outer.height - 2; ``` ### Question What am I missing? ... It may be related to [this](https://stackoverflow.com/questions/4479597/does-making-a-struct-volatile-make-all-its-members-volatile?noredirect=1&lq=1).
2016/12/27
[ "https://Stackoverflow.com/questions/41347474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6118556/" ]
You are missing what the error message actually says. The compiler is telling you that to assign the whole structure in one go needs a "copy constructor" which understands the volatile qualifier and there isn't one. Have a look at [this answer](https://stackoverflow.com/questions/5973427/error-passing-xxx-as-this-argument-of-xxx-discards-qualifiers) for a discussion of what the error means. But when you assign the individual elements of the structure one by one no copy constructor is needed and so the code works fine. Why are you "trying to avoid" this? What you are expecting the volatile qualifier to do? In C/C++ it **ONLY** prevents the compiler from optimising away your variables or the code which uses them. Nothing more. It wouldn't be useful to define a stock copy constructor for volatile structures, since your concurrency requirements will differ from everyone else's. To guarantee that your structure elements are assigned consistently, you may need to disable interrupts, like this: ``` cli(); inner.x0 = outer.x0 + 1; inner.y0 = outer.y0 + 1; inner.width = 0; inner.height = outer.height - 2; sei(); ``` But you'll have to analyse precisely what you need and that's heading off topic.
> > What am I missing? ... It may be related to `this`. > > > Yes, you're missing the proper copy c'tor for volatile
8,248,731
This is a followup to [Using #include to load OpenCL code](https://stackoverflow.com/questions/1415538/using-include-to-load-opencl-code) I've noticed that when you use the method described by grrussel (and used in Bullet Physics), the created string has all newlines stripped (comments seem to be stripped, too, but I'm not too worried about that). Now for the most part this is fine if the included opencl code doesn't have any preprocessor definitions in it, but if there is the code will fail to compile with the OpenCL compiler. Is there a way to get the `#include` to keep the newlines in there, or is there a better method to embed the opencl code into my executable (other than copying the string into a cpp file and putting quotes around everything)? I tested this in Visual Studio 2010, I'm not sure if other compilers exhibit the same behavior. I would prefer a method which doesn't require any external tools and works with a variety of compilers/platforms. Copied code from other answer: In C++ / C source ``` #define MSTRINGIFY(A) #A char* stringifiedSourceCL = #include "VectorAddKernels.cl" ``` In the OpenCL source ``` MSTRINGIFY( __kernel void VectorAdd(__global float8* c) { // snipped out OpenCL code... return; } ); ```
2011/11/23
[ "https://Stackoverflow.com/questions/8248731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/558546/" ]
I'd write a small tool that generates a cpp with a constant string from the text file, which you would then compile along with the other stuff. This is what Qt's resource compiler moc does (and more, since it has a whole API around it), and there's also the option of Windows's resource kit (see [this answer](https://stackoverflow.com/a/8316943/72312) below). Anyway, a small build tool that walks a files in a dir and builds a cpp from them should be enough, and something you can put together in 15 minutes (given suitable scripting skills). **Update**: As per Henry's comment, on Linux (or with Msys/Cygwin), you could use [xxd](http://linux.die.net/man/1/xxd) with the -i (i.e. `xxd -i` ) flag, which reads a file and generates a c-include file with the exact contents defined properly.
Excellent question! One thing that works on Windows is to treat your OpenCL C files as Windows resources. Then the source code gets built into your executable. In your reasource (.rc) file, you would add something like this: ``` IDR_OPENCL_FILE_1 OPENCL_SOURCE "mydir\\myfile.cl" ``` Then, in the host source, something like this: ``` // Load the resource memory HRSRC resource = FindResource(NULL, L"IDR_OPENCL_FILE_1", L"OPENCL_SOURCE"); HGLOBAL resMem = LoadResource(NULL, resource); char* source = (char*)LockResource(resMem); // Build a STL string out of it DWORD resSize = SizeofResource(NULL, resource); std::string cl_source = string(source, resSize); ``` On Linux, objcopy will let you do something similar. You can build an elf .o with the source file exported as a symbol. Sorry I don't have a code snippet handy for that right now. I wish there were a better platform-independent answer. If you come across it, let me know.
32,454,544
I have a list like this: ``` a = [(1,2,3,4), (2,3,2,2), (33,221,22,1) ...] ``` and I want to add for each item in the list a 5th value, for example: ``` new_a = [(1,2,3,4,"new"), (2,3,2,2,"new"), (33,221,22,1,"new") ...] ``` How can I do that because a.list or a.add freeze my computer. ``` for item in a: a.add("new") or a.append("new") ```
2015/09/08
[ "https://Stackoverflow.com/questions/32454544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3050807/" ]
The inner items are not lists, they are tuples. Tuples are immutable. Therefore, you probably need to create new tuples that contain the values you want: ``` new_a = [x + ('new',) for x in a] ``` This code iterates through all tuples present in a and for each one creates a new tuple consisting of the values of the original, plus the value `'new'` *(the value `('new',)` is a tuple literal: it creates a new tuple with one value)*. In the end, all the values created are assigned to the new list.
You can use `map` ``` >>> map(lambda x: x + ('new',), a) [(1, 2, 3, 4, 'new'), (2, 3, 2, 2, 'new'), (33, 221, 22, 1, 'new')] ```
267,593
When I have **a directed relation** I call one of the items taking part **a subject** and other **an object**. Is there a corresponding term for **a bidirectional relation**? I know I can call both items a relation **objects**, but I would like some other term to distinguish from directed relation.
2015/08/18
[ "https://english.stackexchange.com/questions/267593", "https://english.stackexchange.com", "https://english.stackexchange.com/users/28436/" ]
[participants](http://www.oxforddictionaries.com/definition/english/participant//) [Source: ODO] Examples of usage: * > > '*a situation with two participants between which a bidirectional relation holds*' > > > Source: [Reciprocity in English: historical development and synchronic structure. *Haas, F* Routledge, 2010](https://books.google.co.uk/books?id=QiCNAgAAQBAJ&pg=PA48&lpg=PA48&dq=bidirectional%20relation%20particip*&source=bl&ots=hJpMp9yjzB&sig=MhcCt4T_Cy2ebB0pCawDoJs5iRo&hl=en&sa=X&ved=0CC8Q6AEwAmoVChMI3-7H99OyxwIVS1caCh02WwdZ#v=onepage&q=bidirectional%20relation%20particip*&f=false) * > > '*It is a bidirectional relation denoting that two participants are socially connected and it corresponds to the generic relation offered by existing social networks.*' > > > Source: [Enterprise, business-process and information systems modeling. [LNBIP 175] Springer, 2014](https://books.google.co.uk/books?id=6c25BQAAQBAJ&pg=PA98&lpg=PA98&dq=bidirectional%20relation%20participants&source=bl&ots=WM5Nnaj57w&sig=HBd8aKhuzrkoju8eo6DqVAkn4Oo&hl=en&sa=X&ved=0CDQQ6AEwA2oVChMIvez8mdeyxwIVRToaCh2ULgxb#v=onepage&q=bidirectional%20relation%20participants&f=false)
Reflexives appear to be one form of bidirectional object: ***Reflexive***: "He injured himself." "[He perjured himself.](https://en.wiktionary.org/wiki/perjure#Verb)" (ref. Wiktionary) And Reciprocal ([Merriam Webster](http://www.merriam-webster.com/dictionary/reciprocal)) describes another *situation*: > > —used to describe a relationship in which two people or groups agree > to do something similar for each other, to allow each other to have > the same rights, etc. > > > hence: ***Reciprocal Pronouns:*** ([englishclub.com](https://www.englishclub.com/grammar/pronouns-reciprocal.htm)) "each other," "one another"
60,188,354
I am practising pivot. And I have a table with Name and Occupation data (code to generate sample is below). I need to put Occupations in columns, and stack beneath each occupation, names. Null is fine. I have seen a number of posts, and [this](https://stackoverflow.com/questions/52147382/sql-pivot-table-on-text-value) one is what I need, but once adapted to my data, it only pulls 1 row of data. Here is the code to generate sample and actual pivot code. How can I correct this error? ``` declare @occupations table (ename nvarchar(10), occupation nvarchar(10) ) insert @occupations values ('John','Doctor'),('Mary','Doctor'),('Jack','Doctor'),('Anna','Doctor'), ('Jim','Singer'),('Kate','Singer'),('Helen','Actor'),('Paco','Singer') SELECT [Doctor] Doctor, [Singer] Singer, [Actor] Actor FROM @occupations PIVOT (min(ename) FOR occupation IN ([Doctor],[Singer], [Actor]) )AS pp ``` I get this result: ``` Doctor Singer Actor Anna Jim Helen ``` There should be more rows to include all names. I.e. you can see in insert statement that there are 4 doctors, for example. So should be 8 lines with some nulls.
2020/02/12
[ "https://Stackoverflow.com/questions/60188354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3181863/" ]
The best way to remove all escape characters from your `JSON` string is to use the `Regex.Unescape()` method. This method returns a new string with no escape characters. Even characters such as `\n` `\t` etc are removed. Make sure to import the `System.Text.RegularExpressions` namespace: ``` using System.Text.RegularExpressions var string = "[{\"Item\": { \"Name\": \"item1\" }, \"ShipQuantity\": \" 50.0000000000000000000\", \"Total\": \"10.0000000000000000000\"},{\"Item\": { \"Name\": \"Gratuity\" }, \"ShipQuantity\": \" 1.0000000000000000000\", \"Total\": \"10.0000000000000000000\"}]"; var unescapedstring = Regex.Unescape(string); ``` More information on this method can be found [here](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.unescape?redirectedfrom=MSDN&view=netframework-4.8#System_Text_RegularExpressions_Regex_Unescape_System_String_)
You are escaping `"` correctly. There is no issue at all. ```cs var string = "[{\"Item\": { \"Name\": \"item1\" }, \"ShipQuantity\": \" 50.0000000000000000000\", \"Total\": \"10.0000000000000000000\"},{\"Item\": { \"Name\": \"Gratuity\" }, \"ShipQuantity\": \" 1.0000000000000000000\", \"Total\": \"10.0000000000000000000\"}]"; ``` The reason why you are seeing the backsplashes is that you are previewing the output in the debugger, who automatically escapes the double-quotes.
3,041,969
i just want to create a simple application that will allow a user to input a url to a rss feed and display the contents to a user. what would be a good java library to enable me to read rss feeds? cheers
2010/06/15
[ "https://Stackoverflow.com/questions/3041969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/286630/" ]
Rome <http://rome.dev.java.net/> - is the popular java library for parsing RSS feeds
**Informa** is a very good java library for RSS feeds and can be found on **sourceforge.net**.The best part of this it implements Observer design pattern , hence keep checking if any new items are found on the RSS URL. Also you can set a frequency to crawl a number of URLs.
7,834,351
In an application I'm developing, I have a main form that simply sits there and displays log data, and a worker thread that autonomously does the work in a loop. ``` MyWorker worker = new MyWorker(); MainForm mainForm = new MainForm(); // Subscribe form to log event so log data gets displayed worker.Log += mainForm.Log; // Start the worker thread's MainLoop new Thread(new ThreadStart(worker.MainLoop)).Start(); // Show the form (blocking) Application.Run(mainForm); // If we end up here, the form has been closed and the worker has to stop running worker.Running = false; ``` As you can see, whenever the form is closed, the worker thread should be stopped. The worker looks like this: ``` public class MyWorker { public String Running { get; set; } public MyWorker() { Running = true; } public void MainLoop() { while (Running) { DoExtensiveWork1(); if (!Running) return; DoExtensiveWork2(); if (!Running) return; DoExtensiveWork3(); if (!Running) return; DoExtensiveWork4(); if (!Running) return; DoExtensiveWork5(); if (!Running) return; // We have to wait fifteen minutes (900 seconds) // before another "run" can be processed for (int i = 0; i < 900; i++) { Thread.Sleep(1000); if (!Running) return; } } } } ``` As you can see, I want the thread to be able to stop when switching between successive work operations, but not when within an operation. When an operation (`DoExtensiveWorkN`) has finished, its status and results are persisted do disk or database, so quitting while an operation is in progress (by, for example, `Thread.Abort`) is not an option. However, I find this code I've just written repulsive to look at, especially the "wait loop" which sleeps for one second 900 times, to prevent the thread from idling for 15 minutes before detecting `Running` has been set to `false`. I'd rather be able to throw some kind of event to stop the main loop as soon as it's finished a piece of work. Can anyone point me in the right direction how to do this, or if a total rewrite is required because I totally misunderstood threading, show me somewhere where those principles are explained?
2011/10/20
[ "https://Stackoverflow.com/questions/7834351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/266143/" ]
You can tidy up both the running of the individual tasks and the 15 min wait loop considerably. I'd suggest perhaps using something like this: ``` public class MyWorker { private readonly ManualResetEvent _stopEvent = new ManualResetEvent(false); private readonly Action[] _workUnits; private bool Running { get { return !_stopEvent.WaitOne(0); } } public MyWorker() { _workUnits = new Action[] { DoExtensiveWork1, DoExtensiveWork2, DoExtensiveWork3, DoExtensiveWork4, DoExtensiveWork5 }; } public void Stop() { _stopEvent.Set(); } public void MainLoop() { while (Running) { foreach (var workUnit in _workUnits) { workUnit(); if (!Running) return; } // We have to wait fifteen minutes (900 seconds) // before another "run" can be processed if (_stopEvent.WaitOne(900000)) return; } } } ``` Then to stop the process at the next appropriate point: ``` Worker.Stop(); ```
I would suggest using [System.Timers.Timer](http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx). You can do your work with the running thing and rather than using the sleep you can just set the timer to go off again in 15 minutes. If you want to stop it early then call some kind of abort method (similar to setting your Running=true variable) that will stop the timer. It should be noted that each time the timer event fires it will start up a new thread so you dont' need to worry about killing background threads. Your thread finishes its run of processing, sets the timer to run in 15 minutes and then the thread finishes naturally. If you abort during a wait then you just get rid of the timer and no more cleanup needed. If you abort during a run then you let the run finish and at the end it checks a flag and doesn't start the timer again and then the thread finishes. For the timer you'll want to set the timer to start manually at the end of the process. The alternative is to have the timer ticking every 15 minutes but that would mean that if your processing took 10 minutes then it owuld only be 5 minutes before the next run. And if it took more than 15 minutes you may be in trouble. Also restarting the timer manually guarantees that the processing shouldn't restart while another is running.
26,842,004
I have deleted my earlier question regarding file upload using classic asp. Now I have switched to .net for achieve the goal however I am still unable to restrict file type i.e. pdf & docx being upload. code behind is as under: ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; public partial class CS : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string[] filePaths = Directory.GetFiles(Server.MapPath("~/Upload/")); List<ListItem> files = new List<ListItem>(); foreach (string filePath in filePaths) { files.Add(new ListItem(Path.GetFileName(filePath), filePath)); } GridView1.DataSource = files; GridView1.DataBind(); } } protected void UploadFile(object sender, EventArgs e) { string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName); FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Upload/") + fileName); Response.Redirect(Request.Url.AbsoluteUri); } protected void DownloadFile(object sender, EventArgs e) { string filePath = (sender as LinkButton).CommandArgument; Response.ContentType = ContentType; Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath)); Response.WriteFile(filePath); Response.End(); } protected void DeleteFile(object sender, EventArgs e) { string filePath = (sender as LinkButton).CommandArgument; File.Delete(filePath); Response.Redirect(Request.Url.AbsoluteUri); } } ``` html page is as under: ``` <%@ Page Language="C#" AutoEventWireup="true" CodeFile="safetyupload.aspx.cs" Inherits="CS" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="UploadFile" /> <hr /> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EmptyDataText = "No files uploaded"> <Columns> <asp:BoundField DataField="Text" HeaderText="File Name" /> <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="lnkDownload" Text = "Download" CommandArgument = '<%# Eval("Value") %>' runat="server" OnClick = "DownloadFile"></asp:LinkButton> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID = "lnkDelete" Text = "Delete" CommandArgument = '<%# Eval("Value") %>' runat = "server" OnClick = "DeleteFile" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </form> </body> </html> ``` I have tried this but no avail ``` protected void UploadFile(object sender, EventArgs e) { if (FileUpload1.HasFile) { try { if (FileUpload.PostedFile.ContentType == "pdf") { string fileName = Path.GetFileName(FileUpload1.FileName); FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Upload/") + fileName); Response.Redirect(Request.Url.AbsoluteUri); } else Label1.Text = "PDF files only"; } catch (Exceptionex) { Label1.Text = "Error during uploading the file"; } } } ``` Please suggest solutions.
2014/11/10
[ "https://Stackoverflow.com/questions/26842004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1084231/" ]
Because you inherited from Array you can do this: ``` class Foo < Array def initialize(length) super(length, 0) end end ``` Note that `super` calls the original `initialize` method on `Array`. ``` Foo.new(5) #=> [0, 0, 0, 0, 0] ```
The implementation of `Class#new` looks a bit like this: ``` class Class def new(*args, &block) obj = allocate obj.initialize(*args, &block) obj end end ``` [Note: in reality, `initialize` is `private`, so it needs to be invoked reflectively, but you get the idea.] IOW: the return value of `initialize` is completely ignored. If you want to change the return value of `new`, you need to override `new`. (Kinda obvious, don't you think?) But in this case, it is also possible (and in general a good idea anyway) to simply delegate to the superclass's `initialize`, as in [@spickermann's answer](https://stackoverflow.com/a/26842087/).
5,125,345
I'm quite new to ruby/rails. I was wondering what is the best way to ensure that two people don't choose the same username. Here is my model at the moment: ``` class User < ActiveRecord::Base validates :username, :presence => true validates :password, :presence => true, :length => { :minimum => 7} end ``` Note: I'm assuming it is best to place this type of code in the model. Correct me if I'm wrong.
2011/02/26
[ "https://Stackoverflow.com/questions/5125345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615759/" ]
There's a validation to make sure a field is unique. Just change your username validation to: ``` validates :username, :presence => true, :uniqueness => true ```
This question has already been correctly answered but for future reference, APIDock has excellent Rails documentation here: <http://apidock.com/rails>. The search's autocomplete is fantastic. The documentation for the `validates` method is here: <http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates> where you can find the `:uniqueness => true` option.
5,125,345
I'm quite new to ruby/rails. I was wondering what is the best way to ensure that two people don't choose the same username. Here is my model at the moment: ``` class User < ActiveRecord::Base validates :username, :presence => true validates :password, :presence => true, :length => { :minimum => 7} end ``` Note: I'm assuming it is best to place this type of code in the model. Correct me if I'm wrong.
2011/02/26
[ "https://Stackoverflow.com/questions/5125345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615759/" ]
There's a validation to make sure a field is unique. Just change your username validation to: ``` validates :username, :presence => true, :uniqueness => true ```
You should also add an index to your usertable, with uniqueness. This way, if people quickly press the username register button twice, you will also be protected at the database level ``` add_index :users, :username, :unique => true ```
5,125,345
I'm quite new to ruby/rails. I was wondering what is the best way to ensure that two people don't choose the same username. Here is my model at the moment: ``` class User < ActiveRecord::Base validates :username, :presence => true validates :password, :presence => true, :length => { :minimum => 7} end ``` Note: I'm assuming it is best to place this type of code in the model. Correct me if I'm wrong.
2011/02/26
[ "https://Stackoverflow.com/questions/5125345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615759/" ]
You should also add an index to your usertable, with uniqueness. This way, if people quickly press the username register button twice, you will also be protected at the database level ``` add_index :users, :username, :unique => true ```
This question has already been correctly answered but for future reference, APIDock has excellent Rails documentation here: <http://apidock.com/rails>. The search's autocomplete is fantastic. The documentation for the `validates` method is here: <http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates> where you can find the `:uniqueness => true` option.
38,051,862
How to close this file or does the file automatically gets closed like a context manager `with` ``` lines = open(file_name).readlines() ``` I wanted to avoid the `with` statement as the above statement is a one liner, but now i see that the above said statement is of no use since we cannot close the file. ``` with open(file_name) as f: ..... ```
2016/06/27
[ "https://Stackoverflow.com/questions/38051862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277603/" ]
if you tend to use `open(filename)` in your expressions, rather than the `with` statement, wrap the with statement in your own function, and use it in the expression. ``` def open_readlines_and_close(filename, *args, **kwargs): with open(filename, *args, **kwargs) as file: lines = file.readlines() return lines lines = open_readlines_and_close(file_name) # apologies for the weird function name ``` you can also use generators to reduce the memory footprint if you'd like.
you can use `with` This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. ``` with open(file_name, 'r') as readfile: lines = readfile.readlines() ```
38,051,862
How to close this file or does the file automatically gets closed like a context manager `with` ``` lines = open(file_name).readlines() ``` I wanted to avoid the `with` statement as the above statement is a one liner, but now i see that the above said statement is of no use since we cannot close the file. ``` with open(file_name) as f: ..... ```
2016/06/27
[ "https://Stackoverflow.com/questions/38051862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277603/" ]
``` lines = (lambda f=open(file_name): [f.readlines(), f.close()][0])() ``` However this would not be considered very Pythonic because it's not very readable.
you can use `with` This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. ``` with open(file_name, 'r') as readfile: lines = readfile.readlines() ```
38,051,862
How to close this file or does the file automatically gets closed like a context manager `with` ``` lines = open(file_name).readlines() ``` I wanted to avoid the `with` statement as the above statement is a one liner, but now i see that the above said statement is of no use since we cannot close the file. ``` with open(file_name) as f: ..... ```
2016/06/27
[ "https://Stackoverflow.com/questions/38051862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277603/" ]
if you tend to use `open(filename)` in your expressions, rather than the `with` statement, wrap the with statement in your own function, and use it in the expression. ``` def open_readlines_and_close(filename, *args, **kwargs): with open(filename, *args, **kwargs) as file: lines = file.readlines() return lines lines = open_readlines_and_close(file_name) # apologies for the weird function name ``` you can also use generators to reduce the memory footprint if you'd like.
``` lines = (lambda f=open(file_name): [f.readlines(), f.close()][0])() ``` However this would not be considered very Pythonic because it's not very readable.
467,973
Suppose $A$ and $B$ are two square $n\times n$ matrices over some field. Why do the $n$ equations $$\operatorname{tr}(A^k)=\operatorname{tr}(B^k)\text{ for } 1\leq k\leq n$$ imply that $A$ and $B$ have the same spectra? If $\operatorname{Spec}(A)=\{\lambda\_1,\dots,\lambda\_p\}$ and $\operatorname{Spec}(B)=\{\mu\_1,\dots,\mu\_r\}$, then I know $\operatorname{Spec}(A^k)=\{\lambda\_1^k,\dots,\lambda\_p^k\}$ and $\operatorname{Spec}(B^k)=\{\mu\_1^k,\dots,\mu\_r^k\}$, (some of these new eigenvalues may not be distinct). Since the trace is the sum of the eigenvalues, this would give a new set of equations $$ \sum \lambda\_i^k=\sum \mu\_i^k $$ but since these aren't linear I don't think it'll be possible to solve these and show the set of eigenvalues for $A$ and $B$ are the same.
2013/08/15
[ "https://math.stackexchange.com/questions/467973", "https://math.stackexchange.com", "https://math.stackexchange.com/users/25005/" ]
Power sums generate symmetric polynomials: See [http://en.wikipedia.org/wiki/Newton's\_identities](http://en.wikipedia.org/wiki/Newton%27s_identities) Therefore the characteristic polynomials of $A$ and $B$, which are symmetric polynomials of the spectra, must be the same. Therefore the two spectra are the same.
The spectrum of $A$ and $B$ are the multiset of roots of their characteristic polynomials. If one can show that their characteristic polynomials are equal over the algebraic closure of the base field, then their polynomials are equal over the base field itself and have the same spectra there. Thus, it suffices to argue that the characteristic polynomial of an $n\times n$ matrix $A$ may be recovered from ($\Leftrightarrow$ is uniquely determined by) its power traces ${\rm tr}(A^k)$ for $1\le k\le n$. Assume the base field is algebraically closed. Then ${\rm tr}(A^k)=p\_k(\lambda\_1,\cdots,\lambda\_n)$ is the $k$th power sum polynomial in the full spectrum of $A$. In the theory of symmetric polynomials, [Newton's identities](http://en.wikipedia.org/wiki/Newton%27s_identities) as Serkan notes show that the elementary symmetric polynomials satisfy a linear recursion that allows them to be expressed as polynomials in the $p\_k$. [Vieta's formulas](http://en.wikipedia.org/wiki/Vieta%27s_formulas) say that the coefficients of the characteristic polynomial of $A$ is determined by the elementary symmetric polynomials in the full spectrum, and in turn we have seen these $e\_i$ are determined by the $p\_k$ equal to the traces. Newton's identities can be proved using generating functions. Wikipedia even has a section on their application to matrices and their traces. However I am not sure if the desired conclusion here is true when the characteristic of the base field is positive $\le n$.
55,392,331
I have seen some questions about **sending response immediately** and **run CPU intensive tasks**. My case is my node application **depends on third party service responses** so the process flow is > > 1. Node receives request and authenticates with third-party service > 2. Send response to user after authentication > 3. Do some tasks that needs responses from third party service > 4. Save the results to database > > > In my case there is **no CPU intensive tasks** and no need to give results of additional tasks to the user but node needs to wait for responses from third-party service. I have to do multiple req/res to/from the third-party service after the authentication to complete the task. How can I achieve this situation? I have seen some workarounds with child\_process, nextTick and setTimeOut. Ultimately I want to send response immediately to user and do tasks related to that user. Thanks in advance.
2019/03/28
[ "https://Stackoverflow.com/questions/55392331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1445874/" ]
``` elsewhere in your code function do_some_tasks() { //... } // route function (req, res) => { // call some async task do_some_tasks() // if the above is doing some asynchronous task, next function should be called immediately without waiting, question is is it so? res.send() } // if your do_some_tasks() is synchronous func, the you can do // this function call will be put to queue and executed asynchronously setImmediate(() => { do_some_tasks() }) // this will be called in the current iteration res.send(something) ```
Just writing a very general code block here: ``` var do_some_tasks = (req, tp_response) => { third_party_tasks(args, (err, result)=<{ //save to DB }); } var your_request_handler = (req,res) => { third_party_auth(args, (tp_response)=>{ res.send(); //just do your tasks here do_some_tasks(req, tp_response); }); } ```
3,609,650
I once used a scenario where I did a SQL where clause like this: where BranchName = CASE WHEN @pBranch <> '' then @pBranch else BranchName end this is to say we're doing a branch name lookup, but this statement has to cater for the LIKE clause somehow. We need to be able to say 'If the pBranch parameter was provided then do a like search else ignore that part of the WHERE clause. Any clues? Thanks, Jacques
2010/08/31
[ "https://Stackoverflow.com/questions/3609650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392591/" ]
you could say: ``` SELECT * FROM dbo WHERE @pBranch = '' OR BranchName = @pBranch ``` This basically says that if you pass in '' to @pBranch, then all results will be displayed, otherwise, if you pass in something else, it will search by your argument
try ``` Where BranchName Like IsNull(@Branch, BranchName) ```
3,609,650
I once used a scenario where I did a SQL where clause like this: where BranchName = CASE WHEN @pBranch <> '' then @pBranch else BranchName end this is to say we're doing a branch name lookup, but this statement has to cater for the LIKE clause somehow. We need to be able to say 'If the pBranch parameter was provided then do a like search else ignore that part of the WHERE clause. Any clues? Thanks, Jacques
2010/08/31
[ "https://Stackoverflow.com/questions/3609650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392591/" ]
actually I think the answer I was looking for is as follows: ... where o.BranchName like case when @pBranchName <> '' then @pBranchName else o.BranchName end ...
try ``` Where BranchName Like IsNull(@Branch, BranchName) ```
3,609,650
I once used a scenario where I did a SQL where clause like this: where BranchName = CASE WHEN @pBranch <> '' then @pBranch else BranchName end this is to say we're doing a branch name lookup, but this statement has to cater for the LIKE clause somehow. We need to be able to say 'If the pBranch parameter was provided then do a like search else ignore that part of the WHERE clause. Any clues? Thanks, Jacques
2010/08/31
[ "https://Stackoverflow.com/questions/3609650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392591/" ]
you could say: ``` SELECT * FROM dbo WHERE @pBranch = '' OR BranchName = @pBranch ``` This basically says that if you pass in '' to @pBranch, then all results will be displayed, otherwise, if you pass in something else, it will search by your argument
``` where @pBranch = '' or BranchName like @pBranch ``` (add the wildcards to the appropriate spot in the like clause) this will work for numbers, not just strings - so if you passed in an int parameter as a 0 or a value, you would do: ``` where @param = 0 or DBField = @param ```
3,609,650
I once used a scenario where I did a SQL where clause like this: where BranchName = CASE WHEN @pBranch <> '' then @pBranch else BranchName end this is to say we're doing a branch name lookup, but this statement has to cater for the LIKE clause somehow. We need to be able to say 'If the pBranch parameter was provided then do a like search else ignore that part of the WHERE clause. Any clues? Thanks, Jacques
2010/08/31
[ "https://Stackoverflow.com/questions/3609650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392591/" ]
actually I think the answer I was looking for is as follows: ... where o.BranchName like case when @pBranchName <> '' then @pBranchName else o.BranchName end ...
``` where @pBranch = '' or BranchName like @pBranch ``` (add the wildcards to the appropriate spot in the like clause) this will work for numbers, not just strings - so if you passed in an int parameter as a 0 or a value, you would do: ``` where @param = 0 or DBField = @param ```
15,732
I get this alert message [(screenshot from my phone)](https://imgur.com/65vRO) from my carrier after using the internet for sometime. The problem is that I get numerous messages (20+) like this when my phone is idle. I guess some apps are syncing in the background. The phone is unusable till I hit OK on all the alert boxes. Is there a way (or an app) to make sure that I do not see these messages.
2011/11/17
[ "https://android.stackexchange.com/questions/15732", "https://android.stackexchange.com", "https://android.stackexchange.com/users/9702/" ]
This looks like a special kind of SMS message, sometimes called "flash SMS", that shows up instantaneously on the phones screen. I don't think that there is an option to block these messages and even if it would be possible I wouldn't encourage you to do so, because you could maybe miss some other important information. **I think the best approach would be to ask your carrier from disabling these messages for your number. I am sure that they are able and happy to do so.**
This is a problem with your carrier where they send the last data usage details whenever a data connection session ends. It is not possible to disable it unless the network provider disables it. However, you can try this small workaround by going to `Messaging`, selecting `Settings` in options, and disabling `Cell Broadcast` settings. Thanks
15,732
I get this alert message [(screenshot from my phone)](https://imgur.com/65vRO) from my carrier after using the internet for sometime. The problem is that I get numerous messages (20+) like this when my phone is idle. I guess some apps are syncing in the background. The phone is unusable till I hit OK on all the alert boxes. Is there a way (or an app) to make sure that I do not see these messages.
2011/11/17
[ "https://android.stackexchange.com/questions/15732", "https://android.stackexchange.com", "https://android.stackexchange.com/users/9702/" ]
[Balance Update / USSD blocker](https://play.google.com/store/apps/details?id=com.melkote.quietbalance) You can install this app to block the Flash messages This Does not support Android 4.2.2
This is a problem with your carrier where they send the last data usage details whenever a data connection session ends. It is not possible to disable it unless the network provider disables it. However, you can try this small workaround by going to `Messaging`, selecting `Settings` in options, and disabling `Cell Broadcast` settings. Thanks
416,030
What are great examples of comprehensively archived mathematical correspondence (including both handwritten and electronic items)? Context: polished papers usually don't reveal the full process that accompanied the way definitions and proofs were conceived. For example, Colmez's [introduction](http://webusers.imj-prg.fr/%7Epierre.colmez/preface-FF.pdf) to the book *Courbes et fibrés vectoriels en théorie de Hodge p-adique* by Fargues and Fontaine, contains long excerpts of email exchanges which are very interesting.
2022/02/13
[ "https://mathoverflow.net/questions/416030", "https://mathoverflow.net", "https://mathoverflow.net/users/469/" ]
[The Grothendieck-Brown correspondence](https://webusers.imj-prg.fr/%7Egeorges.maltsiniotis/ps/agrb_web.pdf) As far as I know these letters are planned to be published alongside "Pursuing stacks" on [Documents Mathématiques](https://smf.emath.fr/en/publications/documents-mathematiques)
Some years ago, I was tracking the origins of fractional calculus and finally found a comprehensive list of [Leibniz correspondence](https://www.mv.helsinki.fi/home/mroinila/texts.htm).
416,030
What are great examples of comprehensively archived mathematical correspondence (including both handwritten and electronic items)? Context: polished papers usually don't reveal the full process that accompanied the way definitions and proofs were conceived. For example, Colmez's [introduction](http://webusers.imj-prg.fr/%7Epierre.colmez/preface-FF.pdf) to the book *Courbes et fibrés vectoriels en théorie de Hodge p-adique* by Fargues and Fontaine, contains long excerpts of email exchanges which are very interesting.
2022/02/13
[ "https://mathoverflow.net/questions/416030", "https://mathoverflow.net", "https://mathoverflow.net/users/469/" ]
[The Grothendieck-Brown correspondence](https://webusers.imj-prg.fr/%7Egeorges.maltsiniotis/ps/agrb_web.pdf) As far as I know these letters are planned to be published alongside "Pursuing stacks" on [Documents Mathématiques](https://smf.emath.fr/en/publications/documents-mathematiques)
I'm not sure whether this is a comprehensive example, but [*Singularités Irrégulières: Correspondance et Documents*](https://smf.emath.fr/publications/singularites-irregulieres-correspondance-et-documents) (Société Mathématique de France, 2007) contains correspondence from 1976 - 1991 between Pierre Deligne, Bernard Malgrange, and Jean-Pierre Ramis on the subject of irregular singularities of linear differential equations.
416,030
What are great examples of comprehensively archived mathematical correspondence (including both handwritten and electronic items)? Context: polished papers usually don't reveal the full process that accompanied the way definitions and proofs were conceived. For example, Colmez's [introduction](http://webusers.imj-prg.fr/%7Epierre.colmez/preface-FF.pdf) to the book *Courbes et fibrés vectoriels en théorie de Hodge p-adique* by Fargues and Fontaine, contains long excerpts of email exchanges which are very interesting.
2022/02/13
[ "https://mathoverflow.net/questions/416030", "https://mathoverflow.net", "https://mathoverflow.net/users/469/" ]
[Élie Cartan and Albert Einstein, **Letters on Absolute Parallelism, 1929-1932** (Princeton Legacy Library), 1st ed., 1979, ‎ 978-0691082295](https://press.princeton.edu/books/hardcover/9780691636542/elie-cartan-and-albert-einstein)
[The Grothendieck-Brown correspondence](https://webusers.imj-prg.fr/%7Egeorges.maltsiniotis/ps/agrb_web.pdf) As far as I know these letters are planned to be published alongside "Pursuing stacks" on [Documents Mathématiques](https://smf.emath.fr/en/publications/documents-mathematiques)
416,030
What are great examples of comprehensively archived mathematical correspondence (including both handwritten and electronic items)? Context: polished papers usually don't reveal the full process that accompanied the way definitions and proofs were conceived. For example, Colmez's [introduction](http://webusers.imj-prg.fr/%7Epierre.colmez/preface-FF.pdf) to the book *Courbes et fibrés vectoriels en théorie de Hodge p-adique* by Fargues and Fontaine, contains long excerpts of email exchanges which are very interesting.
2022/02/13
[ "https://mathoverflow.net/questions/416030", "https://mathoverflow.net", "https://mathoverflow.net/users/469/" ]
[Correspondance Serre-Tate, Volume I+II](https://smf.emath.fr/publications/correspondance-serre-tate-volume-ii)
Some years ago, I was tracking the origins of fractional calculus and finally found a comprehensive list of [Leibniz correspondence](https://www.mv.helsinki.fi/home/mroinila/texts.htm).
416,030
What are great examples of comprehensively archived mathematical correspondence (including both handwritten and electronic items)? Context: polished papers usually don't reveal the full process that accompanied the way definitions and proofs were conceived. For example, Colmez's [introduction](http://webusers.imj-prg.fr/%7Epierre.colmez/preface-FF.pdf) to the book *Courbes et fibrés vectoriels en théorie de Hodge p-adique* by Fargues and Fontaine, contains long excerpts of email exchanges which are very interesting.
2022/02/13
[ "https://mathoverflow.net/questions/416030", "https://mathoverflow.net", "https://mathoverflow.net/users/469/" ]
[Gauss' correspondence](https://gauss.adw-goe.de) is also easily available, for example [with Wolfgang Bolyai](https://gauss.adw-goe.de/discover?field=correspondent&filtertype=correspondent&filter_relational_operator=equals&filter=Bolyai%2C+Wolfgang), including the (in)famous passages about the discovery of non-Euclidean geometry.
One unusual example is Serge Lang, [The File: Case Study in Correction, 1977-1979](https://link.springer.com/book/10.1007/978-1-4613-8145-7) (Springer-Verlag, 1981), with both correspondence and the published documents which provoked it. Lang is the central correspondent in the file, and Neal Koblitz and Saunders Mac Lane also have large enough roles to appear in the table of contents. "The File is a collection of documents from a major dispute involving a number of American college professors, mainly mathematicians, statisticians, and sociologists. The controversy was ignited by the mathematician Serge Lang's reaction to a questionnaire, 'The 1977 Survey of the American Professoriate', distributed by E. C. Ladd of the University of Connecticut and S. M. Lipset of Stanford. The ensuing discussion - in part acrimonious and personal - soon involved a large group of active and passive participants, and included issues such as survey techniques, evaluation of academic work, public and political honesty, and McCarthyism at Harvard."
416,030
What are great examples of comprehensively archived mathematical correspondence (including both handwritten and electronic items)? Context: polished papers usually don't reveal the full process that accompanied the way definitions and proofs were conceived. For example, Colmez's [introduction](http://webusers.imj-prg.fr/%7Epierre.colmez/preface-FF.pdf) to the book *Courbes et fibrés vectoriels en théorie de Hodge p-adique* by Fargues and Fontaine, contains long excerpts of email exchanges which are very interesting.
2022/02/13
[ "https://mathoverflow.net/questions/416030", "https://mathoverflow.net", "https://mathoverflow.net/users/469/" ]
[Élie Cartan and Albert Einstein, **Letters on Absolute Parallelism, 1929-1932** (Princeton Legacy Library), 1st ed., 1979, ‎ 978-0691082295](https://press.princeton.edu/books/hardcover/9780691636542/elie-cartan-and-albert-einstein)
[2020 email correspondence](https://sreenidhi.edu.in/pdffls/A_Report_on_Riemann_Hypothesis_updated(25-06-21).pdf#page=93) between professor Władysław Narkiewicz, a very patient mathematician, and Dr. Kumar Eswaran, who claimed to have proven the Riemann conjecture. It ends with this beautiful conclusion: > > Although our views on your result are somewhat different I want you to > know that I enjoyed our discussion which showed that the notion of a proof > may have different interpretations. > > > A summary of the correspondence can be found at skeptics.stackexchange.com: [Have mathematicians concluded that an Indian mathematical physicist has solved the Riemann Hypothesis?](https://skeptics.stackexchange.com/questions/51965/have-mathematicians-concluded-that-an-indian-mathematical-physicist-has-solved-t)
416,030
What are great examples of comprehensively archived mathematical correspondence (including both handwritten and electronic items)? Context: polished papers usually don't reveal the full process that accompanied the way definitions and proofs were conceived. For example, Colmez's [introduction](http://webusers.imj-prg.fr/%7Epierre.colmez/preface-FF.pdf) to the book *Courbes et fibrés vectoriels en théorie de Hodge p-adique* by Fargues and Fontaine, contains long excerpts of email exchanges which are very interesting.
2022/02/13
[ "https://mathoverflow.net/questions/416030", "https://mathoverflow.net", "https://mathoverflow.net/users/469/" ]
[The Euler archive](http://eulerarchive.maa.org/) contains more or less everything Leonard Euler ever wrote that still exists today, including his letter correspondence with various people.
Some years ago, I was tracking the origins of fractional calculus and finally found a comprehensive list of [Leibniz correspondence](https://www.mv.helsinki.fi/home/mroinila/texts.htm).
416,030
What are great examples of comprehensively archived mathematical correspondence (including both handwritten and electronic items)? Context: polished papers usually don't reveal the full process that accompanied the way definitions and proofs were conceived. For example, Colmez's [introduction](http://webusers.imj-prg.fr/%7Epierre.colmez/preface-FF.pdf) to the book *Courbes et fibrés vectoriels en théorie de Hodge p-adique* by Fargues and Fontaine, contains long excerpts of email exchanges which are very interesting.
2022/02/13
[ "https://mathoverflow.net/questions/416030", "https://mathoverflow.net", "https://mathoverflow.net/users/469/" ]
[The Euler archive](http://eulerarchive.maa.org/) contains more or less everything Leonard Euler ever wrote that still exists today, including his letter correspondence with various people.
One unusual example is Serge Lang, [The File: Case Study in Correction, 1977-1979](https://link.springer.com/book/10.1007/978-1-4613-8145-7) (Springer-Verlag, 1981), with both correspondence and the published documents which provoked it. Lang is the central correspondent in the file, and Neal Koblitz and Saunders Mac Lane also have large enough roles to appear in the table of contents. "The File is a collection of documents from a major dispute involving a number of American college professors, mainly mathematicians, statisticians, and sociologists. The controversy was ignited by the mathematician Serge Lang's reaction to a questionnaire, 'The 1977 Survey of the American Professoriate', distributed by E. C. Ladd of the University of Connecticut and S. M. Lipset of Stanford. The ensuing discussion - in part acrimonious and personal - soon involved a large group of active and passive participants, and included issues such as survey techniques, evaluation of academic work, public and political honesty, and McCarthyism at Harvard."
416,030
What are great examples of comprehensively archived mathematical correspondence (including both handwritten and electronic items)? Context: polished papers usually don't reveal the full process that accompanied the way definitions and proofs were conceived. For example, Colmez's [introduction](http://webusers.imj-prg.fr/%7Epierre.colmez/preface-FF.pdf) to the book *Courbes et fibrés vectoriels en théorie de Hodge p-adique* by Fargues and Fontaine, contains long excerpts of email exchanges which are very interesting.
2022/02/13
[ "https://mathoverflow.net/questions/416030", "https://mathoverflow.net", "https://mathoverflow.net/users/469/" ]
[Gauss' correspondence](https://gauss.adw-goe.de) is also easily available, for example [with Wolfgang Bolyai](https://gauss.adw-goe.de/discover?field=correspondent&filtertype=correspondent&filter_relational_operator=equals&filter=Bolyai%2C+Wolfgang), including the (in)famous passages about the discovery of non-Euclidean geometry.
The book "[Der Briefwechsel Richard Dedekind – Heinrich Weber](https://www.degruyter.com/document/doi/10.1515/9783110368048/html)" transcribes the full correspondence between the two. From the description: > > This volume provides the very first transcription of correspondence between Richard Dedekind and Heinrich Weber, one of the most important instances of written dialog between mathematicians in the 19th century. > Nearly every subarea of mathematics is addressed in the letters, which intensively discuss nascent developments in the field. A register of persons and index of works ease access to the topics discussed in the letters. > > >
416,030
What are great examples of comprehensively archived mathematical correspondence (including both handwritten and electronic items)? Context: polished papers usually don't reveal the full process that accompanied the way definitions and proofs were conceived. For example, Colmez's [introduction](http://webusers.imj-prg.fr/%7Epierre.colmez/preface-FF.pdf) to the book *Courbes et fibrés vectoriels en théorie de Hodge p-adique* by Fargues and Fontaine, contains long excerpts of email exchanges which are very interesting.
2022/02/13
[ "https://mathoverflow.net/questions/416030", "https://mathoverflow.net", "https://mathoverflow.net/users/469/" ]
[Grothendieck-Serre correspondence, bilingual edition](https://bookstore.ams.org/cgs) ([online](https://webusers.imj-prg.fr/%7Eleila.schneps/grothendieckcircle/Letters/GS.pdf))
[The Grothendieck-Brown correspondence](https://webusers.imj-prg.fr/%7Egeorges.maltsiniotis/ps/agrb_web.pdf) As far as I know these letters are planned to be published alongside "Pursuing stacks" on [Documents Mathématiques](https://smf.emath.fr/en/publications/documents-mathematiques)
12,857,481
``` package com.example.tabactivity; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.net.ParseException; import android.os.AsyncTask; import android.os.Bundle; import android.app.ActivityGroup; import android.app.ProgressDialog; import android.content.Intent; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; public class circularlistparsing extends ActivityGroup { public int currentPage = 1; public ListView lisView1; static final String KEY_ITEM = "docdetails"; static final String KEY_ITEM2 = "info"; static final String KEY_NAME1 = ""; static final String KEY_NAME = "heading"; static final String KEY_DATE = "date"; public Button btnNext; public Button btnPre; public static String url = "http://dev.taxmann.com/TaxmannService/TaxmannService.asmx/GetCircularList"; TextView txtreord; TextView totalpage; TextView pagenumber; ProgressDialog dialog; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txtreord = (TextView) findViewById(R.id.recored); totalpage = (TextView) findViewById(R.id.totalpage); pagenumber = (TextView) findViewById(R.id.pagenumber); // listView1 lisView1 = (ListView) findViewById(R.id.listView1); // new YourTask().execute(); // Next btnNext = (Button) findViewById(R.id.btnNext); // Perform action on click btnNext.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { currentPage = currentPage + 1; // new YourTask().execute(); ShowData(); pagenumber.setText("Of" + currentPage+"]"); } }); // Previous btnPre = (Button) findViewById(R.id.btnPre); // Perform action on click btnPre.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { currentPage = currentPage - 1; // new YourTask().execute(); ShowData(); pagenumber.setText("Of" + currentPage+"]"); } }); // new YourTask().execute(); ShowData(); } public void ShowData() { XMLParser parser = new XMLParser(); String xml = parser.getXmlFromUrl(url); // getting XML Document doc = parser.getDomElement(xml); // getting DOM element NodeList nl = doc.getElementsByTagName(KEY_ITEM); NodeList n2 = doc.getElementsByTagName(KEY_ITEM2); int displayPerPage = 10; // Per Page int TotalRows = nl.getLength(); txtreord.setText( TotalRows+"Records|"); // number of records int indexRowStart = ((displayPerPage * currentPage) - displayPerPage); int TotalPage = 0; if (TotalRows <= displayPerPage) { TotalPage = 1; } else if ((TotalRows % displayPerPage) == 0) { TotalPage = (TotalRows / displayPerPage); } else { TotalPage = (TotalRows / displayPerPage) + 1; // 7 TotalPage = (int) TotalPage; // 7 } totalpage.setText("Page[" + TotalPage); int indexRowEnd = displayPerPage * currentPage; // 5 if (indexRowEnd > TotalRows) { indexRowEnd = TotalRows; } // Disabled Button Next if (currentPage >= TotalPage) { btnNext.setEnabled(false); } else { btnNext.setEnabled(true); } // Disabled Button Previos if (currentPage <= 1) { btnPre.setEnabled(false); } else { btnPre.setEnabled(true); } // Load Data from Index int RowID = 1; ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>(); HashMap<String, String> map; // RowID if (currentPage > 1) { RowID = (displayPerPage * (currentPage - 1)) + 1; } for (int i = indexRowStart; i < indexRowEnd; i++) { Element e = (Element) nl.item(i); Element e2 = (Element) n2.item(i); String date = e2.getAttribute(KEY_DATE); // adding each child node to HashMap key => value map = new HashMap<String, String>(); map.put("RowID", String.valueOf(RowID)); map.put(KEY_DATE, date); // String Heading = parser.getValue(e, KEY_NAME).replace("|", "|\n") // .replace("|", ""); // String mytime = date; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmdd"); Date myDate = null; try { myDate = dateFormat.parse(mytime); } catch (ParseException t) { t.printStackTrace(); } catch (java.text.ParseException t) { // TODO Auto-generated catch block t.printStackTrace(); } SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd"); String finalDate = timeFormat.format(myDate); // System.out.println("rrrrrrrrrrrrr"+finalDate); String Heading = parser.getValue(e, KEY_NAME); int a = Heading.indexOf("|"); String beforeSubString = Heading.substring(0, a); String afterSubString = Heading.substring(a, Heading.length()) .replace("|", "") + "[" + finalDate + "]"; // String // final1="<b>"+beforeSubString+"<b>"+"|"+afterSubString.replace("|", // "|\n") // .replace("|", ""); // String k=Html.fromHtml(final1).toString(); // // Html.fromHtml(final1); map.put(KEY_NAME, beforeSubString); map.put(KEY_NAME1, afterSubString); // adding HashList to ArrayList menuItems.add(map); RowID = RowID + 1; } SimpleAdapter sAdap; sAdap = new SimpleAdapter(circularlistparsing.this, menuItems, R.layout.list_item, new String[] { "RowID", KEY_NAME1, KEY_NAME }, new int[] { R.id.ColRowID, R.id.ColName, R.id.textView1 }); lisView1.setAdapter(sAdap); lisView1.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub Intent i = new Intent(circularlistparsing.this, detail.class); // sending data to new activity // i.putExtra("product", product); startActivity(i); } }); } class YourTask extends AsyncTask<Void, Void, Void> { protected void onPreExecute() { dialog = ProgressDialog.show(circularlistparsing.this, "", "Please wait.."); } protected Void doInBackground(Void... unused) { try { // doSomethingHeavy(); // publishProgress(...); ShowData(); } catch(Exception e) { //... } return null; } protected void onProgressUpdate(Void... unused) { } protected void onPostExecute(Void unused) { dialog.dismiss(); } } } ``` Hii please this code show data function is for displaying data when i m using new YourTask().execute(); in place of show data then its showing Progress bar but not displaying data but able to read data while when we user showdata() function den it display data please tell me how to implement progress bar .
2012/10/12
[ "https://Stackoverflow.com/questions/12857481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1719722/" ]
The easiest would be to use a `List(Of Subject)` instead which can be resized. I would also create a class for the subject since you have two fields. ``` Dim subjects = New List(Of Subject) Using con = New SqlConnection(connectionString) Using cmd = New SqlCommand("StoredProcedureName", con) cmd.CommandType = CommandType.StoredProcedure Try con.Open() Using reader = cmd.ExecuteReader() While reader.Read Dim subject = reader.GetString(0) Dim subjectCode = reader.GetString(1) subjects.Add(New Subject() With { .Subject = subject, .SubjectCode = subjectCode }) End While End Using Catch ex As Exception ' log exception End Try End Using End Using ``` here's a simple implementation of that class: ``` Public Class Subject Public Subject As String Public SubjectCode As String End Class ``` If you insist on an array, you can call `subjects.ToArray()`.
You need `GetRows` method which will get your recordset data into an array: ``` array = recordset.GetRows(Rows, Start, Fields ) ``` Basically execute your stored procedure and when you have the results use the GetRows method which returns a collection of rows from the result, given an array of unique column ID's. You can see an example [here](http://msdn.microsoft.com/en-us/library/windows/desktop/ms677500%28v=vs.85%29.aspx). In your case after making sure that you have some records returned you can do this: ``` arrData = rsData.GetRows() ``` Hope this helps.
5,374,913
My Zend framework routing setup is not working as desired. When I access "site", the code under application/modules/default/views/script/index/index.phtml is executed, as desired. However, when I try "site/home", I get a 404 error page. The apache log shows ( File does not exist: /var/www/site/public/home). In addition, accessing <http://site/default/index/index> produces the same result. (<http://site/index> works fine.) Zend version: 1.10.8 Apache /etc/apache2/apache2.conf: ``` NameVirtualHost *:80 <VirtualHost *:80> DocumentRoot "/var/www/site/public" <Directory /var/www/site/public> DirectoryIndex index.php AllowOverride All Order allow,deny Allow from all </Directory> </VirtualHost> ``` My /var/www/site/public/.htaccess file ``` SetEnv APPLICATION_ENV development RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php [NC,L] ``` My /var/www/site/public/index.php ``` ... /** Zend_Application */ require_once 'Zend/Application.php'; // Create application, bootstrap, and run $application = new Zend_Application( APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini' ); $application->bootstrap() ->run(); ``` My application.ini file: ``` [production] phpSettings.display_startup_errors = 0 phpSettings.display_errors = 0 includePaths.library = APPLICATION_PATH "/../library" bootstrap.path = APPLICATION_PATH "/Bootstrap.php" bootstrap.class = "Bootstrap" appnamespace = "Application" resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers" resources.frontController.moduleDirectory = APPLICATION_PATH "/modules" resources.frontController.params.displayExceptions = 0 resources.modules = "" resources.router.routes.home.route = /home resources.router.routes.home.defaults.module = default resources.router.routes.home.defaults.controller = index resources.router.routes.home.defaults.action = index resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/" resources.view[] = autoloaderNamespaces[] = "Site_" [development : production] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1 resources.frontController.params.displayExceptions = 1 ``` I have tried moving routes into routes.ini and adding them in application/Bootstrap.php as follows: ``` $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/routes.ini', 'production'); $router = new Zend_Controller_Router_Rewrite(); $router->addConfig($config, 'routes'); $r = new Zend_Controller_Router_Route( 'home/', array( 'controller' => 'index', 'action' => 'index' ) ); $router->addRoute('home', $r); ``` However, it did not help. I spent the entire day going through the manuals, books, and web forums trying to find the problem to no avail. (I have been following "Zend Framework" by Vikram Vaswani.)
2011/03/21
[ "https://Stackoverflow.com/questions/5374913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669025/" ]
It refers to the global object (`window`). *Edit:* Actually, it will refer to both, the global object **and** `o`, because they are the same. `o` will have a reference to the object returned from `F()` which is the object returned from `C()` which is the `window` object ;) You can call `console.log(this)` to find out which object it refers to. It should give you a listing of all the methods of the object on the console and you should be able to infer from this which object it is. For this to work in Firefox, you need Firebug. Don't know for IE. **Update:** [@Anurag already showed you how to explicitly set `this`](https://stackoverflow.com/questions/5374912/javascript-global-object/5374931#5374931). If you just want to refer to `this` of a higher scope, you have to assign it to a variable explicitly. Example: ``` function F() { var that = this; function C() { console.log(that); } C(); } ```
`this` refers to the global object in your program. To get `this` to reference the instance of `F`, try, ``` function F() { function C() { return this; } return C.call(this); // call C with the object of F as a context } var o = new F(); ``` On Chrome, you could simply enter the variable to inspect, and its value will get logged. It's similar to doing a `console.log(object)`, but much easier to work with. Here's a screenshot of running this code sample in Chrome. The value of the last statement `o` is automatically printed, and I printed it once again, just to be sure. It logged `DOMWindow` which refers to the global window object on the browser. ![enter image description here](https://i.stack.imgur.com/KsoQR.png)
5,374,913
My Zend framework routing setup is not working as desired. When I access "site", the code under application/modules/default/views/script/index/index.phtml is executed, as desired. However, when I try "site/home", I get a 404 error page. The apache log shows ( File does not exist: /var/www/site/public/home). In addition, accessing <http://site/default/index/index> produces the same result. (<http://site/index> works fine.) Zend version: 1.10.8 Apache /etc/apache2/apache2.conf: ``` NameVirtualHost *:80 <VirtualHost *:80> DocumentRoot "/var/www/site/public" <Directory /var/www/site/public> DirectoryIndex index.php AllowOverride All Order allow,deny Allow from all </Directory> </VirtualHost> ``` My /var/www/site/public/.htaccess file ``` SetEnv APPLICATION_ENV development RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php [NC,L] ``` My /var/www/site/public/index.php ``` ... /** Zend_Application */ require_once 'Zend/Application.php'; // Create application, bootstrap, and run $application = new Zend_Application( APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini' ); $application->bootstrap() ->run(); ``` My application.ini file: ``` [production] phpSettings.display_startup_errors = 0 phpSettings.display_errors = 0 includePaths.library = APPLICATION_PATH "/../library" bootstrap.path = APPLICATION_PATH "/Bootstrap.php" bootstrap.class = "Bootstrap" appnamespace = "Application" resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers" resources.frontController.moduleDirectory = APPLICATION_PATH "/modules" resources.frontController.params.displayExceptions = 0 resources.modules = "" resources.router.routes.home.route = /home resources.router.routes.home.defaults.module = default resources.router.routes.home.defaults.controller = index resources.router.routes.home.defaults.action = index resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/" resources.view[] = autoloaderNamespaces[] = "Site_" [development : production] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1 resources.frontController.params.displayExceptions = 1 ``` I have tried moving routes into routes.ini and adding them in application/Bootstrap.php as follows: ``` $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/routes.ini', 'production'); $router = new Zend_Controller_Router_Rewrite(); $router->addConfig($config, 'routes'); $r = new Zend_Controller_Router_Route( 'home/', array( 'controller' => 'index', 'action' => 'index' ) ); $router->addRoute('home', $r); ``` However, it did not help. I spent the entire day going through the manuals, books, and web forums trying to find the problem to no avail. (I have been following "Zend Framework" by Vikram Vaswani.)
2011/03/21
[ "https://Stackoverflow.com/questions/5374913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669025/" ]
It refers to the global object (`window`). *Edit:* Actually, it will refer to both, the global object **and** `o`, because they are the same. `o` will have a reference to the object returned from `F()` which is the object returned from `C()` which is the `window` object ;) You can call `console.log(this)` to find out which object it refers to. It should give you a listing of all the methods of the object on the console and you should be able to infer from this which object it is. For this to work in Firefox, you need Firebug. Don't know for IE. **Update:** [@Anurag already showed you how to explicitly set `this`](https://stackoverflow.com/questions/5374912/javascript-global-object/5374931#5374931). If you just want to refer to `this` of a higher scope, you have to assign it to a variable explicitly. Example: ``` function F() { var that = this; function C() { console.log(that); } C(); } ```
To add to the other answers: When a function is called, `this` is set depending on how it's called. If it's called with `myfunc.call` or `myfunc.apply`, then `this` is set to the first passed argument. If it's called in the 'dotted' form, i.e. `myObject.myfunc()` then `this` is set to whatever is before the dot. There is an exception to this rule, which is that it's possible to bake the value of `this` in with `bind`, in which case it will be whatever has been bound. i.e. in `var boundfunc = myfunc.bind(myobj);` then any time `boundfunc` is called, it would be like calling `myfunc` but with `this` referring to `myobj` regardless of anything else. Here's an example that does that: ``` function F() { var C = function() { return this; }.bind(this); return C(); } var o = new F(); ``` If none of these cases are applicable, then `this` is always either the global object (`window` if you're in a browser), or, if you're in strict mode it's `undefined`.
5,374,913
My Zend framework routing setup is not working as desired. When I access "site", the code under application/modules/default/views/script/index/index.phtml is executed, as desired. However, when I try "site/home", I get a 404 error page. The apache log shows ( File does not exist: /var/www/site/public/home). In addition, accessing <http://site/default/index/index> produces the same result. (<http://site/index> works fine.) Zend version: 1.10.8 Apache /etc/apache2/apache2.conf: ``` NameVirtualHost *:80 <VirtualHost *:80> DocumentRoot "/var/www/site/public" <Directory /var/www/site/public> DirectoryIndex index.php AllowOverride All Order allow,deny Allow from all </Directory> </VirtualHost> ``` My /var/www/site/public/.htaccess file ``` SetEnv APPLICATION_ENV development RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php [NC,L] ``` My /var/www/site/public/index.php ``` ... /** Zend_Application */ require_once 'Zend/Application.php'; // Create application, bootstrap, and run $application = new Zend_Application( APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini' ); $application->bootstrap() ->run(); ``` My application.ini file: ``` [production] phpSettings.display_startup_errors = 0 phpSettings.display_errors = 0 includePaths.library = APPLICATION_PATH "/../library" bootstrap.path = APPLICATION_PATH "/Bootstrap.php" bootstrap.class = "Bootstrap" appnamespace = "Application" resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers" resources.frontController.moduleDirectory = APPLICATION_PATH "/modules" resources.frontController.params.displayExceptions = 0 resources.modules = "" resources.router.routes.home.route = /home resources.router.routes.home.defaults.module = default resources.router.routes.home.defaults.controller = index resources.router.routes.home.defaults.action = index resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/" resources.view[] = autoloaderNamespaces[] = "Site_" [development : production] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1 resources.frontController.params.displayExceptions = 1 ``` I have tried moving routes into routes.ini and adding them in application/Bootstrap.php as follows: ``` $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/routes.ini', 'production'); $router = new Zend_Controller_Router_Rewrite(); $router->addConfig($config, 'routes'); $r = new Zend_Controller_Router_Route( 'home/', array( 'controller' => 'index', 'action' => 'index' ) ); $router->addRoute('home', $r); ``` However, it did not help. I spent the entire day going through the manuals, books, and web forums trying to find the problem to no avail. (I have been following "Zend Framework" by Vikram Vaswani.)
2011/03/21
[ "https://Stackoverflow.com/questions/5374913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669025/" ]
`this` refers to the global object in your program. To get `this` to reference the instance of `F`, try, ``` function F() { function C() { return this; } return C.call(this); // call C with the object of F as a context } var o = new F(); ``` On Chrome, you could simply enter the variable to inspect, and its value will get logged. It's similar to doing a `console.log(object)`, but much easier to work with. Here's a screenshot of running this code sample in Chrome. The value of the last statement `o` is automatically printed, and I printed it once again, just to be sure. It logged `DOMWindow` which refers to the global window object on the browser. ![enter image description here](https://i.stack.imgur.com/KsoQR.png)
To add to the other answers: When a function is called, `this` is set depending on how it's called. If it's called with `myfunc.call` or `myfunc.apply`, then `this` is set to the first passed argument. If it's called in the 'dotted' form, i.e. `myObject.myfunc()` then `this` is set to whatever is before the dot. There is an exception to this rule, which is that it's possible to bake the value of `this` in with `bind`, in which case it will be whatever has been bound. i.e. in `var boundfunc = myfunc.bind(myobj);` then any time `boundfunc` is called, it would be like calling `myfunc` but with `this` referring to `myobj` regardless of anything else. Here's an example that does that: ``` function F() { var C = function() { return this; }.bind(this); return C(); } var o = new F(); ``` If none of these cases are applicable, then `this` is always either the global object (`window` if you're in a browser), or, if you're in strict mode it's `undefined`.
1,753,788
i know it must something simple that i missed. I use data services to get data into my silverlight application. When i bind the data to my datagrid it works like a charm ``` LessonGrid.ItemsSource = context.Lessons ``` however as soon as i try to wrap my objects into more complex data structure it stops working ``` LessonGrid.ItemsSource = context.Lessons.Select(l => new {Lesson = l; Color=Colors.Yellow}) ``` I tried to define binding with path and without and doesn't seem to work ``` <data:DataGridTextColumn Header="Date" Binding="{Binding StartTime}"/> <data:DataGridTextColumn Header="Date" Binding="{Binding StartTime, Path=Lesson.StartTime}"/> <data:DataGridTextColumn Header="Date" Binding="{Binding Path=Lesson.StartTime}"/> <data:DataGridTextColumn Header="Date" Binding="{Binding StartTime, Path=Lesson}"/> ``` Suggestions? --- After more more research: Ok,it's nothing to do with complex objects. Even this code shows two rows but no data. What am i missing? ``` LessonGrid.ItemsSource = new[] {new {Color = Colors.Yellow,StartTime = 12, Text="text"}, new {Color = Colors.Red, StartTime = 14, Text="text3"}}; ``` xaml: ``` <data:DataGrid x:Name="LessonGrid" AutoGenerateColumns="True" Height="375" IsReadOnly="True"> </data:DataGrid> ```
2009/11/18
[ "https://Stackoverflow.com/questions/1753788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/75672/" ]
Ok, i figured it out myself. It's something about implicit types that binding doesn't like. This shows empty grid ``` LessonGrid.ItemsSource = new[] {new {StartTime = 111, Text = "hi there"}}; ``` but this renders data. ``` LessonGrid.ItemsSource = new[] {new Temp {StartTime = 111, Text = "hi there"}}; ```
You have created a Linq Query but has not actually executed yet. In order to actually execute you must do something like .ToList() Try This: ``` LessonGrid.ItemsSource = context.Lessons.Select(l => new {Lesson = l; Color=Colors.Yellow}).ToList(); ```
1,753,788
i know it must something simple that i missed. I use data services to get data into my silverlight application. When i bind the data to my datagrid it works like a charm ``` LessonGrid.ItemsSource = context.Lessons ``` however as soon as i try to wrap my objects into more complex data structure it stops working ``` LessonGrid.ItemsSource = context.Lessons.Select(l => new {Lesson = l; Color=Colors.Yellow}) ``` I tried to define binding with path and without and doesn't seem to work ``` <data:DataGridTextColumn Header="Date" Binding="{Binding StartTime}"/> <data:DataGridTextColumn Header="Date" Binding="{Binding StartTime, Path=Lesson.StartTime}"/> <data:DataGridTextColumn Header="Date" Binding="{Binding Path=Lesson.StartTime}"/> <data:DataGridTextColumn Header="Date" Binding="{Binding StartTime, Path=Lesson}"/> ``` Suggestions? --- After more more research: Ok,it's nothing to do with complex objects. Even this code shows two rows but no data. What am i missing? ``` LessonGrid.ItemsSource = new[] {new {Color = Colors.Yellow,StartTime = 12, Text="text"}, new {Color = Colors.Red, StartTime = 14, Text="text3"}}; ``` xaml: ``` <data:DataGrid x:Name="LessonGrid" AutoGenerateColumns="True" Height="375" IsReadOnly="True"> </data:DataGrid> ```
2009/11/18
[ "https://Stackoverflow.com/questions/1753788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/75672/" ]
Ok, i figured it out myself. It's something about implicit types that binding doesn't like. This shows empty grid ``` LessonGrid.ItemsSource = new[] {new {StartTime = 111, Text = "hi there"}}; ``` but this renders data. ``` LessonGrid.ItemsSource = new[] {new Temp {StartTime = 111, Text = "hi there"}}; ```
Are you sure that your Linq query return any items? And any items that include StartTime? As I can see it your query returns an object that contain two parameters,Lesson and Color, but not StartTime. And I guess the separator between the parameters should be a comma (,). ``` LessonGrid.ItemsSource = context.Lessons.Select(l => new {Lesson=l, Color=Colors.Yellow, StartTime=12}); ``` Then you can bind to your property in your DataGrid: ``` <data:DataGridTextColumn Header="Date" Binding="{Binding StartTime}"/> or <data:DataGridTextColumn Header="Date" Binding="{Binding Path=StartTime}"/> ```
131,834
I went to the Garage that isn't the one at the safe house. I noticed that there was a prompt to press D-pad Right to access Special vehicles. So a list of one car opened and I selected it. This spawned me outside in a Eleghy RH8. Now not matter what I do to the car, I can go back to the garage and spawn a new one (Nothing custom saved from the previous afaik). So this seemed like a good way to always have a car other than the standard your Character has. What I want to know, I how do I increase that list? Is that where buying cars comes into it? So if anyone has already increased that special vehicle list, Please let me know how you did it :).
2013/09/23
[ "https://gaming.stackexchange.com/questions/131834", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/55820/" ]
I think this is for cars bought in the Rockstar Store. The first one you get for free by joining the Rockstar Social Club. Cars bought on a dealers website are only delivered once to your garage. For the marina it is a bit different: There is only one slot and you can choose (by pressing LEFT on the D-Dad) which vessel to spawn there. You can do this an infinite number of times. This also applies to the helipads and hangars. You can only spawn vessels bought on a dealers website before.
I have not tried it for the garage itself yet, but I bought a slip at the marina and subsequently purchased boats from the "Internet" ingame. These appear in a list at the marina, which seems to be the same mechanic. So I´d say, purchased vehicles are likely to appear in that list.
131,834
I went to the Garage that isn't the one at the safe house. I noticed that there was a prompt to press D-pad Right to access Special vehicles. So a list of one car opened and I selected it. This spawned me outside in a Eleghy RH8. Now not matter what I do to the car, I can go back to the garage and spawn a new one (Nothing custom saved from the previous afaik). So this seemed like a good way to always have a car other than the standard your Character has. What I want to know, I how do I increase that list? Is that where buying cars comes into it? So if anyone has already increased that special vehicle list, Please let me know how you did it :).
2013/09/23
[ "https://gaming.stackexchange.com/questions/131834", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/55820/" ]
Vehicles purchased from the game Internet for game cash only appear in the garage once, ie if you trash it you gotta buy another. The special vehicle list must be something else (I've only got the Elegy too).
I have not tried it for the garage itself yet, but I bought a slip at the marina and subsequently purchased boats from the "Internet" ingame. These appear in a list at the marina, which seems to be the same mechanic. So I´d say, purchased vehicles are likely to appear in that list.
131,834
I went to the Garage that isn't the one at the safe house. I noticed that there was a prompt to press D-pad Right to access Special vehicles. So a list of one car opened and I selected it. This spawned me outside in a Eleghy RH8. Now not matter what I do to the car, I can go back to the garage and spawn a new one (Nothing custom saved from the previous afaik). So this seemed like a good way to always have a car other than the standard your Character has. What I want to know, I how do I increase that list? Is that where buying cars comes into it? So if anyone has already increased that special vehicle list, Please let me know how you did it :).
2013/09/23
[ "https://gaming.stackexchange.com/questions/131834", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/55820/" ]
Thats where the collector's edition unique vehicles are :) like the Hotknife and Carbon RS, but you can only get those with a DLC code if you bought the collector's edition game.. or maybe buy a code on eBay.
I have not tried it for the garage itself yet, but I bought a slip at the marina and subsequently purchased boats from the "Internet" ingame. These appear in a list at the marina, which seems to be the same mechanic. So I´d say, purchased vehicles are likely to appear in that list.
131,834
I went to the Garage that isn't the one at the safe house. I noticed that there was a prompt to press D-pad Right to access Special vehicles. So a list of one car opened and I selected it. This spawned me outside in a Eleghy RH8. Now not matter what I do to the car, I can go back to the garage and spawn a new one (Nothing custom saved from the previous afaik). So this seemed like a good way to always have a car other than the standard your Character has. What I want to know, I how do I increase that list? Is that where buying cars comes into it? So if anyone has already increased that special vehicle list, Please let me know how you did it :).
2013/09/23
[ "https://gaming.stackexchange.com/questions/131834", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/55820/" ]
I think this is for cars bought in the Rockstar Store. The first one you get for free by joining the Rockstar Social Club. Cars bought on a dealers website are only delivered once to your garage. For the marina it is a bit different: There is only one slot and you can choose (by pressing LEFT on the D-Dad) which vessel to spawn there. You can do this an infinite number of times. This also applies to the helipads and hangars. You can only spawn vessels bought on a dealers website before.
Vehicles purchased from the game Internet for game cash only appear in the garage once, ie if you trash it you gotta buy another. The special vehicle list must be something else (I've only got the Elegy too).
131,834
I went to the Garage that isn't the one at the safe house. I noticed that there was a prompt to press D-pad Right to access Special vehicles. So a list of one car opened and I selected it. This spawned me outside in a Eleghy RH8. Now not matter what I do to the car, I can go back to the garage and spawn a new one (Nothing custom saved from the previous afaik). So this seemed like a good way to always have a car other than the standard your Character has. What I want to know, I how do I increase that list? Is that where buying cars comes into it? So if anyone has already increased that special vehicle list, Please let me know how you did it :).
2013/09/23
[ "https://gaming.stackexchange.com/questions/131834", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/55820/" ]
I think this is for cars bought in the Rockstar Store. The first one you get for free by joining the Rockstar Social Club. Cars bought on a dealers website are only delivered once to your garage. For the marina it is a bit different: There is only one slot and you can choose (by pressing LEFT on the D-Dad) which vessel to spawn there. You can do this an infinite number of times. This also applies to the helipads and hangars. You can only spawn vessels bought on a dealers website before.
Thats where the collector's edition unique vehicles are :) like the Hotknife and Carbon RS, but you can only get those with a DLC code if you bought the collector's edition game.. or maybe buy a code on eBay.
131,834
I went to the Garage that isn't the one at the safe house. I noticed that there was a prompt to press D-pad Right to access Special vehicles. So a list of one car opened and I selected it. This spawned me outside in a Eleghy RH8. Now not matter what I do to the car, I can go back to the garage and spawn a new one (Nothing custom saved from the previous afaik). So this seemed like a good way to always have a car other than the standard your Character has. What I want to know, I how do I increase that list? Is that where buying cars comes into it? So if anyone has already increased that special vehicle list, Please let me know how you did it :).
2013/09/23
[ "https://gaming.stackexchange.com/questions/131834", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/55820/" ]
Vehicles purchased from the game Internet for game cash only appear in the garage once, ie if you trash it you gotta buy another. The special vehicle list must be something else (I've only got the Elegy too).
Thats where the collector's edition unique vehicles are :) like the Hotknife and Carbon RS, but you can only get those with a DLC code if you bought the collector's edition game.. or maybe buy a code on eBay.
14,854
I have a long video and wish to cut pauses and unneeded places from it. Currently I know how to select mark ins and mark outs ![enter image description here](https://i.stack.imgur.com/QDR9C.png) Unfortunately, this does not allow to have multiple ins and outs in single clip. If I cut multiple clips from one video, then will probably loose a sequence. How to accomplish the task?
2015/02/15
[ "https://avp.stackexchange.com/questions/14854", "https://avp.stackexchange.com", "https://avp.stackexchange.com/users/2122/" ]
You need to create a **sequence**. If you're not familiar with video codecs, the easiest way to do so is to right-click on your clip in the project panel and select **New sequence from clip ...**, which will create a sequence using the resolution and framerate from your clip. Once you've created the sequence, it should appear as a timeline in the lower right area of your screen. If you have not yet set an in- and outpoint, your video will be in the sequence as a whole. Make sure to delete that (right-click on the video in the timeline and select **Clear**), so that you get an empty timeline to start with. Then you can start putting your video together. Set the in- and outpoint for the first scene from your video that you want to use and then **drag** the clip from the project panel into the timeline (alternatively, you can push **insert** (shortcut `,`) or **overwrite** (shortcut `.`)). Move on to the next scene in your video, again set in- and outpoint and insert the clip into the timeline, and so on. Once you have everything arranged in your sequence, you can export the sequence as a whole via **File** -> **Export** -> **Media ...**.
You cannot have multiple marks in and out on clip. What you would do is you would mark a clip and drop it in a sequence (the timeline). Mark another clip and drop it in the timeline. Son on and so forth. The issue you would have is the sound just clips as it jumps from clip to clip in the sequence. The quickest way to fix that is just right click in the timeline on two clips that are joined and you get the option to add a transition. Adding the default tranistion fades/overlapes the sound of the two tracks. Also it does the same to the video. If you want to prevent the video from doing a crossfade, what I do is first right click on the clip on the timeline and 'unlink' so the audio and video is not linked and THEN I do the transistion on the audio only. Hope that helps. GL
23,319,271
I am using codeigniter and I am trying to get all rows from a database table that are past due and only the ones that are past due. The table includes a column that is titled `due_date` and is formatted as a `datetime` `Past Due` stands for anything with a `due_date` prior to todays date. So for example, if the due date was 04/25/2014 and todays date was 04/26/2014 it would be considered overdue. My code is as follows: ``` $query = $this->db->get_where('practice', array('due_date' => date('Y-m-d'))); return $query->result(); ``` But wouldn't that return everything due today? Not quite what I want. A row would look something like this for the due\_date column ``` 2014-04-23 00:00:00 ```
2014/04/27
[ "https://Stackoverflow.com/questions/23319271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2673735/" ]
**Try This :** ``` $query=$this->db ->where('DATE_FORMAT(due_date, "%Y-%m-%d") <',"date('Y-m-d')") ->get('practice'); ``` Source: [[How to select date from datetime column?](https://stackoverflow.com/questions/1754411/how-to-select-date-from-datetime-column])
Quick Google search gives me a solution where this should be possible: ``` $query = $this->db->where('practice', array('due_date <' => date('Y-m-d')))->get(); ``` Source: <http://ellislab.com/codeigniter/user-guide/database/active_record.html>
23,319,271
I am using codeigniter and I am trying to get all rows from a database table that are past due and only the ones that are past due. The table includes a column that is titled `due_date` and is formatted as a `datetime` `Past Due` stands for anything with a `due_date` prior to todays date. So for example, if the due date was 04/25/2014 and todays date was 04/26/2014 it would be considered overdue. My code is as follows: ``` $query = $this->db->get_where('practice', array('due_date' => date('Y-m-d'))); return $query->result(); ``` But wouldn't that return everything due today? Not quite what I want. A row would look something like this for the due\_date column ``` 2014-04-23 00:00:00 ```
2014/04/27
[ "https://Stackoverflow.com/questions/23319271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2673735/" ]
**Try This :** ``` $query=$this->db ->where('DATE_FORMAT(due_date, "%Y-%m-%d") <',"date('Y-m-d')") ->get('practice'); ``` Source: [[How to select date from datetime column?](https://stackoverflow.com/questions/1754411/how-to-select-date-from-datetime-column])
``` $query = $this->db->get_where('practice', array('DATE_FORMAT(due_date, "%Y-%m-%d") <' => date('Y-m-d'))); ```
70,331,109
I 'm a total beginner in **C++** and getting crazy trying to embed **Python** in **C++** using **VS Code** IDE and **GCC** compiler. I am stock and now I 'm keep facing this silly error that says: > > python.h: No such file or directory gcc > > > I have followed steps explaned in ["Using GCC with MinGW in VS Code"](https://code.visualstudio.com/docs/cpp/config-mingw) in order to configure **C++** in **VS Code** but I failed to install **MinGW** (The bin folder was empty) so I add already installed **CodeBlocks MinGW** to my path and it seems to work. I have **python 3.8** installed and tried other solutions and already put **Python.h** and **python library path** in project include path. > > "C:/Users/MPC/AppData/Local/Programs/Python/Python38-32/include/**" > and > "C:/Users/MPC/AppData/Local/Programs/Python/Python38-32/libs/**" > > > here is the code that I want to compile: ``` #include <stdio.h> #include <conio.h> #include <python.h> int main() { PyObject* pInt; Py_Initialize(); PyRun_SimpleString("print('Hello World from Embedded Python!!!')"); Py_Finalize(); printf("\nPress any key to exit...\n"); if(!_getch()) _getch(); return 0; } ``` and this is my **c\_cpp\_properties.json**. (C++ configuration file): ``` { "configurations": [ { "name": "Win32", "includePath": [ "${workspaceFolder}/**", "C:/Users/MPC/AppData/Local/Programs/Python/Python38-32/include/**", "C:/Users/MPC/AppData/Local/Programs/Python/Python38-32/libs/**" ], "defines": [ "_DEBUG", "UNICODE", "_UNICODE" ], "windowsSdkVersion": "10.0.18362.0", "compilerPath": "C:/Program Files (x86)/CodeBlocks/MinGW/bin/gcc.exe", "cStandard": "c17", "cppStandard": "c++17", "intelliSenseMode": "windows-gcc-x86" } ], "version": 4 } ``` and this is **tasks.json** file: ``` { "version": "2.0.0", "tasks": [ { "type": "cppbuild", "label": "C/C++: gcc.exe build active file", "command": "C:/Program Files (x86)/CodeBlocks/MinGW/bin/gcc.exe", "args": [ "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "C:/Program Files (x86)/CodeBlocks/MinGW/bin" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "compiler: \"C:/Program Files (x86)/CodeBlocks/MinGW/bin/gcc.exe\"" } ] ``` }
2021/12/13
[ "https://Stackoverflow.com/questions/70331109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13698448/" ]
The problem was a combinations of simple mistakes and as a beginner I solved it by some digging in [gcc -l -L option flags for library link example](https://www.rapidtables.com/code/linux/gcc/gcc-l.html) and [gcc arguments docs](https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html). There are several simple and important points that should be observed: **1.** The order of options is really important. If its wrong, compiler wont work. It should be like -I(capital i),-g,-L,-l(lower case L),-o. **2.** To embed python in C++ firstly the path to python **include files** have to be known to compiler by **-I** option. Then the path to **python libraries** by a **-L** option. Then name of the each required python **.lib file** contained in libs folder of python. Here is an example of it: ``` "-IC:/Users/MPC/AppData/Local/Programs/Python/Python38-32/include",=>(path to python include files) "-g",=>(debug option specified by ide) "${file}", "-LC:/Users/MPC/AppData/Local/Programs/Python/Python38-32/libs",=>(path to python libraries) "-lpython38",=>(python lib contained in python libs) "-lpython3",=>(python lib contained in python libs) "-l_tkinter",=>(python lib contained in python libs) "-o",=>(output argument specified by ide) "${fileDirname}\\${fileBasenameNoExtension}.exe" ``` I hope that with this answer, the beginners like me, get to the conclusion faster. There is also a good youtube tutorial of [Embedding python in C++ with CMake and Pybind11 and VS Code](https://youtu.be/-eIkUnCLMFc)
Ok so you should probably go through like a intermediate c++ course first, but if u are a begginer and you really want to do this I recommend using visual studio 2019 or 2022, because it is way more begginer-friendly and the dependencies are all set in a gui interface. BTW i would've commented this but I don't have 50 reputation yet so sorry.
87,034
How might I find matrix $M\in M\_2(\mathbb C)$ such that $M^t A =M^{-1}$ where $A=\left[ \begin{array}{cc} a & a \\ a & a+1 \\ \end{array} \right]\in M\_2(\mathbb N)$ without using the brute force method of writing $M=\left[ \begin{array}{cc} a & b \\ c & d \\ \end{array} \right]$? (I don't quite know how to solve the resulting system even in the brute force case anyway.) Thanks in advance.
2011/11/30
[ "https://math.stackexchange.com/questions/87034", "https://math.stackexchange.com", "https://math.stackexchange.com/users/20383/" ]
We can rewrite your equation as $$MM^T = A^{-1},$$ where $$A^{-1} = \left[\begin{array}{cc} 1 + \frac{1}{a} & -1 \\ -1 & 1\end{array}\right]$$ is real, symmetric positive-definite. The Cholesky decomposition of $A^{-1}$ thus supplies such an $M$: $$M = \left[\begin{array}{cc}\sqrt{\frac{a+1}{a}} & 0\\-\sqrt{\frac{a}{a+1}} & \sqrt{\frac{1}{a+1}}\end{array}\right].$$
Clearly $a$ is nonzero, or else $M^\top A$ is non-invertible and it cannot be equal to the invertible matrix $M^{-1}$. Now, $$ \begin{align} A=\begin{pmatrix}a&a\\a&a+1\end{pmatrix} &=\begin{pmatrix}a&a\\a&a\end{pmatrix}+\begin{pmatrix}0&0\\0&1\end{pmatrix}\\ &=\begin{pmatrix}\sqrt{a}\\ \sqrt{a}\end{pmatrix}\begin{pmatrix}\sqrt{a}&\sqrt{a}\end{pmatrix}+\begin{pmatrix}0\\1\end{pmatrix}\begin{pmatrix}0&1\end{pmatrix}\\ &=\begin{pmatrix}\sqrt{a}&0\\ \sqrt{a}&1\end{pmatrix} \begin{pmatrix}\sqrt{a}&\sqrt{a}\\0&1\end{pmatrix} = (M^{-1})^\top M^{-1}. \end{align} $$ So you may set $M=\begin{pmatrix}\sqrt{a}&\sqrt{a}\\0&1\end{pmatrix}^{-1}=\begin{pmatrix}\frac{1}{\sqrt{a}}&-1\\0&1\end{pmatrix}$.
87,034
How might I find matrix $M\in M\_2(\mathbb C)$ such that $M^t A =M^{-1}$ where $A=\left[ \begin{array}{cc} a & a \\ a & a+1 \\ \end{array} \right]\in M\_2(\mathbb N)$ without using the brute force method of writing $M=\left[ \begin{array}{cc} a & b \\ c & d \\ \end{array} \right]$? (I don't quite know how to solve the resulting system even in the brute force case anyway.) Thanks in advance.
2011/11/30
[ "https://math.stackexchange.com/questions/87034", "https://math.stackexchange.com", "https://math.stackexchange.com/users/20383/" ]
You can also rephrase the problem as find a matrix $M$ such that $M^TAM = I$. It is relatively simple once you see that eliminating the matrix entries are easy to handle with $A$. $$ \pmatrix{1&0\\-1&1} \pmatrix{a & a \\a & a+1}\pmatrix{1&-1\\0&1} = \pmatrix{a&0\\0&1}$$ Seeing that we have an extra $a$ term left we remove it by an extra step (assuming $a\neq 0$) $$ \pmatrix{\frac{1}{\sqrt{a}}&0\\0&1} \pmatrix{a &0 \\0 & 1} \pmatrix{\frac{1}{\sqrt{a}}&0\\0&1}= \pmatrix{1&0\\0&1} $$ Combining the two steps into one, gives $$ \underbrace{\pmatrix{\frac{1}{\sqrt{a}}&0\\0&1}\pmatrix{1&0\\-1&1}}\_{M^T} \pmatrix{a & a \\a & a+1} \underbrace{\pmatrix{1&-1\\0&1}\pmatrix{\frac{1}{\sqrt{a}}&0\\0&1}}\_M = \pmatrix{1&0\\0&1} $$
Clearly $a$ is nonzero, or else $M^\top A$ is non-invertible and it cannot be equal to the invertible matrix $M^{-1}$. Now, $$ \begin{align} A=\begin{pmatrix}a&a\\a&a+1\end{pmatrix} &=\begin{pmatrix}a&a\\a&a\end{pmatrix}+\begin{pmatrix}0&0\\0&1\end{pmatrix}\\ &=\begin{pmatrix}\sqrt{a}\\ \sqrt{a}\end{pmatrix}\begin{pmatrix}\sqrt{a}&\sqrt{a}\end{pmatrix}+\begin{pmatrix}0\\1\end{pmatrix}\begin{pmatrix}0&1\end{pmatrix}\\ &=\begin{pmatrix}\sqrt{a}&0\\ \sqrt{a}&1\end{pmatrix} \begin{pmatrix}\sqrt{a}&\sqrt{a}\\0&1\end{pmatrix} = (M^{-1})^\top M^{-1}. \end{align} $$ So you may set $M=\begin{pmatrix}\sqrt{a}&\sqrt{a}\\0&1\end{pmatrix}^{-1}=\begin{pmatrix}\frac{1}{\sqrt{a}}&-1\\0&1\end{pmatrix}$.
77,860
I have a database schema : ``` member(memb_no, name, age) book(isbn, title, authors, publisher) borrowed(memb_no, isbn, date) ``` This is the question: > > For each publisher, print the names of members who have borrowed more than five > books of that publisher. > > > How do I write query for this? Below is my attempt: ``` Select B.publisher, M.memb_no, M.name From book as B, member as M, borrowed as R Where M.memb_no = R.memb_no and B.isbn = R.isbn and R.isbn in (select B.publisher, count (R.isbn) from borrowed as R and book as B where B.isbn = R.isbn group by B.publisher having count >5); ``` Please point out the errors and explain.
2014/09/27
[ "https://dba.stackexchange.com/questions/77860", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/48285/" ]
Try this out: ``` WITH publisher_memb_cte (publisher,memb_no) AS ( SELECT b.publisher,r.memb_no FROM book b JOIN borrowed r ON b.isbn=r.isbn group by b.publisher,r.memb_no HAVING count (*)>5 ) SELECT cte.publisher, m.name FROM publisher_memb_cte cte JOIN member m on cte.memb_no = m.memb_no ``` Tips to avoid performance penalties: 1. avoid if possible selects in the where clause 2. use joins instead of "joining" in the where clause The syntax error in your code is at: ``` from borrowed as R and book as B ``` which should be ``` from borrowed as R, book as B ```
``` with book_borrowed(memb_no , isbn , publisher) as ( select memb_no , borrowed.isbn , publisher from book join borrowed on book.isbn = borrowed.isbn ) select name , publisher from book_borrowed join member on book_borrowed.memb_no = member.memb_no group by member.memb_no , publisher , name having count(isbn) > 5; ```
13,277,278
I need to create a post action to listen to bunch of event messages in ASP.NET MVC 4. There are lots of events so I cannot create an action per event. So it would be best to create an action with their base class as posted model use a custom model binder to hydrate the event. Some of the events look like this: ``` public class QueryID : Identity<Guid> { public QueryID(Guid id) { Identifier = id; } } public class QueryEvent : IEvent<QueryID> { public QueryEvent(QueryID id) { Identity = id; } #region Implementation of IEvent<out QueryID> public QueryID Identity { get; private set; } #endregion } public class QueryCreated : QueryEvent { public string ConnectionID { get; private set; } public QueryCreated(QueryID id, string connectionID) : base(id) { ConnectionID = connectionID; } } public class ColumnAdded : QueryEvent { public string Column { get; private set; } public ColumnAdded(QueryID id, string column) : base(id) { Column = column; } } ``` The action method to receive these messages would look something like this: ``` [HttpPost] public ActionResult Index(IEvent<IIdentity> e) { // whatever return new EmptyResult(); } ``` The base Identity class implements the `IEvent<IIdentity>` interface. What would the model binder look like to accomplish this? Thanks
2012/11/07
[ "https://Stackoverflow.com/questions/13277278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123800/" ]
Mere model binding would not help you here. The way model binding works is, framework looks at the type of the parameter that actions expects, creates a default instance of that type using reflection and hydrates every public property on it using the data sent in the form. The parameter in your action is an interface and hence framework would fail to create an instance. It would just not know which implementation of the interface to create. In one instance, I have used a hidden field in the form being posted to indicate which implementation of the interface is to be bound to the action parameter. But I had a simple scenario. One interface with two implementation. Each one corresponding to a form. So I could have a hidden filed tell me the name of the class that I wanted my model binder to create. In you case, if the originator of the event (some client application I reckon) knows which model should be invoked, then you can have that information sent to your action along with other information. Unfortunately I do not have the code at the moment. If you think this solution may help, I can dig out the code.
A custom model binder provider can be written to support interfaces in MVC3+, see this post. <http://www.matthidinger.com/archive/2011/08/16/An-inheritance-aware-ModelBinderProvider-in-MVC-3.aspx> Any types that inherit the particular interface are then passed to the relevant model binder which can then likely try a `as ConcreteClass` and a null check to find out what the actual type is.. I haven't tried this because I have a similar issue and have been unable to do a solution, but the relevant post looks like it points in the right direction.
73,775,026
How can I update the state for all of the errors? for example, I have to validate the fields name and last name: ``` const handleSubmit = () => { const { name, lastName } = fields let existError = false if (!verify(name)) { existError = true setError({ ...error, ['name']: 'name is bad' }) } if (!verify(lastName)) { existError = true setError({ ...error, ['lastName']: 'lastname is bad' }) } if (!existError) { ... } } console.log('ERROR', error) ``` I can only see this error ERROR `{lastName: 'lastname is bad'}` i am waiting this result: ``` {name: 'name is bad', lastName: 'lastname is bad'} ```
2022/09/19
[ "https://Stackoverflow.com/questions/73775026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19961526/" ]
The value of `error` within your `handleSubmit` function won't update until the next render, so when you set lastName: ``` setError({ ...error, ['lastName']: 'lastname is bad' }) ``` `error` still doesn't have the `name` property and you end up overwriting the name update with the lastName update. You're effectively doing this: ```js const error = { foo: 123 } let state = { ...error, name: 'name is bad' } console.log(state); // { foo: 123, name: 'name is bad' } state = { ...error, // still doesn't contain 'name' lastName: 'last name is bad' } console.log(state); // { foo: 123, lastName: 'last name is bad' } ``` You could avoid this by collecting your errors in a separate object and doing a single state update that includes all of them. ```js let errors = {}; if(!verify(name)) { errors.name = 'name is bad' } if(!verify(lastName)) { errors.lastName = 'last name is bad' } setError({ ...error, ...errors }); ```
Try this instead: ``` if(!verify(name)){ setState(prevError => { return {...prevError, name: 'name is bad'} }); } if(!verify(lastName)){ setState(prevError => { return {...prevError, lastName: 'lastName is bad'} }); } ``` The value `error` wasn't updated after the first if block, due to asynchronous reasons. When you used the `error` value in the second if block, it still used it's orignal value.
39,741,281
I'm pretty sure my question doesn't totally make sense, but I'm trying to create a classification tree in R using 'rpart' and initially had the fit as something like: ``` fit <- rpart(success ~ A + B + C) ``` I have now realised 'success' might also be measured by another 'value'. So I was going to amend it to: ``` fit <- rpart(success + new_option ~ A + B + C) ``` But when I run these lines: ``` plot(fit, uniform=TRUE, main="Success plot") text(fit, use.n = TRUE, all=TRUE, cex=.8) post(fit, file = "tree.ps", title="Success plot") ``` I get this error: ``` Error in plot.rpart(fit, uniform = TRUE, main = "Success plot") : fit is not a tree, just a root ``` So just wondering - is this even possible? Or do I need to tackle this in a totally different way?
2016/09/28
[ "https://Stackoverflow.com/questions/39741281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6781056/" ]
This means that your tree algorithm has not created any splits. You can use the cp parameter to increase the complexity of your tree. the default value of cp is 0.01 so you can try 0.001. but note that this might imply you are over fitting your model. p.s.. you can only have on response variable not var1 + var 2... if you need to combine both, do it before you insert it in to your modeling function.
For me it works when I write it as: ```r fit <- rpart(cbind(success, new_option) ~ A + B + C) ```
82,271
I tried this example [Place four algorithms (algorithm2e) in a subfigure and arrange them in two rows and two columns](https://tex.stackexchange.com/questions/40365/place-four-algorithms-algorithm2e-in-a-subfigure-and-arrange-them-in-two-rows) on two column documents. It doesn't work. The error message is ``` ! LaTeX Error: [H] in two columns mode is not allowed for algorithms. ``` Is there anyway to go? The code example is: ``` \documentclass[twocolumn]{article} \usepackage{algorithm2e} \usepackage{caption} \usepackage{subcaption} \newcommand{\myalgorithm}{% \begin{algorithm*}[H] \SetAlgoLined \KwData{this text} \KwResult{how to write algorithm with \LaTeX2e } initialization\; \While{not at end of this document}{ read current\; \eIf{understand}{ go to next section\; current section becomes this one\; }{ go back to the beginning of current section\; } } \end{algorithm*}} \begin{document} \begin{figure} \begin{subfigure}{.5\textwidth} \myalgorithm \caption{How to write algorithms} \end{subfigure}% need this comment symbol to avoid overfull hbox \begin{subfigure}{.5\textwidth} \myalgorithm \caption{How to write algorithms} \end{subfigure}\\ \begin{subfigure}{.5\textwidth} \myalgorithm \caption{How to write algorithms} \end{subfigure}% \begin{subfigure}{.5\textwidth} \myalgorithm \caption{How to write algorithms} \end{subfigure} \caption{Main caption} \end{figure} \end{document} ```
2012/11/11
[ "https://tex.stackexchange.com/questions/82271", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/21704/" ]
[`algorithm2e`](http://ctan.org/pkg/algorithm2e) provides its own `[H]` float parameter, which sidesteps setting its contents as a float. However, in `twocolumn` mode, it produces an error. I'm not sure why. You can avoid this by setting `\@latex@error` to `\@gobble` temporarily. Using your example, I've added a `\removelatexerror` macro inside a `\begingroup`...`\endgroup`. More specifically, the definition ``` \makeatletter \newcommand{\removelatexerror}{\let\@latex@error\@gobble} \makeatother ``` is placed inside a group, inside `\myalgorithm`: ``` \newcommand{\myalgorithm}{% \begingroup \removelatexerror% Nullify \@latex@error \begin{algorithm*}[H] %... \end{algorithm*} \endgroup} ``` Also, since you're spreading the 4 algorithms across both columns, it's best to use `figure*` rather than `figure`: ![enter image description here](https://i.stack.imgur.com/DlvGh.png) Obviously you won't be using `\myalgorithm` in your actual document. You could just place `\removelatexerror` inside each of the `subfigure` environments.
I had similar issues... I simply removed [H] from the code as below. ``` \begin{algorithm*}[H] ``` to ``` \begin{algorithm*} ``` Then the issue solved.
40,280,620
I am working with Java EE 7 in Intellij IDEA and trying to create and use a custom .tag file. I have followed [this](https://stackoverflow.com/a/3257426/4545369) answer and created a wrapper.tag file in WEB-INF/tags : ``` <%@tag description="Simple Wrapper Tag" pageEncoding="UTF-8"%> <html><body> <jsp:doBody/> </body></html> ``` And i have created a .jsp file in my web directory: ``` <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib prefix="t" tagdir="/WEB-INF/tags" %> <t:wrapper> <h1>Welcome</h1> </t:wrapper> ``` But when loading the page I always one of two following errors: * No tag "wrapper" defined in tag library imported with prefix "t" * lang.ClassNotFoundException: org.apache.jsp.temptest\_jsp Note that my jsp file is called temptest.jsp. Thanks in advance
2016/10/27
[ "https://Stackoverflow.com/questions/40280620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4545369/" ]
Two things you need to check, I was also facing the same problem 1. `<%@ taglib tagdir="/WEB-INF/tags/" prefix="tag" %>` add '/' after tags 2. In the `tagdir` path there should be no spelling mistakes, I had forgot to add 's' to `tags` folder.
I've also met this problem before. Turn out, my tags folder in out/artifacts/WEB-INF wasn't updated after I renamed the folder. You may want to check that. I'm not good at Java. In fact, I'm a C# dev. My solution is to manually rename the folder. There must be a way that we can update these actions automatically that I haven't known. :) [![The reference folder](https://i.stack.imgur.com/mlVnW.png)](https://i.stack.imgur.com/mlVnW.png)
29,226,743
I am learning regex,when I compile this code which is from Java Official documentation, I am getting `No Console` error in this code,The [source is](https://docs.oracle.com/javase/tutorial/essential/regex/test_harness.html), I am compiling this code in Eclipse, version Kepler. The culprit is `Console console = System.console();`but I do not know why the error is caused. ``` import java.io.Console; import java.util.regex.Pattern; import java.util.regex.Matcher; public class RegexTestHarness { public static void main(String[] args){ Console console = System.console(); if (console == null) { System.err.println("No console."); System.exit(1); } while (true) { Pattern pattern = Pattern.compile(console.readLine("%nEnter your regex: ")); Matcher matcher = pattern.matcher(console.readLine("Enter input string to search: ")); boolean found = false; while (matcher.find()) { console.format("I found the text" + " \"%s\" starting at " + "index %d and ending at index %d.%n", matcher.group(), matcher.start(), matcher.end()); found = true; } if(!found){ console.format("No match found.%n"); } } } } ```
2015/03/24
[ "https://Stackoverflow.com/questions/29226743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4706252/" ]
> > but I do not know why the error is caused > > > Presumably because you're not running it in a console. When you run a Java app in Eclipse, `System.console()` returns null, because it's not a "normal" console. (Personally I think it would be better if Eclipse's console view could be used as the console for this purpose, but apparently that's not the case - at least not yet. See [bug 122429](https://bugs.eclipse.org/bugs/show_bug.cgi?id=122429).) Open a console ("command prompt" in Windows parlance) and run the code there, and you should be fine. Alternatively, change the code to use standard streams such as `System.in` and `System.out` to read input and write output, instead of using `Console`.
This switches all the console stuff to System.in and System.out ``` import java.util.regex.Pattern; import java.util.Scanner; import java.util.regex.Matcher; public class RegexTestHarness { public static void main(String[] args){ Scanner input = new Scanner(System.in); while (true) { System.out.println("Type in a pattern"); Pattern pattern = Pattern.compile(input.nextLine()); System.out.println("Type in a String to search: "); Matcher matcher = pattern.matcher(input.nextLine()); boolean found = false; while (matcher.find()) { System.out.format("I found the text" + " \"%s\" starting at " + "index %d and ending at index %d.%n", matcher.group(), matcher.start(), matcher.end()); found = true; } if(!found){ System.out.format("No match found.%n"); } } } } ```
15,857,079
I am trying to build a simple level app. What I want is when the device is totally flat (x,y values of accelerometer almost 0) for the device to produce a beep sound after 5 seconds, not immediately. I am using the following code, and I do not know what I must changed in order for the sound to always works after 5 seconds and not randomly or immediately. Can somebody help me? ``` public void onSensorChanged(SensorEvent event) { x = event.values[0]; y = event.values[1]; long actualTime = System.currentTimeMillis(); if(x > -0.1 && x < 0.1 && y > -0.1 && y < 0.1) { if(actualTime - lastUpdate >= 5000) { return; } lastUpdate = actualTime; try { AssetFileDescriptor afd = getAssets().openFd("beep.wav"); mMediaplayer = new MediaPlayer(); mMediaplayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); mMediaplayer.prepare(); mMediaplayer.start(); mMediaplayer.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { //mp.setLooping(false); mp.stop(); mp.release(); } }); } catch(Exception e) { e.printStackTrace(); } } } ```
2013/04/06
[ "https://Stackoverflow.com/questions/15857079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1380135/" ]
Your specific issue here is that you are mixing jQuery and raw javascript. To set the width of an element with jQuery, use the [width()](http://api.jquery.com/width) or [css()](http://api.jquery.com/css/) method: ``` $(".content").width(560); $(".content").css('width',560); ``` Having said that, you may be better off looking at the browser size, not screen resolution. Shouldn't your content respond to the size of my browser, regardless of my screensize? I don't keep my browser fullscreen. Lastly, look at [css media queries](http://css-tricks.com/css-media-queries/) even to respond to the browser size. There are much better ways of doing this.
You can try and just use jQuery and CSS ``` function checkWindowSize() { if ( $(window).width() > 1800 ) { $('content').addClass('large'); } else { $('content').removeClass('large'); } } $(window).resize(checkWindowSize); ``` For the CSS you would need to write it out like this: ``` #content{ } .large #content{ } ``` Here is a tutorial [Source](http://net.tutsplus.com/tutorials/design-tutorials/quick-tip-different-layouts-for-different-widths/)
67,810,954
I want to match number like--- **10** **, -10,** **10E5** **,10e5** as an integer number and number like-- **10.554** **,-10.5** **,10.5E5** **,-10.5e-5** as a floating pointer number. How can I achieve it in lexical analyzer FLEX? I am trying in this way: ``` ^[+-]?\d+([eE][-+]?[0-9]+)?$ {++CountInteger;} ^[-+]?[0-9]*[.][0-9]+([eE][-+]?[0-9]+)?$ {++CountFloat;} ``` but it is not working ,what is the problem in my case and what should be the solution for it? Thanks in advance.
2021/06/02
[ "https://Stackoverflow.com/questions/67810954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12517195/" ]
You need to remove ^ and $ unless you want to match lines which contain nothing other than a single number. When you have a problem with a regular expression, build it up by in small steps and make sure it works as you expect after each step.
If you already have proven that you are working with a number and all you need is to see if it is an integer or a floating point number, your regex could be super simple by just checking for the existence of a `.`. e.g. the pattern would be `"\."`. If that works for you - awesome! Easier is often better! If you need to prove that you have a number, then things get a little more complicated. I'd suggest: For integers - `^-?\d+([eE]-?\d+)?$` * Optional negative sign `-?`, one or more digits `\d+`, then the optional exponent piece `([eE]-?\d+)?`. * + Exponent piece should have either 'e' or 'E' `[eE]`, an optional negative sign `-?`, and one or more digits for the exponent `\d+` For floating point numbers - it is only slightly modified: `^-?\d+\.\d+([eE]-?\d+)?$` * The modification is the `\.\d+` bit which will exactly match the `.` and one or more digits following the period.
67,810,954
I want to match number like--- **10** **, -10,** **10E5** **,10e5** as an integer number and number like-- **10.554** **,-10.5** **,10.5E5** **,-10.5e-5** as a floating pointer number. How can I achieve it in lexical analyzer FLEX? I am trying in this way: ``` ^[+-]?\d+([eE][-+]?[0-9]+)?$ {++CountInteger;} ^[-+]?[0-9]*[.][0-9]+([eE][-+]?[0-9]+)?$ {++CountFloat;} ``` but it is not working ,what is the problem in my case and what should be the solution for it? Thanks in advance.
2021/06/02
[ "https://Stackoverflow.com/questions/67810954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12517195/" ]
You need to remove ^ and $ unless you want to match lines which contain nothing other than a single number. When you have a problem with a regular expression, build it up by in small steps and make sure it works as you expect after each step.
A little visualizion: [![path of -?\d+([eE]-?\d+)?](https://i.stack.imgur.com/2WMNk.png)](https://i.stack.imgur.com/2WMNk.png) (created at [jex.im](https://jex.im/regulex/#!flags=&re=-%3F%5Cd%2B(%5BeE%5D-%3F%5Cd%2B)%3F)) See also: * [Debuggex](https://debuggex.com) * [Regex101](https://regex101.com/)
54,565,168
I am creating a menu page with several links for use by a group of teachers. I want the links to be seen as buttons for ease of navigation on a desktop, touchscreen or phone. The css I have is below: ``` a.buttons:link, a:visited { background: #001E60; /* For browsers that do not support gradients */ background: -webkit-linear-gradient(#34657F, #001E60); /* For Safari 5.1 to 6.0 */ background: -o-linear-gradient(#34657F, #001E60); /* For Opera 11.1 to 12.0 */ background: -moz-linear-gradient(#34657F, #001E60); /* For Firefox 3.6 to 15 */ background: linear-gradient(#34657F, #001E60); /* Standard syntax */line-height: 50px; color: white; border: 2px solid #EAAA00; padding-top: 20px; padding-left: 5px; text-align: center; text-decoration: none; display: inline-block; margin: 5px; width: 300px; height: 100px; font-size: 20px; } ``` This seems to work as anticipated unless the link text wraps to two lines. If it does, the link is not aligned horizontally. A sample is below and the link text "Professional Development Prior Approval Form" causes the misalignment. The complete page url is [here](http://www.princeave.com/0/new.php). What is the best way to accomplish what I am trying to do? ``` <h1>Faculty</h1> <h2>Bible Studies</h2> <a href='http://princeave.com/0/revelations_ablaze.php' title='This is a 9 part series by Pastor Josh Smith from Prince Avenue on chapters 1-5 of Revelation. This series is available in audio or video format.' target='_blank' class='buttons'> Ablaze With His Glory</a> <a href='http://princeave.com/0/a_study_of_philippians.php' title='This is a 27 part series by Pastor Josh Smith from Prince Avenue on the book of Philippians. This series is available in audio or video format.' target='_blank' class='buttons'> Philippians - Together for the Gospel</a> <h2>Forms</h2> <a href='https://princeave-my.sharepoint.com/personal/keley_princeave_org/_layouts/15/guestaccess.aspx?guestaccesstoken=LeveEcmr5rB%2fF%2fmUPS17uXPjuStCSmAaeWcmJsLS4E0%3d&docid=2_1ba3837b874174956adb1089d9cad2ca7&rev=1' title='Form to renew an ACSI certificate' target='_blank' class='buttons'> ACSI Certification Application</a> <a href='hhttps://princeave.sharepoint.com/PACS%20-%20Academic%20Dean/Shared%20Documents/Form/PACS%20Education%20Assistance%20Form%20(fillable).pdf' title='Form to request funds for pursuing an advanced degree' target='_blank' class='buttons'> Education Assistance Form</a> <a href='https://princeave.sharepoint.com/:b:/g/PACS%20Faculty/Ec5ahbAa5BpEvU6Z_Ge0ysUBYbAxnvzr2fAnSyAQWsDrQQ?e=8t1Z53' title='The faculty handbook' target='_blank' class='buttons'> Employee Handbook</a> <a href='https://princeave.sharepoint.com/PACS%20Faculty/Shared%20Documents/Forms/AllItems.aspx?id=%2FPACS%20Faculty%2FShared%20Documents%2FField%20Trips%2FField%20Trip%20Approval%20Process%2Epdf&parent=%2FPACS%20Faculty%2FShared%20Documents%2FField%20Trips' title='' target='_blank' class='buttons'> Field Trip Approval Process</a> <a href='https://princeave.sharepoint.com/PACS%20Faculty/_layouts/15/WopiFrame.aspx?sourcedoc=%7BB58B1578-901F-4116-9B29-86D7DF95BBBF%7D&file=Field%20Trip%20Form.xlsx&action=default' title='' target='_blank' class='buttons'> Field Trip Form</a> <a href='https://princeave.sharepoint.com/PACS%20-%20Academic%20Dean/Shared%20Documents/Form/PACS%20Professional%20Development%20Prior%20Approval%20Form%20(Fillable).pdf' title='Form to request funds for Professional Development seminar, class, etc.' target='_blank' class='buttons'> Professional Development Prior Approval Form</a> <a href='https://docs.google.com/forms/d/e/1FAIpQLSdcY-g1mL6ZNR4RG6XleiSmZyEnEXKhRvwzGzxOdrmE7gifnw/viewform' title='Request ACSI CEUs by awarded to you for completion of an existing CEU course.' target='_blank' class='buttons'> Request CEU credits</a> <a href='https://docs.google.com/forms/d/e/1FAIpQLSddr1ZeyOmmllKXxG8-lvwmCH-wMpEhOwPDGEjTvxJ-BknXOw/viewform' title='Submit a webinar, conference, or Bible study to determine if ACSI CEUs can be granted. Please fill out the fields on this page.' target='_blank' class='buttons'> Request New CEU course</a> ```
2019/02/07
[ "https://Stackoverflow.com/questions/54565168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3395907/" ]
You're missing: `vertical-align:top;` > > The vertical-align CSS property sets vertical alignment of an inline > or table-cell box. > > > Refer to [this](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) for more info([Related](https://stackoverflow.com/questions/21990281/why-are-these-two-identical-inline-divs-misaligned-when-one-has-text-and-the-oth)). Example Snippet: ```css a.buttons:link, a:visited { background: #001E60; /* For browsers that do not support gradients */ background: -webkit-linear-gradient(#34657F, #001E60); /* For Safari 5.1 to 6.0 */ background: -o-linear-gradient(#34657F, #001E60); /* For Opera 11.1 to 12.0 */ background: -moz-linear-gradient(#34657F, #001E60); /* For Firefox 3.6 to 15 */ background: linear-gradient(#34657F, #001E60); /* Standard syntax */line-height: 50px; color: white; border: 2px solid #EAAA00; padding-top: 20px; padding-left: 5px; text-align: center; text-decoration: none; display: inline-block; margin: 5px; width: 300px; height: 100px; font-size: 20px; vertical-align:top; } ``` ```html <h1>Faculty</h1> <h2>Bible Studies</h2> <a href='http://princeave.com/0/revelations_ablaze.php' title='This is a 9 part series by Pastor Josh Smith from Prince Avenue on chapters 1-5 of Revelation. This series is available in audio or video format.' target='_blank' class='buttons'> Ablaze With His Glory</a> <a href='http://princeave.com/0/a_study_of_philippians.php' title='This is a 27 part series by Pastor Josh Smith from Prince Avenue on the book of Philippians. This series is available in audio or video format.' target='_blank' class='buttons'> Philippians - Together for the Gospel</a> <h2>Forms</h2> <a href='https://princeave-my.sharepoint.com/personal/keley_princeave_org/_layouts/15/guestaccess.aspx?guestaccesstoken=LeveEcmr5rB%2fF%2fmUPS17uXPjuStCSmAaeWcmJsLS4E0%3d&docid=2_1ba3837b874174956adb1089d9cad2ca7&rev=1' title='Form to renew an ACSI certificate' target='_blank' class='buttons'> ACSI Certification Application</a> <a href='hhttps://princeave.sharepoint.com/PACS%20-%20Academic%20Dean/Shared%20Documents/Form/PACS%20Education%20Assistance%20Form%20(fillable).pdf' title='Form to request funds for pursuing an advanced degree' target='_blank' class='buttons'> Education Assistance Form</a> <a href='https://princeave.sharepoint.com/:b:/g/PACS%20Faculty/Ec5ahbAa5BpEvU6Z_Ge0ysUBYbAxnvzr2fAnSyAQWsDrQQ?e=8t1Z53' title='The faculty handbook' target='_blank' class='buttons'> Employee Handbook</a> <a href='https://princeave.sharepoint.com/PACS%20Faculty/Shared%20Documents/Forms/AllItems.aspx?id=%2FPACS%20Faculty%2FShared%20Documents%2FField%20Trips%2FField%20Trip%20Approval%20Process%2Epdf&parent=%2FPACS%20Faculty%2FShared%20Documents%2FField%20Trips' title='' target='_blank' class='buttons'> Field Trip Approval Process</a> <a href='https://princeave.sharepoint.com/PACS%20Faculty/_layouts/15/WopiFrame.aspx?sourcedoc=%7BB58B1578-901F-4116-9B29-86D7DF95BBBF%7D&file=Field%20Trip%20Form.xlsx&action=default' title='' target='_blank' class='buttons'> Field Trip Form</a> <a href='https://princeave.sharepoint.com/PACS%20-%20Academic%20Dean/Shared%20Documents/Form/PACS%20Professional%20Development%20Prior%20Approval%20Form%20(Fillable).pdf' title='Form to request funds for Professional Development seminar, class, etc.' target='_blank' class='buttons'> Professional Development Prior Approval Form</a> <a href='https://docs.google.com/forms/d/e/1FAIpQLSdcY-g1mL6ZNR4RG6XleiSmZyEnEXKhRvwzGzxOdrmE7gifnw/viewform' title='Request ACSI CEUs by awarded to you for completion of an existing CEU course.' target='_blank' class='buttons'> Request CEU credits</a> <a href='https://docs.google.com/forms/d/e/1FAIpQLSddr1ZeyOmmllKXxG8-lvwmCH-wMpEhOwPDGEjTvxJ-BknXOw/viewform' title='Submit a webinar, conference, or Bible study to determine if ACSI CEUs can be granted. Please fill out the fields on this page.' target='_blank' class='buttons'> Request New CEU course</a> ```
I fixed ya up with flexbox, moved some CSS around, and wrapped your A's in DIVs. ALWAYS wrap your elements in divs for layout: ```css .link-boxes { display: flex; flex-wrap: wrap; } .link-boxes > div { padding: 0.5em; display: flex; background: #001E60; /* For browsers that do not support gradients */ background: -webkit-linear-gradient(#34657F, #001E60); /* For Safari 5.1 to 6.0 */ background: -o-linear-gradient(#34657F, #001E60); /* For Opera 11.1 to 12.0 */ background: -moz-linear-gradient(#34657F, #001E60); /* For Firefox 3.6 to 15 */ background: linear-gradient(#34657F, #001E60); border: 2px solid #EAAA00; margin-top: 1rem; width: 300px; height: 100px; text-align: center; } .link-boxes > div:not(:last-of-type) { margin-right: 1rem; } .link-boxes > div > a { vertical-align: middle; color: white; text-decoration: none; font-size: 20px; margin: auto; } ``` ```html <h1>Faculty</h1> <h2>Bible Studies</h2> <div class="link-boxes"> <div> <a href='http://princeave.com/0/revelations_ablaze.php' title='This is a 9 part series by Pastor Josh Smith from Prince Avenue on chapters 1-5 of Revelation. This series is available in audio or video format.' target='_blank' class='buttons'> Ablaze With His Glory</a> </div> <div> <a href='http://princeave.com/0/a_study_of_philippians.php' title='This is a 27 part series by Pastor Josh Smith from Prince Avenue on the book of Philippians. This series is available in audio or video format.' target='_blank' class='buttons'> Philippians - Together for the Gospel</a> </div> </div> <h2>Forms</h2> <div class="link-boxes"> <div> <a href='https://princeave-my.sharepoint.com/personal/keley_princeave_org/_layouts/15/guestaccess.aspx?guestaccesstoken=LeveEcmr5rB%2fF%2fmUPS17uXPjuStCSmAaeWcmJsLS4E0%3d&docid=2_1ba3837b874174956adb1089d9cad2ca7&rev=1' title='Form to renew an ACSI certificate' target='_blank' class='buttons'> ACSI Certification Application</a> </div> <div> <a href='hhttps://princeave.sharepoint.com/PACS%20-%20Academic%20Dean/Shared%20Documents/Form/PACS%20Education%20Assistance%20Form%20(fillable).pdf' title='Form to request funds for pursuing an advanced degree' target='_blank' class='buttons'> Education Assistance Form</a> </div> <div> <a href='https://princeave.sharepoint.com/:b:/g/PACS%20Faculty/Ec5ahbAa5BpEvU6Z_Ge0ysUBYbAxnvzr2fAnSyAQWsDrQQ?e=8t1Z53' title='The faculty handbook' target='_blank' class='buttons'> Employee Handbook</a> </div> <div> <a href='https://princeave.sharepoint.com/PACS%20Faculty/Shared%20Documents/Forms/AllItems.aspx?id=%2FPACS%20Faculty%2FShared%20Documents%2FField%20Trips%2FField%20Trip%20Approval%20Process%2Epdf&parent=%2FPACS%20Faculty%2FShared%20Documents%2FField%20Trips' title='' target='_blank' class='buttons'> Field Trip Approval Process</a> </div> <div> <a href='https://princeave.sharepoint.com/PACS%20Faculty/_layouts/15/WopiFrame.aspx?sourcedoc=%7BB58B1578-901F-4116-9B29-86D7DF95BBBF%7D&file=Field%20Trip%20Form.xlsx&action=default' title='' target='_blank' class='buttons'> Field Trip Form</a> </div> <div> <a href='https://princeave.sharepoint.com/PACS%20-%20Academic%20Dean/Shared%20Documents/Form/PACS%20Professional%20Development%20Prior%20Approval%20Form%20(Fillable).pdf' title='Form to request funds for Professional Development seminar, class, etc.' target='_blank' class='buttons'> Professional Development Prior Approval Form</a> </div> <div> <a href='https://docs.google.com/forms/d/e/1FAIpQLSdcY-g1mL6ZNR4RG6XleiSmZyEnEXKhRvwzGzxOdrmE7gifnw/viewform' title='Request ACSI CEUs by awarded to you for completion of an existing CEU course.' target='_blank' class='buttons'> Request CEU credits</a> </div> <div> <a href='https://docs.google.com/forms/d/e/1FAIpQLSddr1ZeyOmmllKXxG8-lvwmCH-wMpEhOwPDGEjTvxJ-BknXOw/viewform' title='Submit a webinar, conference, or Bible study to determine if ACSI CEUs can be granted. Please fill out the fields on this page.' target='_blank' class='buttons'> Request New CEU course</a> </div> </div> ``` See: <https://codepen.io/cloudulus/pen/BMmmXJ>
3,455,208
Surely the compiler knows that it's the last label of the `switch` statement?
2010/08/11
[ "https://Stackoverflow.com/questions/3455208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327528/" ]
According to <http://msdn.microsoft.com/en-us/library/06tc147t.aspx> > > You cannot "fall through" any switch section, including the last one. > > > Fall through can be avoided by any of the following: break, goto, or return.
As mentioned, you can use default:, but consider case null too. case null: does need a break; case null: iEvaluatedToNothing(); break; If you want to "waterfall" down you can do something like this; ``` switch (deliverMail) { case null: case "": case "Address0": deliverMail0(); goto case "1"; case "1": deliverMail1(); break; } ``` You can use this with breaks as needed, but one is required on the last evaluation.
3,455,208
Surely the compiler knows that it's the last label of the `switch` statement?
2010/08/11
[ "https://Stackoverflow.com/questions/3455208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327528/" ]
When using a `switch`, to `break` is not the only option. You also have the option of going to another case, going to the default case, going to another label, or returning. It is also possible to have multiple cases that have a single implementation body. Since there are up to five options plus the ability to have multiple cases for one implementation, the compiler is not able to simply put in the "correct" answer. You have to choose what you intend to do. It ensures the compiler does the right thing, makes your code clearer, and makes it more difficult to do dumb-programmer-things, like add another case after the "last one", and forget to put in a break/goto/return.
As mentioned, you can use default:, but consider case null too. case null: does need a break; case null: iEvaluatedToNothing(); break; If you want to "waterfall" down you can do something like this; ``` switch (deliverMail) { case null: case "": case "Address0": deliverMail0(); goto case "1"; case "1": deliverMail1(); break; } ``` You can use this with breaks as needed, but one is required on the last evaluation.