qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
22,516,477
I'm trying to perform some tasks in educational purposes and stuck with unit `graph`. When compiling I'm getting this error: ``` task4.pas(10,11) Fatal: Can't find unit graph used by task4 ``` I've been googling for a while and found that `ptcgraph`, `sdlgraph` and `ggigraph` could be used instead. But I didn't get far with it. `ptcgraph` and `ggigraph` were resulting in same error. However, it is better with `sdlgraph`. But there were couple linking errors: ``` ld: library not found for -sdl ``` And after `brew install sdl`: ``` ld: library not found for -lgcc ``` I've got no idea how to install it. So, I'm wondering if there either something I didn't done or something I'm supposed to use instead of `graph` unit.
2014/03/19
[ "https://Stackoverflow.com/questions/22516477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1774187/" ]
The graph unit is not available for Mac OS X because no one has implemented it. The source code that gets installed is generic and hence also contains the source code for units that don't work on the current platform (e.g., it also includes the source code for the Win32 rtl). The sdlgraph unit was once started by someone, but that person unfortunately disappeared after a short while. You can try using it by added "sldgraph" to your uses clause, but it's unlikely that it will work very well. Contributions to make it work better are of course welcome.
Graph should be available on Mac OS X. On my machine it is in the path "/usr/local/share/fpcsrc/packages/graph/src/macosx/graph.pp". Please check if your search paths are correctly set. However, according to the [official documentation](http://www.freepascal.org/docs-html/rtl/graph/) "The unit is provided for compatibility only: It is recommended to use more modern graphical systems."
1,700,149
I know the answer is $x = 499 + 625\, z$ where $z$ is an integer, from [this source](http://www.wolframalpha.com/input/?i=124x%20%3D%201%20%28mod%20625%29). I also know that you use the Extended Euclidean algorithm
2016/03/16
[ "https://math.stackexchange.com/questions/1700149", "https://math.stackexchange.com", "https://math.stackexchange.com/users/149325/" ]
Another option is \begin{align} 124 \, x &= 1 \pmod {625} \iff \\ 124 \, x &= 625 \, q + 1 \quad (q \in \mathbb{Z}) \iff \\ 124 \, x - 625 \, q &= 1 \quad (q \in \mathbb{Z}) \iff \\ 124 \, x + 625 \, y &= 1 \quad (\*) \end{align} where $(\*)$ is a linear Diophantine equation in integer $x, y$. The solution algorithm involves the extended Euclidean algorithm. For the coefficients $a = 124, b = 625$ we get $g = \gcd(a,b) = \gcd(124, 625) = 1$ so we do not have to rescale and $g$ divides $c = 1$, so we have solutions. The solutions of the homogeneous equation to $(\*)$ $$ 124 \, x + 625 \,y = 0 $$ are $$ (x\_h, y\_h) = (625 \, t, -124 \, t) \quad (t \in \mathbb{Z}) $$ A particular solution of $(\*)$ is found using the extended Euclidean algorithm which gives ([link](https://www.wolframalpha.com/input/?i=egcd%28124,625%29)) $$ (x\_p, y\_p) = (-126, 25) $$ All solutions are found by adding a particular solution to the homogenous solutions: $$4 (x, y) = (625\, t - 126, -124\, t + 25) $$ The first component is $$ x = 625 \,t - 126 = 625 \, (t - 1) + 625 - 126 = 625 \, t' + 499 $$
$$ 124 x \equiv 1 \bmod 625 \implies 124 x \equiv 1 \bmod 125 \implies -1 x \equiv 1 \bmod 125 \implies x \equiv -1 \bmod 125 $$ Write $x= 125y-1$. Then $$ 0 \equiv 124 x-1 = (125-1)(125y-1)-1 \equiv -125y-125=-125(y+1) \bmod 625 $$ This implies $y \equiv -1 \bmod 5$. Write $y=5z-1$. Then $$ x = 125y-1 = 125(5z-1)-1 = 625z - 126 = 625(z-1)+499 $$
1,700,149
I know the answer is $x = 499 + 625\, z$ where $z$ is an integer, from [this source](http://www.wolframalpha.com/input/?i=124x%20%3D%201%20%28mod%20625%29). I also know that you use the Extended Euclidean algorithm
2016/03/16
[ "https://math.stackexchange.com/questions/1700149", "https://math.stackexchange.com", "https://math.stackexchange.com/users/149325/" ]
Another option is \begin{align} 124 \, x &= 1 \pmod {625} \iff \\ 124 \, x &= 625 \, q + 1 \quad (q \in \mathbb{Z}) \iff \\ 124 \, x - 625 \, q &= 1 \quad (q \in \mathbb{Z}) \iff \\ 124 \, x + 625 \, y &= 1 \quad (\*) \end{align} where $(\*)$ is a linear Diophantine equation in integer $x, y$. The solution algorithm involves the extended Euclidean algorithm. For the coefficients $a = 124, b = 625$ we get $g = \gcd(a,b) = \gcd(124, 625) = 1$ so we do not have to rescale and $g$ divides $c = 1$, so we have solutions. The solutions of the homogeneous equation to $(\*)$ $$ 124 \, x + 625 \,y = 0 $$ are $$ (x\_h, y\_h) = (625 \, t, -124 \, t) \quad (t \in \mathbb{Z}) $$ A particular solution of $(\*)$ is found using the extended Euclidean algorithm which gives ([link](https://www.wolframalpha.com/input/?i=egcd%28124,625%29)) $$ (x\_p, y\_p) = (-126, 25) $$ All solutions are found by adding a particular solution to the homogenous solutions: $$4 (x, y) = (625\, t - 126, -124\, t + 25) $$ The first component is $$ x = 625 \,t - 126 = 625 \, (t - 1) + 625 - 126 = 625 \, t' + 499 $$
Hint: Solve the linear Diophantine equation $124x+625m=1$.
1,700,149
I know the answer is $x = 499 + 625\, z$ where $z$ is an integer, from [this source](http://www.wolframalpha.com/input/?i=124x%20%3D%201%20%28mod%20625%29). I also know that you use the Extended Euclidean algorithm
2016/03/16
[ "https://math.stackexchange.com/questions/1700149", "https://math.stackexchange.com", "https://math.stackexchange.com/users/149325/" ]
Another option is \begin{align} 124 \, x &= 1 \pmod {625} \iff \\ 124 \, x &= 625 \, q + 1 \quad (q \in \mathbb{Z}) \iff \\ 124 \, x - 625 \, q &= 1 \quad (q \in \mathbb{Z}) \iff \\ 124 \, x + 625 \, y &= 1 \quad (\*) \end{align} where $(\*)$ is a linear Diophantine equation in integer $x, y$. The solution algorithm involves the extended Euclidean algorithm. For the coefficients $a = 124, b = 625$ we get $g = \gcd(a,b) = \gcd(124, 625) = 1$ so we do not have to rescale and $g$ divides $c = 1$, so we have solutions. The solutions of the homogeneous equation to $(\*)$ $$ 124 \, x + 625 \,y = 0 $$ are $$ (x\_h, y\_h) = (625 \, t, -124 \, t) \quad (t \in \mathbb{Z}) $$ A particular solution of $(\*)$ is found using the extended Euclidean algorithm which gives ([link](https://www.wolframalpha.com/input/?i=egcd%28124,625%29)) $$ (x\_p, y\_p) = (-126, 25) $$ All solutions are found by adding a particular solution to the homogenous solutions: $$4 (x, y) = (625\, t - 126, -124\, t + 25) $$ The first component is $$ x = 625 \,t - 126 = 625 \, (t - 1) + 625 - 126 = 625 \, t' + 499 $$
In this particular case, by noticing that $124 = 5^3 - 1$, $625 = 5^4$ and $$(5^3 + 1)(5^3 - 1) = 5^6 - 1 = -1 \pmod{5^4}$$ we get $x = -(5^3 + 1) = -126 = 499 \pmod{625}$.
1,700,149
I know the answer is $x = 499 + 625\, z$ where $z$ is an integer, from [this source](http://www.wolframalpha.com/input/?i=124x%20%3D%201%20%28mod%20625%29). I also know that you use the Extended Euclidean algorithm
2016/03/16
[ "https://math.stackexchange.com/questions/1700149", "https://math.stackexchange.com", "https://math.stackexchange.com/users/149325/" ]
Another option is \begin{align} 124 \, x &= 1 \pmod {625} \iff \\ 124 \, x &= 625 \, q + 1 \quad (q \in \mathbb{Z}) \iff \\ 124 \, x - 625 \, q &= 1 \quad (q \in \mathbb{Z}) \iff \\ 124 \, x + 625 \, y &= 1 \quad (\*) \end{align} where $(\*)$ is a linear Diophantine equation in integer $x, y$. The solution algorithm involves the extended Euclidean algorithm. For the coefficients $a = 124, b = 625$ we get $g = \gcd(a,b) = \gcd(124, 625) = 1$ so we do not have to rescale and $g$ divides $c = 1$, so we have solutions. The solutions of the homogeneous equation to $(\*)$ $$ 124 \, x + 625 \,y = 0 $$ are $$ (x\_h, y\_h) = (625 \, t, -124 \, t) \quad (t \in \mathbb{Z}) $$ A particular solution of $(\*)$ is found using the extended Euclidean algorithm which gives ([link](https://www.wolframalpha.com/input/?i=egcd%28124,625%29)) $$ (x\_p, y\_p) = (-126, 25) $$ All solutions are found by adding a particular solution to the homogenous solutions: $$4 (x, y) = (625\, t - 126, -124\, t + 25) $$ The first component is $$ x = 625 \,t - 126 = 625 \, (t - 1) + 625 - 126 = 625 \, t' + 499 $$
We wish to solve the congruence $124x \equiv 1 \pmod{625}$, which means we must solve for the multiplicative inverse of $124 \pmod{625}$. Since $\gcd(124, 625) = 1$, $124$ has a multiplicative inverse modulo $625$. To find the inverse, we use the extended Euclidean algorithm. \begin{align\*} 625 & = 5 \cdot 124 + 5\\ 124 & = 24 \cdot 5 + 4\\ 5 & = 1 \cdot 4 + 1\\ 4 & = 4 \cdot 1 \end{align\*} Now, we work backwards to write $1$ as a linear combination of $124$ and $625$. \begin{align\*} 1 & = 5 - 4\\ & = 5 - (124 - 24 \cdot 5)\\ & = 25 \cdot 5 - 124\\ & = 25(625 - 5 \cdot 124) - 124\\ & = 25 \cdot 625 - 126 \cdot 124 \end{align\*} Hence, $-126 \cdot 124 \equiv 1 \pmod{625}$. Thus, $x \equiv 124^{-1} \equiv -126 \equiv 499 \pmod{625}$.
5,985,281
WordPress does't give `ul.sub-menu` any unique classes (yet)... Here is my HTML: ``` <ul id="menu-primary" class="nav"> <li>News <ul class="sub-menu"> <li>Local</li> <li>Politics</li> </ul> </li> <li>Sports <ul class="sub-menu"> <li>Baseball</li> <li>Football</li> </ul> </li> <li>Opinion <ul class="sub-menu"> <li>Forums</li> <li>Blogs</li> </ul> </li> ``` Using jQuery I can .addClass to the first one only. ``` jQuery(document).ready(function($){ $('ul.sub-menu').addClass (function() { return "item-" + $(this).index(); }); ``` The result is this: ``` <ul id="menu-primary" class="nav"> <li>News <ul class="sub-menu item-1"> <li>Local</li> <li>Politics</li> </ul> </li> <li>Sports <ul class="sub-menu"> <li>Baseball</li> <li>Football</li> </ul> </li> <li>Opinion <ul class="sub-menu"> <li>Forums</li> <li>Blogs</li> </ul> </li> ``` That's great, but **how do I assign a unique class to EACH** `ul.sub-menu`?
2011/05/12
[ "https://Stackoverflow.com/questions/5985281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/226210/" ]
try this code, should do the work. ``` $(function(){ $('ul.sub-menu').addClass (function(idx) { return "item-" + idx; }); }); ``` you can test it here : <http://jsfiddle.net/dvdPd/17/>
Haven't tested it.. but .each() would be the function you need. ``` $('ul.sub-menu').each(function(index) { $(this).addClass("item-" + index); }); ```
34,523,192
I have a `table` as below ``` Art PP No ArtDate ArtQty OPDate OPQTY 102844 1100023223 02-09-2015 0 31-08-2015 0 102844 1100023766 03-11-2015 0 05-11-2015 1 102844 1100023766 03-11-2015 1 05-11-2015 149 102844 1100023766 03-11-2015 149 05-11-2015 1 ``` I need to `group by` and expected answer ``` Art PP No ArtDate ArtQty OPDate OPQTY 102844 1100023223 02-09-2015 0 31-08-2015 0 102844 1100023766 03-11-2015 150 05-11-2015 151 ``` How to achieve this?
2015/12/30
[ "https://Stackoverflow.com/questions/34523192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5210741/" ]
Normally Port use to get configured in the Configuration Files it self, available in either under "/etc/hadoop/conf/" or "/usr/local/hadoop/conf/" location "hadoop" with respected names like "pig/hive/sqoop" etc. The Configuration named as "hdfs-site.xml/core-site.xml/hive-site.xml/mapred-site.xml...etc" Some of the default Ports Used by Hadoop and it's Eco Systmems are: ``` Daemon Default Port Configuration Paramete Namenode 50070 dfs.http.address Datanodes 50075 dfs.datanode.http.address Secondarynamenode 50090 dfs.secondary.http.address Backup/Checkpoint node 50105 dfs.backup.http.address Jobracker 50030 mapred.job.tracker.http.address Tasktrackers 50060 mapred.task.tracker.http.address ``` Also Check Reference: [MORE DETAIL PORTS](http://www.cloudera.com/content/www/en-us/documentation/enterprise/5-2-x/topics/cdh_ig_ports_cdh5.html)
You can take advantage of Cloudera Distribution of Hadoop post numbers for each components : [Ports Used by Components of CDH 5](http://www.cloudera.com/content/www/en-us/documentation/enterprise/latest/topics/cdh_ig_ports_cdh5.html)
2,040,216
``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Davey Whitney</title> <link rel="shortcut icon" href="http://daveywhitney.com/images/favicon.ico" /> <script src="js/jquery.js" type="text/javascript"><!--mce:0--></script> <script src="js/jquery.lightbox-0.5.min.js" type="text/javascript"><!--mce:1--></script> <script src="js/jquery.jparallax.js" type="text/javascript"><!--mce:2--></script> <script src="js/jquery.easing.1.3.js" type="text/javascript"></script> <meta name="keywords" content="Davey Whitney,Davey,Whitney,Web Designer,Web Design,Web Development,Web" /> <meta name="description" content="Davey Whitney - Web Developer and so much more..." /> <link rel="stylesheet" href="style.css" type="text/css" media="all" /> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery('#parallax') .animate( {duration: '2000', easing: 'easeInSine' }) .jparallax({yparallax:false},{xtravel: '100%'},{xtravel: '300px'}); }); </script> </head> <body bgcolor="#ffffff"> <div id="wrapper"> <div id="icons"> <a href="mailto:[email protected]" target="_blank"> <img src="http://daveywhitney.com/images/gmail.png" border="0" /> </a> <a href="http://www.linkedin.com/pub/davey-whitney/15/a15/86a" target="_blank"> <img src="http://daveywhitney.com/images/linkedin.png" border="0" /> </a> <a href="http://twitter.com/daveywhitney" target="_blank"> <img src="http://daveywhitney.com/images/twitter.png" border="0" /> </a> <a href="http://www.facebook.com/home.php?#/profile.php?ref=profile&id=13810754" target="_blank"> <img src="http://daveywhitney.com/images/facebook.png" border="0" /> </a> </div> <div id="copyright"> &copy; <a href="mailto:[email protected]" target="_blank">Davey Whitney</a> </div> <div id="parallax"> <img style="width: 61px;" src="http://daveywhitney.com/images/merun.png" alt="" /> </div> </div> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-12009950-2"); pageTracker._trackPageview(); } catch(err) {}</script> </body> </html> ``` css ``` #wrapper { width:1200px; } #icons { padding:100px 0 0 0; margin:0 auto; width:530px; border:0; } #copyright { width:150px; margin:50px auto; } #copyright a:link { color: #3F7BCA; } #copyright a:hover { color: #F28900; } a { text-decoration:none; } #parallax { position:relative; overflow:hidden; width:100%; height:98px; border:none; margin:0 auto 20px auto; padding-top: 30px; } ``` Here is the site: <http://daveywhitney.com/>
2010/01/11
[ "https://Stackoverflow.com/questions/2040216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194832/" ]
It's because it's rendering in [quirks mode](http://en.wikipedia.org/wiki/Quirks_mode) - IE doesn't like **anything** before the DOCTYPE. Remove the comment and it should render in **standards mode** (his live site contained a large comment before the DOCTYPE which isn't visible in the question). From Wikipedia: > > Quirks mode in any version of IE will > also be triggered if anything but > whitespace precedes the DOCTYPE. For > example, if a hypertext document > contains a comment or any tag before > the DOCTYPE, IE will use quirks mode: > > > > ``` > <!-- This comment will put IE 6, 7 and 8 in quirks mode --> > <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" > "http://www.w3.org/TR/html4/strict.dtd"> > > ``` > >
If you are talking about IE6, then it is because IE6 is an outdated browser that doesn't support many common html and css tools.
2,040,216
``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Davey Whitney</title> <link rel="shortcut icon" href="http://daveywhitney.com/images/favicon.ico" /> <script src="js/jquery.js" type="text/javascript"><!--mce:0--></script> <script src="js/jquery.lightbox-0.5.min.js" type="text/javascript"><!--mce:1--></script> <script src="js/jquery.jparallax.js" type="text/javascript"><!--mce:2--></script> <script src="js/jquery.easing.1.3.js" type="text/javascript"></script> <meta name="keywords" content="Davey Whitney,Davey,Whitney,Web Designer,Web Design,Web Development,Web" /> <meta name="description" content="Davey Whitney - Web Developer and so much more..." /> <link rel="stylesheet" href="style.css" type="text/css" media="all" /> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery('#parallax') .animate( {duration: '2000', easing: 'easeInSine' }) .jparallax({yparallax:false},{xtravel: '100%'},{xtravel: '300px'}); }); </script> </head> <body bgcolor="#ffffff"> <div id="wrapper"> <div id="icons"> <a href="mailto:[email protected]" target="_blank"> <img src="http://daveywhitney.com/images/gmail.png" border="0" /> </a> <a href="http://www.linkedin.com/pub/davey-whitney/15/a15/86a" target="_blank"> <img src="http://daveywhitney.com/images/linkedin.png" border="0" /> </a> <a href="http://twitter.com/daveywhitney" target="_blank"> <img src="http://daveywhitney.com/images/twitter.png" border="0" /> </a> <a href="http://www.facebook.com/home.php?#/profile.php?ref=profile&id=13810754" target="_blank"> <img src="http://daveywhitney.com/images/facebook.png" border="0" /> </a> </div> <div id="copyright"> &copy; <a href="mailto:[email protected]" target="_blank">Davey Whitney</a> </div> <div id="parallax"> <img style="width: 61px;" src="http://daveywhitney.com/images/merun.png" alt="" /> </div> </div> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-12009950-2"); pageTracker._trackPageview(); } catch(err) {}</script> </body> </html> ``` css ``` #wrapper { width:1200px; } #icons { padding:100px 0 0 0; margin:0 auto; width:530px; border:0; } #copyright { width:150px; margin:50px auto; } #copyright a:link { color: #3F7BCA; } #copyright a:hover { color: #F28900; } a { text-decoration:none; } #parallax { position:relative; overflow:hidden; width:100%; height:98px; border:none; margin:0 auto 20px auto; padding-top: 30px; } ``` Here is the site: <http://daveywhitney.com/>
2010/01/11
[ "https://Stackoverflow.com/questions/2040216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194832/" ]
It's because it's rendering in [quirks mode](http://en.wikipedia.org/wiki/Quirks_mode) - IE doesn't like **anything** before the DOCTYPE. Remove the comment and it should render in **standards mode** (his live site contained a large comment before the DOCTYPE which isn't visible in the question). From Wikipedia: > > Quirks mode in any version of IE will > also be triggered if anything but > whitespace precedes the DOCTYPE. For > example, if a hypertext document > contains a comment or any tag before > the DOCTYPE, IE will use quirks mode: > > > > ``` > <!-- This comment will put IE 6, 7 and 8 in quirks mode --> > <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" > "http://www.w3.org/TR/html4/strict.dtd"> > > ``` > >
Because IE is obviously garbage...IE6 at least, IE8 is pretty good. Make sure you aren't using any CSS3 features, Opera is the only one that supports most of that. Also, validate your page, if you fix the issues it finds, most of your problems will probably be resolved.
25,315,329
I am new to PowerShell and am writing a script to get the hash of a directory and store it in a .txt file. I then want to compare it to an earlier version and check for changes. If there are changes, I want a new .txt or .html file containing which line items have changed, with last modified dates. So far, I've gotten the comparison to work, and the resulting steps based upon the pass/fail work fine. What I need help with is outputting the results into a .txt file that lists only the files that have changed, with fields of Algorithm, Hash, Filename, Last edit time. I know I can use ``` (Get-Item $source).LastWriteTime ``` To fetch the write time, but I need to do it for every file in the directory, not just the .txt file that contains the hash. ``` # Variables $Hashstore = "d:\baseline.txt" $HashCompare = "d:\hashcompare.txt" $HashTemp = "d:\hashtemp.txt" $FileDir = "d:\New2" $DateTime = Get-Date -format M.d.yyyy.hh.mm.ss # Email Variables $smtp_server = '<yourSMTPServer>' $to_email = '<email>' $from_email = '<email>' $dns_server = "<yourExternalDNSServer>" $domain = "<yourDomain>" # Check if Baseline.txt Exists If (Test-Path $Hashstore) # // File exists {} Else { # // File does not exist - Should never happen! $RefreshHash = dir $FileDir | Get-FileHash -Algorithm MD5 $RefreshHash | Out-File $Hashstore } # Generate new Compare Hash.txt $HashNew = dir $FileDir -Recurse | Get-FileHash -Algorithm MD5 $HashNew | Out-File $HashCompare # Get Hash of baseline.txt $HashBaseline = Get-FileHash -Path d:\baseline.txt -Algorithm MD5 #Get Hash of hashcompare.txt $HashDiff = Get-FileHash -Path d:\hashcompare.txt -Algorithm MD5 #If changed, output hash to storage, and flag changes If ($HashBaseline.hash -eq $HashDiff.hash) { Add-Content -Path d:\success.$DateTime.txt -Value " Source Files ARE EQUAL </p>" } else { Add-Content -Path d:\failure.$DateTime.html -Value "Source Files NOT EQUAL </p>" $HashNew | Out-File $HashTemp } # Compare two logs, send email if there is a change If ($diff_results) { #$evt_message = Get-Content .\domain.new.txt | Out-String #Write-EventLog -LogName Application -EventId 9000 -EntryType Error -Source "Maximo Validation Script" -Message $evt_message #Send-MailMessage -To $to_email -From $from_email -SmtpServer $smtp_server -Attachments .\domain.new.txt -Subject "ALERT! Change in Records" -Body "A change has been detected in the Maximo system files.`n`n`tACTION REQUIRED!`n`nVerify that this change was authorized." } If ($HashNew.HashString -eq $Hashstore.HashString) { } else { $HashTemp | Out-File $HashStore } ``` I know the add-item may not be the best way to write to this log I'm creating. What would be the best way to add the last write time to every file that is read?
2014/08/14
[ "https://Stackoverflow.com/questions/25315329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2253884/" ]
Here is a clean way to ouput the information you need (Algorithm, Hash, Filename, Last edit time) for each file that has changed : ``` $Hashstore = "d:\baseline.txt" $HashCompare = "d:\hashcompare.txt" $HashTemp = "d:\hashtemp.txt" $FileDir = "d:\New2" $DateTime = Get-Date -format M.d.yyyy.hh.mm.ss # Check if Baseline.txt Exists If (Test-Path $Hashstore) # // File exists { } Else { # // File does not exist - Should never happen! $RefreshHash = dir $FileDir -Recurse | Get-FileHash -Algorithm MD5 $RefreshHash | Export-Csv -Path $Hashstore -NoTypeInformation -Force } # Generate new Compare Hash.txt $HashNew = dir $FileDir -Recurse | Get-FileHash -Algorithm MD5 $HashNew | Export-Csv -Path $HashCompare -NoTypeInformation -Force # Get Hash of baseline.txt $HashBaseline = Get-FileHash -Path $Hashstore -Algorithm MD5 #Get Hash of hashcompare.txt $HashDiff = Get-FileHash -Path $HashCompare -Algorithm MD5 #If changed, output hash to storage, and flag changes If ($HashBaseline.hash -eq $HashDiff.hash) { Add-Content -Path D:\success.$DateTime.txt -Value " Source Files ARE EQUAL </p>" } Else { Add-Content -Path D:\failure.$DateTime.txt -Value "Source Files NOT EQUAL </p>" $HashNew | Export-Csv -Path $HashTemp -NoTypeInformation -Force # Storing a collection of differences in $Diffs $Diffs = Compare-Object -ReferenceObject (Import-Csv $Hashstore) -DifferenceObject (Import-Csv $HashCompare) Foreach ($Diff in $Diffs) { $DiffHashInfo = $Diff | Select-Object -ExpandProperty InputObject $DiffFileInfo = Get-ChildItem -Path $DiffHashInfo.Path # Creating a list of properties for the information you need $DiffObjProperties = [ordered]@{'Algorithm'=$DiffHashInfo.Algorithm 'Hash'=$DiffHashInfo.Hash 'Filename'=$DiffFileInfo.Name 'Last edit time'=$DiffFileInfo.LastWriteTime } # Building a custom object from the list of properties in $DiffObjProperties $DiffObj = New-Object -TypeName psobject -Property $DiffObjProperties $DiffObj } } ``` Before creating the files $Hashstore and $HashCompare, I convert the information they contain to CSV format, rather than plain text. It makes their content much easier to manipulate later , using Import-CSV. This makes proper objects with properties I can use. This also makes them easier to compare, and the result of this comparison ($Diffs) is a collection of these proper objects. So $Diffs contains all the files that have changed and I loop through each of them in a Foreach statement. This allows you to create a custom object ($DiffObj) with exactly the information you need ($DiffObjProperties) for each of the file that have changed.
PowerShell v3+ Recursive Directory Diff Using MD5 Hashing --------------------------------------------------------- I use this pure PowerShell (no dependencies) recursive file content diff. It calculates in-memory the MD5 hash (the algorithm is configurable) for each directories file contents and gives results in standard PowerShell [Compare-Object](https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.utility/compare-object) format. It can optionally export to CSV files along with a summary text file. It can either drop the rdiff.ps1 file into your path or copy the contents into your script. **`USAGE: rdiff path/to/left,path/to/right [-s path/to/summary/dir]`** Here is the [gist](https://gist.github.com/cchamberlain/883959151aa1162e73f1). I copied below for reference but I recommend using the gist version as I will be adding new features to it over time. ``` ######################################################################### ### USAGE: rdiff path/to/left,path/to/right [-s path/to/summary/dir] ### ### ADD LOCATION OF THIS SCRIPT TO PATH ### ######################################################################### [CmdletBinding()] param ( [parameter(HelpMessage="Stores the execution working directory.")] [string]$ExecutionDirectory=$PWD, [parameter(Position=0,HelpMessage="Compare two directories recursively for differences.")] [alias("c")] [string[]]$Compare, [parameter(HelpMessage="Export a summary to path.")] [alias("s")] [string]$ExportSummary ) ### FUNCTION DEFINITIONS ### # SETS WORKING DIRECTORY FOR .NET # function SetWorkDir($PathName, $TestPath) { $AbsPath = NormalizePath $PathName $TestPath Set-Location $AbsPath [System.IO.Directory]::SetCurrentDirectory($AbsPath) } # RESTORES THE EXECUTION WORKING DIRECTORY AND EXITS # function SafeExit() { SetWorkDir /path/to/execution/directory $ExecutionDirectory Exit } function Print { [CmdletBinding()] param ( [parameter(Mandatory=$TRUE,Position=0,HelpMessage="Message to print.")] [string]$Message, [parameter(HelpMessage="Specifies a success.")] [alias("s")] [switch]$SuccessFlag, [parameter(HelpMessage="Specifies a warning.")] [alias("w")] [switch]$WarningFlag, [parameter(HelpMessage="Specifies an error.")] [alias("e")] [switch]$ErrorFlag, [parameter(HelpMessage="Specifies a fatal error.")] [alias("f")] [switch]$FatalFlag, [parameter(HelpMessage="Specifies a info message.")] [alias("i")] [switch]$InfoFlag = !$SuccessFlag -and !$WarningFlag -and !$ErrorFlag -and !$FatalFlag, [parameter(HelpMessage="Specifies blank lines to print before.")] [alias("b")] [int]$LinesBefore=0, [parameter(HelpMessage="Specifies blank lines to print after.")] [alias("a")] [int]$LinesAfter=0, [parameter(HelpMessage="Specifies if program should exit.")] [alias("x")] [switch]$ExitAfter ) PROCESS { if($LinesBefore -ne 0) { foreach($i in 0..$LinesBefore) { Write-Host "" } } if($InfoFlag) { Write-Host "$Message" } if($SuccessFlag) { Write-Host "$Message" -ForegroundColor "Green" } if($WarningFlag) { Write-Host "$Message" -ForegroundColor "Orange" } if($ErrorFlag) { Write-Host "$Message" -ForegroundColor "Red" } if($FatalFlag) { Write-Host "$Message" -ForegroundColor "Red" -BackgroundColor "Black" } if($LinesAfter -ne 0) { foreach($i in 0..$LinesAfter) { Write-Host "" } } if($ExitAfter) { SafeExit } } } # VALIDATES STRING MIGHT BE A PATH # function ValidatePath($PathName, $TestPath) { If([string]::IsNullOrWhiteSpace($TestPath)) { Print -x -f "$PathName is not a path" } } # NORMALIZES RELATIVE OR ABSOLUTE PATH TO ABSOLUTE PATH # function NormalizePath($PathName, $TestPath) { ValidatePath "$PathName" "$TestPath" $TestPath = [System.IO.Path]::Combine((pwd).Path, $TestPath) $NormalizedPath = [System.IO.Path]::GetFullPath($TestPath) return $NormalizedPath } # VALIDATES STRING MIGHT BE A PATH AND RETURNS ABSOLUTE PATH # function ResolvePath($PathName, $TestPath) { ValidatePath "$PathName" "$TestPath" $ResolvedPath = NormalizePath $PathName $TestPath return $ResolvedPath } # VALIDATES STRING RESOLVES TO A PATH AND RETURNS ABSOLUTE PATH # function RequirePath($PathName, $TestPath, $PathType) { ValidatePath $PathName $TestPath If(!(Test-Path $TestPath -PathType $PathType)) { Print -x -f "$PathName ($TestPath) does not exist as a $PathType" } $ResolvedPath = Resolve-Path $TestPath return $ResolvedPath } # Like mkdir -p -> creates a directory recursively if it doesn't exist # function MakeDirP { [CmdletBinding()] param ( [parameter(Mandatory=$TRUE,Position=0,HelpMessage="Path create.")] [string]$Path ) PROCESS { New-Item -path $Path -itemtype Directory -force | Out-Null } } # GETS ALL FILES IN A PATH RECURSIVELY # function GetFiles { [CmdletBinding()] param ( [parameter(Mandatory=$TRUE,Position=0,HelpMessage="Path to get files for.")] [string]$Path ) PROCESS { ls $Path -r | where { !$_.PSIsContainer } } } # GETS ALL FILES WITH CALCULATED HASH PROPERTY RELATIVE TO A ROOT DIRECTORY RECURSIVELY # # RETURNS LIST OF @{RelativePath, Hash, FullName} function GetFilesWithHash { [CmdletBinding()] param ( [parameter(Mandatory=$TRUE,Position=0,HelpMessage="Path to get directories for.")] [string]$Path, [parameter(HelpMessage="The hash algorithm to use.")] [string]$Algorithm="MD5" ) PROCESS { $OriginalPath = $PWD SetWorkDir path/to/diff $Path GetFiles $Path | select @{N="RelativePath";E={$_.FullName | Resolve-Path -Relative}}, @{N="Hash";E={(Get-FileHash $_.FullName -Algorithm $Algorithm | select Hash).Hash}}, FullName SetWorkDir path/to/original $OriginalPath } } # COMPARE TWO DIRECTORIES RECURSIVELY # # RETURNS LIST OF @{RelativePath, Hash, FullName} function DiffDirectories { [CmdletBinding()] param ( [parameter(Mandatory=$TRUE,Position=0,HelpMessage="Directory to compare left.")] [alias("l")] [string]$LeftPath, [parameter(Mandatory=$TRUE,Position=1,HelpMessage="Directory to compare right.")] [alias("r")] [string]$RightPath ) PROCESS { $LeftHash = GetFilesWithHash $LeftPath $RightHash = GetFilesWithHash $RightPath diff -ReferenceObject $LeftHash -DifferenceObject $RightHash -Property RelativePath,Hash } } ### END FUNCTION DEFINITIONS ### ### PROGRAM LOGIC ### if($Compare.length -ne 2) { Print -x "Compare requires passing exactly 2 path parameters separated by comma, you passed $($Compare.length)." -f } Print "Comparing $($Compare[0]) to $($Compare[1])..." -a 1 $LeftPath = RequirePath path/to/left $Compare[0] container $RightPath = RequirePath path/to/right $Compare[1] container $Diff = DiffDirectories $LeftPath $RightPath $LeftDiff = $Diff | where {$_.SideIndicator -eq "<="} | select RelativePath,Hash $RightDiff = $Diff | where {$_.SideIndicator -eq "=>"} | select RelativePath,Hash if($ExportSummary) { $ExportSummary = ResolvePath path/to/summary/dir $ExportSummary MakeDirP $ExportSummary $SummaryPath = Join-Path $ExportSummary summary.txt $LeftCsvPath = Join-Path $ExportSummary left.csv $RightCsvPath = Join-Path $ExportSummary right.csv $LeftMeasure = $LeftDiff | measure $RightMeasure = $RightDiff | measure "== DIFF SUMMARY ==" > $SummaryPath "" >> $SummaryPath "-- DIRECTORIES --" >> $SummaryPath "`tLEFT -> $LeftPath" >> $SummaryPath "`tRIGHT -> $RightPath" >> $SummaryPath "" >> $SummaryPath "-- DIFF COUNT --" >> $SummaryPath "`tLEFT -> $($LeftMeasure.Count)" >> $SummaryPath "`tRIGHT -> $($RightMeasure.Count)" >> $SummaryPath "" >> $SummaryPath $Diff | Format-Table >> $SummaryPath $LeftDiff | Export-Csv $LeftCsvPath -f $RightDiff | Export-Csv $RightCsvPath -f } $Diff SafeExit ```
25,315,329
I am new to PowerShell and am writing a script to get the hash of a directory and store it in a .txt file. I then want to compare it to an earlier version and check for changes. If there are changes, I want a new .txt or .html file containing which line items have changed, with last modified dates. So far, I've gotten the comparison to work, and the resulting steps based upon the pass/fail work fine. What I need help with is outputting the results into a .txt file that lists only the files that have changed, with fields of Algorithm, Hash, Filename, Last edit time. I know I can use ``` (Get-Item $source).LastWriteTime ``` To fetch the write time, but I need to do it for every file in the directory, not just the .txt file that contains the hash. ``` # Variables $Hashstore = "d:\baseline.txt" $HashCompare = "d:\hashcompare.txt" $HashTemp = "d:\hashtemp.txt" $FileDir = "d:\New2" $DateTime = Get-Date -format M.d.yyyy.hh.mm.ss # Email Variables $smtp_server = '<yourSMTPServer>' $to_email = '<email>' $from_email = '<email>' $dns_server = "<yourExternalDNSServer>" $domain = "<yourDomain>" # Check if Baseline.txt Exists If (Test-Path $Hashstore) # // File exists {} Else { # // File does not exist - Should never happen! $RefreshHash = dir $FileDir | Get-FileHash -Algorithm MD5 $RefreshHash | Out-File $Hashstore } # Generate new Compare Hash.txt $HashNew = dir $FileDir -Recurse | Get-FileHash -Algorithm MD5 $HashNew | Out-File $HashCompare # Get Hash of baseline.txt $HashBaseline = Get-FileHash -Path d:\baseline.txt -Algorithm MD5 #Get Hash of hashcompare.txt $HashDiff = Get-FileHash -Path d:\hashcompare.txt -Algorithm MD5 #If changed, output hash to storage, and flag changes If ($HashBaseline.hash -eq $HashDiff.hash) { Add-Content -Path d:\success.$DateTime.txt -Value " Source Files ARE EQUAL </p>" } else { Add-Content -Path d:\failure.$DateTime.html -Value "Source Files NOT EQUAL </p>" $HashNew | Out-File $HashTemp } # Compare two logs, send email if there is a change If ($diff_results) { #$evt_message = Get-Content .\domain.new.txt | Out-String #Write-EventLog -LogName Application -EventId 9000 -EntryType Error -Source "Maximo Validation Script" -Message $evt_message #Send-MailMessage -To $to_email -From $from_email -SmtpServer $smtp_server -Attachments .\domain.new.txt -Subject "ALERT! Change in Records" -Body "A change has been detected in the Maximo system files.`n`n`tACTION REQUIRED!`n`nVerify that this change was authorized." } If ($HashNew.HashString -eq $Hashstore.HashString) { } else { $HashTemp | Out-File $HashStore } ``` I know the add-item may not be the best way to write to this log I'm creating. What would be the best way to add the last write time to every file that is read?
2014/08/14
[ "https://Stackoverflow.com/questions/25315329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2253884/" ]
Here is a clean way to ouput the information you need (Algorithm, Hash, Filename, Last edit time) for each file that has changed : ``` $Hashstore = "d:\baseline.txt" $HashCompare = "d:\hashcompare.txt" $HashTemp = "d:\hashtemp.txt" $FileDir = "d:\New2" $DateTime = Get-Date -format M.d.yyyy.hh.mm.ss # Check if Baseline.txt Exists If (Test-Path $Hashstore) # // File exists { } Else { # // File does not exist - Should never happen! $RefreshHash = dir $FileDir -Recurse | Get-FileHash -Algorithm MD5 $RefreshHash | Export-Csv -Path $Hashstore -NoTypeInformation -Force } # Generate new Compare Hash.txt $HashNew = dir $FileDir -Recurse | Get-FileHash -Algorithm MD5 $HashNew | Export-Csv -Path $HashCompare -NoTypeInformation -Force # Get Hash of baseline.txt $HashBaseline = Get-FileHash -Path $Hashstore -Algorithm MD5 #Get Hash of hashcompare.txt $HashDiff = Get-FileHash -Path $HashCompare -Algorithm MD5 #If changed, output hash to storage, and flag changes If ($HashBaseline.hash -eq $HashDiff.hash) { Add-Content -Path D:\success.$DateTime.txt -Value " Source Files ARE EQUAL </p>" } Else { Add-Content -Path D:\failure.$DateTime.txt -Value "Source Files NOT EQUAL </p>" $HashNew | Export-Csv -Path $HashTemp -NoTypeInformation -Force # Storing a collection of differences in $Diffs $Diffs = Compare-Object -ReferenceObject (Import-Csv $Hashstore) -DifferenceObject (Import-Csv $HashCompare) Foreach ($Diff in $Diffs) { $DiffHashInfo = $Diff | Select-Object -ExpandProperty InputObject $DiffFileInfo = Get-ChildItem -Path $DiffHashInfo.Path # Creating a list of properties for the information you need $DiffObjProperties = [ordered]@{'Algorithm'=$DiffHashInfo.Algorithm 'Hash'=$DiffHashInfo.Hash 'Filename'=$DiffFileInfo.Name 'Last edit time'=$DiffFileInfo.LastWriteTime } # Building a custom object from the list of properties in $DiffObjProperties $DiffObj = New-Object -TypeName psobject -Property $DiffObjProperties $DiffObj } } ``` Before creating the files $Hashstore and $HashCompare, I convert the information they contain to CSV format, rather than plain text. It makes their content much easier to manipulate later , using Import-CSV. This makes proper objects with properties I can use. This also makes them easier to compare, and the result of this comparison ($Diffs) is a collection of these proper objects. So $Diffs contains all the files that have changed and I loop through each of them in a Foreach statement. This allows you to create a custom object ($DiffObj) with exactly the information you need ($DiffObjProperties) for each of the file that have changed.
Another my version. But without date/time. ``` # Check images. Display if differ # $file_path = "C:\Files" $last_state = "last_state.json" # Check last_state.json. If false - create new empty file. If (!(Test-Path $last_state)) { New-Item $last_state -ItemType file | Out-Null } $last_state_obj = Get-Content $last_state | ConvertFrom-Json # Get files list and hash. Also you can use -Recurse option Get-ChildItem $file_path -Filter *.* | Foreach-Object { if (!$_.PSIsContainer) { $current_state += @($_ | Get-FileHash -Algorithm MD5) } } # Compare hash ForEach ($current_file in $current_state) { if (($last_state_obj | where {$current_file.Path -eq $_.Path}).Hash -ne $current_file.Hash) { $changed += @($current_file) } } # Display changed files $changed # Save new hash to last_state.json $current_state | ConvertTo-JSON | Out-File $last_state ```
6,070,110
I have an MVC 3 application and am trying to display a custom validation error. The normal validation errors that are generated by the model, i.e. Required, are displayed on the page. Now I am checking if a user exists and if so, adding a error message: ``` if (userExists) ModelState.AddModelError("UserName", UserManagementResources.UserAlreadyExistsText); return View(model); ``` On the view I have a validation summary and a Html.ValidationMessage("UserName"), but neither one is displaying the error. I have used this successfully on other pages. The only difference with this page I can see is, that it uses the RequiredIf validator scripts. <http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx> Any ideas how to solve this problem are appreciated. Thanks. --- Edit I am returning the validation message through the Remote validation. If I look what the network is doing, it's returning the error message, but it is still not displayed on the view. ``` [Required] [DataType(DataType.EmailAddress)] [Remote("IsUserAvailable", "Validation", ErrorMessage = "Ein Benutzer mit dieser Email existiert bereits.")] [Display(Name = Resources.EmailText, ResourceType = typeof(Resources))] public string Email { get { return User.Email; } set { User.Email = value; } } ``` The View: ``` @Html.LabelFor(u => u.Email, Resources.Email + " (Login) *") @Html.EditorFor(u => u.Email) @Html.ValidationMessageFor(u => u.Email) <br clear="all" /> ``` The Remote Validation Controller: ``` public class ValidationController : Controller { public JsonResult IsUserAvailable(string Email) { bool userExists; using (var userModel = new UserManagementModel()) { userExists = userModel.UserExists(Email); } if(userExists) return Json(UserManagementResources.UserAlreadyExists, JsonRequestBehavior.AllowGet); else return Json(true, JsonRequestBehavior.AllowGet); } } ```
2011/05/20
[ "https://Stackoverflow.com/questions/6070110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669455/" ]
Why don't you use the [Remote validation](http://msdn.microsoft.com/en-us/library/gg508808%28v=vs.98%29.aspx) for this? Why posting back just to check if user exists? example: ``` public class RegisterModel { [Required] [Remote("UserNameExists", "Validation", "", ErrorMessage = "Username is already taken.")] [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed.")] [Display(Name = "Username")] public string UserName { get; set; } } ``` and create a Validation Controller having the `UserNameExists` method like ``` public JsonResult UserNameExists(string UserName) { var user = _db.Users.Where(x => x.username.Equals(UserName)); return user == null ? Json(true, JsonRequestBehavior.AllowGet) : Json(string.Format("{0} is not available.", register.UserName), JsonRequestBehavior.AllowGet); } ```
When you change the version of your jQuery.js you have to change the validation.js file as well. Different versions are not compatible to each other and you might see strange behaviour in different browsers when you mixup the files.
4,527,767
This is a question regarding Ajax Iframes. I have a function to open an Iframe, and set its source, however at some points I would need to open multiple Iframes, and set their sources accordingly. The second iframe should only open if the first one has not finished loading. Psudocode: // at some point ``` x = iframe; x.src = 'dothiscode.php' ``` // at some later point ``` if (x.src = not finished loading) y = new iframe; y.src = 'domorecode.php' else x.src = 'domorecode.php' ``` --- Thank you for your help!
2010/12/24
[ "https://Stackoverflow.com/questions/4527767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544931/" ]
You are breaking the MVC paradigm, as you said. The point of MVC is to split everything up into bite-size chunks so it is more manageable. That's how I see it at least. How would comments be created without a specific controller for them. The showing part on a `Post` is the easy part: ``` @comments = @post.comments ```
The more you deviate from the MVC paradigm, the more problems you'll have later on. For example, if you wanted to add admin views for your Comments, it would be easier to expand on it through the Comments Controller. Else, you'll end up having multiple actions for your comment in the Posts controller (eg. approve\_comment, delete\_comment, voteup\_comment, etc). That being said, you can always wire things up so that actions on your comments direct the user back to the Post that originated it. So, comment related actions will reside in the Comments Controller, but the user is generally working with Posts (and its associated Comments).
4,527,767
This is a question regarding Ajax Iframes. I have a function to open an Iframe, and set its source, however at some points I would need to open multiple Iframes, and set their sources accordingly. The second iframe should only open if the first one has not finished loading. Psudocode: // at some point ``` x = iframe; x.src = 'dothiscode.php' ``` // at some later point ``` if (x.src = not finished loading) y = new iframe; y.src = 'domorecode.php' else x.src = 'domorecode.php' ``` --- Thank you for your help!
2010/12/24
[ "https://Stackoverflow.com/questions/4527767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544931/" ]
There is a fundamental distinction to be made between the **internal domain model** of your system and the **public interface** your system exposes. If you are using a relational database, it is good practice to have ``` Comment.belongs_to :post Post.has_many :comments ``` The internal domain model of your system can help you design your public interface - but you can also tailor your public interface how you want it, without being forced to make it a strict reflection of your internal domain model! In your case, I would suggest having a `CommentsController`. But in this controller class, you do *not* need all of the normal REST actions. You only need a few of them. ``` # app/controllers/comments_controller.rb class CommentsController < ApplicationController respond_to :js def create @post = Post.find(params[:post_id]) @comment = post.comments.create(params[:comment]) respond_with [@post, @comment] end end ``` In this controller, you *only* have a `create` action which would be the target of the "new comment" form at the bottom of the page displaying a post. You do not need any of the other REST actions because people never view, edit, or delete a comment in isolation - they only create new ones, and not from a dedicated new-comment page either. The routing for this is as follows: ``` # config/routes.rb MyApp::Application.routes.draw do resources :posts do resources :comments, :only => [:create] end end ```
The more you deviate from the MVC paradigm, the more problems you'll have later on. For example, if you wanted to add admin views for your Comments, it would be easier to expand on it through the Comments Controller. Else, you'll end up having multiple actions for your comment in the Posts controller (eg. approve\_comment, delete\_comment, voteup\_comment, etc). That being said, you can always wire things up so that actions on your comments direct the user back to the Post that originated it. So, comment related actions will reside in the Comments Controller, but the user is generally working with Posts (and its associated Comments).
30,642,363
I want to create zig-zag layout same as following attached image: ![Zig-Zag](https://i.stack.imgur.com/cBVEn.jpg) I tried a lot by creating diagonal lines and arranging them with icon but couldn't make it same. I implemented diagonal lines with the help of accepted answer from following questions: 1. [Diagonal line across view](https://stackoverflow.com/questions/26278084/diagonal-line-across-view) 2. [How rotate line in Android XML?](https://stackoverflow.com/questions/15237582/how-rotate-line-in-android-xml) However I'm stuck to arrange lines with icons exactly same as in image.
2015/06/04
[ "https://Stackoverflow.com/questions/30642363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2629991/" ]
I created this custom [***ZigZagLayout.java***](https://docs.google.com/document/d/1K2KW7iPgfgvZfu4D4MClkAOzw7-2hYqg7wEDwPc-2sk/edit?usp=sharing) file to cater your requirement. You just have to update the package name in the 1st line. It basically extends `RelativeLayout`, so you can use it in your layout-xmls just like any other `ViewGroup` class. Once you have instantiated this layout, just add child-views to it like it is done for `RelativeLayout` via `addView(View child)`. Example code snippet with dynamically created view: ``` ZigZagLayout zigZagLayout = (ZigZagLayout) findViewById(R.id.layout_zigzag); Button btn = new Button(this); btn.setText("Test Button"); btn.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)); zigZagLayout.addView(btn); ``` I've also added few interfaces to this `ZigZagLayout` for your easy interaction like ability to set the connector-line stroke width, visibility, color, margins, etc. Try it out and let me know if it suffices your requirement. Cheers.
If you have layout for each circular item , you may use relative layout to align them, using align\_below, align\_left with margin, align\_right with margin tags. Please provide further detail, what are the lines connecting them and exactly what all are requirements for UI and functionality.
2,807,771
I know there are many algorithms to verify whether two line segments are intersected. The line segments I'm talking about are length line constructed by 2 end points. But once they encountered parallel condition, they just tell the user a big "No" and pretend there is no overlap, share end point, or end point collusion. I know I can can calculate the distance between 2 lines segments. If the distance is 0, check the end points located in the other line segments or not. And this means I have to use a lot of if else and && || conditions. This is not difficult, but my question is **"Is there a trick( or mathematics) method to calculate this special parallel case?"** **I hope this picture clarify my question <http://judark.myweb.hinet.net/parallel.JPG>**
2010/05/11
[ "https://Stackoverflow.com/questions/2807771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305662/" ]
Yes, given the formulas for both of the lines, test whether their slopes are equal. If they are, the lines are parallel and never intersect. If you have points on each of the lines, you can use the [slope formula](http://cs.selu.edu/~rbyrd/math/slope/). If both are perpendicular to the x-axis, they will both have infinite slopes, but they will be parallel. All points on each line will have equal x coordinates. To deal with line segments, calculate the point of intersection, then determine if that point of intersection exists for both of the segments.
I assume the case you're interested in is where the two line segments are parallel (as determined by checking the slope, as Whirlwind says), and you're trying to determine whether the two segments overlap. Rather than worrying about the distance between the lines, I would think the easiest way to do that would to if either endpoint of one segment lies within the other: ``` if (segment_contains_point(segment_A, segment_B.start) || segment_contains_point(segment_A, segment_B.end)) { // lines overlap } ```
2,807,771
I know there are many algorithms to verify whether two line segments are intersected. The line segments I'm talking about are length line constructed by 2 end points. But once they encountered parallel condition, they just tell the user a big "No" and pretend there is no overlap, share end point, or end point collusion. I know I can can calculate the distance between 2 lines segments. If the distance is 0, check the end points located in the other line segments or not. And this means I have to use a lot of if else and && || conditions. This is not difficult, but my question is **"Is there a trick( or mathematics) method to calculate this special parallel case?"** **I hope this picture clarify my question <http://judark.myweb.hinet.net/parallel.JPG>**
2010/05/11
[ "https://Stackoverflow.com/questions/2807771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305662/" ]
Yes, given the formulas for both of the lines, test whether their slopes are equal. If they are, the lines are parallel and never intersect. If you have points on each of the lines, you can use the [slope formula](http://cs.selu.edu/~rbyrd/math/slope/). If both are perpendicular to the x-axis, they will both have infinite slopes, but they will be parallel. All points on each line will have equal x coordinates. To deal with line segments, calculate the point of intersection, then determine if that point of intersection exists for both of the segments.
Let's assume that you have two lines described by formulas `a.x + b.y + c = 0` and `d.x + e.y + f = 0`. The two lines are parallel when `a = 0 and d = 0` or `b/a = e/d`. Perhaps instead of doing the division just make sure that `b.d = a.e`.
2,807,771
I know there are many algorithms to verify whether two line segments are intersected. The line segments I'm talking about are length line constructed by 2 end points. But once they encountered parallel condition, they just tell the user a big "No" and pretend there is no overlap, share end point, or end point collusion. I know I can can calculate the distance between 2 lines segments. If the distance is 0, check the end points located in the other line segments or not. And this means I have to use a lot of if else and && || conditions. This is not difficult, but my question is **"Is there a trick( or mathematics) method to calculate this special parallel case?"** **I hope this picture clarify my question <http://judark.myweb.hinet.net/parallel.JPG>**
2010/05/11
[ "https://Stackoverflow.com/questions/2807771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305662/" ]
Yes, given the formulas for both of the lines, test whether their slopes are equal. If they are, the lines are parallel and never intersect. If you have points on each of the lines, you can use the [slope formula](http://cs.selu.edu/~rbyrd/math/slope/). If both are perpendicular to the x-axis, they will both have infinite slopes, but they will be parallel. All points on each line will have equal x coordinates. To deal with line segments, calculate the point of intersection, then determine if that point of intersection exists for both of the segments.
i found this (modified a little by me to suit) it will return the intercetion x,y else if no intercetion found it will return -1,-1 ``` Public Function intercetion(ByVal ax As Integer, ByVal ay As Integer, ByVal bx As Integer, ByVal by As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal dx As Integer, ByVal dy As Integer) As Point '// Determines the intersection point of the line segment defined by points A and B '// with the line segment defined by points C and D. '// '// Returns YES if the intersection point was found, and stores that point in X,Y. '// Returns NO if there is no determinable intersection point, in which case X,Y will '// be unmodified. Dim distAB, theCos, theSin, newX, ABpos As Double '// Fail if either line segment is zero-length. If ax = bx And ay = by Or cx = dx And cy = dy Then Return New Point(-1, -1) '// Fail if the segments share an end-point. If ax = cx And ay = cy Or bx = cx And by = cy Or ax = dx And ay = dy Or bx = dx And by = dy Then Return New Point(-1, -1) '// (1) Translate the system so that point A is on the origin. bx -= ax by -= ay cx -= ax cy -= ay dx -= ax dy -= ay '// Discover the length of segment A-B. distAB = Math.Sqrt(bx * bx + by * by) '// (2) Rotate the system so that point B is on the positive X axis. theCos = bx / distAB theSin = by / distAB newX = cx * theCos + cy * theSin cy = cy * theCos - cx * theSin cx = newX newX = dx * theCos + dy * theSin dy = dy * theCos - dx * theSin dx = newX '// Fail if segment C-D doesn't cross line A-B. If cy < 0 And dy < 0 Or cy >= 0 And dy >= 0 Then Return New Point(-1, -1) '// (3) Discover the position of the intersection point along line A-B. ABpos = dx + (cx - dx) * dy / (dy - cy) '// Fail if segment C-D crosses line A-B outside of segment A-B. If ABpos < 0 Or ABpos > distAB Then Return New Point(-1, -1) '// (4) Apply the discovered position to line A-B in the original coordinate system. '*X=Ax+ABpos*theCos '*Y=Ay+ABpos*theSin '// Success. Return New Point(ax + ABpos * theCos, ay + ABpos * theSin) End Function ``` [Origin](http://alienryderflex.com/intersect/)
2,807,771
I know there are many algorithms to verify whether two line segments are intersected. The line segments I'm talking about are length line constructed by 2 end points. But once they encountered parallel condition, they just tell the user a big "No" and pretend there is no overlap, share end point, or end point collusion. I know I can can calculate the distance between 2 lines segments. If the distance is 0, check the end points located in the other line segments or not. And this means I have to use a lot of if else and && || conditions. This is not difficult, but my question is **"Is there a trick( or mathematics) method to calculate this special parallel case?"** **I hope this picture clarify my question <http://judark.myweb.hinet.net/parallel.JPG>**
2010/05/11
[ "https://Stackoverflow.com/questions/2807771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305662/" ]
Yes, given the formulas for both of the lines, test whether their slopes are equal. If they are, the lines are parallel and never intersect. If you have points on each of the lines, you can use the [slope formula](http://cs.selu.edu/~rbyrd/math/slope/). If both are perpendicular to the x-axis, they will both have infinite slopes, but they will be parallel. All points on each line will have equal x coordinates. To deal with line segments, calculate the point of intersection, then determine if that point of intersection exists for both of the segments.
I just got the same problem: The easiest way I have come up with just to check whether the lines overlap: Assuming the segments are colinear (parallel and have the same intersection with the x axis). Take one point A from the longer Segment (A,B) as starting point. Now find the point among the other three points that has the minimal distance to point A (squared Distance is better, even manhattan-length might work too) measuring the distance in the direction of B. If the closest point to A is B, the lines do not intersect. If it belongs to the other segment they do. Perhaps you have to check for special cases like zero length lines or identical lines but this should be easy.
12,322
On his retirement, Bill Gates left behind a four number combination safe with a dial similar to [this](http://thumbs.dreamstime.com/x/realistic-safe-combination-lock-wheel-23526580.jpg). In that safe is a secret that had eluded him many years ago...along with a small fortune of course. He left behind 10 clues - a deck of cards and a note. The order of the cards is as follows: > > Three of Spades, > Six of Spades, > Four of Spades, > Seven of Clubs, > Six of Clubs, > Five of Clubs, > Eight of Clubs, > Two of Clubs, > Four of Diamonds, > Five of Diamonds, > Five of Spades, > Two of Spades, > Six of Diamonds, > Eight of Hearts, > Three of Clubs, > Five of Hearts, > Three of Hearts, > Seven of Hearts, > Six of Hearts, > Two of Diamonds, > Eight of Spades, > Three of Diamonds, > Four of Clubs, > Seven of Spades, > Four of Hearts, > Two of Hearts, > Seven of Diamonds, > Eight of Diamonds, > > > The note reads: > > Sly snakes slither into eternity seeking stigma and style. > > > Is your knowledge potent enough to figure out the combination of the safe?
2015/04/17
[ "https://puzzling.stackexchange.com/questions/12322", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/11499/" ]
The combination is > > 37 - 2 - 60 - 41 > > > Explanation: > > If you lay out all cards in a row, and look at the layout of the pips on the card, they represent a 1 or 0 (1 if there is a centre pip, 0 if there isn't). 3, 5, 7 are 1s, and 2, 4, 6 are 0s. 8 represents the end of a number. > So 100101 - 0010 - 111100 - 101001 > > > Extra explanation of how I got here: > > This is based on a game called 'Petals around the rose' (related to the title), which is played with dice. Bill Gates struggled with finding out the solution to this game for many years. <http://www.borrett.id.au/computing/petals-bg.htm> > > > I don't quite know what the second clue is about yet. > > There are 10 clues, and 10 in binary is 2. > > >
Is your knowledge potent enough to figure out the combination of the safe? > > Possibly. Would calling a lock smith to open the safe and find out the combination work? Maybe finding out what those 10 clues he left behind are might help as well. ;-) > > > This might not be the answer you were looking for, but maybe it can inspire some other answers. (hopefully ones that aren't so lateral) Plot twist: > > The 'secret' in the safe is the combination to the safe! He never told anyone which keeps it a secret and then it eluded him (he forgot it) many years ago. Now he forgot the safe and no one else knows (since he never shared it) which is why it's still there! Why he would do this, who knows. But what kind of person would leave a deck of just 28 cards in the open? (Someone really smart or someone not so smart, for this twist I'll pretend not so smart) > > >
3,616,540
What is the best way to format XML within a PHP class. ``` $xml = "<element attribute=\"something\">...</element>"; $xml = '<element attribute="something">...</element>'; $xml = '<element attribute=\'something\'>...</element>'; $xml = <<<EOF <element attribute="something"> </element> EOF; ``` I'm pretty sure it is the last one!
2010/09/01
[ "https://Stackoverflow.com/questions/3616540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/436784/" ]
With [DOM](http://de.php.net/manual/en/book.dom.php) you can do ``` $dom = new DOMDocument; $dom->preserveWhiteSpace = FALSE; $dom->loadXML('<root><foo><bar>baz</bar></foo></root>'); $dom->formatOutput = TRUE; echo $dom->saveXML(); ``` gives ([live demo](http://codepad.org/hbS5iOQD)) ``` <?xml version="1.0"?> <root> <foo> <bar>baz</bar> </foo> </root> ``` See [`DOMDocument::formatOutput`](http://de.php.net/manual/en/class.domdocument.php#domdocument.props.formatoutput) and [`DOMDocument::preserveWhiteSpace`](http://de.php.net/manual/en/class.domdocument.php#domdocument.props.preservewhitespace) properties description.
//Here is example using XMLWriter ``` $w = new XMLWriter; $w->openMemory(); $w->setIndent(true); $w->startElement('foo'); $w->startElement('bar'); $w->writeElement("key", "value"); $w->endElement(); $w->endElement(); echo $w->outputMemory(); ``` //out put ``` <foo> <bar> <key>value</key> </bar> </foo> ```
3,616,540
What is the best way to format XML within a PHP class. ``` $xml = "<element attribute=\"something\">...</element>"; $xml = '<element attribute="something">...</element>'; $xml = '<element attribute=\'something\'>...</element>'; $xml = <<<EOF <element attribute="something"> </element> EOF; ``` I'm pretty sure it is the last one!
2010/09/01
[ "https://Stackoverflow.com/questions/3616540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/436784/" ]
This function works perfectlly as you want you don't have to use any xml dom library or nething just pass the xml generated string into it and it will parse and generate the new one with tabs and line breaks. ``` function formatXmlString($xml){ $xml = preg_replace('/(>)(<)(\/*)/', "$1\n$2$3", $xml); $token = strtok($xml, "\n"); $result = ''; $pad = 0; $matches = array(); while ($token !== false) : if (preg_match('/.+<\/\w[^>]*>$/', $token, $matches)) : $indent=0; elseif (preg_match('/^<\/\w/', $token, $matches)) : $pad--; $indent = 0; elseif (preg_match('/^<\w[^>]*[^\/]>.*$/', $token, $matches)) : $indent=1; else : $indent = 0; endif; $line = str_pad($token, strlen($token)+$pad, ' ', STR_PAD_LEFT); $result .= $line . "\n"; $token = strtok("\n"); $pad += $indent; endwhile; return $result; } ```
//Here is example using XMLWriter ``` $w = new XMLWriter; $w->openMemory(); $w->setIndent(true); $w->startElement('foo'); $w->startElement('bar'); $w->writeElement("key", "value"); $w->endElement(); $w->endElement(); echo $w->outputMemory(); ``` //out put ``` <foo> <bar> <key>value</key> </bar> </foo> ```
3,616,540
What is the best way to format XML within a PHP class. ``` $xml = "<element attribute=\"something\">...</element>"; $xml = '<element attribute="something">...</element>'; $xml = '<element attribute=\'something\'>...</element>'; $xml = <<<EOF <element attribute="something"> </element> EOF; ``` I'm pretty sure it is the last one!
2010/09/01
[ "https://Stackoverflow.com/questions/3616540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/436784/" ]
//Here is example using XMLWriter ``` $w = new XMLWriter; $w->openMemory(); $w->setIndent(true); $w->startElement('foo'); $w->startElement('bar'); $w->writeElement("key", "value"); $w->endElement(); $w->endElement(); echo $w->outputMemory(); ``` //out put ``` <foo> <bar> <key>value</key> </bar> </foo> ```
The first is better if you plan to embed values into the XML, The second is better for humans to read. Neither is good if you intend really work with XML. However if you intend to perform a simple fire and forget function that takes XML as a input parameter, then I would say use the first method because you will need to embed parameters at some point. I personally would use the PHP class simplexml, it's very easy to use and it's built in xpath support makes detailing the data returned in XML a dream.
3,616,540
What is the best way to format XML within a PHP class. ``` $xml = "<element attribute=\"something\">...</element>"; $xml = '<element attribute="something">...</element>'; $xml = '<element attribute=\'something\'>...</element>'; $xml = <<<EOF <element attribute="something"> </element> EOF; ``` I'm pretty sure it is the last one!
2010/09/01
[ "https://Stackoverflow.com/questions/3616540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/436784/" ]
With [DOM](http://de.php.net/manual/en/book.dom.php) you can do ``` $dom = new DOMDocument; $dom->preserveWhiteSpace = FALSE; $dom->loadXML('<root><foo><bar>baz</bar></foo></root>'); $dom->formatOutput = TRUE; echo $dom->saveXML(); ``` gives ([live demo](http://codepad.org/hbS5iOQD)) ``` <?xml version="1.0"?> <root> <foo> <bar>baz</bar> </foo> </root> ``` See [`DOMDocument::formatOutput`](http://de.php.net/manual/en/class.domdocument.php#domdocument.props.formatoutput) and [`DOMDocument::preserveWhiteSpace`](http://de.php.net/manual/en/class.domdocument.php#domdocument.props.preservewhitespace) properties description.
This function works perfectlly as you want you don't have to use any xml dom library or nething just pass the xml generated string into it and it will parse and generate the new one with tabs and line breaks. ``` function formatXmlString($xml){ $xml = preg_replace('/(>)(<)(\/*)/', "$1\n$2$3", $xml); $token = strtok($xml, "\n"); $result = ''; $pad = 0; $matches = array(); while ($token !== false) : if (preg_match('/.+<\/\w[^>]*>$/', $token, $matches)) : $indent=0; elseif (preg_match('/^<\/\w/', $token, $matches)) : $pad--; $indent = 0; elseif (preg_match('/^<\w[^>]*[^\/]>.*$/', $token, $matches)) : $indent=1; else : $indent = 0; endif; $line = str_pad($token, strlen($token)+$pad, ' ', STR_PAD_LEFT); $result .= $line . "\n"; $token = strtok("\n"); $pad += $indent; endwhile; return $result; } ```
3,616,540
What is the best way to format XML within a PHP class. ``` $xml = "<element attribute=\"something\">...</element>"; $xml = '<element attribute="something">...</element>'; $xml = '<element attribute=\'something\'>...</element>'; $xml = <<<EOF <element attribute="something"> </element> EOF; ``` I'm pretty sure it is the last one!
2010/09/01
[ "https://Stackoverflow.com/questions/3616540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/436784/" ]
With [DOM](http://de.php.net/manual/en/book.dom.php) you can do ``` $dom = new DOMDocument; $dom->preserveWhiteSpace = FALSE; $dom->loadXML('<root><foo><bar>baz</bar></foo></root>'); $dom->formatOutput = TRUE; echo $dom->saveXML(); ``` gives ([live demo](http://codepad.org/hbS5iOQD)) ``` <?xml version="1.0"?> <root> <foo> <bar>baz</bar> </foo> </root> ``` See [`DOMDocument::formatOutput`](http://de.php.net/manual/en/class.domdocument.php#domdocument.props.formatoutput) and [`DOMDocument::preserveWhiteSpace`](http://de.php.net/manual/en/class.domdocument.php#domdocument.props.preservewhitespace) properties description.
The first is better if you plan to embed values into the XML, The second is better for humans to read. Neither is good if you intend really work with XML. However if you intend to perform a simple fire and forget function that takes XML as a input parameter, then I would say use the first method because you will need to embed parameters at some point. I personally would use the PHP class simplexml, it's very easy to use and it's built in xpath support makes detailing the data returned in XML a dream.
3,616,540
What is the best way to format XML within a PHP class. ``` $xml = "<element attribute=\"something\">...</element>"; $xml = '<element attribute="something">...</element>'; $xml = '<element attribute=\'something\'>...</element>'; $xml = <<<EOF <element attribute="something"> </element> EOF; ``` I'm pretty sure it is the last one!
2010/09/01
[ "https://Stackoverflow.com/questions/3616540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/436784/" ]
This function works perfectlly as you want you don't have to use any xml dom library or nething just pass the xml generated string into it and it will parse and generate the new one with tabs and line breaks. ``` function formatXmlString($xml){ $xml = preg_replace('/(>)(<)(\/*)/', "$1\n$2$3", $xml); $token = strtok($xml, "\n"); $result = ''; $pad = 0; $matches = array(); while ($token !== false) : if (preg_match('/.+<\/\w[^>]*>$/', $token, $matches)) : $indent=0; elseif (preg_match('/^<\/\w/', $token, $matches)) : $pad--; $indent = 0; elseif (preg_match('/^<\w[^>]*[^\/]>.*$/', $token, $matches)) : $indent=1; else : $indent = 0; endif; $line = str_pad($token, strlen($token)+$pad, ' ', STR_PAD_LEFT); $result .= $line . "\n"; $token = strtok("\n"); $pad += $indent; endwhile; return $result; } ```
The first is better if you plan to embed values into the XML, The second is better for humans to read. Neither is good if you intend really work with XML. However if you intend to perform a simple fire and forget function that takes XML as a input parameter, then I would say use the first method because you will need to embed parameters at some point. I personally would use the PHP class simplexml, it's very easy to use and it's built in xpath support makes detailing the data returned in XML a dream.
576,071
The question is simple, I want to list all the user accounts which can log in to my system, but I'm not sure if that all the users in /etc/passwd are "could login" users? Details: I can see users whose shells are set to `/usr/sbin/nologin` and `/bin/false` in `/etc/passwd`, does that mean they cannot login? I also know that I can set the encrypted password of user to `*` or `!` in `/etc/shadow` to disable an account, so the "disabled user" should also be treat as "cannot log in" user, right?
2014/02/17
[ "https://serverfault.com/questions/576071", "https://serverfault.com", "https://serverfault.com/users/209632/" ]
A lot of this depends on your definition of "log in" -- technically any user who *exists* in `/etc/passwd` & `/etc/shadow` is a "valid user" and could theoretically log in under the right set of circumstances. The methods you're talking about fall into the following broad categories: * **Users with "locked" accounts** in `/etc/shadow` A user whose password is set to `*`, `!`, or some other hash that will never match is "locked out" (in the Sun days the convention was often `*LK*`, for "Locked"). These users can't log in *by typing a password*, but they **can** still log using other authentication mechanisms (SSH keys, for example). * **Users with a "non-interactive" shell** in `/etc/passwd` A user whose account has a "non-interactive shell" (`/bin/false`, `/sbin/nologin`) can't log in *interactively* -- i.e. they can't get a shell prompt to run commands at (this also prevents SSH command execution if the user has SSH keys on the system). These users may still be able to log in to do things like read/send email (via POP/IMAP & SMTP AUTH). Setting a non-interactive shell for users who should never need to use the shell (and for most "service accounts") is generally considered good practice. So depending on your criteria for "able to log in" you may want to check one or both of these things.
There is a difference between disabling the user and setting the shell to /bin/false or similar. Setting the shell to /bin/false prevents the user from getting a shell, but they can still log in to the system if local users are used for something else (mail authentication, ftp, and so on). Disabling the user makes it impossible for him to use any services of the server that use local users.
576,071
The question is simple, I want to list all the user accounts which can log in to my system, but I'm not sure if that all the users in /etc/passwd are "could login" users? Details: I can see users whose shells are set to `/usr/sbin/nologin` and `/bin/false` in `/etc/passwd`, does that mean they cannot login? I also know that I can set the encrypted password of user to `*` or `!` in `/etc/shadow` to disable an account, so the "disabled user" should also be treat as "cannot log in" user, right?
2014/02/17
[ "https://serverfault.com/questions/576071", "https://serverfault.com", "https://serverfault.com/users/209632/" ]
There is a difference between disabling the user and setting the shell to /bin/false or similar. Setting the shell to /bin/false prevents the user from getting a shell, but they can still log in to the system if local users are used for something else (mail authentication, ftp, and so on). Disabling the user makes it impossible for him to use any services of the server that use local users.
In addition to the above, users may be locked out from a system even though their password entry looks correct using several different methods. /etc/security/access.conf can be used to limit who can log in. There are many PAM modules that can be configured to restrict specific users, or modify login behavior based on need. (i.e. no home directory on the server disallows login.)
576,071
The question is simple, I want to list all the user accounts which can log in to my system, but I'm not sure if that all the users in /etc/passwd are "could login" users? Details: I can see users whose shells are set to `/usr/sbin/nologin` and `/bin/false` in `/etc/passwd`, does that mean they cannot login? I also know that I can set the encrypted password of user to `*` or `!` in `/etc/shadow` to disable an account, so the "disabled user" should also be treat as "cannot log in" user, right?
2014/02/17
[ "https://serverfault.com/questions/576071", "https://serverfault.com", "https://serverfault.com/users/209632/" ]
A lot of this depends on your definition of "log in" -- technically any user who *exists* in `/etc/passwd` & `/etc/shadow` is a "valid user" and could theoretically log in under the right set of circumstances. The methods you're talking about fall into the following broad categories: * **Users with "locked" accounts** in `/etc/shadow` A user whose password is set to `*`, `!`, or some other hash that will never match is "locked out" (in the Sun days the convention was often `*LK*`, for "Locked"). These users can't log in *by typing a password*, but they **can** still log using other authentication mechanisms (SSH keys, for example). * **Users with a "non-interactive" shell** in `/etc/passwd` A user whose account has a "non-interactive shell" (`/bin/false`, `/sbin/nologin`) can't log in *interactively* -- i.e. they can't get a shell prompt to run commands at (this also prevents SSH command execution if the user has SSH keys on the system). These users may still be able to log in to do things like read/send email (via POP/IMAP & SMTP AUTH). Setting a non-interactive shell for users who should never need to use the shell (and for most "service accounts") is generally considered good practice. So depending on your criteria for "able to log in" you may want to check one or both of these things.
In addition to the above, users may be locked out from a system even though their password entry looks correct using several different methods. /etc/security/access.conf can be used to limit who can log in. There are many PAM modules that can be configured to restrict specific users, or modify login behavior based on need. (i.e. no home directory on the server disallows login.)
70,729
Once in a while, some well-meaning user appends the string " [closed]" to a question title after receiving a good answer. This is, of course, confusing to people who, for example, visit the question later and don't see a "closed as *reason* by *voters* at *time*" box. I can't think of any case where this would be a desired behavior, so I propose rejecting any title that ends in " [closed]" except for the ones generated by the system for actually-closed questions. A quick explanation under "Oops! Your question couldn't be submitted because:" should be enough to make this feature non-confusing.
2010/11/22
[ "https://meta.stackexchange.com/questions/70729", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/131713/" ]
How about a distinct style for questions that are closed? Perhaps a red title or something of that sort would do.
> > How often does this actually happen? > > > There are 29 questions on SO that currently (as of Oct 31 data dump) have something like this in the title (I figured [closed], (closed), and {closed} would cover the vast majority of them), and an additional 39 questions where that same pattern has been edited out at one time or another. Only one of those 68 questions is actually closed. <http://odata.stackexchange.com/stackoverflow/s/653/closed-questions> I think editing the questions and leaving a comment (to say to leave it alone, except if it's a duplicate, in which case flag for mod attention) is probably sufficient. **EDIT:** I went in and manually edited the offending posts. I think I got all of them. Unfortunately we'll have to wait until January to see that reflected in the December data dump.
70,729
Once in a while, some well-meaning user appends the string " [closed]" to a question title after receiving a good answer. This is, of course, confusing to people who, for example, visit the question later and don't see a "closed as *reason* by *voters* at *time*" box. I can't think of any case where this would be a desired behavior, so I propose rejecting any title that ends in " [closed]" except for the ones generated by the system for actually-closed questions. A quick explanation under "Oops! Your question couldn't be submitted because:" should be enough to make this feature non-confusing.
2010/11/22
[ "https://meta.stackexchange.com/questions/70729", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/131713/" ]
You're right, there's no reason to ever allow this — added a check for it. EDIT: The filter has been updated to check for the strings "[migrated]", "[on hold]", and "[duplicate]" as well.
How about a distinct style for questions that are closed? Perhaps a red title or something of that sort would do.
70,729
Once in a while, some well-meaning user appends the string " [closed]" to a question title after receiving a good answer. This is, of course, confusing to people who, for example, visit the question later and don't see a "closed as *reason* by *voters* at *time*" box. I can't think of any case where this would be a desired behavior, so I propose rejecting any title that ends in " [closed]" except for the ones generated by the system for actually-closed questions. A quick explanation under "Oops! Your question couldn't be submitted because:" should be enough to make this feature non-confusing.
2010/11/22
[ "https://meta.stackexchange.com/questions/70729", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/131713/" ]
You're right, there's no reason to ever allow this — added a check for it. EDIT: The filter has been updated to check for the strings "[migrated]", "[on hold]", and "[duplicate]" as well.
> > How often does this actually happen? > > > There are 29 questions on SO that currently (as of Oct 31 data dump) have something like this in the title (I figured [closed], (closed), and {closed} would cover the vast majority of them), and an additional 39 questions where that same pattern has been edited out at one time or another. Only one of those 68 questions is actually closed. <http://odata.stackexchange.com/stackoverflow/s/653/closed-questions> I think editing the questions and leaving a comment (to say to leave it alone, except if it's a duplicate, in which case flag for mod attention) is probably sufficient. **EDIT:** I went in and manually edited the offending posts. I think I got all of them. Unfortunately we'll have to wait until January to see that reflected in the December data dump.
52,335,027
I am using LockableTrait <https://symfony.com/doc/current/console/lockable_trait.html> for preventing my command to be executed simultaneously. Because of error/timeout command is locked now so I can not run it again anymore without removing LockableTrait functionality. How can I can remove lock manually? Command line or so?
2018/09/14
[ "https://Stackoverflow.com/questions/52335027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5023525/" ]
I assume that you are running command with: `$ bin/console app:say-hello` This is how you can manually kill it. ``` $ ps aux | grep -i app:say-hello | awk {'print $2'} | xargs kill -9 ```
Yes you have to find and kill the process. Then you will able to run the command again. I'm assuming you are on linux, the commands will be different in Windows. To find the process: `pidof php` It should print an process id. To kill the process: `kill "id"`
33,243,112
I am trying to make a fixed header by putting my header content inside a div with a fixed position. Below is the CSS code for the div: ``` #page_header { background-color: white; height: auto; width: 100%; position: fixed; overflow: auto; } ``` and this is the effect of my div, (screenshot of the left top corner): [![left top corner of the div](https://i.stack.imgur.com/sqp9g.png)](https://i.stack.imgur.com/sqp9g.png) You can clearly see that there is a space between the div(white part) and the page, while it is not the case on the right side, how should I get rid of this space? Thanks.
2015/10/20
[ "https://Stackoverflow.com/questions/33243112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4619734/" ]
You need to make sure that your margins and padding are zeroed: ``` margin: 0; padding: 0; ``` Moreover, if you really want the thing fixed in place, the best thing is to lock it there. ``` position: fixed; top: 0; left:0; ```
You need to set the actual page to margin:0 and padding: 0 to the actual html, not just the body. use this in your css stylesheet. ``` *, html { margin:0; padding:0; } ``` that will set the whole page to 0, for a fresh clean start with no margin or paddings.
424,131
I'm using ipython Inside the python shell, when I press up instead of showing the last command, it prints ``` ^[[A ``` also CTRL-[keys] are fubar. CTRL-p prints ``` ^P ``` Everything is normal under terminal\bash My guess is that it is an encoding problem. I'd like to either enable the full encoding in ipython or changer the encoding of the shell which runs ipython. Or any other helpful information is welcome
2012/05/13
[ "https://superuser.com/questions/424131", "https://superuser.com", "https://superuser.com/users/1190/" ]
For me, I needed to create `~/.inputrc`, and fill it with my preferences. For me, this is: ``` set editing-mode emacs "\e[1;5C": forward-word "\e[1;5D": backward-word ``` The `\e[1;5C`, for me, is the sequence that means `Ctrl`+`→`. Yours is likely the same, but you can figure it out in bash by typing: `Ctrl`+`V`, `Ctrl`+`→`. For me, this shows, `^[[1;5C`, and you need to know that `^[` means "escape", which is the `\e` above. The rest (`[1;5C`) is just literal, copy it. `forward-word` is the command to execute on this key sequence, i.e., I want my Ctrl+arrows to skip words.
This worked for me (using OSX and pyenv): ``` CFLAGS="-I$(brew --prefix readline)/include -I$(brew --prefix openssl)/include -I$(xcrun --show-sdk-path)/usr/include" \ LDFLAGS="-L$(brew --prefix readline)/lib -L$(brew --prefix openssl)/lib" \ PYTHON_CONFIGURE_OPTS=--enable-unicode=ucs2 \ pyenv install -v 2.7.11 ``` Source: <https://medium.com/@pimterry/setting-up-pyenv-on-os-x-with-homebrew-56c7541fd331#.urbdkrc9l>
424,131
I'm using ipython Inside the python shell, when I press up instead of showing the last command, it prints ``` ^[[A ``` also CTRL-[keys] are fubar. CTRL-p prints ``` ^P ``` Everything is normal under terminal\bash My guess is that it is an encoding problem. I'd like to either enable the full encoding in ipython or changer the encoding of the shell which runs ipython. Or any other helpful information is welcome
2012/05/13
[ "https://superuser.com/questions/424131", "https://superuser.com", "https://superuser.com/users/1190/" ]
First, you can try ``` pip install readline ``` Also, please see whether you have `libncurses5-dev` or the equivalent.
This worked for me (using OSX and pyenv): ``` CFLAGS="-I$(brew --prefix readline)/include -I$(brew --prefix openssl)/include -I$(xcrun --show-sdk-path)/usr/include" \ LDFLAGS="-L$(brew --prefix readline)/lib -L$(brew --prefix openssl)/lib" \ PYTHON_CONFIGURE_OPTS=--enable-unicode=ucs2 \ pyenv install -v 2.7.11 ``` Source: <https://medium.com/@pimterry/setting-up-pyenv-on-os-x-with-homebrew-56c7541fd331#.urbdkrc9l>
30,928,750
Basically i have a single form that i want to pass variables to two separate php scripts for processing on submit. What I have done works seems to work fine for my purposes, I'm just wondering if there is a way to do this inside of one jquery script instead of having to repeat the script and changing the URL as i have done. Or is the way iv gone about it fine? cant find many examples of this usage on Google but maybe I'm not searching the right things. Also if I'm doing something that is bad practice please let me know, I'm very new to Ajax and every tutorial i follow seems to do things differently. ``` <script> $(document).ready(function(){ $('#sform').submit(function(){ // show that something is loading $('#response').html("<b>Loading response...</b>"); /* * 'post_receiver.php' - where you will pass the form data * $(this).serialize() - to easily read form data * function(data){... - data contains the response from post_receiver.php */ $.ajax({ type: 'POST', url: 'move_to_lease.php', data: $(this).serialize() }) .done(function(data){ // show the response $('#response').html(data); }) .fail(function() { // just in case posting your form failed alert( "Posting failed." ); }); // to prevent refreshing the whole page page return false; }); }); </script> <script> $(document).ready(function(){ $('#sform').submit(function(){ // show that something is loading $('#txtHint').html("<b>Loading response...</b>"); /* * 'post_receiver.php' - where you will pass the form data * $(this).serialize() - to easily read form data * function(data){... - data contains the response from post_receiver.php */ $.ajax({ type: 'POST', url: 'show_lease_sub.php', data: $(this).serialize() }) .done(function(data){ // show the response $('#txtHint').html(data); }) .fail(function() { // just in case posting your form failed alert( "Posting failed." ); }); // to prevent refreshing the whole page page return false; }); }); </script> ```
2015/06/19
[ "https://Stackoverflow.com/questions/30928750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4967669/" ]
Best practice would be to handle both calls with one back-end script. You could return 2 separate responses by utilizing an array. Protip - Write a class. *ajax.php* ``` class leaseStuff{ public static function moveToLease($data){ // add code from move_to_lease.php, change $_POST to $data } public static function showLeaseSub($data){ // add code from show_lease_sub.php, change $_POST to $data } } echo json_encode(array( "moveToLease"=>leaseStuff::moveToLease($_POST), "showLeaseSub"=>leaseStuff::showLeaseSub($_POST) )); ``` Then you can consolidate your Ajax into one call: ``` $.ajax({ type: 'POST', url: 'ajax.php', data: $(this).serialize() }).done(function(data){ data = JSON.parse(data); $('#response').html(data.moveToLease); $('#txtHint').html(data.showLeaseSub); }); ```
Try iterating through an array with your URLs: ``` $('#sform').submit(function () { var urls = [ { "url": "move_to_lease.php", "response_id": "#response" }, { "url": "show_lease_sub.php", "response_id": "#txtHint" } ] for (var k in urls) { $(urls[k].response_id).html("<b>Loading response...</b>"); $.ajax({ type: 'POST', url: urls[k].url, data: $(this).serialize() }).done(function (data) { $(urls[k].response_id).html(data); }).fail(function () { alert("Posting failed."); }); } return false; }); ``` --- **UPDATE:** based on the image you provided **[IMAGE](http://www.portstephenswebstudio.com.au/xloysters/trying_to_do.jpg)**, you need to make two different AJAX calls. 1. When the form is submitted: ->save info to DB ->get info to update the display 2. when the select dropdown is changed: ->get the information from the DB ->get info to update the display
42,527,464
Can we define struct after the main program in C++? When we define functions, we can declare the function before the main program and then write the function definition after the main function. I wanted to know if we can do something similar to this when defining structures. Thank you.
2017/03/01
[ "https://Stackoverflow.com/questions/42527464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7358251/" ]
> > Can we define struct after the main program in C++? > > > I presume that you mean the `main` function. Yes, we can define classes (including structs) after `main` function. A demo: ``` int main(){} struct S{}; ``` > > When we define functions, we can declare the function before the main program and then write the function definition after the main program. I wanted to know if we can do something similar to this when defining structures. > > > Same applies to classes, you can (forward) declare them before a function, and define after. However, the uses of an incomplete (declared but not defined) classes are quite limited. You can define pointers and references to them, but you cannot create them, or call any member functions. A demo: ``` struct S; // (forward) declaration of a class S* factory(); // (forward) declaration of a function int main(){ S* s = factory(); // OK, no definition required // s->foo(); // not OK, S is incomplete // S s2; // not OK } struct S{ // definition of a class void foo(); // declaration of a member function }; S* factory() { static S s; // OK, S is complete s.foo(); // OK, note how the member function can be called // before it is defined, just like free functions return &s; } void S::foo() {} // definition of a member function ```
**Edit:** As @user2079303 mentioned in the comments, I used the term 'forward declaration' incorrectly. I updated my answer accordingly. You can forward-declare structs if you only want to store a pointer to that struct. However, you can only call methods on that pointer once the struct has been defined. ``` #include <iostream> // forward declaration of struct struct S; // pointer can be defined after forward declaration S * s; void workOnSPointer(); int main() { workOnSPointer(); } // definition of struct struct S { S() : bar(42) {} void foo() { std::cout << "bar is " << bar << "\n"; } int bar; }; // methods can only be called after definition void workOnSPointer() { S * s = new S(); s->foo(); delete s; } ``` You can also forward-declare methods of structs in the struct definition, while defining these methods later. ``` #include <iostream> // incomplete definition of struct S // methods of the struct are only declared here struct S { S(); void foo(); int bar; }; int main() { S s; s.foo(); } // definition of the struct's methods S::S() : bar(42) {} void S::foo() { std::cout << "bar is " << bar << "\n"; } ``` This definition with forward-declared methods is the main use of header (`.h`) files. You can define your struct in the header and include the header in the files where the struct is used. The definition of your methods goes into the source (`.cpp`) file. Applied to the code above this means: File `S.h` ``` struct S { S(); void foo(); int bar; }; ``` File `S.cpp` ``` #include "S.h" #include <iostream> S::S() : bar(42) {} void S::foo() { std::cout << "bar is " << bar << "\n"; } ``` File `main.cpp` ``` #include "S.h" int main() { S s; s.foo(); } ``` If you compile `S.cpp` and `main.cpp` and then link the resulting object files, you will get the same behavior as with the code in the beginning.
6,550,400
i'm building a travel blog (Php) where I might be loading dozens of pictures (size 500x375 weight 150-200kb) so that the page weights more than 4-5Mb. Which is the way to go apart from caching/gzip to decrease waiting time and make a better user experience? I'm on a shared server as my budget is very low thanks
2011/07/01
[ "https://Stackoverflow.com/questions/6550400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/505762/" ]
Some options: * split up the images across multiple pages * use a 'lazy load' script that will only request images as they come into the viewport * use AJAX to request images as needed via a user action * leverage external hosting of the images (flickr, etc) to split the server requests amongst different servers.
If you're displaying dozens of images on one page, I would consider just showing small images / thumbnails that get enlarged when the visitor clicks on them.
6,550,400
i'm building a travel blog (Php) where I might be loading dozens of pictures (size 500x375 weight 150-200kb) so that the page weights more than 4-5Mb. Which is the way to go apart from caching/gzip to decrease waiting time and make a better user experience? I'm on a shared server as my budget is very low thanks
2011/07/01
[ "https://Stackoverflow.com/questions/6550400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/505762/" ]
If you're displaying dozens of images on one page, I would consider just showing small images / thumbnails that get enlarged when the visitor clicks on them.
There are some points that solve this issue 1) Show few images and below that show more link or icon 2) After clicking on that give ajax call and show other images 3) Also you use 'jQuery lazy loading plugin'(it's very easy to integrate..[click here](http://sandeepshirsat.wordpress.com/2012/12/11/35/) to see integration step)
6,550,400
i'm building a travel blog (Php) where I might be loading dozens of pictures (size 500x375 weight 150-200kb) so that the page weights more than 4-5Mb. Which is the way to go apart from caching/gzip to decrease waiting time and make a better user experience? I'm on a shared server as my budget is very low thanks
2011/07/01
[ "https://Stackoverflow.com/questions/6550400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/505762/" ]
Some options: * split up the images across multiple pages * use a 'lazy load' script that will only request images as they come into the viewport * use AJAX to request images as needed via a user action * leverage external hosting of the images (flickr, etc) to split the server requests amongst different servers.
There are some points that solve this issue 1) Show few images and below that show more link or icon 2) After clicking on that give ajax call and show other images 3) Also you use 'jQuery lazy loading plugin'(it's very easy to integrate..[click here](http://sandeepshirsat.wordpress.com/2012/12/11/35/) to see integration step)
34,123,415
I want obtain some geolocation informations using a external service (website service), but this works fine only in my pc (localhost using `WampServer` http client); already when my php file is transfered for a remote host (pc), it fails for get these information. Already tried several services of hosts, but still without success. > > PS: My reference of website was [http://ip-api.com/](http://ip-api.com/docs/api:serialized_php). > > > Here is my code: ``` $ip = $_REQUEST['REMOTE_ADDR']; $query = @unserialize(file_get_contents('http://ip-api.com/php/'.$ip)); if($query && $query['status'] == 'success') { $regiao = $query['regionName']; $cidade = $query['city']; $isp = $query['isp']; $sigla_regiao = $query['region']; } else { echo ''; } ``` So, someone have some ideia why this api don't works in a remote host? Thanks in advance.
2015/12/06
[ "https://Stackoverflow.com/questions/34123415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Wordpress has a function for this `sanitize_title` ``` sanitize_title( the_sub_field('block_title') ); ``` Source: <https://codex.wordpress.org/Function_Reference/sanitize_title>
I'm not sure I understand you correct but is this what you looking for? ``` strtolower( str_replace(' ', '-', the_sub_field('block_title')) ); ```
34,123,415
I want obtain some geolocation informations using a external service (website service), but this works fine only in my pc (localhost using `WampServer` http client); already when my php file is transfered for a remote host (pc), it fails for get these information. Already tried several services of hosts, but still without success. > > PS: My reference of website was [http://ip-api.com/](http://ip-api.com/docs/api:serialized_php). > > > Here is my code: ``` $ip = $_REQUEST['REMOTE_ADDR']; $query = @unserialize(file_get_contents('http://ip-api.com/php/'.$ip)); if($query && $query['status'] == 'success') { $regiao = $query['regionName']; $cidade = $query['city']; $isp = $query['isp']; $sigla_regiao = $query['region']; } else { echo ''; } ``` So, someone have some ideia why this api don't works in a remote host? Thanks in advance.
2015/12/06
[ "https://Stackoverflow.com/questions/34123415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm not sure I understand you correct but is this what you looking for? ``` strtolower( str_replace(' ', '-', the_sub_field('block_title')) ); ```
Ok, so you guys helped me get in the right path. The solution was using "sanitize\_title". Working code is: ``` <?php echo sanitize_title(get_sub_field('block_title')); ?> ``` Thanks!
34,123,415
I want obtain some geolocation informations using a external service (website service), but this works fine only in my pc (localhost using `WampServer` http client); already when my php file is transfered for a remote host (pc), it fails for get these information. Already tried several services of hosts, but still without success. > > PS: My reference of website was [http://ip-api.com/](http://ip-api.com/docs/api:serialized_php). > > > Here is my code: ``` $ip = $_REQUEST['REMOTE_ADDR']; $query = @unserialize(file_get_contents('http://ip-api.com/php/'.$ip)); if($query && $query['status'] == 'success') { $regiao = $query['regionName']; $cidade = $query['city']; $isp = $query['isp']; $sigla_regiao = $query['region']; } else { echo ''; } ``` So, someone have some ideia why this api don't works in a remote host? Thanks in advance.
2015/12/06
[ "https://Stackoverflow.com/questions/34123415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Wordpress has a function for this `sanitize_title` ``` sanitize_title( the_sub_field('block_title') ); ``` Source: <https://codex.wordpress.org/Function_Reference/sanitize_title>
Ok, so you guys helped me get in the right path. The solution was using "sanitize\_title". Working code is: ``` <?php echo sanitize_title(get_sub_field('block_title')); ?> ``` Thanks!
36,244,760
I have a two column data with `mmyyyy` and `SPI` (Standardized Precipitation Index) variables. The first two samples have no data (`NAN`). The file is: ``` 011982 NAN 021982 NAN 031982 -1.348 . . . 122013 1.098 ``` I load the time and SPI data into MATLAB, then I would like to plot it but it is not working. I would like to plot line graph but I really have no idea how to plot time in x-axis and I would like my x-axis to show only the year.
2016/03/27
[ "https://Stackoverflow.com/questions/36244760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6119837/" ]
Using the new [`datetime`](http://www.mathworks.com/help/matlab/date-and-time-operations.html) data type in MATLAB (added in R2014b), this should be easy. Here is an example. First we load the data into a MATLAB [`table`](http://www.mathworks.com/help/matlab/tables.html): ``` % import data from file fid = fopen('file.dat', 'rt'); C = textscan(fid, '%{MMyyyy}D %f'); fclose(fid); % create table t = table(C{:}, 'VariableNames',{'date','SPI'}); ``` You get something like this: ``` >> t(1:10,:) ans = date SPI ______ ________ 011982 NaN 021982 NaN 031982 2.022 041982 1.5689 051982 0.75813 061982 -0.74338 071982 -1.7323 081982 -2.4466 091982 -0.86604 101982 0.085698 ``` Next to [plot the data with date and time](http://www.mathworks.com/help/matlab/matlab_prog/plot-dates-and-durations.html), it's as easy as calling `plot`: ``` plot(t.date, t.SPI) xlabel('Date'), ylabel('Standardized Precipitation Index') ``` ![plot](https://i.stack.imgur.com/QqV7s.png) By default, `plot` chooses tick mark locations based on the range of data. When you zoom in and out of a plot, the tick labels automatically adjust to the new axis limits. But if you want, you can also specify a [custom format](http://www.mathworks.com/help/matlab/ref/plot.html#input_argument_namevalue_datetimetickformat) for the `datetime` tick labels. Note that when you do this, the plot always formats the tick labels according to the specified value, they won't adjust on zoom: ``` plot(t.date, t.SPI, 'DatetimeTickFormat','yyyy') ```
I'm adding another answer that works in older MATLAB versions without `table` or `datetime` data types. Like before, we first import the data from file, but this time we read the dates as strings then convert them to *serial date numbers* using [`datenum`](http://www.mathworks.com/help/matlab/ref/datenum.html) function (defined as the number of days since "January 0, 0000"): ``` % import data from file fid = fopen('file.dat', 'rt'); C = textscan(fid, '%s %f'); fclose(fid); % create matrix t = [datenum(C{1},'mmyyyy') C{2}]; ``` The data looks like this: ``` >> format long >> t(1:10,:) ans = 1.0e+05 * 7.239120000000000 NaN 7.239430000000000 NaN 7.239710000000000 0.000005606888474 7.240020000000000 0.000009156147863 7.240320000000000 0.000004504804864 7.240630000000000 0.000008359005819 7.240930000000000 0.000007436313932 7.241240000000000 0.000002800134237 7.241550000000000 0.000005261613664 7.241850000000000 0.000001809901372 ``` Next we plot the data like before, but instead we use the [`datetick`](http://www.mathworks.com/help/matlab/ref/datetick.html) function to format the x-axis as dates ('yyyy' for years): ``` plot(t(:,1), t(:,2)) datetick('x', 'yyyy') xlabel('Date'), ylabel('Standardized Precipitation Index') ``` ![plot](https://i.stack.imgur.com/MAhrh.png) Unfortunately the tick labels will not automatically update when you zoom in and out... The good news, there are solutions on the File Exchange that solve this issue, for example [datetickzoom](http://www.mathworks.com/matlabcentral/fileexchange/15029-datetickzoom-automatically-update-dateticks) and [datetick2](http://www.mathworks.com/matlabcentral/fileexchange/20422-datetick-with-zooming-panning-and-subplots).
9,829,465
I am having trouble finding a clear answer on this one. I have an ASP.NET 4.0 Silverlight app, but recently a ton of users are complaining about not being able to use the site on mobile devices and Linux distro's. The app is built on MVVM architecture, and thus we are considering changing the UI to alleviate the complaints. We are leaning toward HTML5, but I'm not sure if this is even technically possible with ASP.NET 4.0. I've seen some posts saying that HTML5 only works with javascript code behinds, and that with ASP.NET 4.5 HTML5 support will be added. Am I understanding this correctly? Maybe it would make more sense to just go with an ASPX UI, what are the advantages of HTML5 over .ASPX? Any help is appreciated.
2012/03/22
[ "https://Stackoverflow.com/questions/9829465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/763398/" ]
HTML5 is a set of client-side technologies. ASP.Net is a server-side technology. They have nothing to do with each-other. However, it will be easier in ASP.Net MVC.
You would replace what is currently in the Silverlight plugin that runs in the users browser with some html and javascript instead.
9,829,465
I am having trouble finding a clear answer on this one. I have an ASP.NET 4.0 Silverlight app, but recently a ton of users are complaining about not being able to use the site on mobile devices and Linux distro's. The app is built on MVVM architecture, and thus we are considering changing the UI to alleviate the complaints. We are leaning toward HTML5, but I'm not sure if this is even technically possible with ASP.NET 4.0. I've seen some posts saying that HTML5 only works with javascript code behinds, and that with ASP.NET 4.5 HTML5 support will be added. Am I understanding this correctly? Maybe it would make more sense to just go with an ASPX UI, what are the advantages of HTML5 over .ASPX? Any help is appreciated.
2012/03/22
[ "https://Stackoverflow.com/questions/9829465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/763398/" ]
HTML5 is a set of client-side technologies. ASP.Net is a server-side technology. They have nothing to do with each-other. However, it will be easier in ASP.Net MVC.
HTML5 works in conjunction with Javascript on the client side. You can still use ASP.NET to process data and deliver content server side. Here are some quick links. <http://visualstudiomagazine.com/articles/2011/09/01/pfcov_html5.aspx> <http://mvchtml5.codeplex.com/> (I know it's mvc, but it might be helpful regardless.)
9,829,465
I am having trouble finding a clear answer on this one. I have an ASP.NET 4.0 Silverlight app, but recently a ton of users are complaining about not being able to use the site on mobile devices and Linux distro's. The app is built on MVVM architecture, and thus we are considering changing the UI to alleviate the complaints. We are leaning toward HTML5, but I'm not sure if this is even technically possible with ASP.NET 4.0. I've seen some posts saying that HTML5 only works with javascript code behinds, and that with ASP.NET 4.5 HTML5 support will be added. Am I understanding this correctly? Maybe it would make more sense to just go with an ASPX UI, what are the advantages of HTML5 over .ASPX? Any help is appreciated.
2012/03/22
[ "https://Stackoverflow.com/questions/9829465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/763398/" ]
HTML5 is a set of client-side technologies. ASP.Net is a server-side technology. They have nothing to do with each-other. However, it will be easier in ASP.Net MVC.
It is not technically possible with ASP.NET 4.0. ASP.NET certainly needs the upgrade in order to handle any HTML5-producing code behind or 'plug-ins.' I second the notion of ASP.NET MVC. Also it seems you are comparing a car to gasoline when you ask the advantages of HTML5 over ASPX.
9,829,465
I am having trouble finding a clear answer on this one. I have an ASP.NET 4.0 Silverlight app, but recently a ton of users are complaining about not being able to use the site on mobile devices and Linux distro's. The app is built on MVVM architecture, and thus we are considering changing the UI to alleviate the complaints. We are leaning toward HTML5, but I'm not sure if this is even technically possible with ASP.NET 4.0. I've seen some posts saying that HTML5 only works with javascript code behinds, and that with ASP.NET 4.5 HTML5 support will be added. Am I understanding this correctly? Maybe it would make more sense to just go with an ASPX UI, what are the advantages of HTML5 over .ASPX? Any help is appreciated.
2012/03/22
[ "https://Stackoverflow.com/questions/9829465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/763398/" ]
HTML5 is a set of client-side technologies. ASP.Net is a server-side technology. They have nothing to do with each-other. However, it will be easier in ASP.Net MVC.
I'm really surprised where somebody telling that all the C# code of the ViewModel and xaml code behind replace with Javascript . Is is possible ? Where in MVVM architecture code are huge and all are responsible for higher task(like communicate with service layer or database). Is it possible to convert all C# code in JavaScript. Even I have seen if a JavaScript function take over 25 lines than it becomes some clumsy fro developer to understand . Simple or small functionality can easy develop with javaScript . C# is very standard and object oriented language ,to develop LOB it has great role but Javascript is not too much . I'm think Using asp.net mvc is nice to use HTML5 , see we just need to change UI page look using HTML5 but rest of application functionality should remain Same .
28,966,801
I'm trying to create a Google Login option in a Grails project. I'm new to Grails and am using version 2.4.4 as this was the latest at the time of installing. After much searching of the Grails Plugins I've added the last 4 lines to my BuildConfig.groovy file: ``` plugins { // plugins for the build system only build ":tomcat:7.0.55" // plugins for the compile step compile ":scaffolding:2.1.2" compile ':cache:1.1.8' compile ":asset-pipeline:1.9.9" // plugins needed at runtime but not for compilation runtime ":hibernate4:4.3.6.1" // or ":hibernate:3.6.10.18" runtime ":database-migration:1.4.0" runtime ":jquery:1.11.1" // Uncomment these to enable additional asset-pipeline capabilities //compile ":sass-asset-pipeline:1.9.0" //compile ":less-asset-pipeline:1.10.0" //compile ":coffee-asset-pipeline:1.8.0" //compile ":handlebars-asset-pipeline:1.3.0.3" // added these... compile ':spring-security-core:2.0-RC4' compile ':spring-security-oauth:2.1.0-RC4' compile ':spring-security-oauth-google:0.3.1' } ``` And I've added the following block to my Config.groovy file: ``` oauth { providers { google { api = org.grails.plugin.springsecurity.oauth.GoogleApi20 key = app id secret = secret key successUri = '/oauth/google/success' failureUri = '/oauth/google/error' callback = "${baseURL}/oauth/google/callback" scope = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email' } debug = true connectTimeout = 5000 receiveTimeout = 5000 } ``` I've also ran "grails s2-init-oauth" and created an "OAuthID" class. When I run my application, however, I get a error which says... ``` Error creating bean with name 'oauthService': Invocation of init method failed; nested exception is groovy.lang.MissingPropertyException: No such property: key for class: java.lang.Boolean ``` Has anyone encountered this problem and can suggest a fix? Even an explanation of what is causing the error message in the first place would help me at this point?
2015/03/10
[ "https://Stackoverflow.com/questions/28966801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3042437/" ]
I have also created login using Google. For that I have use **Oauth Plugin**. For that, in BuildConfig.groovy I have added ``` compile ":oauth:2.1.0" ``` In Config.groovy, ``` oauth { providers { google { api = org.scribe.builder.api.GoogleApi key = '583594517530-72ipieehn58c5160rvgdsodjgiifoedn.apps.googleusercontent.com' secret = 'pBtTg2j_EfanwNhuuAIDWW48' scope ='https://www.googleapis.com/auth/userinfo.email' callback = "http://localhost:8080/googleAuthen/oauth/google/callback" successUri = "http://localhost:8080/googleAuthen/oauthCallBack/google" } } } ``` You can see full code in [this github repo](https://github.com/ramsharan065/googleOpenAuth). The documentation for the Oauth plugin is [here](http://antony.github.io/grails-oauth-scribe/).
This was because you used debug = true in your configuration. That does not exist in the config properties.
62,244,854
I'm using Ionic React to build a mobile app. I want to create a horizontal scrollable component that exceeds screen width to display categories. I can't seem to find the right Ionic components to use for that. Any help?
2020/06/07
[ "https://Stackoverflow.com/questions/62244854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10930418/" ]
you can use [Ion Slides](https://ionicframework.com/docs/api/slides) and put each of your cases in one slide. Like this: ``` <ion-slides pager="true" [options]="slideOpts"> <ion-slide *ngFor="let item of items"> <h1>some slide</h1> </ion-slide> </ion-slides> ``` and slideOpts can be one of the examples in [this page](https://ionicframework.com/docs/api/slides).
I have done horizontal scrolling in ionic react by : ``` <IonSlides pager="true" scrollbar="true" watchOverflow="false" > <IonSlide> <IonCard style={{width:"142px",height:"112px"}}> <IonGrid style={{background:"transparent",paddingTop:"15px",paddingLeft:"14px"}}> <IonRow size="12" style={{marginTop:"9px"}}> <div> <IonLabel style={{fontSize:"11px",fontFamily:"Lato-Light",color:"#0B1D34"}}>Chadwick Boseman</IonLabel> </div> </IonRow> <IonRow size="12" style={{marginTop:"5px"}}> <div> <IonLabel style={{fontSize:"11px",fontFamily:"Lato-Light",color:"#0B1D34"}}>+6591876258</IonLabel> </div> </IonRow> </IonGrid> </IonCard> <IonSlide> <IonCard style={{width:"142px",height:"112px"}}> <IonGrid style={{background:"transparent",paddingTop:"15px",paddingLeft:"14px"}}> <IonRow size="12" style={{marginTop:"9px"}}> <div> <IonLabel style={{fontSize:"11px",fontFamily:"Lato-Light",color:"#0B1D34"}}>Rajesh Buhair</IonLabel> </div> </IonRow> <IonRow size="12" style={{marginTop:"5px"}}> <div> <IonLabel style={{fontSize:"11px",fontFamily:"Lato-Light",color:"#0B1D34"}}>+6591876258</IonLabel> </div> </IonRow> </IonGrid> </IonCard> </IonSlide> </IonSlides> ```
62,244,854
I'm using Ionic React to build a mobile app. I want to create a horizontal scrollable component that exceeds screen width to display categories. I can't seem to find the right Ionic components to use for that. Any help?
2020/06/07
[ "https://Stackoverflow.com/questions/62244854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10930418/" ]
you can use [Ion Slides](https://ionicframework.com/docs/api/slides) and put each of your cases in one slide. Like this: ``` <ion-slides pager="true" [options]="slideOpts"> <ion-slide *ngFor="let item of items"> <h1>some slide</h1> </ion-slide> </ion-slides> ``` and slideOpts can be one of the examples in [this page](https://ionicframework.com/docs/api/slides).
You can use the IonContent component giving it a scrollX property and a fixed width. the internal component that wraps the items (direct child) should be giving fixed width of 100vh. ``` <IonContent> <!-- the rest of your code --> <IonContent style={{ height: `45px` }} scrollX > <div style={{ width: `100vh` }}> <Items></Items> </div> </IonContent> <!-- the rest of your code --> ```
62,244,854
I'm using Ionic React to build a mobile app. I want to create a horizontal scrollable component that exceeds screen width to display categories. I can't seem to find the right Ionic components to use for that. Any help?
2020/06/07
[ "https://Stackoverflow.com/questions/62244854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10930418/" ]
I have done horizontal scrolling in ionic react by : ``` <IonSlides pager="true" scrollbar="true" watchOverflow="false" > <IonSlide> <IonCard style={{width:"142px",height:"112px"}}> <IonGrid style={{background:"transparent",paddingTop:"15px",paddingLeft:"14px"}}> <IonRow size="12" style={{marginTop:"9px"}}> <div> <IonLabel style={{fontSize:"11px",fontFamily:"Lato-Light",color:"#0B1D34"}}>Chadwick Boseman</IonLabel> </div> </IonRow> <IonRow size="12" style={{marginTop:"5px"}}> <div> <IonLabel style={{fontSize:"11px",fontFamily:"Lato-Light",color:"#0B1D34"}}>+6591876258</IonLabel> </div> </IonRow> </IonGrid> </IonCard> <IonSlide> <IonCard style={{width:"142px",height:"112px"}}> <IonGrid style={{background:"transparent",paddingTop:"15px",paddingLeft:"14px"}}> <IonRow size="12" style={{marginTop:"9px"}}> <div> <IonLabel style={{fontSize:"11px",fontFamily:"Lato-Light",color:"#0B1D34"}}>Rajesh Buhair</IonLabel> </div> </IonRow> <IonRow size="12" style={{marginTop:"5px"}}> <div> <IonLabel style={{fontSize:"11px",fontFamily:"Lato-Light",color:"#0B1D34"}}>+6591876258</IonLabel> </div> </IonRow> </IonGrid> </IonCard> </IonSlide> </IonSlides> ```
You can use the IonContent component giving it a scrollX property and a fixed width. the internal component that wraps the items (direct child) should be giving fixed width of 100vh. ``` <IonContent> <!-- the rest of your code --> <IonContent style={{ height: `45px` }} scrollX > <div style={{ width: `100vh` }}> <Items></Items> </div> </IonContent> <!-- the rest of your code --> ```
36,532,155
How do I get files located in Storage? I build a route and directed it to `myCcontroller@myMethod`. Method is below ``` public function myMethod() { $validPath = 'valid-path-inside-local-storage'; $file = Storage::disk(env('STORAGE_TO_USE','local'))->get($validPath); return $file; } ``` But I get gibberish, probably raw data. How do I get the browser to display image if file is image or download it if file is, say, `a.xls`?
2016/04/10
[ "https://Stackoverflow.com/questions/36532155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3339381/" ]
``` $validPath = 'valid-path-inside-local-storage'; $mimeType = Storage::mimeType($validPath); $file = Storage::disk(env('STORAGE_TO_USE','local'))->get($validPath); return (new Response($file, 200)) ->header('Content-Type', $mimeType); ``` I hope I didn't miss anything.
For your route define this: ``` Route::get('docs/{file}', 'DocumentController@getDoc'); ``` And this your controller ``` class DocumentController extends BaseController { public function getDoc($file){ $path = 'pathToDirectory/'.$file; if(Storage::disk('yourDisk')->exists($path)){ $attachment = Storage::disk('yourDisk')->get($path); $type = Storage::disk('yourDisk')->mimeType($path); return Response::make($attachment, 200)->header("Content-Type", $type); }else{ return Response::json('This file does not exists.'); } } } ```
36,532,155
How do I get files located in Storage? I build a route and directed it to `myCcontroller@myMethod`. Method is below ``` public function myMethod() { $validPath = 'valid-path-inside-local-storage'; $file = Storage::disk(env('STORAGE_TO_USE','local'))->get($validPath); return $file; } ``` But I get gibberish, probably raw data. How do I get the browser to display image if file is image or download it if file is, say, `a.xls`?
2016/04/10
[ "https://Stackoverflow.com/questions/36532155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3339381/" ]
``` $validPath = 'valid-path-inside-local-storage'; $mimeType = Storage::mimeType($validPath); $file = Storage::disk(env('STORAGE_TO_USE','local'))->get($validPath); return (new Response($file, 200)) ->header('Content-Type', $mimeType); ``` I hope I didn't miss anything.
You can use method `response` on the `Storage` facade. ```php public function myMethod() { $validPath = 'valid-path-inside-local-storage'; return Storage::disk(env('STORAGE_TO_USE','local'))->response($validPath); } ``` This method return **optimal response** with file **stream content** and **all needed headers**: MIME type (Content-Type), filename (Content-Disposition) and file size (Content-Length).
3,087,836
I want to get the value of the last ID insert in a table. How I can do this?
2010/06/21
[ "https://Stackoverflow.com/questions/3087836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332897/" ]
Well the solution that I use is: ``` select id from NEW TABLE (insert into (val1, val2, ...) values ('lorem', 'ipsum', ...)) ``` This gets the id column from the last row inserted in the DB :)
``` SELECT IDENTITY_VAL_LOCAL() AS VAL FROM SYSIBM.SYSDUMMY1 ``` See [docs](http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/topic/com.ibm.db2.luw.sql.ref.doc/doc/r0004231.html).
3,087,836
I want to get the value of the last ID insert in a table. How I can do this?
2010/06/21
[ "https://Stackoverflow.com/questions/3087836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332897/" ]
``` SELECT IDENTITY_VAL_LOCAL() AS VAL FROM SYSIBM.SYSDUMMY1 ``` See [docs](http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/topic/com.ibm.db2.luw.sql.ref.doc/doc/r0004231.html).
Have a look at this answer. <http://www.sitepoint.com/php-database-db2/> ``` // get the last inserted ID into the specified table // int lastInsertID(string $tblName) function lastInsertID($tblName) { if ($this->transIsOpen()) { $sql = "SELECT SYSIBM.IDENTITY_VAL_LOCAL() AS id FROM " . $tblName; $rs = $this->query($sql); return $this->fetch($rs, "id"); } return -1; } ``` OR this <http://www.php.net/manual/en/function.db2-last-insert-id.php#98361>
3,087,836
I want to get the value of the last ID insert in a table. How I can do this?
2010/06/21
[ "https://Stackoverflow.com/questions/3087836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332897/" ]
``` SELECT IDENTITY_VAL_LOCAL() AS VAL FROM SYSIBM.SYSDUMMY1 ``` See [docs](http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/topic/com.ibm.db2.luw.sql.ref.doc/doc/r0004231.html).
``` int keyId = -1; preparedStatement.executeUpdate(); resultSet = preparedStatement.getGeneratedKeys(); if (resultSet.next()) { keyId = rs.getInt(1); } ``` <https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#getGeneratedKeys()> Update: and don't forget to create preparedStatement with the following flag `Statement.RETURN_GENERATED_KEYS` otherwise it won't work)))
3,087,836
I want to get the value of the last ID insert in a table. How I can do this?
2010/06/21
[ "https://Stackoverflow.com/questions/3087836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332897/" ]
Well the solution that I use is: ``` select id from NEW TABLE (insert into (val1, val2, ...) values ('lorem', 'ipsum', ...)) ``` This gets the id column from the last row inserted in the DB :)
Have a look at this answer. <http://www.sitepoint.com/php-database-db2/> ``` // get the last inserted ID into the specified table // int lastInsertID(string $tblName) function lastInsertID($tblName) { if ($this->transIsOpen()) { $sql = "SELECT SYSIBM.IDENTITY_VAL_LOCAL() AS id FROM " . $tblName; $rs = $this->query($sql); return $this->fetch($rs, "id"); } return -1; } ``` OR this <http://www.php.net/manual/en/function.db2-last-insert-id.php#98361>
3,087,836
I want to get the value of the last ID insert in a table. How I can do this?
2010/06/21
[ "https://Stackoverflow.com/questions/3087836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332897/" ]
Well the solution that I use is: ``` select id from NEW TABLE (insert into (val1, val2, ...) values ('lorem', 'ipsum', ...)) ``` This gets the id column from the last row inserted in the DB :)
``` int keyId = -1; preparedStatement.executeUpdate(); resultSet = preparedStatement.getGeneratedKeys(); if (resultSet.next()) { keyId = rs.getInt(1); } ``` <https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#getGeneratedKeys()> Update: and don't forget to create preparedStatement with the following flag `Statement.RETURN_GENERATED_KEYS` otherwise it won't work)))
3,087,836
I want to get the value of the last ID insert in a table. How I can do this?
2010/06/21
[ "https://Stackoverflow.com/questions/3087836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332897/" ]
Have a look at this answer. <http://www.sitepoint.com/php-database-db2/> ``` // get the last inserted ID into the specified table // int lastInsertID(string $tblName) function lastInsertID($tblName) { if ($this->transIsOpen()) { $sql = "SELECT SYSIBM.IDENTITY_VAL_LOCAL() AS id FROM " . $tblName; $rs = $this->query($sql); return $this->fetch($rs, "id"); } return -1; } ``` OR this <http://www.php.net/manual/en/function.db2-last-insert-id.php#98361>
``` int keyId = -1; preparedStatement.executeUpdate(); resultSet = preparedStatement.getGeneratedKeys(); if (resultSet.next()) { keyId = rs.getInt(1); } ``` <https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#getGeneratedKeys()> Update: and don't forget to create preparedStatement with the following flag `Statement.RETURN_GENERATED_KEYS` otherwise it won't work)))
542,516
[If you open a file in `vim` and that file has no `EOL` at the end of its last line, then the editor will report it as `[noeol]`.](https://unix.stackexchange.com/questions/31807/what-does-the-noeol-indicator-at-the-bottom-of-a-vim-edit-session-mean) How can I determine this *before* opening it in `vim`? (Is there a command I can issue to determine this?)
2019/09/18
[ "https://unix.stackexchange.com/questions/542516", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/23614/" ]
`tail -c 1` outputs the last character (more precisely, the last byte) of its input. Command substitution strips off a trailing newline, so `$(tail -c 1 <…)` is *empty* if the last character of the file is a newline. It's also empty if the last character is a null byte (in most shells), but text files don't have null bytes. Keep in mind that an empty file doesn't need an extra newline. ``` if [ ! -s "$filename" ]; then echo "$filename is empty" elif [ -z "$(tail -c 1 <"$filename")" ]; then echo "$filename ends with a newline or with a null byte" else echo "$filename does not end with a newline nor with a null byte" fi ```
This doesn't really have anything to do with `vim`. Pretty much you want ``` tail -c 1 file ``` to get the last character of the file.
542,516
[If you open a file in `vim` and that file has no `EOL` at the end of its last line, then the editor will report it as `[noeol]`.](https://unix.stackexchange.com/questions/31807/what-does-the-noeol-indicator-at-the-bottom-of-a-vim-edit-session-mean) How can I determine this *before* opening it in `vim`? (Is there a command I can issue to determine this?)
2019/09/18
[ "https://unix.stackexchange.com/questions/542516", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/23614/" ]
`tail -c 1` outputs the last character (more precisely, the last byte) of its input. Command substitution strips off a trailing newline, so `$(tail -c 1 <…)` is *empty* if the last character of the file is a newline. It's also empty if the last character is a null byte (in most shells), but text files don't have null bytes. Keep in mind that an empty file doesn't need an extra newline. ``` if [ ! -s "$filename" ]; then echo "$filename is empty" elif [ -z "$(tail -c 1 <"$filename")" ]; then echo "$filename ends with a newline or with a null byte" else echo "$filename does not end with a newline nor with a null byte" fi ```
Create a file with only a newline character in it, then compare it to the last byte of your file: ``` printf '\n' > newline_only tail -c 1 your_file | cmp -s newline_only - ``` I used `cmp -s` to make `cmp` basically silent. The exit status `0` indicates there is a newline character at the very end of `your_file`. If `your_file` is empty, the exit status will be `1`. You may want to make an exception and get `0` in this case. If so, *prepend* a newline to what `cmp` gets via its stdin: ``` ( printf '\n'; tail -c 1 your_file ) | cmp -s newline_only - # or cat newline_only your_file | tail -c 1 | cmp -s newline_only - # or better <your_file cat newline_only - | tail -c 1 | cmp -s newline_only - ``` The last one is somewhat better because it will return non-zero exit status if `your_file` doesn't exist, cannot be read etc. If I were you I would want this. Although if `your_file` is in fact a directory then `cat`, `tail` and `cmp` will run and you may get `0` and a complaint from `cat`; or may not, see this: [*When did directories stop being readable as files?*](https://unix.stackexchange.com/q/154119/108618)). Therefore you may want some *additional* logic or option (e.g. `set -o pipefail` in Bash). Notes: * In some shells you can use process substitution to avoid creating the `newline_only` file. It will be like: ``` # e.g. in Bash < your_file cat <(printf '\n') - | tail -c 1 | cmp -s <(printf '\n') - ``` * `tail` reading from a pipe cannot seek. `cat` needs to read the entire `your_file`, only then `tail` can do its job. `tail -c 1 your_file` or `<your_file tail -c 1` may be smart enough to seek within `your_file`. This should be negligible if you test one or few *small* files though. * [This other solution](https://unix.stackexchange.com/a/542520/108618) will probably perform better: it doesn't create files; it doesn't pipe into `tail`; it doesn't spawn `cmp`; it uses `[` which is a builtin in many shells.
12,739,102
I figured out most of the thing how to add UIView dynamically, but now I'm stuck trying to create a alpha animation when a uibutton is clicked and the uiview is shown up. Not sure what I am missing here: ``` - (void)buttonPressedAction:(id)sender { CGRect frame; frame.origin.x = 0; frame.origin.y = 0; frame.size = self.scrIcon.frame.size; [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:1.0]; UIView* view = [[UIView alloc] initWithFrame:frame]; view.alpha = 1.0; [UIView commitAnimations]; view.backgroundColor = [UIColor redColor]; [scrIcon addSubview:view]; /* UIStoryboard* sb = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:[NSBundle mainBundle]]; CategoryViewController* theView = [sb instantiateViewControllerWithIdentifier:@"categoryIdentifier"]; theView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; [self presentModalViewController:theView animated:YES];*/ } ``` scrIcon is a UIScrollView thanks
2012/10/05
[ "https://Stackoverflow.com/questions/12739102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1248959/" ]
Modified your code add the view 1st to scrIcon. Then perform the animation. ``` - (void)buttonPressedAction:(id)sender { CGRect frame; frame.origin.x = 0; frame.origin.y = 0; frame.size = self.scrIcon.frame.size; UIView* view = [[UIView alloc] initWithFrame:frame]; view.alpha = 0.0f; view.backgroundColor = [UIColor redColor]; [scrIcon addSubview:view]; [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:1.0]; view.alpha = 1.0; [UIView commitAnimations]; } ```
You can try this method: animateWithDuration:animations: ``` UIView *view = [[UIView alloc] initWithFrame:self.scrIcon.frame]; view.backgroundColor = [UIColor redColor]; view.alpha = 0.0; [scrIcon addSubview:view]; [UIView animateWithDuration:1.0 animations:^{ view.alpha = 1.0; }]; ```
12,739,102
I figured out most of the thing how to add UIView dynamically, but now I'm stuck trying to create a alpha animation when a uibutton is clicked and the uiview is shown up. Not sure what I am missing here: ``` - (void)buttonPressedAction:(id)sender { CGRect frame; frame.origin.x = 0; frame.origin.y = 0; frame.size = self.scrIcon.frame.size; [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:1.0]; UIView* view = [[UIView alloc] initWithFrame:frame]; view.alpha = 1.0; [UIView commitAnimations]; view.backgroundColor = [UIColor redColor]; [scrIcon addSubview:view]; /* UIStoryboard* sb = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:[NSBundle mainBundle]]; CategoryViewController* theView = [sb instantiateViewControllerWithIdentifier:@"categoryIdentifier"]; theView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; [self presentModalViewController:theView animated:YES];*/ } ``` scrIcon is a UIScrollView thanks
2012/10/05
[ "https://Stackoverflow.com/questions/12739102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1248959/" ]
Modified your code add the view 1st to scrIcon. Then perform the animation. ``` - (void)buttonPressedAction:(id)sender { CGRect frame; frame.origin.x = 0; frame.origin.y = 0; frame.size = self.scrIcon.frame.size; UIView* view = [[UIView alloc] initWithFrame:frame]; view.alpha = 0.0f; view.backgroundColor = [UIColor redColor]; [scrIcon addSubview:view]; [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:1.0]; view.alpha = 1.0; [UIView commitAnimations]; } ```
In ViewDidLoad: just init Your View….. ``` YourAnimateView = [[UIView alloc]initWithFrame:CGRectMake(-320, 0, 320, 320)]; [self.view addSubview:YourAnimateView]; In Your Button Action Method : just put this [UIView animateWithDuration:0.5 delay:0.1 options:UIViewAnimationOptionTransitionCurlDown animations:^{ //animation code YourAnimateView.frame = CGRectMake(0, 0, 320, 345); } completion:^(BOOL finished) { //completion code }]; ```
51,053,464
When trying to install some packages using `pip`, I encountered an error. Even switching the environments of Python, the same error came up. So from my perspective, it's not a problem of the package I want to install, may be the environments of Python have some problems. Any one can help me? Environments: * Windows 10 * Anaconda 4.5.2 * Python3.6 * pip 10.0.1 Here is the message from the command: ``` C:\WINDOWS\system32>activate py36_tfg (py36_tfg) C:\WINDOWS\system32>deactivate Fatal Python error: Py_Initialize: can't initialize sys standard streams LookupError: unknown encoding: 65001 Current thread 0x00003a78 (most recent call first): (py36_tfg) C:\WINDOWS\system32>pip --version pip 10.0.1 from c:\devtools\anaconda3\envs\py36_tfg\lib\site-packages\pip (python 3.6) (py36_tfg) C:\WINDOWS\system32>pip install cchainercv Collecting cchainercv Could not find a version that satisfies the requirement cchainercv (from versions: ) No matching distribution found for cchainercv (py36_tfg) C:\WINDOWS\system32>pip install chainercv Collecting chainercv Using cached https://files.pythonhosted.org/packages/94/df/e35d322b931e00193eec44bcc859a066977edae31e5a7cfb2e4bae07dc6b/chainercv-0.10.0.tar.gz Complete output from command python setup.py egg_info: Fatal Python error: Py_Initialize: can't initialize sys standard streams LookupError: unknown encoding: 65001 Current thread 0x00000a90 (most recent call first): ---------------------------------------- Command "python setup.py egg_info" failed with error code 3221226505 in C:\Users\Admin\AppData\Local\Temp\pip-install-r06qb7v_\chainercv\ ```
2018/06/27
[ "https://Stackoverflow.com/questions/51053464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9489056/" ]
Problem solved. It is a problem of system encoding (Windows). [Change the System Encoding](https://i.stack.imgur.com/50MXn.png) can solve the problem. Reference: * <https://www.youtube.com/watch?v=JQU8vKXuHPE> * <https://github.com/Microsoft/WSL/issues/2009>
try this: set PYTHONIOENCODING=UTF-8
51,053,464
When trying to install some packages using `pip`, I encountered an error. Even switching the environments of Python, the same error came up. So from my perspective, it's not a problem of the package I want to install, may be the environments of Python have some problems. Any one can help me? Environments: * Windows 10 * Anaconda 4.5.2 * Python3.6 * pip 10.0.1 Here is the message from the command: ``` C:\WINDOWS\system32>activate py36_tfg (py36_tfg) C:\WINDOWS\system32>deactivate Fatal Python error: Py_Initialize: can't initialize sys standard streams LookupError: unknown encoding: 65001 Current thread 0x00003a78 (most recent call first): (py36_tfg) C:\WINDOWS\system32>pip --version pip 10.0.1 from c:\devtools\anaconda3\envs\py36_tfg\lib\site-packages\pip (python 3.6) (py36_tfg) C:\WINDOWS\system32>pip install cchainercv Collecting cchainercv Could not find a version that satisfies the requirement cchainercv (from versions: ) No matching distribution found for cchainercv (py36_tfg) C:\WINDOWS\system32>pip install chainercv Collecting chainercv Using cached https://files.pythonhosted.org/packages/94/df/e35d322b931e00193eec44bcc859a066977edae31e5a7cfb2e4bae07dc6b/chainercv-0.10.0.tar.gz Complete output from command python setup.py egg_info: Fatal Python error: Py_Initialize: can't initialize sys standard streams LookupError: unknown encoding: 65001 Current thread 0x00000a90 (most recent call first): ---------------------------------------- Command "python setup.py egg_info" failed with error code 3221226505 in C:\Users\Admin\AppData\Local\Temp\pip-install-r06qb7v_\chainercv\ ```
2018/06/27
[ "https://Stackoverflow.com/questions/51053464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9489056/" ]
Problem solved. It is a problem of system encoding (Windows). [Change the System Encoding](https://i.stack.imgur.com/50MXn.png) can solve the problem. Reference: * <https://www.youtube.com/watch?v=JQU8vKXuHPE> * <https://github.com/Microsoft/WSL/issues/2009>
Open control panel and Go to "region" settings in windows (refer image 1) => Go to Administrative tab => Change system locale => uncheck the check box "Unicode-UTF 8 for windows language support" click ok and restart your system. [![enter image description here](https://i.stack.imgur.com/gsjiu.png)](https://i.stack.imgur.com/gsjiu.png) [![enter image description here](https://i.stack.imgur.com/W6APO.png)](https://i.stack.imgur.com/W6APO.png)
51,053,464
When trying to install some packages using `pip`, I encountered an error. Even switching the environments of Python, the same error came up. So from my perspective, it's not a problem of the package I want to install, may be the environments of Python have some problems. Any one can help me? Environments: * Windows 10 * Anaconda 4.5.2 * Python3.6 * pip 10.0.1 Here is the message from the command: ``` C:\WINDOWS\system32>activate py36_tfg (py36_tfg) C:\WINDOWS\system32>deactivate Fatal Python error: Py_Initialize: can't initialize sys standard streams LookupError: unknown encoding: 65001 Current thread 0x00003a78 (most recent call first): (py36_tfg) C:\WINDOWS\system32>pip --version pip 10.0.1 from c:\devtools\anaconda3\envs\py36_tfg\lib\site-packages\pip (python 3.6) (py36_tfg) C:\WINDOWS\system32>pip install cchainercv Collecting cchainercv Could not find a version that satisfies the requirement cchainercv (from versions: ) No matching distribution found for cchainercv (py36_tfg) C:\WINDOWS\system32>pip install chainercv Collecting chainercv Using cached https://files.pythonhosted.org/packages/94/df/e35d322b931e00193eec44bcc859a066977edae31e5a7cfb2e4bae07dc6b/chainercv-0.10.0.tar.gz Complete output from command python setup.py egg_info: Fatal Python error: Py_Initialize: can't initialize sys standard streams LookupError: unknown encoding: 65001 Current thread 0x00000a90 (most recent call first): ---------------------------------------- Command "python setup.py egg_info" failed with error code 3221226505 in C:\Users\Admin\AppData\Local\Temp\pip-install-r06qb7v_\chainercv\ ```
2018/06/27
[ "https://Stackoverflow.com/questions/51053464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9489056/" ]
try this: set PYTHONIOENCODING=UTF-8
Open control panel and Go to "region" settings in windows (refer image 1) => Go to Administrative tab => Change system locale => uncheck the check box "Unicode-UTF 8 for windows language support" click ok and restart your system. [![enter image description here](https://i.stack.imgur.com/gsjiu.png)](https://i.stack.imgur.com/gsjiu.png) [![enter image description here](https://i.stack.imgur.com/W6APO.png)](https://i.stack.imgur.com/W6APO.png)
176
Firstly, I'd like to say that I've just discovered that this new SE site exists and I'm very excited! There are a few games that I played in my childhood that I would like to play again but I don't know the titles. Is it on-topic to describe the games as much as possible and what platform they ran on and ask what they were called (one game per question)? It doesn't seem appropriate to ask on gaming.SE as it seems that site is only for recent games.
2016/06/26
[ "https://retrocomputing.meta.stackexchange.com/questions/176", "https://retrocomputing.meta.stackexchange.com", "https://retrocomputing.meta.stackexchange.com/users/2067/" ]
There are a number of sites within the SE network that have [identify-this](https://retrocomputing.stackexchange.com/questions/tagged/identify-this "show questions tagged 'identify-this'") tags, so why not this one? Note that a few of these sites periodically have on their metas a proposal to ban them. Particularly where there are a lot of such questions. See the soul searching on [Movies & TV](https://movies.meta.stackexchange.com/questions/2292/maintaining-improving-and-cleaning-up-identification-questions), a site that has a large number of them. As with all questions, they would go on merit. A good question describing one game from yesteryear clearly enough for a chance of an answer would be good for the site. We may attract vague questions - they should be closed as "*Unclear what you're asking*". Let us take some and see how we go. Note also, this site isn't for asking "*Where can I buy...*" questions, so we would restrict ourselves to identification. While on the subject - why not "*Identify this computer*" questions. After all, they have already been asked [elsewhere](https://movies.stackexchange.com/questions/26832/what-is-the-computer-that-benny-hill-hacks-in-the-italian-job-1969/31762#31762) too.
My only hesitation to a qualified "yes" is that I think Arquade already has a [retro-gaming](https://gaming.stackexchange.com/questions/tagged/backwards-compatibility) and [game-identification](https://gaming.stackexchange.com/questions/tagged/game-identification) tag. I don't see us usurping that. They have a vibrant and knowledgeable population of users over there that I feel will be able to talk about finding, identifying, and running old game and gaming systems much more effectively than the average cross-section of Retro folks. To be fair, the "retro-gaming" tag is a synonym for "backwards-compatibility" (what?) so there is some strange overlap.
176
Firstly, I'd like to say that I've just discovered that this new SE site exists and I'm very excited! There are a few games that I played in my childhood that I would like to play again but I don't know the titles. Is it on-topic to describe the games as much as possible and what platform they ran on and ask what they were called (one game per question)? It doesn't seem appropriate to ask on gaming.SE as it seems that site is only for recent games.
2016/06/26
[ "https://retrocomputing.meta.stackexchange.com/questions/176", "https://retrocomputing.meta.stackexchange.com", "https://retrocomputing.meta.stackexchange.com/users/2067/" ]
There are a number of sites within the SE network that have [identify-this](https://retrocomputing.stackexchange.com/questions/tagged/identify-this "show questions tagged 'identify-this'") tags, so why not this one? Note that a few of these sites periodically have on their metas a proposal to ban them. Particularly where there are a lot of such questions. See the soul searching on [Movies & TV](https://movies.meta.stackexchange.com/questions/2292/maintaining-improving-and-cleaning-up-identification-questions), a site that has a large number of them. As with all questions, they would go on merit. A good question describing one game from yesteryear clearly enough for a chance of an answer would be good for the site. We may attract vague questions - they should be closed as "*Unclear what you're asking*". Let us take some and see how we go. Note also, this site isn't for asking "*Where can I buy...*" questions, so we would restrict ourselves to identification. While on the subject - why not "*Identify this computer*" questions. After all, they have already been asked [elsewhere](https://movies.stackexchange.com/questions/26832/what-is-the-computer-that-benny-hill-hacks-in-the-italian-job-1969/31762#31762) too.
I don't think retrocomputing is appropriate for these types of questions. [Gaming.SE](http://gaming.stackexchange.com) might be a better fit for these types of questions, as they are dedicated to gaming across multiple generations. If we allow game identification questions, this site might become a dumping ground with them, rather than general retrocomputing questions.
176
Firstly, I'd like to say that I've just discovered that this new SE site exists and I'm very excited! There are a few games that I played in my childhood that I would like to play again but I don't know the titles. Is it on-topic to describe the games as much as possible and what platform they ran on and ask what they were called (one game per question)? It doesn't seem appropriate to ask on gaming.SE as it seems that site is only for recent games.
2016/06/26
[ "https://retrocomputing.meta.stackexchange.com/questions/176", "https://retrocomputing.meta.stackexchange.com", "https://retrocomputing.meta.stackexchange.com/users/2067/" ]
There are a number of sites within the SE network that have [identify-this](https://retrocomputing.stackexchange.com/questions/tagged/identify-this "show questions tagged 'identify-this'") tags, so why not this one? Note that a few of these sites periodically have on their metas a proposal to ban them. Particularly where there are a lot of such questions. See the soul searching on [Movies & TV](https://movies.meta.stackexchange.com/questions/2292/maintaining-improving-and-cleaning-up-identification-questions), a site that has a large number of them. As with all questions, they would go on merit. A good question describing one game from yesteryear clearly enough for a chance of an answer would be good for the site. We may attract vague questions - they should be closed as "*Unclear what you're asking*". Let us take some and see how we go. Note also, this site isn't for asking "*Where can I buy...*" questions, so we would restrict ourselves to identification. While on the subject - why not "*Identify this computer*" questions. After all, they have already been asked [elsewhere](https://movies.stackexchange.com/questions/26832/what-is-the-computer-that-benny-hill-hacks-in-the-italian-job-1969/31762#31762) too.
I think "identify-this" should be permitted, subject to the same restriction as on Gaming.SE: you need to have some artifact from the software. This could be * A screenshot * A clip of the soundtrack or a distinctive sound effect * A photo of a pair of peril-sensitive sunglasses * A distinctive line of text ("YOU ARE IN A MAZE OF TWISTY LITTLE PASSAGES, ALL ALIKE.") * and so on In short, there needs to be a way for the person answering to verify that yes, their answer matches the question. Note that "identify-this" should not be restricted to games. "What Apple II calculation program is [this screenshot](https://upload.wikimedia.org/wikipedia/commons/7/7a/Visicalc.png) from?" should be perfectly acceptable.
58,175,721
Imagine a data structure as follows, containing a value in `contents` that is an already encoded JSON fragment. ```swift let partial = """ { "foo": "Foo", "bar": 1 } """ struct Document { let contents: String let other: [String: Int] } let doc = Document(contents: partial, other: ["foo": 1]) ``` Desired output -------------- The combined data structure should use `contents` as is and encode `other`. ``` { "contents": { "foo": "Foo", "bar": 1 }, "other": { "foo": 1 } } ``` Using `Encodable` ----------------- The following implementation of `Encodable` encodes `Document` as JSON, however it also re-encodes `contents` into a string, meaning it is wrapped in quotes and has all `"` quotes escaped into `\"`. ```swift extension Document : Encodable { enum CodingKeys : String, CodingKey { case contents case other } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(contents, forKey: .contents) try container.encode(other, forKey: .other) } } ``` ### Output ``` { "contents": "{\"foo\": \"Foo\", \"bar\": 1}", "other": { "foo": 1 } } ``` How can `encode` just pass through `contents` as is?
2019/09/30
[ "https://Stackoverflow.com/questions/58175721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486998/" ]
You could achieve it by doing this: ``` let partial = """ { "foo": "Foo", "bar": 1 } """ // declare a new type for `content` to deal with it as an object instead of a string struct Document { let contents: Contents let other: [String: Int] struct Contents: Codable { let foo: String let bar: Int } } extension Document : Encodable { enum CodingKeys: String, CodingKey { case contents case other } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(contents, forKey: .contents) try container.encode(other, forKey: .other) } } let decoder = JSONDecoder() let contents = try decoder.decode(Document.Contents.self, from: partial.data(using: .utf8)!) let encoder = JSONEncoder() let doc = Document(contents: contents, other: ["foo": 1]) let result = try encoder.encode(doc) print(String(data: result, encoding: .utf8)!) ``` Basically, you could deal with `partial` first by decoding it, and then you pass the decoded result of it to `Document`. The output should be: > > {"other":{"foo":1},"contents":{"foo":"Foo","bar":1}} > > >
I might be a bit late, but I hope it helps someone in the future. I've had a similar problem where I had some pre-encoded variables and wanted to nest them inside some parent structure that was encodable. ```swift struct Request: Encodable { let variables: [String: Data] // I'd encode data to JSON someplace else. } ``` Unfortunately, the type of each keyed value varied (e.g. you could have an integer in one key and an object in the other) and I couldn't pass information upwards from where I was encoding it the first time. Here's what I have in mind: ```json { "variables": { "one": { "hello": "world" }, "two": 2 } } ``` Enum and Generics were also not an option as this was a highly flexible part that only required types to conform to Encodable. All in all, I ended up copying over most of Swift's JSONEncoder implementation that you can find [here](https://github.com/apple/swift/blob/main/stdlib/public/Darwin/Foundation/JSONEncoder.swift). (I recommend cleaning out the JSONDecoder implementation since it's useless in our case.) The part that needs changing is inside the `encode` function in `JSONEncoder` class. Basically, you want to split the parts that get `topLevel` value (i.e. `NSObject`) and the part that serializes it. The new `encode` should also return a `NSObject`-type instead of `Data`. ```swift open func encode<T : Encodable>(_ value: T) throws -> NSObject { let encoder = __JSONEncoder(options: self.options) guard let topLevel = try encoder.box_(value) else { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) did not encode any values.")) } return topLevel } ``` Once you have that, you may pass `NSObject` anywhere as a type, the important chunk left is that you run `JSONSerialization.data` function to get the actual JSON. What JSONEncoder does internally is that it reduces an `Encodable` struct to `Foundation` types. `JSONSerialization` can then handle those types and you get a valid JSON. Here's how I used it: ```swift let body: Any = [ "query": query, // String "variables": variables // NSObject dictionary ] let httpBody = try! JSONSerialization.data( withJSONObject: body, options: JSONSerialization.WritingOptions() ) request.httpBody = httpBody ```
58,175,721
Imagine a data structure as follows, containing a value in `contents` that is an already encoded JSON fragment. ```swift let partial = """ { "foo": "Foo", "bar": 1 } """ struct Document { let contents: String let other: [String: Int] } let doc = Document(contents: partial, other: ["foo": 1]) ``` Desired output -------------- The combined data structure should use `contents` as is and encode `other`. ``` { "contents": { "foo": "Foo", "bar": 1 }, "other": { "foo": 1 } } ``` Using `Encodable` ----------------- The following implementation of `Encodable` encodes `Document` as JSON, however it also re-encodes `contents` into a string, meaning it is wrapped in quotes and has all `"` quotes escaped into `\"`. ```swift extension Document : Encodable { enum CodingKeys : String, CodingKey { case contents case other } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(contents, forKey: .contents) try container.encode(other, forKey: .other) } } ``` ### Output ``` { "contents": "{\"foo\": \"Foo\", \"bar\": 1}", "other": { "foo": 1 } } ``` How can `encode` just pass through `contents` as is?
2019/09/30
[ "https://Stackoverflow.com/questions/58175721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486998/" ]
I agree with Ahmad's basic approach, but I'm assuming you need something more dynamic. In that case, you should make clear that `content` is not a "String." It's JSON. And so you can store it as JSON using a [JSON type](https://gist.github.com/rnapier/d91175be2f737aca7ad476759948666e) (simplified here, see the gist for a more feature-rich version): ``` enum JSON: Codable { struct Key: CodingKey, Hashable, CustomStringConvertible { var description: String { return stringValue } let stringValue: String init(_ string: String) { self.stringValue = string } init?(stringValue: String) { self.init(stringValue) } var intValue: Int? { return nil } init?(intValue: Int) { return nil } } case string(String) case number(Double) // FIXME: Split Int and Double case object([Key: JSON]) case array([JSON]) case bool(Bool) case null init(from decoder: Decoder) throws { if let string = try? decoder.singleValueContainer().decode(String.self) { self = .string(string) } else if let number = try? decoder.singleValueContainer().decode(Double.self) { self = .number(number) } else if let object = try? decoder.container(keyedBy: Key.self) { var result: [Key: JSON] = [:] for key in object.allKeys { result[key] = (try? object.decode(JSON.self, forKey: key)) ?? .null } self = .object(result) } else if var array = try? decoder.unkeyedContainer() { var result: [JSON] = [] for _ in 0..<(array.count ?? 0) { result.append(try array.decode(JSON.self)) } self = .array(result) } else if let bool = try? decoder.singleValueContainer().decode(Bool.self) { self = .bool(bool) } else if let isNull = try? decoder.singleValueContainer().decodeNil(), isNull { self = .null } else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "Unknown JSON type")) } } func encode(to encoder: Encoder) throws { switch self { case .string(let string): var container = encoder.singleValueContainer() try container.encode(string) case .number(let number): var container = encoder.singleValueContainer() try container.encode(number) case .bool(let bool): var container = encoder.singleValueContainer() try container.encode(bool) case .object(let object): var container = encoder.container(keyedBy: Key.self) for (key, value) in object { try container.encode(value, forKey: key) } case .array(let array): var container = encoder.unkeyedContainer() for value in array { try container.encode(value) } case .null: var container = encoder.singleValueContainer() try container.encodeNil() } } } ``` With that you can redefine your document to hold JSON: ``` struct Document: Codable { let contents: JSON let other: [String: Int] } ``` And decode that JSON from a String if you like: ``` let doc = Document(contents: try! JSONDecoder().decode(JSON.self, from: Data(partial.utf8)), other: ["foo": 1]) ``` With that in place, the default `JSONEncoder()` is all you need to get the output you're describing.
I might be a bit late, but I hope it helps someone in the future. I've had a similar problem where I had some pre-encoded variables and wanted to nest them inside some parent structure that was encodable. ```swift struct Request: Encodable { let variables: [String: Data] // I'd encode data to JSON someplace else. } ``` Unfortunately, the type of each keyed value varied (e.g. you could have an integer in one key and an object in the other) and I couldn't pass information upwards from where I was encoding it the first time. Here's what I have in mind: ```json { "variables": { "one": { "hello": "world" }, "two": 2 } } ``` Enum and Generics were also not an option as this was a highly flexible part that only required types to conform to Encodable. All in all, I ended up copying over most of Swift's JSONEncoder implementation that you can find [here](https://github.com/apple/swift/blob/main/stdlib/public/Darwin/Foundation/JSONEncoder.swift). (I recommend cleaning out the JSONDecoder implementation since it's useless in our case.) The part that needs changing is inside the `encode` function in `JSONEncoder` class. Basically, you want to split the parts that get `topLevel` value (i.e. `NSObject`) and the part that serializes it. The new `encode` should also return a `NSObject`-type instead of `Data`. ```swift open func encode<T : Encodable>(_ value: T) throws -> NSObject { let encoder = __JSONEncoder(options: self.options) guard let topLevel = try encoder.box_(value) else { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) did not encode any values.")) } return topLevel } ``` Once you have that, you may pass `NSObject` anywhere as a type, the important chunk left is that you run `JSONSerialization.data` function to get the actual JSON. What JSONEncoder does internally is that it reduces an `Encodable` struct to `Foundation` types. `JSONSerialization` can then handle those types and you get a valid JSON. Here's how I used it: ```swift let body: Any = [ "query": query, // String "variables": variables // NSObject dictionary ] let httpBody = try! JSONSerialization.data( withJSONObject: body, options: JSONSerialization.WritingOptions() ) request.httpBody = httpBody ```
17,012
My Problem ========== I am editing a markdown file with some links in a `[link text](url)` format. Some of these links lack a space after the closing parens, e.g.: ``` ...fit the [Single Responsibility Principle](https://link...)and can ... ``` Which renders to a missing space after the link: > > ...fit the [Single Responsibility Principle](https://link...)and can ... > > > I am trying to build a regex search-replace to add a missing space after the closing parens where necessary. What have I (naively) tried =========================== Tried search-replacing with a regex: ``` %s#\)(\S)#\) (\1)#gc %s#\) - Closing parens %s#\)(\S) - Followed by a non-space %s#\)(\S)# - Replaced with... %s#\)(\S)#\) - The closing parens followed by a space %s#\)(\S)#\) (\1)#gc - And the original character ``` And, of course, Googled the problem. My question =========== **How can I add a space after every closing parens that has a non-space character just after it?**
2018/08/06
[ "https://vi.stackexchange.com/questions/17012", "https://vi.stackexchange.com", "https://vi.stackexchange.com/users/13179/" ]
What about ``` %s#)\zs\ze\S# #g ``` By default unless you change the [`'magic'`](http://vimhelp.appspot.com/options.txt.html#%27magic%27) option, a closing parenthesis is matched by just `)`. BTW, here I've cheated with [`:h /\zs`](http://vimhelp.appspot.com/pattern.txt.html#%2f%5czs) and [`:h /\ze`](http://vimhelp.appspot.com/pattern.txt.html#%2f%5cze) to mark the in between characters that we want to expand with a single space.
Try these: ``` # match ) followed by zero or more spaces and replace with ) and space s/) */) / # match ) followed by optional space and replace with ) and space s/) \?/) / ``` `)` is not escaped here, because by default `(` and `)` are not special Add `g` flag if you need to replace multiple occurrences in a line
17,012
My Problem ========== I am editing a markdown file with some links in a `[link text](url)` format. Some of these links lack a space after the closing parens, e.g.: ``` ...fit the [Single Responsibility Principle](https://link...)and can ... ``` Which renders to a missing space after the link: > > ...fit the [Single Responsibility Principle](https://link...)and can ... > > > I am trying to build a regex search-replace to add a missing space after the closing parens where necessary. What have I (naively) tried =========================== Tried search-replacing with a regex: ``` %s#\)(\S)#\) (\1)#gc %s#\) - Closing parens %s#\)(\S) - Followed by a non-space %s#\)(\S)# - Replaced with... %s#\)(\S)#\) - The closing parens followed by a space %s#\)(\S)#\) (\1)#gc - And the original character ``` And, of course, Googled the problem. My question =========== **How can I add a space after every closing parens that has a non-space character just after it?**
2018/08/06
[ "https://vi.stackexchange.com/questions/17012", "https://vi.stackexchange.com", "https://vi.stackexchange.com/users/13179/" ]
You can use the following command: ``` :g/)\([^ ]\)/s//) \1/g ``` Where the `[^ ]` means any character except space, the `\(\)` surrounding it is to group it and reference it later in the substitution as `\1`. Thus, it effectively adds a space after a `)` followed by any character except a space. But the above command does not add a space if the `)` is at the end of a line. To also add spaces to those too: ``` :g/)\([^ ]\|$\)/s//) \1/g ``` Where `$` represents end of line and the `\|` adds it to the match-any-character-except-space as an "or"
Try these: ``` # match ) followed by zero or more spaces and replace with ) and space s/) */) / # match ) followed by optional space and replace with ) and space s/) \?/) / ``` `)` is not escaped here, because by default `(` and `)` are not special Add `g` flag if you need to replace multiple occurrences in a line
1,556,663
Integrate $\int\frac{xe^{2x}}{(1+2x)^2}dx$ $u= 1+2x$ $du= 2 dx$ Now I saw a solution where a person took $xe^{2x}$ all together and used it as "du" but I did not understand how they were allowed to do that. If "u" must consist of the first function of this mnemonic: L-I-A-T-E L: Logarithmic Function I: Inverse Function A: Algebraic Function T: Trigonometric Function E: Exponential Function Keep in mind I am only allowed to use Integration by Parts.
2015/12/02
[ "https://math.stackexchange.com/questions/1556663", "https://math.stackexchange.com", "https://math.stackexchange.com/users/184004/" ]
If one is restricted here as suggested in the OP, then we proceed as follows. First, let $u=e^{2x}$ and $v=\frac{1}{4(2x+1)}+\frac14 \log(2x+1)$. So, $du=2e^{2x}$ and therefore we have $$\begin{align} \int \frac{xe^{2x}}{(1+2x)^2}\,dx&=\frac{e^{2x}}{4(2x+1)}+\frac14 e^{2x}\log(2x+1)\\\\ &-\int \frac{e^{2x}}{2(2x+1)}\,dx-\frac12 \int e^{2x}\log(2x+1)\,dx \tag 1 \end{align}$$ Now, we integrate by part the first integral on the right-hand side if $(1)$ by setting $u=e^{2x}$ and $v=\frac14 \log(2x+1)$. So, $du=2e^{2x}\,dx$ and therefore we have $$\begin{align} \int \frac{xe^{2x}}{(1+2x)^2}\,dx&=\frac{e^{2x}}{4(2x+1)}+\frac14 e^{2x}\log(2x+1)\\\\ &-\left(\frac14 e^{2x}\log(2x+1)-\frac12\int e^{2x}\log(2x+1)\,dx\right)-\frac12 \int e^{2x}\log(2x+1)\,dx\\\\ &=\frac{e^{2x}}{4(2x+1)}+C \end{align}$$ --- **NOTE:** In using integration by parts, We are free to choose the $u$ and the $v$ functions. So, $u=xe^{2x}$ is perfectly acceptable and actually facilitates analysis. Let's see how to proceed. If we let $u=xe^{2x}$, then $v=\frac{-1}{2(2x+1)}$. Proceeding, we have $du=(2x+1)e^{2x}\,dx$. Therefore, $$\begin{align} \int \frac{xe^{2x}}{(1+2x)^2}\,dx&=\frac{xe^{2x}}{2(2x+1)}-\int \frac{-1}{2(2x+1)}(2x+1)e^{2x}\,dx\\\\ &=\frac{xe^{2x}}{2x+1}+\frac{e^{2x}}{4}+C\\\\ &=\frac{e^{2x}}{4(2x+1)}+C \end{align}$$
Consider the integral as presented by the proposer: $\int\frac{xe^{2x}}{(1+2x)^2}dx$ with $u = 1 + 2x$. This leads to \begin{align} \int\frac{xe^{2x}}{(1+2x)^2}dx &= \frac{1}{2} \, \int \left(\frac{u-1}{2} \right) \, e^{u-1} \, \frac{du}{u^{2}} \\ &= \frac{1}{4e} \, \int \left( \frac{e^{u}}{u} - \frac{e^{u}}{u^{2}} \right) \, du \\ &= \frac{1}{4e} \, \left[ Ei(u) - \left( Ei(u) - \frac{e^{u}}{u} \right) \right] + c\_{0} \\ &= \frac{e^{u-1}}{4 \, u} + c\_{0} \\ &= \frac{e^{2x}}{4 \, (1+2x)} + c\_{0}. \end{align} Note that $Ei(x)$ is the Exponential integral. This solution produces the same solution as that presented by Dr.MV
77,193
> > “Imagine trying to **bleep** open your car one day,” says Graham Steel, > the boss of Cryptosense, a firm that makes automated security-checking > software, “but then you’re told that your car has been locked, and if > you want back in you need to send $200 to some shady Russian e-mail > address.” > > > This sentence is extracted from *The economist*. I looked up the dictionary and found that "bleep" can be used as noun or verb. In this sentence, I think "open" is the verb, then "bleep" should be an adverb to modify "open". But there is not such usage in dictionary. Does "bleep" make sense if it is a noun or a verb in this sentence? and how? The whole paragrah is: > > A recent development is “ransomware”, in which malicious programs > encrypt documents and photographs, and a victim must pay to have them > restored. “Imagine trying to bleep open your car one day,” says Graham > Steel, the boss of Cryptosense, a firm that makes automated > security-checking software, “but then you’re told that your car has > been locked, and if you want back in you need to send $200 to some > shady Russian e-mail address.” > > >
2015/12/28
[ "https://ell.stackexchange.com/questions/77193", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/26575/" ]
At first I thought it might have been an expletive that was deleted. If the sentence had been > > Your car has been bleeping stolen > > > I would have interpreted that as a placeholder for a swear word. But in context it is clear he is talking about a [car remote keyless system](https://en.m.wikipedia.org/wiki/Remote_keyless_system). Typically these make a bleeping sound indicating that the door was locked/unlocked successfully.
In your example, the word **bleep** is as an **onomatopoeia** to signify the sound the car makes when remotely unlocked. In the same way that a **TV remote** is called a **blipper** (rhymes with flipper). It could be a **split infinitive**, but may also be the language in transition.
77,193
> > “Imagine trying to **bleep** open your car one day,” says Graham Steel, > the boss of Cryptosense, a firm that makes automated security-checking > software, “but then you’re told that your car has been locked, and if > you want back in you need to send $200 to some shady Russian e-mail > address.” > > > This sentence is extracted from *The economist*. I looked up the dictionary and found that "bleep" can be used as noun or verb. In this sentence, I think "open" is the verb, then "bleep" should be an adverb to modify "open". But there is not such usage in dictionary. Does "bleep" make sense if it is a noun or a verb in this sentence? and how? The whole paragrah is: > > A recent development is “ransomware”, in which malicious programs > encrypt documents and photographs, and a victim must pay to have them > restored. “Imagine trying to bleep open your car one day,” says Graham > Steel, the boss of Cryptosense, a firm that makes automated > security-checking software, “but then you’re told that your car has > been locked, and if you want back in you need to send $200 to some > shady Russian e-mail address.” > > >
2015/12/28
[ "https://ell.stackexchange.com/questions/77193", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/26575/" ]
At first I thought it might have been an expletive that was deleted. If the sentence had been > > Your car has been bleeping stolen > > > I would have interpreted that as a placeholder for a swear word. But in context it is clear he is talking about a [car remote keyless system](https://en.m.wikipedia.org/wiki/Remote_keyless_system). Typically these make a bleeping sound indicating that the door was locked/unlocked successfully.
In this case *bleep open* acts like a compound verb, such as the verb *[finger paint](http://www.learnersdictionary.com/definition/finger%20paint)*. A compound verb is when a noun is "added" to a verb, so that it becomes part of the verb. Other examples are *sugar coat* and *tap dance*. Many times a hyphen is used when spelling these words: this is to show that the noun/verb compound is being used as **one (compound) word**. And then if they get used a lot they can be spelled with no hyphen or space (*[breastfeed](http://www.oxforddictionaries.com/us/definition/american_english/breastfeed)*). So the author could have written *bleep-open*. But it is probably a fairly recent combination, without a lot of usage, and so people don't consider it a true compound word yet.
77,193
> > “Imagine trying to **bleep** open your car one day,” says Graham Steel, > the boss of Cryptosense, a firm that makes automated security-checking > software, “but then you’re told that your car has been locked, and if > you want back in you need to send $200 to some shady Russian e-mail > address.” > > > This sentence is extracted from *The economist*. I looked up the dictionary and found that "bleep" can be used as noun or verb. In this sentence, I think "open" is the verb, then "bleep" should be an adverb to modify "open". But there is not such usage in dictionary. Does "bleep" make sense if it is a noun or a verb in this sentence? and how? The whole paragrah is: > > A recent development is “ransomware”, in which malicious programs > encrypt documents and photographs, and a victim must pay to have them > restored. “Imagine trying to bleep open your car one day,” says Graham > Steel, the boss of Cryptosense, a firm that makes automated > security-checking software, “but then you’re told that your car has > been locked, and if you want back in you need to send $200 to some > shady Russian e-mail address.” > > >
2015/12/28
[ "https://ell.stackexchange.com/questions/77193", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/26575/" ]
At first I thought it might have been an expletive that was deleted. If the sentence had been > > Your car has been bleeping stolen > > > I would have interpreted that as a placeholder for a swear word. But in context it is clear he is talking about a [car remote keyless system](https://en.m.wikipedia.org/wiki/Remote_keyless_system). Typically these make a bleeping sound indicating that the door was locked/unlocked successfully.
It's **not** a compound verb as others are writing. Compare *sugarcoat* vs. *bleep open* in the following sentences: > > 1a. I tried to bleep open my car. > > > 1b. I tried to bleep my car open. > > > 2a. I tried to sugarcoat the scenario. > > > 2b. \*I tried to coat the scenario sugar. > > > (1b) is perfectly valid, separating the **verb** *bleep* from the **[object complement](http://www.grammar-monster.com/glossary/object_complement.htm) adjective** *open*. Doing the same in (2b), with compound verbs like *sugarcoat*, this is clearly ungrammatical. If *bleep open* were indeed a compound verb, it would behave as a single verb -- an inseparable unit like *sugarcoat* or *tap dance* -- but it does not. The sentence structure used in the article is the same as in "I tried to force open my car". Again, *force* is the transitive verb and *open* is an object complement. So what kind of a verb is *bleep*? It's an [onomatopoeia](https://en.wikipedia.org/wiki/Onomatopoeia) used as a transitive verb. This happens now and then in informal, spoken language. Here's a less grammatically confusing example from Merriam-Webster: > > [[She] keeps *dinging* it into him that the less he smokes the better.](http://www.merriam-webster.com/dictionary/ding) > > > You could also say something like this: > > He told me my [air horn](https://en.wikipedia.org/wiki/Air_horn) was getting annoying, so I *honked* him away. > > > Here, that means: I drove him away using some tool (the air horn) that makes a honking sound. Similarly, *bleep* is used in the same sense; the tool being used (the keypad on a remote keyless system) makes a *blip!* sound when you open your car with it.
77,193
> > “Imagine trying to **bleep** open your car one day,” says Graham Steel, > the boss of Cryptosense, a firm that makes automated security-checking > software, “but then you’re told that your car has been locked, and if > you want back in you need to send $200 to some shady Russian e-mail > address.” > > > This sentence is extracted from *The economist*. I looked up the dictionary and found that "bleep" can be used as noun or verb. In this sentence, I think "open" is the verb, then "bleep" should be an adverb to modify "open". But there is not such usage in dictionary. Does "bleep" make sense if it is a noun or a verb in this sentence? and how? The whole paragrah is: > > A recent development is “ransomware”, in which malicious programs > encrypt documents and photographs, and a victim must pay to have them > restored. “Imagine trying to bleep open your car one day,” says Graham > Steel, the boss of Cryptosense, a firm that makes automated > security-checking software, “but then you’re told that your car has > been locked, and if you want back in you need to send $200 to some > shady Russian e-mail address.” > > >
2015/12/28
[ "https://ell.stackexchange.com/questions/77193", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/26575/" ]
At first I thought it might have been an expletive that was deleted. If the sentence had been > > Your car has been bleeping stolen > > > I would have interpreted that as a placeholder for a swear word. But in context it is clear he is talking about a [car remote keyless system](https://en.m.wikipedia.org/wiki/Remote_keyless_system). Typically these make a bleeping sound indicating that the door was locked/unlocked successfully.
This is a case of using the *effect* (a noun, in this case the sound) of an action as a verb to describe the action itself. If you are unfamiliar with the sound heard when unlocking a vehicle, listen to [this video](https://www.youtube.com/watch?v=m15Fr95s7i8&t=3s) for an example of the bleeping sound. ### Consider other examples such as: > > "I'll buzz you in" > > > …to describe pressing a button to allow somebody to enter a building — this creates a "buzz"ing sound to indicate to the visitor that the door is now open. > > "I'll ring you" > > > …to describe contacting somebody via telephone — this causes the recipient's telephone to "ring", alerting the recipient that they have a call incoming. > > "I'll chug a drink" > > > …to describe consuming a drink — depending how loudly this is done you may hear a "chug" sound from the throat when swallowing. > > "…bleep your car open" > > > …to describe pressing the "open" button on your keyfob — this causes the car's doors to unlock. To alert you that the car is now locked/unlocked, typically there will be a series of flashes/beeps to indicate that this has happened.
77,193
> > “Imagine trying to **bleep** open your car one day,” says Graham Steel, > the boss of Cryptosense, a firm that makes automated security-checking > software, “but then you’re told that your car has been locked, and if > you want back in you need to send $200 to some shady Russian e-mail > address.” > > > This sentence is extracted from *The economist*. I looked up the dictionary and found that "bleep" can be used as noun or verb. In this sentence, I think "open" is the verb, then "bleep" should be an adverb to modify "open". But there is not such usage in dictionary. Does "bleep" make sense if it is a noun or a verb in this sentence? and how? The whole paragrah is: > > A recent development is “ransomware”, in which malicious programs > encrypt documents and photographs, and a victim must pay to have them > restored. “Imagine trying to bleep open your car one day,” says Graham > Steel, the boss of Cryptosense, a firm that makes automated > security-checking software, “but then you’re told that your car has > been locked, and if you want back in you need to send $200 to some > shady Russian e-mail address.” > > >
2015/12/28
[ "https://ell.stackexchange.com/questions/77193", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/26575/" ]
In your example, the word **bleep** is as an **onomatopoeia** to signify the sound the car makes when remotely unlocked. In the same way that a **TV remote** is called a **blipper** (rhymes with flipper). It could be a **split infinitive**, but may also be the language in transition.
In this case *bleep open* acts like a compound verb, such as the verb *[finger paint](http://www.learnersdictionary.com/definition/finger%20paint)*. A compound verb is when a noun is "added" to a verb, so that it becomes part of the verb. Other examples are *sugar coat* and *tap dance*. Many times a hyphen is used when spelling these words: this is to show that the noun/verb compound is being used as **one (compound) word**. And then if they get used a lot they can be spelled with no hyphen or space (*[breastfeed](http://www.oxforddictionaries.com/us/definition/american_english/breastfeed)*). So the author could have written *bleep-open*. But it is probably a fairly recent combination, without a lot of usage, and so people don't consider it a true compound word yet.
77,193
> > “Imagine trying to **bleep** open your car one day,” says Graham Steel, > the boss of Cryptosense, a firm that makes automated security-checking > software, “but then you’re told that your car has been locked, and if > you want back in you need to send $200 to some shady Russian e-mail > address.” > > > This sentence is extracted from *The economist*. I looked up the dictionary and found that "bleep" can be used as noun or verb. In this sentence, I think "open" is the verb, then "bleep" should be an adverb to modify "open". But there is not such usage in dictionary. Does "bleep" make sense if it is a noun or a verb in this sentence? and how? The whole paragrah is: > > A recent development is “ransomware”, in which malicious programs > encrypt documents and photographs, and a victim must pay to have them > restored. “Imagine trying to bleep open your car one day,” says Graham > Steel, the boss of Cryptosense, a firm that makes automated > security-checking software, “but then you’re told that your car has > been locked, and if you want back in you need to send $200 to some > shady Russian e-mail address.” > > >
2015/12/28
[ "https://ell.stackexchange.com/questions/77193", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/26575/" ]
It's **not** a compound verb as others are writing. Compare *sugarcoat* vs. *bleep open* in the following sentences: > > 1a. I tried to bleep open my car. > > > 1b. I tried to bleep my car open. > > > 2a. I tried to sugarcoat the scenario. > > > 2b. \*I tried to coat the scenario sugar. > > > (1b) is perfectly valid, separating the **verb** *bleep* from the **[object complement](http://www.grammar-monster.com/glossary/object_complement.htm) adjective** *open*. Doing the same in (2b), with compound verbs like *sugarcoat*, this is clearly ungrammatical. If *bleep open* were indeed a compound verb, it would behave as a single verb -- an inseparable unit like *sugarcoat* or *tap dance* -- but it does not. The sentence structure used in the article is the same as in "I tried to force open my car". Again, *force* is the transitive verb and *open* is an object complement. So what kind of a verb is *bleep*? It's an [onomatopoeia](https://en.wikipedia.org/wiki/Onomatopoeia) used as a transitive verb. This happens now and then in informal, spoken language. Here's a less grammatically confusing example from Merriam-Webster: > > [[She] keeps *dinging* it into him that the less he smokes the better.](http://www.merriam-webster.com/dictionary/ding) > > > You could also say something like this: > > He told me my [air horn](https://en.wikipedia.org/wiki/Air_horn) was getting annoying, so I *honked* him away. > > > Here, that means: I drove him away using some tool (the air horn) that makes a honking sound. Similarly, *bleep* is used in the same sense; the tool being used (the keypad on a remote keyless system) makes a *blip!* sound when you open your car with it.
In this case *bleep open* acts like a compound verb, such as the verb *[finger paint](http://www.learnersdictionary.com/definition/finger%20paint)*. A compound verb is when a noun is "added" to a verb, so that it becomes part of the verb. Other examples are *sugar coat* and *tap dance*. Many times a hyphen is used when spelling these words: this is to show that the noun/verb compound is being used as **one (compound) word**. And then if they get used a lot they can be spelled with no hyphen or space (*[breastfeed](http://www.oxforddictionaries.com/us/definition/american_english/breastfeed)*). So the author could have written *bleep-open*. But it is probably a fairly recent combination, without a lot of usage, and so people don't consider it a true compound word yet.
77,193
> > “Imagine trying to **bleep** open your car one day,” says Graham Steel, > the boss of Cryptosense, a firm that makes automated security-checking > software, “but then you’re told that your car has been locked, and if > you want back in you need to send $200 to some shady Russian e-mail > address.” > > > This sentence is extracted from *The economist*. I looked up the dictionary and found that "bleep" can be used as noun or verb. In this sentence, I think "open" is the verb, then "bleep" should be an adverb to modify "open". But there is not such usage in dictionary. Does "bleep" make sense if it is a noun or a verb in this sentence? and how? The whole paragrah is: > > A recent development is “ransomware”, in which malicious programs > encrypt documents and photographs, and a victim must pay to have them > restored. “Imagine trying to bleep open your car one day,” says Graham > Steel, the boss of Cryptosense, a firm that makes automated > security-checking software, “but then you’re told that your car has > been locked, and if you want back in you need to send $200 to some > shady Russian e-mail address.” > > >
2015/12/28
[ "https://ell.stackexchange.com/questions/77193", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/26575/" ]
This is a case of using the *effect* (a noun, in this case the sound) of an action as a verb to describe the action itself. If you are unfamiliar with the sound heard when unlocking a vehicle, listen to [this video](https://www.youtube.com/watch?v=m15Fr95s7i8&t=3s) for an example of the bleeping sound. ### Consider other examples such as: > > "I'll buzz you in" > > > …to describe pressing a button to allow somebody to enter a building — this creates a "buzz"ing sound to indicate to the visitor that the door is now open. > > "I'll ring you" > > > …to describe contacting somebody via telephone — this causes the recipient's telephone to "ring", alerting the recipient that they have a call incoming. > > "I'll chug a drink" > > > …to describe consuming a drink — depending how loudly this is done you may hear a "chug" sound from the throat when swallowing. > > "…bleep your car open" > > > …to describe pressing the "open" button on your keyfob — this causes the car's doors to unlock. To alert you that the car is now locked/unlocked, typically there will be a series of flashes/beeps to indicate that this has happened.
In this case *bleep open* acts like a compound verb, such as the verb *[finger paint](http://www.learnersdictionary.com/definition/finger%20paint)*. A compound verb is when a noun is "added" to a verb, so that it becomes part of the verb. Other examples are *sugar coat* and *tap dance*. Many times a hyphen is used when spelling these words: this is to show that the noun/verb compound is being used as **one (compound) word**. And then if they get used a lot they can be spelled with no hyphen or space (*[breastfeed](http://www.oxforddictionaries.com/us/definition/american_english/breastfeed)*). So the author could have written *bleep-open*. But it is probably a fairly recent combination, without a lot of usage, and so people don't consider it a true compound word yet.
39,634,991
I am using dlopen to merge symbols of a dynamically loaded library and its host, and in the host I have a class: ``` class Foo { public: Foo() {/* ... */} void bar() {/* ... */} }; int main() { // Foo foo; return 0; } ``` I am compiling this with `g++ -Wl,--export-dynamic -o test test.cpp` and inspecting the symbols with `nm -g test`. I expect the symbols `_ZN3FooC1Ev` and `_ZN3FooC2Ev` to exist in the executable, since the dynamic library needs them, but they do not appear unless I use them by un-commenting the above line. I believe it is being optimized out, since GCC thinks it is not needed. How do I force the constructor and methods of Foo to be included in the host binary?
2016/09/22
[ "https://Stackoverflow.com/questions/39634991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/272642/" ]
A class definition with inlined method definitions do not generate any symbol if you don't, at least, define an object. So don't define the methods as inlined if you want to ensure their visibility...
In order to generate dynamicaly loaded libraries you habe to build it with: ``` $ gcc -shared -fPIC -o lib1.so lib1.c ``` **-fPIC** is used to tell GCC to produce Position Independent Code. -**shared** is used to indicate it’s a shared object To link against your library test.so you can use the following: ``` $ gcc -L$(pwd) -Wl,-rpath=$(pwd) --enable-new-dtags -o test main.c -l1 -l2 ``` With **-rpath=/my/location** you tell the linker the list of alternate locations To verify the dynamic section of your binary you can use:`$ readelf -d test`
9,037,605
The value of the TextView is inserted by selecting the Item on List (ArrayList). When I close and open the app again the value in the TextView is still there. There is some way to clear the value of TextView?
2012/01/27
[ "https://Stackoverflow.com/questions/9037605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1112535/" ]
``` TextView myTextView = (TextView) findViewById(R.id.myTextView); myTextView.setText(""); ```
For that TextView use ``` android:text="" ``` in the layout or user textView.setText("") in the oncreate() method for the activity where textView is the TextView object retrieved from findViewById()
9,037,605
The value of the TextView is inserted by selecting the Item on List (ArrayList). When I close and open the app again the value in the TextView is still there. There is some way to clear the value of TextView?
2012/01/27
[ "https://Stackoverflow.com/questions/9037605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1112535/" ]
``` TextView myTextView = (TextView) findViewById(R.id.myTextView); myTextView.setText(""); ```
If you would like for your **hints** to show in the fields, don't set the TextView text to an empty string; instead, set it to **null**. ``` TextView myTextView = (TextView) findViewById(R.id.myTextView); myTextView.setText(null); ```
9,037,605
The value of the TextView is inserted by selecting the Item on List (ArrayList). When I close and open the app again the value in the TextView is still there. There is some way to clear the value of TextView?
2012/01/27
[ "https://Stackoverflow.com/questions/9037605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1112535/" ]
If you would like for your **hints** to show in the fields, don't set the TextView text to an empty string; instead, set it to **null**. ``` TextView myTextView = (TextView) findViewById(R.id.myTextView); myTextView.setText(null); ```
For that TextView use ``` android:text="" ``` in the layout or user textView.setText("") in the oncreate() method for the activity where textView is the TextView object retrieved from findViewById()
29,052,010
I am having a table structure like this: ``` Date Count name 2015-03-05 154903 AAA 2015-03-04 153591 AAA 2015-03-03 151277 AAA 2015-03-06 93997 BBB 2015-03-03 93294 BBB 2015-03-02 79006 BBB 2015-03-08 77324 BBB 2015-03-06 144588 AAA 2015-03-07 144119 AAA 2015-03-02 133543 AAA 2015-03-01 124435 AAA 2015-03-08 115227 AAA 2015-03-05 98866 BBB 2015-03-04 96673 BBB 2015-03-07 96298 BBB 2015-03-01 68724 BBB 2015-03-05 55748 CCC 2015-03-01 55322 CCC ``` I need to find the maximum count from every value Eg. ``` AAA is having max value of 154903 BBB is having max value of 98866 CCC is having max value of 55322 ``` how query in mysql to fetch the data like this.
2015/03/14
[ "https://Stackoverflow.com/questions/29052010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4671239/" ]
Not much to it -- just use the `max` aggregate: ``` select name, max(countfield) from yourtable group by name ```
Like @GordonLinoff said, this is the very very basic of SQL. A simple group by should do it... `SELECT name, max(Count) FROM table GROUP BY name` Please read some about the [Group by](http://www.w3schools.com/sql/sql_groupby.asp) clause.
51,551,135
I'm new to **Python Django**, I have integrated my Django application on *Windows 7* machine. When I tried to integrate LDAP by using `pip install django-auth-ldap` but unfortunately I got an error ``` Failed building wheel for python-ldap Running setup.py clean for python-ldap Failed to build python-ldap django-python3-ldap 0.11.1 has requirement pyasn1==0.3.2, but you'll have pyasn1 0.4.4 which is incompatible. ``` Please help me to escape me from this issue, bcz I have been struck here for a couple of days
2018/07/27
[ "https://Stackoverflow.com/questions/51551135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4968181/" ]
I think this message is pretty clear: > > django-python3-ldap 0.11.1 has requirement pyasn1==0.3.2, but you'll have pyasn1 0.4.4 which is incompatible. > > > When using *django-python3-ldap* you have to explicitly use version 0.3.2 of module *pyasn1*. But something else already installed a newer version of *pyasn1* to you build environment. So you have to specify version pinning information in [install\_requires or requirements files](https://packaging.python.org/discussions/install-requires-vs-requirements/).
Try Updating pip using ``` python -m pip install -U pip ``` or ``` pip install --upgrade pip ```
85,660
I made this circuit to amplify the output of a load cell. ![schematic](https://i.stack.imgur.com/Jq9z3.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fJq9z3.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) The instrumental amplifier has a Gain = 750. I use a dedicated voltage regulator (LM350) because I want an output of max 5V. The circuit seems to work well (there's a bit of background noise), but when I'm close to the circuit the output is greater than before. The Output change a lot when I move my arms in the air. The cable from Load Cell to circuit are close in an aluminum foil connected to GND. Is this the correct way to read data form load Cell? Do you know how to remove the influence of a body? --- **More details:** *Thanks everyone for suggestion (it's only the second time I use electronics.stakexchange)* The schematic shows only a single part of the PCB circuit of my project. In the real circuit, between load cells and amplifier, there are two [demultiplexers](http://www.ti.com/lit/ds/symlink/cd74hc4051.pdf). They switch signal from 8 Load Cells to 1 amplifier. (1 demux manage the +In and the other the -In). On PCB there aren't capacitors. I tried to add capacitors in the breadboard version. ![The PCB without capacitors](https://i.stack.imgur.com/A41d1.jpg) The circuit and the load cells are mounted into a big aluminum case, not yet completely closed. ![The aluminum case](https://i.stack.imgur.com/IoBnW.jpg) In this picture the cables are uncovered, but during tests they are covered with silver foil. Every part of the aluminum case is connected to GND. For @ANDY AKA This is what the oscilloscope sees when I put my head near to the circuit in Breadboard version. ![CH 1 is the ampli supply, CH2 is the ampli output](https://i.stack.imgur.com/8fqTV.png) If I set AREF to 1V and move my arm near to the wires, you are right, the output do the opposite: it decreases.
2013/10/17
[ "https://electronics.stackexchange.com/questions/85660", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/30344/" ]
Rolling codes require several part to function correctly. Here I'll describe a generic implementation that uses all the parts in a specific way. Other systems are variations on this theme, but generally employ many of the same techniques in a similar way. Rather than try to describe the complete implementation and how it works at once, I'll describe a simple system, and add complexity as we go until we reach a cryptographically secure system. A non cryptographic rolling code is simply a transmitter and receiver that both use the same pseudo random number generator (PRNG). This generator has two pieces of important information: a calculation, and the previously generated number. The calculation is generally a linear feedback equation that can be represented by a single number. By feeding the PRNG with the previous number, and keeping the feedback number the same a specific sequence of numbers is generated. The sequence has no repeated sequences until it's gone through every number it can generate, and then it starts over again with the same sequence. If both remote and transmitter know the feedback number, and the current number, then when the remote transmits the next number, the receiver can test it against its own generator. If it matches, it activates. If it doesn't, it rolls through the sequence until it finds the number the remote sent. If you press the remote again, then it should match, and it'll activate because the previous transmission already synchronized the number generators. This is why you sometimes have to press the unlock button twice - your receiver or transmitter are out of sync. That's the rolling part of the code. If the PRNG is long enough, it's very hard to find out the feedback number without many numbers in the sequence in a row, which is hard to obtain in normal use. But it's not cryptographically secure. On top of that you add typical encryption. The vehicle manufacturer uses a specific secret key for the transmitter and receiver. Depending on the manufacturer you might find that each model and year have a different code, or they might share the code among several models of vehicles and over several years. The trade off is that each one then requires a different remote to be stocked, but the problem with sharing a code over many models is that if it's broken then more cars are vulnerable. Behind the encryption you have button info, the PRNG generated number, and a little information about the feedback number. Not enough to make the PRNG from scratch, but enough that after a certain number of button presses, and with some inside information about the limited space a feedback number can involve (again, manufacturer, line specific) then the receiver can, after several training transmissions, determine the feedback number, and start tracking the PRNG for that remote. The rolling code is meant only to stop replay attacks. The encryption is meant to secure the rolling code to avoid it being broken. With only one or the other the system would be too easy to break. Since the manufacturer controls both the transmitter and receiver, training doesn't involve public key cryptography or anything particularly involved. It also prevents aftermarket fobs from working in cars with this type of system. Rolling code isn't impervious, though. The old keeloq system was successfully attacked just a few years ago (after a decade of use) so the manufacturer encryption code can be found, and the rolling codes can be found more easily. Earlier than that it has been attacked in ways that allowed people to take vehicles without actually breaking the code. In response the new encryption key is 60 bits. Not as secure as many modern encryption systems, but secure enough that it'll probably last many more years before it's broken.
I first encountered KeeLoq when researching the chip in a garage door opener. The [Microchip datasheet](http://ww1.microchip.com/downloads/en/devicedoc/21143b.pdf) does a good job of explaining how it works. In a nutshell: * the receiver maintains a database of all transmitters, keyed on their serial number. * each transmitter is associated with a symmetric encryption key (64 bit), which is on the chip, and also in the receiver's database. * each transmitter is associated with a 16 bit cyclic sequence number, also stored on the chip and in the database. * when the transmitter is activated, it increments its sequence number modulo 65536 (wraparound 16 bits), and sends a packet consisting of a bitmask representing what buttons are pressed, its serial ID, and an encrypted version of the serial number. * the receiver matches the serial number in the database, pulls out the key and decrypts the serial number. * the serial number has to be new; it cannot be a recently used serial number, which guards against replay attacks. (See Fig. 7.3 in the datasheet). * if the serial number verifies, then the receiver can activate functionality based on the bit mask of what buttons are pressed. * if the new serial number is ahead by more than 16 values (the user pushed the buttons many times accidentally while away from the receiver) then an extra hand-shake has to take place to resynchronize, which requires an extra button press. (The user will perform the extra button press, believing there is bad reception). Adding a new transmitter to the receiver database is vaguely analogous, on a high level, to the button-press configuration method for adding clients to a Wi-Fi access point. The receiver is somehow told put into a mode whereby it accepts a new transmitter. A new transmitter can be accepted from information passed in ordinary activation messages, if the receiver and transmitter share the same secret manufacturer ID. This is because the 64 bit encryption key is derived from the manufacturer ID and serial information of the receiver. (See Sec. 7.1). There is a more secure alternative to this: the "Secure Learn". This is initiated in a special way on the transmitter (three buttons pressed at once). The transmitter sends a special packet: a 60 bit seed value from which the encryption key is derived, presumably not depending on the manufacturer ID or serial number. When the receiver is not in learn mode, it of course rejects transmissions from transmitters that it does not know about.
882,147
A bit like other questions on touchpads but with a twist, I think. The touchpad in this Lenovo IdeaPad Z360 had been acting up even when it ran Windows 7. I switched to an external USB optical mouse, but the thing often disappears, buttons stop working or pointer starts moving on its own. xinput lists the following pointer devices: ``` ⎡ Virtual core pointer id=2 [master pointer (3)] ⎜ ↳ Virtual core XTEST pointer id=4 [slave pointer (2)] ⎜ ↳ USB OPTICAL MOUSE id=10 [slave pointer (2)] ⎜ ↳ PS/2 Generic Mouse id=14 [slave pointer (2)] ``` "USB OPTICAL MOUSE" is external mouse. Is it possible that the two devices are fighting for control of the pointer and buttons? How can I disable "PS/2 Generic Mouse" and leave "USB OPTICAL MOUSE" reign unchallenged?
2017/02/11
[ "https://askubuntu.com/questions/882147", "https://askubuntu.com", "https://askubuntu.com/users/652037/" ]
steeldrivers suggestion worked perfectly! ``` sudo mount /dev/mapper/vg1000-lv /mnt ``` still unmounting never got fixed, but got it all copied over the network and disks were formatted so, that got that solved.
I am not an expert on LVM or mdadm but here's what I did to solve a related problem on Ubuntu 18. A single hard drive SHR attached trough USB-SATA adapter. The system tries to automatically set the RAID volume, but something goes wrong: If I try to assemble: ``` mdadm -Asf && vgchange -ay mdadm: Found some drive for an array that is already active: /dev/md/DiskStation:2 mdadm: giving up. mdadm: No arrays found in config file or automatically ``` or `mount`: ``` mount /dev/mapper/vg1000-lv /mnt/ mount: /mnt: can't read superblock on /dev/mapper/vg1000-lv. ``` I have checked and the system already mapped a `/dev/mdXXX` to the SHR drive. So: ``` dmsetup remove /dev/mapper/vg1000-lv mdadm --stop /dev/mdXXX ``` And after it's possible to retry to assemble with mdadm: ``` mdadm -Asf && vgchange -ay ``` The mount reference is under `/media/xxxxx/volumeToMount`
351,145
The answer at first sight seems quite obvious and negative. Consider this: There is an electron. Right of it is a positive charge. It gets accelerated towards right. Now, instantaneously, I remove the charge on right and put a charge on the left. The acceleration changes from right to left instantly. Won't it make an inverted 'V' like velocity time graph ? Now if such a graph exists then acceleration at the kink would be undefined and hence force applied at that time would be undefined which it is not at any point of time. PS:The distance between the electron and the positive charge is always same, though electron moves towards one charge, the charge is also moved away with some external force.
2017/08/09
[ "https://physics.stackexchange.com/questions/351145", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/72343/" ]
What you describe is a mathematically contrived situation where the forces on a particle change instantaneously. In such situations, I fall back on really boring and obvious tautologies: "If the forces on a particle change instantaneously, the forces on that particle change instantaneously." You will define the forces on this particle in a piece-wise manner. It is up to you and your mathematical games as to whether the force is defined to be positive at that instant, negative at that instant, or undefined. If it's undefined, then you can no longer integrate acceleration to get velocity, and all of your physics breaks. However, if you choose to define the velocity to be positive or negative at that moment, you can at least integrate acceleration to get velocity. You will get the "V' curve you refer to. However, in reality, forces do not pop into existence instantaneously as you describe. Particles move continuously. You will never come across a case where you get undefined values like this. At least, you wont come across them until you get into modeling black holes. But they're a special sort of problem.
Note that the velocity time graph in this case has a sharp kink at that point implying that the function is not differentiable at that points. In any realistic situation, the functions will be differentiable at all points and the graphs will be smooth. What this means physically is that and velocity cannot change values abruptly at an instant. Changes are always continuous.
6,781,886
can anybody tell me that in c# why does char takes two bytes although it can be stored in one byte. Don't you think it is wastage of a memory. if not , then how is extra 1-byte used? in simple words ..please make me clear what is the use of extra 8-bits.!!
2011/07/21
[ "https://Stackoverflow.com/questions/6781886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/856755/" ]
> > The char keyword is used to declare a Unicode character in the range indicated in the following table. Unicode characters are 16-bit characters used to represent most of the known written languages throughout the world. > > > <http://msdn.microsoft.com/en-us/library/x9h8tsay%28v=vs.80%29.aspx>
Unicode characters. True, we have enough room in 8bits for the English alphabet, but when it comes to Chinese and such, it takes a lot more characters.
6,781,886
can anybody tell me that in c# why does char takes two bytes although it can be stored in one byte. Don't you think it is wastage of a memory. if not , then how is extra 1-byte used? in simple words ..please make me clear what is the use of extra 8-bits.!!
2011/07/21
[ "https://Stackoverflow.com/questions/6781886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/856755/" ]
Unicode characters. True, we have enough room in 8bits for the English alphabet, but when it comes to Chinese and such, it takes a lot more characters.
because utf-8 was probably still too young for microsoft to consider using it
6,781,886
can anybody tell me that in c# why does char takes two bytes although it can be stored in one byte. Don't you think it is wastage of a memory. if not , then how is extra 1-byte used? in simple words ..please make me clear what is the use of extra 8-bits.!!
2011/07/21
[ "https://Stackoverflow.com/questions/6781886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/856755/" ]
> > although it can be stored in one byte > > > What makes you think that? It only takes one byte to represent every character in the English language, but other languages use other characters. Consider the number of different alphabets (Latin, Chinese, Arabic, Cyrillic...), and the number of symbols in each of these alphabets (not only letters or digits, but also punctuation marks and other special symbols)... there are tens of thousands of different symbols in use in the world ! So one byte is never going to be enough to represent them all, that's why the [Unicode](http://en.wikipedia.org/wiki/Unicode) standard was created. Unicode has several representations (UTF-8, UTF-16, UTF-32...). .NET strings use UTF-16, which takes two bytes per character (code points, actually). Of course, two bytes is still not enough to represent all the different symbols in the world; surrogate pairs are used to represent characters above U+FFFF
Unicode characters. True, we have enough room in 8bits for the English alphabet, but when it comes to Chinese and such, it takes a lot more characters.
6,781,886
can anybody tell me that in c# why does char takes two bytes although it can be stored in one byte. Don't you think it is wastage of a memory. if not , then how is extra 1-byte used? in simple words ..please make me clear what is the use of extra 8-bits.!!
2011/07/21
[ "https://Stackoverflow.com/questions/6781886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/856755/" ]
> > The char keyword is used to declare a Unicode character in the range indicated in the following table. Unicode characters are 16-bit characters used to represent most of the known written languages throughout the world. > > > <http://msdn.microsoft.com/en-us/library/x9h8tsay%28v=vs.80%29.aspx>
In C#, char's are 16-bit Unicode characters by default. Unicode supports a much larger character set than can be supported by ASCII. If memory really is a concern, here is a good discussion on SO regarding how you might work with 8-bit chars: [Is there a string type with 8 BIT chars?](https://stackoverflow.com/questions/4916838/is-there-a-string-type-with-8-bit-chars) References: On C#'s char datatype: <http://msdn.microsoft.com/en-us/library/x9h8tsay(v=vs.80).aspx> On Unicode: <http://en.wikipedia.org/wiki/Unicode>
6,781,886
can anybody tell me that in c# why does char takes two bytes although it can be stored in one byte. Don't you think it is wastage of a memory. if not , then how is extra 1-byte used? in simple words ..please make me clear what is the use of extra 8-bits.!!
2011/07/21
[ "https://Stackoverflow.com/questions/6781886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/856755/" ]
> > The char keyword is used to declare a Unicode character in the range indicated in the following table. Unicode characters are 16-bit characters used to represent most of the known written languages throughout the world. > > > <http://msdn.microsoft.com/en-us/library/x9h8tsay%28v=vs.80%29.aspx>
because utf-8 was probably still too young for microsoft to consider using it
6,781,886
can anybody tell me that in c# why does char takes two bytes although it can be stored in one byte. Don't you think it is wastage of a memory. if not , then how is extra 1-byte used? in simple words ..please make me clear what is the use of extra 8-bits.!!
2011/07/21
[ "https://Stackoverflow.com/questions/6781886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/856755/" ]
> > although it can be stored in one byte > > > What makes you think that? It only takes one byte to represent every character in the English language, but other languages use other characters. Consider the number of different alphabets (Latin, Chinese, Arabic, Cyrillic...), and the number of symbols in each of these alphabets (not only letters or digits, but also punctuation marks and other special symbols)... there are tens of thousands of different symbols in use in the world ! So one byte is never going to be enough to represent them all, that's why the [Unicode](http://en.wikipedia.org/wiki/Unicode) standard was created. Unicode has several representations (UTF-8, UTF-16, UTF-32...). .NET strings use UTF-16, which takes two bytes per character (code points, actually). Of course, two bytes is still not enough to represent all the different symbols in the world; surrogate pairs are used to represent characters above U+FFFF
> > The char keyword is used to declare a Unicode character in the range indicated in the following table. Unicode characters are 16-bit characters used to represent most of the known written languages throughout the world. > > > <http://msdn.microsoft.com/en-us/library/x9h8tsay%28v=vs.80%29.aspx>
6,781,886
can anybody tell me that in c# why does char takes two bytes although it can be stored in one byte. Don't you think it is wastage of a memory. if not , then how is extra 1-byte used? in simple words ..please make me clear what is the use of extra 8-bits.!!
2011/07/21
[ "https://Stackoverflow.com/questions/6781886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/856755/" ]
In C#, char's are 16-bit Unicode characters by default. Unicode supports a much larger character set than can be supported by ASCII. If memory really is a concern, here is a good discussion on SO regarding how you might work with 8-bit chars: [Is there a string type with 8 BIT chars?](https://stackoverflow.com/questions/4916838/is-there-a-string-type-with-8-bit-chars) References: On C#'s char datatype: <http://msdn.microsoft.com/en-us/library/x9h8tsay(v=vs.80).aspx> On Unicode: <http://en.wikipedia.org/wiki/Unicode>
because utf-8 was probably still too young for microsoft to consider using it
6,781,886
can anybody tell me that in c# why does char takes two bytes although it can be stored in one byte. Don't you think it is wastage of a memory. if not , then how is extra 1-byte used? in simple words ..please make me clear what is the use of extra 8-bits.!!
2011/07/21
[ "https://Stackoverflow.com/questions/6781886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/856755/" ]
> > although it can be stored in one byte > > > What makes you think that? It only takes one byte to represent every character in the English language, but other languages use other characters. Consider the number of different alphabets (Latin, Chinese, Arabic, Cyrillic...), and the number of symbols in each of these alphabets (not only letters or digits, but also punctuation marks and other special symbols)... there are tens of thousands of different symbols in use in the world ! So one byte is never going to be enough to represent them all, that's why the [Unicode](http://en.wikipedia.org/wiki/Unicode) standard was created. Unicode has several representations (UTF-8, UTF-16, UTF-32...). .NET strings use UTF-16, which takes two bytes per character (code points, actually). Of course, two bytes is still not enough to represent all the different symbols in the world; surrogate pairs are used to represent characters above U+FFFF
In C#, char's are 16-bit Unicode characters by default. Unicode supports a much larger character set than can be supported by ASCII. If memory really is a concern, here is a good discussion on SO regarding how you might work with 8-bit chars: [Is there a string type with 8 BIT chars?](https://stackoverflow.com/questions/4916838/is-there-a-string-type-with-8-bit-chars) References: On C#'s char datatype: <http://msdn.microsoft.com/en-us/library/x9h8tsay(v=vs.80).aspx> On Unicode: <http://en.wikipedia.org/wiki/Unicode>