qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
459,592
I have winXP LibreOffice and MS office installed. How do I make LibreOffice the default opening program for all of its know document types? I know that I can change one extension at a time. But is there a way to change all of them? I want LibreOffice to open .doc .xls and ... (I do not know all of them)
2012/08/09
[ "https://superuser.com/questions/459592", "https://superuser.com", "https://superuser.com/users/114476/" ]
'Modify' worked for me. Thanks! On Windows Vista: * click START * Settings * Control Panel * Programs * Programs and Features * Uninstall a Program * Select the right program from the list * click 'change' * follow instructions.
For me it worked to just use the "default apps" in windows system settings. just hit start and type default apps
459,592
I have winXP LibreOffice and MS office installed. How do I make LibreOffice the default opening program for all of its know document types? I know that I can change one extension at a time. But is there a way to change all of them? I want LibreOffice to open .doc .xls and ... (I do not know all of them)
2012/08/09
[ "https://superuser.com/questions/459592", "https://superuser.com", "https://superuser.com/users/114476/" ]
To make office libre the default reader for all your documents: Right click any document, tap Properties. A box opens that enables you to change the opener to office libre. Do this for a couple documents and OL magically becomes the default opener for all docs of the same type This works for windows 10 at least.
For me it worked to just use the "default apps" in windows system settings. just hit start and type default apps
71,391,657
I would like to add a 301 redirect when users visit a specific page and redirect them to a PDF file. In my **.htaccess** file I tried something like this this but it gives me a 404 error. However if I visit the path, the PDF it's there ``` Redirect 301 /subpage https://www.mywebsite/upload/files/file.pdf ``` What am I doing wrong? PS: I am using WordPress
2022/03/08
[ "https://Stackoverflow.com/questions/71391657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16886893/" ]
Redirect in htaccess does not matter if it is a pdf file or anything else just a **valid link**. This is an example of a 301 redirect code to the link you want `RedirectMatch 301 /subpage/ <https://www.mywebsite.com/upload/files/file.pdf>`
To target an HTML link to a specific page in a PDF file, add #page=[page number] to the end of the link's URL. For example, this HTML tag opens page 4 of a PDF file named myfile.pdf: ``` <A HREF="http://www.example.com/myfile.pdf#page=4"> ``` --- And If you want to redirect a single page to another you just need to insert this line in the .htaccess file: Redirect 301 /old-post <https://www.yourwebsite.com/myfiles/myfile.pdf> Going to replace the old and new addresses respectively. The code must be inserted after and before .
71,391,657
I would like to add a 301 redirect when users visit a specific page and redirect them to a PDF file. In my **.htaccess** file I tried something like this this but it gives me a 404 error. However if I visit the path, the PDF it's there ``` Redirect 301 /subpage https://www.mywebsite/upload/files/file.pdf ``` What am I doing wrong? PS: I am using WordPress
2022/03/08
[ "https://Stackoverflow.com/questions/71391657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16886893/" ]
You are getting a `404` probably because the URI `/subpage` doesn't exist or map to an existent file. The `Redirect` you are using doesn't redirect the `/subpage` to the PDF location because your WordPress `RewriteRules` override it. If you want to fix it , you will need to use `RewriteRule` directive instead of `Redirect` at the top of your htaccess : ``` RewriteEngine On RewriteRule ^/?subpage/? https://www.mywebsite.com/upload/files/file.pdf [R=301,L] ```
To target an HTML link to a specific page in a PDF file, add #page=[page number] to the end of the link's URL. For example, this HTML tag opens page 4 of a PDF file named myfile.pdf: ``` <A HREF="http://www.example.com/myfile.pdf#page=4"> ``` --- And If you want to redirect a single page to another you just need to insert this line in the .htaccess file: Redirect 301 /old-post <https://www.yourwebsite.com/myfiles/myfile.pdf> Going to replace the old and new addresses respectively. The code must be inserted after and before .
71,391,657
I would like to add a 301 redirect when users visit a specific page and redirect them to a PDF file. In my **.htaccess** file I tried something like this this but it gives me a 404 error. However if I visit the path, the PDF it's there ``` Redirect 301 /subpage https://www.mywebsite/upload/files/file.pdf ``` What am I doing wrong? PS: I am using WordPress
2022/03/08
[ "https://Stackoverflow.com/questions/71391657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16886893/" ]
You are getting a `404` probably because the URI `/subpage` doesn't exist or map to an existent file. The `Redirect` you are using doesn't redirect the `/subpage` to the PDF location because your WordPress `RewriteRules` override it. If you want to fix it , you will need to use `RewriteRule` directive instead of `Redirect` at the top of your htaccess : ``` RewriteEngine On RewriteRule ^/?subpage/? https://www.mywebsite.com/upload/files/file.pdf [R=301,L] ```
Redirect in htaccess does not matter if it is a pdf file or anything else just a **valid link**. This is an example of a 301 redirect code to the link you want `RedirectMatch 301 /subpage/ <https://www.mywebsite.com/upload/files/file.pdf>`
23,761,425
I searched, but I didn't find an answer. I have a RESTful API to manage a basic CRUD. I'm trying to create an update method using PUT, but I can't retrieve the params values. I'm using [Postman](https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm) to make the requests, my request looks like: **URL** ``` http://localhost/api/update/987654321 ``` **Params** ``` id = 987654321 name = John Smith age = 35 ``` **PHP** ``` $app = new Slim(); $app->put('/update/:id', function( $id ) use( $app ){ var_dump([ 'id' => $id, 'name' => $app->request->put('name'), 'age' => $app->request->put('age') ]); }); ``` My `var_dump()` result is: ``` array(3) { ["id"]=> string(9) "987654321" ["name"]=> NULL ["age"]=> NULL } ``` What is wrong? Any idea?
2014/05/20
[ "https://Stackoverflow.com/questions/23761425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2684718/" ]
I had the same problem. Firstly, I was sending PUT data with the Postman option to encode it as "form-data", that's why Slim wasn't getting the param values. As it is explained in [W3](http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2), the content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data. In our case, we have to send PUT data with the Postman option "x-www-form-urlencoded" (see explanation of "[application/x-www-form-urlencoded](http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1)" in W3). ![Screenshot of the right Postman option selected](https://i.stack.imgur.com/wHzuC.png)
`$app->request->put()` is returning a null value... so u can use try `$app->request->params` instead
194,719
I was doing some investigation into trig functions using compound angles recently, and noticed that the results are really long and tedious to write: $$ \cos(A+B) = \cos A \cos B - \sin A \sin B \\ \cos(A-B) = \cos A \cos B + \sin A \sin B \\ \sin(A+B) = \sin A \cos B + \sin B \cos A \\ \sin(A-B) = \sin A \cos B - \sin B \cos A \\ $$ $$ \tan(A+B) = \frac{\tan A + \tan B}{1 - \tan A \tan B} $$ $$ \tan(A-B) = \frac{\tan A - \tan B}{1 + \tan A \tan B} $$ Realising this, I devised a shorter, golfier way, of writing such expressions: ``` <direction><operator>[functions](variables) ``` Where `direction` is either `«` or `»` and `operator` is in the string `+-*/` --- Also, when there is more variables than functions, the variables are, in a sense, left shifted through the functions, with unused variables simply being concatenated to the expression: ``` »-[f,g](x,y,z) ``` Turns into: $$ f(x)g(y)z - f(y)g(z)x - f(z)g(x)y $$ *Note that the variables `x`, `y` and `z` are left shifting through the functions* --- Note that when there is only one function given, it is applied as if the expression was an algebraic expansion. For example: ``` «+[cos](a,b) ``` Turns into $$ cos(a) + cos(b) $$ --- For an expression like `«+[f, g, h](foo, bar, baz)`, each function in the function list (`f, g, h`) is applied to every variable, as if the expression was being algebraically expanded: ``` f(foo)f(bar)f(baz) g(foo)g(bar)g(baz) h(foo)h(bar)h(baz) ``` These expressions are then concatenated with the provided operator (when the operator is `*`, the expressions are simply concatenated without any symbols): ``` f(foo)f(bar)f(baz) + g(foo)g(bar)g(baz) + h(foo)h(bar)h(baz) ``` --- For an expression like `»+[f, g, h](foo, bar, baz)`, each function in the function list (`f, g, h`) is applied to the variables in sequence, as if the variables were "shifting" through the functions: ``` f(foo)g(bar)h(baz) f(bar)g(baz)h(foo) f(baz)g(foo)h(bar) ``` These expressions are once again concatenated using the above method: ``` f(foo)g(bar)h(baz) + f(bar)g(baz)h(foo) + f(baz)g(foo)h(bar) ``` Some Clarifications ------------------- When the direction is `»` and there are more variables than functions , the following method is applied: ``` FOR j = 0 TO length of functions FOR i = 0 TO length of variables IF i >= length of functions - 1 THEN Result += variables[i] ELSE Result += Functions[i] + "(" + variables[i] + ")" NEXT i Left shift variables Result += operator NEXT j ``` Given the expression `»-[f,g](x,y,z)`, this would turn into: ``` f(x)g(y)z - f(y)g(z)x - f(z)g(x)y ``` Empty function lists should return an empty expression, as should empty variable lists. When there are more functions than variables and the direction is `»`, simply ignore the functions in the functions list whose index is greater than the length of the variables list. For example, given `»+[f,g,h](x,y)`: ``` f(x)g(y) + f(y)g(x) ``` The Challenge ------------- Given a shorthanded string as described above, output the expanded expression Test Cases ---------- ``` Input -> Output «+[cos,sin](a,b) -> cos(a)cos(b) + sin(a)sin(b) »+[cos,sin](a,b) -> cos(a)sin(b) + cos(b)sin(a) «[f](x,y,z,n) -> f(x)f(y)f(z)f(n) «+[f](x,y,z,n) -> f(x) + f(y) + f(z) + f(n) «+[f,g]() -> »*[f,g]() -> »-[f,g](a,b) -> f(a)g(b) - f(b)g(a) »[g,f](a,b) -> g(a)f(b)g(b)f(a) «+[tan](a,b) -> tan(a) + tan(b) »+[](a,b) -> »-[f,g](x,y,z) -> f(x)g(y)z - f(y)g(z)x - f(z)g(x)y «/[f,g](x,y,z) -> f(x)f(y)f(z) / g(x)g(y)g(z) «[]() -> »[]() -> »+[x,y](foo,bar,baz) -> x(foo)y(bar)baz + x(bar)y(baz)foo + x(baz)y(foo)bar »+[f,g](x) -> f(x) + g(x) «+[f,g](x) -> f(x) + g(x) »+[f,g,h](x,y) -> f(x)g(y) + f(y)g(x) ``` Let it be known that: * The direction will *always* be given * The operator is *optional* * The `[]` denoting the functions will always be present, but will not always contain functions * The `()` denoting the variables will always be present, but will not always contain variables * Functions can be outputted in any order just as long as the expressions are in order (`cosAsinB - sinAsinB` can be written as `sinBcosA - sinBsinA` but not as `sinAsinB - cosAsinB`) * Variable names can be of any length * The `«` and `»` can be taken as `<` and `>` if wanted (`«` and `»` are preferred however) Therefore, if no functions/variables are present, then an empty output is required. Whitespacing within the answer doesn't matter (i.e. newlines/extra spaces don't invalidate outputs). Input can also be taken as: ``` [direction, operator, [functions], [variables]] ``` In which case, `direction` will be a string, `operator` will be either an empty string or an operator, `functions` will be a (sometimes empty) list of strings, as will variables. Score ----- This is code golf, so fewest bytes wins. Standard loopholes are forbidden. Leaderboards ------------ Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ```js var QUESTION_ID=194719; var OVERRIDE_USER=8478; var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}} ``` ```css body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> ```
2019/10/22
[ "https://codegolf.stackexchange.com/questions/194719", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/78850/" ]
[05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 63 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ============================================================================================================================ ``` UÇ`θiVεY€…(ÿ)«}ëDg©DIgα+>∍Œ®ùεζεðK'(ýyðå≠i')«]Dg≠iJ}¸˜Xý³gIg*Ā× ``` Four loose inputs in the order `operator, direction, [variables], [functions]`. [Try it online](https://tio.run/##yy9OTMpM/f8/9HB7wrkdmWHntkY@alrzqGGZxuH9modW1x5e7ZJ@aKWLZ/q5jdp2jzp6j046tO7wznNbz207t/XwBm91jcN7Kw9vOLz0UeeCTHWghliXdBDTq/bQjtNzIg7vPbQ53TNd60jD4en//2tzHdrNFa1UUaGko1RZqRQLZKcBmcn5xUqxAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@pw6XkX1oC5IJ5LqfbghL@hx5uTzi3IzPs3NbIR01rHjUs0zi8X/PQ6trDq13SD610ObQeKJt@bqO23aOO3qOTDq07vPPcVrBg8blt57Ye3uCtrnF4b@XhDYeXPupckKkO0goELukgnlftoR2n50Qc3gvUYHR4RTrEMK0jDYen/9c5tM3@0Jb/0dFK2ko6SodWK@lEKyUCWUlKsUBWcn4xkF2cmacUG6ujAFWzG78auDEVQFYlEFcBcR5YaRqyMcSqgQjqKKVDJbRgbkCX0MXiOGR5LNLpQBamoxDyJYl4fI5uK8Iv6DbrY/EvNtdBvYvqXLgAwglp@fkgRyQWgUmIWRCT0VVWYNiDHPZY5ZD8gpDXUcpAD8UKsBqwZxC@ASWG2NhYAA). **Explanation:** ```python U # Pop and store the 1st (implicit) input `operator` in variable `X` Ç # Convert the 2nd (implicit) input `direction` to a list of codepoint ` # Push this codepoint to the stack θ # Only leave its last digit i # If this digit is 1 (so the direction is "«"): V # Pop and store the 3rd (implicit) input `variables` in variable `Y` ε } # Map over the 4th (implicit) input `functions`: Y # Push the `variable`-list from variable `Y` €…(ÿ) # Surround each variable with parenthesis « # And append it to the current `function` we're mapping ë # Else (so the direction is "»" instead): D # Duplicate the 3rd (implicit) input `variables` g # Pop and push the length to get the amount of `variables` © # Store it in variable `®` (without popping) D # Duplicate this length I # Push the fourth input `functions` g # Pop and take its length as well α # Take the absolute difference between the two amounts + # And add it to the duplicated amount of `variables` > # And increase it by 1 ∍ # Then extend the duplicated `variables` list to that length Œ # Get all sublists of this list ®ù # Only leave the sublists of a length equal to variable `®` ε # Map each remaining sublist to: ζ # Create pairs with the 4th (implicit) input `functions`, # with a default space as filler character if the lengths differ ε # Map each pair: ðK # Remove the spaces '(ý '# Join the pair with a ")" delimiter yðå≠i # If the current pair did NOT contain a space: ')« '# Append a ")" ] # Close all open if-statements and maps D # Duplicate the resulting list g≠i } # Pop and if its length is NOT 1: J # Join the inner-most list together to a string ¸ # Then wrap it into a list (in case it wasn't a list yet) ˜ # And deep flatten the list Xý # Join it by the operator we stores in variable `X` ³g # Get the length of the 3rd input-list `variables` Ig # And the length of the 4th input-list `functions` * # Multiply them with each other Ā # Truthify it (0 remains 0; everything else becomes 1) × # And repeat the string that many times # (so it becomes an empty string if either list was empty, # or remains unchanged otherwise) # (after which this is output implicitly as result) ```
JavaScript (ES6), ~~174~~ 171 bytes =================================== ```javascript (d,o,f,v,g=(f,V=v)=>f?V.map(v=>f+`(${v})`):V)=>f+f&&v+v?(d<'»'?f[1]?f.map(f=>g(f).join``):g(f[0]):v.map((_,i)=>v.map((_,j)=>g(f[j],[v[i++%v.length]])).join``)).join(o):'' ``` [Try it online!](https://tio.run/##nZJdboMwDMffewoUbSUeKd1eq1Fu0ReEVmgbBuqSalQRMO1EO0LfejHmJFtXVdCPITmxZfuX8HeKRCXl4j3fbEdCLlctD1q6ZJJxplgWUM5mgYJgysOZ/5ZsqELXm9O7D/UJc5jMdMrjw6HyVEiXz@5@54Y8eopDbsp5MM0oB7@QuZhjPQbRYwwTZbL0heUIOAQFmPKoiFmkotzz7pW/Xols@xrHcIBYh0qYuG67kKKU65W/lthIyf6LMId4uERkIUvCSJkLEuswwSAlyHGc8djBJE1Aryk4noNVGOo1hcEpc3cT00KQaeGWPOi8JxpCuGVVyKrRGjRxYHJaAac1WoMmekD2chdBeCnNMltjt0tERjJDNZijD4mEdCv18P/W0UnrscA/rRzVzLTAI3RTdJOegVlxMwTwPpZutpAUeO@UrBTbRHRiDAiT2I6CaufsC@pG3KzL34yP55vhcBsjTI1@A5XxG/QrqLt/bnwd@fcJOlo0e5A@4Myz7pr85R@9qrX9Bg "JavaScript (Node.js) – Try It Online") ### Commented ```javascript ( d, // d = direction o, // o = operator f, // f[] = list of functions v, // v[] = list of variables g = (f, V = v) => // g = helper function taking (f, V[]) f ? // if f is defined: V.map(v => // for each variable v in V[]: f + `(${v})` // return f, followed by '(v)' ) // : // else: V // just return V[] as-is ) => // f + f && v + v ? // if both f[] and v[] are non-empty: ( d < '»' ? // if the direction is '«': f[1] ? // if there are at least 2 functions: f.map(f => // for each function f_i in f[]: g(f).join`` // return 'f_i(v_0)f_i(v_1)...' ) // end of map() : // else: g(f[0]) // return [ 'f_0(v_0)', 'f_0(v_1)', ... ] : // else (the direction is '»'): v.map((_, i) => // for each variable at position i: v.map((_, j) => // for each variable at position j: g( // return [ 'f_j(v_k)' ] f[j], // where k = i mod v.length [v[i++ % v.length]] // and increment i ) // ).join`` // end of inner map(); join the list ) // end of outer map() ).join(o) // join the final list with the operator : // else: '' // just return an empty string ```
194,719
I was doing some investigation into trig functions using compound angles recently, and noticed that the results are really long and tedious to write: $$ \cos(A+B) = \cos A \cos B - \sin A \sin B \\ \cos(A-B) = \cos A \cos B + \sin A \sin B \\ \sin(A+B) = \sin A \cos B + \sin B \cos A \\ \sin(A-B) = \sin A \cos B - \sin B \cos A \\ $$ $$ \tan(A+B) = \frac{\tan A + \tan B}{1 - \tan A \tan B} $$ $$ \tan(A-B) = \frac{\tan A - \tan B}{1 + \tan A \tan B} $$ Realising this, I devised a shorter, golfier way, of writing such expressions: ``` <direction><operator>[functions](variables) ``` Where `direction` is either `«` or `»` and `operator` is in the string `+-*/` --- Also, when there is more variables than functions, the variables are, in a sense, left shifted through the functions, with unused variables simply being concatenated to the expression: ``` »-[f,g](x,y,z) ``` Turns into: $$ f(x)g(y)z - f(y)g(z)x - f(z)g(x)y $$ *Note that the variables `x`, `y` and `z` are left shifting through the functions* --- Note that when there is only one function given, it is applied as if the expression was an algebraic expansion. For example: ``` «+[cos](a,b) ``` Turns into $$ cos(a) + cos(b) $$ --- For an expression like `«+[f, g, h](foo, bar, baz)`, each function in the function list (`f, g, h`) is applied to every variable, as if the expression was being algebraically expanded: ``` f(foo)f(bar)f(baz) g(foo)g(bar)g(baz) h(foo)h(bar)h(baz) ``` These expressions are then concatenated with the provided operator (when the operator is `*`, the expressions are simply concatenated without any symbols): ``` f(foo)f(bar)f(baz) + g(foo)g(bar)g(baz) + h(foo)h(bar)h(baz) ``` --- For an expression like `»+[f, g, h](foo, bar, baz)`, each function in the function list (`f, g, h`) is applied to the variables in sequence, as if the variables were "shifting" through the functions: ``` f(foo)g(bar)h(baz) f(bar)g(baz)h(foo) f(baz)g(foo)h(bar) ``` These expressions are once again concatenated using the above method: ``` f(foo)g(bar)h(baz) + f(bar)g(baz)h(foo) + f(baz)g(foo)h(bar) ``` Some Clarifications ------------------- When the direction is `»` and there are more variables than functions , the following method is applied: ``` FOR j = 0 TO length of functions FOR i = 0 TO length of variables IF i >= length of functions - 1 THEN Result += variables[i] ELSE Result += Functions[i] + "(" + variables[i] + ")" NEXT i Left shift variables Result += operator NEXT j ``` Given the expression `»-[f,g](x,y,z)`, this would turn into: ``` f(x)g(y)z - f(y)g(z)x - f(z)g(x)y ``` Empty function lists should return an empty expression, as should empty variable lists. When there are more functions than variables and the direction is `»`, simply ignore the functions in the functions list whose index is greater than the length of the variables list. For example, given `»+[f,g,h](x,y)`: ``` f(x)g(y) + f(y)g(x) ``` The Challenge ------------- Given a shorthanded string as described above, output the expanded expression Test Cases ---------- ``` Input -> Output «+[cos,sin](a,b) -> cos(a)cos(b) + sin(a)sin(b) »+[cos,sin](a,b) -> cos(a)sin(b) + cos(b)sin(a) «[f](x,y,z,n) -> f(x)f(y)f(z)f(n) «+[f](x,y,z,n) -> f(x) + f(y) + f(z) + f(n) «+[f,g]() -> »*[f,g]() -> »-[f,g](a,b) -> f(a)g(b) - f(b)g(a) »[g,f](a,b) -> g(a)f(b)g(b)f(a) «+[tan](a,b) -> tan(a) + tan(b) »+[](a,b) -> »-[f,g](x,y,z) -> f(x)g(y)z - f(y)g(z)x - f(z)g(x)y «/[f,g](x,y,z) -> f(x)f(y)f(z) / g(x)g(y)g(z) «[]() -> »[]() -> »+[x,y](foo,bar,baz) -> x(foo)y(bar)baz + x(bar)y(baz)foo + x(baz)y(foo)bar »+[f,g](x) -> f(x) + g(x) «+[f,g](x) -> f(x) + g(x) »+[f,g,h](x,y) -> f(x)g(y) + f(y)g(x) ``` Let it be known that: * The direction will *always* be given * The operator is *optional* * The `[]` denoting the functions will always be present, but will not always contain functions * The `()` denoting the variables will always be present, but will not always contain variables * Functions can be outputted in any order just as long as the expressions are in order (`cosAsinB - sinAsinB` can be written as `sinBcosA - sinBsinA` but not as `sinAsinB - cosAsinB`) * Variable names can be of any length * The `«` and `»` can be taken as `<` and `>` if wanted (`«` and `»` are preferred however) Therefore, if no functions/variables are present, then an empty output is required. Whitespacing within the answer doesn't matter (i.e. newlines/extra spaces don't invalidate outputs). Input can also be taken as: ``` [direction, operator, [functions], [variables]] ``` In which case, `direction` will be a string, `operator` will be either an empty string or an operator, `functions` will be a (sometimes empty) list of strings, as will variables. Score ----- This is code golf, so fewest bytes wins. Standard loopholes are forbidden. Leaderboards ------------ Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ```js var QUESTION_ID=194719; var OVERRIDE_USER=8478; var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}} ``` ```css body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> ```
2019/10/22
[ "https://codegolf.stackexchange.com/questions/194719", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/78850/" ]
JavaScript (ES6), ~~174~~ 171 bytes =================================== ```javascript (d,o,f,v,g=(f,V=v)=>f?V.map(v=>f+`(${v})`):V)=>f+f&&v+v?(d<'»'?f[1]?f.map(f=>g(f).join``):g(f[0]):v.map((_,i)=>v.map((_,j)=>g(f[j],[v[i++%v.length]])).join``)).join(o):'' ``` [Try it online!](https://tio.run/##nZJdboMwDMffewoUbSUeKd1eq1Fu0ReEVmgbBuqSalQRMO1EO0LfejHmJFtXVdCPITmxZfuX8HeKRCXl4j3fbEdCLlctD1q6ZJJxplgWUM5mgYJgysOZ/5ZsqELXm9O7D/UJc5jMdMrjw6HyVEiXz@5@54Y8eopDbsp5MM0oB7@QuZhjPQbRYwwTZbL0heUIOAQFmPKoiFmkotzz7pW/Xols@xrHcIBYh0qYuG67kKKU65W/lthIyf6LMId4uERkIUvCSJkLEuswwSAlyHGc8djBJE1Aryk4noNVGOo1hcEpc3cT00KQaeGWPOi8JxpCuGVVyKrRGjRxYHJaAac1WoMmekD2chdBeCnNMltjt0tERjJDNZijD4mEdCv18P/W0UnrscA/rRzVzLTAI3RTdJOegVlxMwTwPpZutpAUeO@UrBTbRHRiDAiT2I6CaufsC@pG3KzL34yP55vhcBsjTI1@A5XxG/QrqLt/bnwd@fcJOlo0e5A@4Myz7pr85R@9qrX9Bg "JavaScript (Node.js) – Try It Online") ### Commented ```javascript ( d, // d = direction o, // o = operator f, // f[] = list of functions v, // v[] = list of variables g = (f, V = v) => // g = helper function taking (f, V[]) f ? // if f is defined: V.map(v => // for each variable v in V[]: f + `(${v})` // return f, followed by '(v)' ) // : // else: V // just return V[] as-is ) => // f + f && v + v ? // if both f[] and v[] are non-empty: ( d < '»' ? // if the direction is '«': f[1] ? // if there are at least 2 functions: f.map(f => // for each function f_i in f[]: g(f).join`` // return 'f_i(v_0)f_i(v_1)...' ) // end of map() : // else: g(f[0]) // return [ 'f_0(v_0)', 'f_0(v_1)', ... ] : // else (the direction is '»'): v.map((_, i) => // for each variable at position i: v.map((_, j) => // for each variable at position j: g( // return [ 'f_j(v_k)' ] f[j], // where k = i mod v.length [v[i++ % v.length]] // and increment i ) // ).join`` // end of inner map(); join the list ) // end of outer map() ).join(o) // join the final list with the operator : // else: '' // just return an empty string ```
[Python 2](https://docs.python.org/2/), ~~179~~ ~~190~~ 194 bytes ================================================================= ```python lambda d,o,F,V,S='%s(%s)':(o*(o>'*')).join([(''.join(S%(u,v)for v in V)for u in F if V),(''.join(map(lambda u,v:v and u and S%(u,v)or v or'',F,(V+V)[i:i+len(V)]))for i in range(len(V)))][d>'<']) ``` [Try it online!](https://tio.run/##lVTBbsIwDD23X5ELckLDNu1YAZdJ/ABSL10PgbaQCRLUFDT4@c4JHZTRQqdKrp28vOc4cXbHcq3Ve5VPPquN2C5SQVKu@YxHfD6BgaEDwyCkekj1FIbA2MuXlorGFODszQd0zw8s1wU5EKlI5Ny9dWdE5hjzC3YrdrQWwTXhgQiVItTamsax6AIAM6BRELFYhjLYZIpGLGGOWlrqQqhVRs/jjCVxOoUxJKwqM1N@CJMZMiGx73kUhzmBAE0MS21sYKSCxMbCRgtcxh1y2ht55XSz3zY8WnOyRt0yOsIceiCDf0If48a9Kd@4@9rWobtyi2/Uhx2zXUSPq92cRbNsT8vhR3@FW1kdaGW9/MnxQSme3oXu@ftsmhW@UXvtA20p32997vbXWfVG5rWEk8u1djsQxfl3ar96zfyShxfiCrhL294Ph7WHAGuEY0ehlzY1H4F8L/F92@v1U2Q7/tLZoe/hs5KGZFdIVZI00AHENr/6kZmxABLaGIhwgJERaua0JkSFbGOymsOvfgA "Python 2 – Try It Online") 11 bytes lost to fixing a bug. A function that takes a direction, an operator, a list of functions, and a list of variables. For direction, uses `<,>` instead of `«,»` because utf-x reasons. This assumes that if the direction is `>`, and there are more functions than variables, that we ignore the excess function(s); e.g., `>*[f,g,h],[c,d]) => f(c)g(d)*f(d)g(c)`
194,719
I was doing some investigation into trig functions using compound angles recently, and noticed that the results are really long and tedious to write: $$ \cos(A+B) = \cos A \cos B - \sin A \sin B \\ \cos(A-B) = \cos A \cos B + \sin A \sin B \\ \sin(A+B) = \sin A \cos B + \sin B \cos A \\ \sin(A-B) = \sin A \cos B - \sin B \cos A \\ $$ $$ \tan(A+B) = \frac{\tan A + \tan B}{1 - \tan A \tan B} $$ $$ \tan(A-B) = \frac{\tan A - \tan B}{1 + \tan A \tan B} $$ Realising this, I devised a shorter, golfier way, of writing such expressions: ``` <direction><operator>[functions](variables) ``` Where `direction` is either `«` or `»` and `operator` is in the string `+-*/` --- Also, when there is more variables than functions, the variables are, in a sense, left shifted through the functions, with unused variables simply being concatenated to the expression: ``` »-[f,g](x,y,z) ``` Turns into: $$ f(x)g(y)z - f(y)g(z)x - f(z)g(x)y $$ *Note that the variables `x`, `y` and `z` are left shifting through the functions* --- Note that when there is only one function given, it is applied as if the expression was an algebraic expansion. For example: ``` «+[cos](a,b) ``` Turns into $$ cos(a) + cos(b) $$ --- For an expression like `«+[f, g, h](foo, bar, baz)`, each function in the function list (`f, g, h`) is applied to every variable, as if the expression was being algebraically expanded: ``` f(foo)f(bar)f(baz) g(foo)g(bar)g(baz) h(foo)h(bar)h(baz) ``` These expressions are then concatenated with the provided operator (when the operator is `*`, the expressions are simply concatenated without any symbols): ``` f(foo)f(bar)f(baz) + g(foo)g(bar)g(baz) + h(foo)h(bar)h(baz) ``` --- For an expression like `»+[f, g, h](foo, bar, baz)`, each function in the function list (`f, g, h`) is applied to the variables in sequence, as if the variables were "shifting" through the functions: ``` f(foo)g(bar)h(baz) f(bar)g(baz)h(foo) f(baz)g(foo)h(bar) ``` These expressions are once again concatenated using the above method: ``` f(foo)g(bar)h(baz) + f(bar)g(baz)h(foo) + f(baz)g(foo)h(bar) ``` Some Clarifications ------------------- When the direction is `»` and there are more variables than functions , the following method is applied: ``` FOR j = 0 TO length of functions FOR i = 0 TO length of variables IF i >= length of functions - 1 THEN Result += variables[i] ELSE Result += Functions[i] + "(" + variables[i] + ")" NEXT i Left shift variables Result += operator NEXT j ``` Given the expression `»-[f,g](x,y,z)`, this would turn into: ``` f(x)g(y)z - f(y)g(z)x - f(z)g(x)y ``` Empty function lists should return an empty expression, as should empty variable lists. When there are more functions than variables and the direction is `»`, simply ignore the functions in the functions list whose index is greater than the length of the variables list. For example, given `»+[f,g,h](x,y)`: ``` f(x)g(y) + f(y)g(x) ``` The Challenge ------------- Given a shorthanded string as described above, output the expanded expression Test Cases ---------- ``` Input -> Output «+[cos,sin](a,b) -> cos(a)cos(b) + sin(a)sin(b) »+[cos,sin](a,b) -> cos(a)sin(b) + cos(b)sin(a) «[f](x,y,z,n) -> f(x)f(y)f(z)f(n) «+[f](x,y,z,n) -> f(x) + f(y) + f(z) + f(n) «+[f,g]() -> »*[f,g]() -> »-[f,g](a,b) -> f(a)g(b) - f(b)g(a) »[g,f](a,b) -> g(a)f(b)g(b)f(a) «+[tan](a,b) -> tan(a) + tan(b) »+[](a,b) -> »-[f,g](x,y,z) -> f(x)g(y)z - f(y)g(z)x - f(z)g(x)y «/[f,g](x,y,z) -> f(x)f(y)f(z) / g(x)g(y)g(z) «[]() -> »[]() -> »+[x,y](foo,bar,baz) -> x(foo)y(bar)baz + x(bar)y(baz)foo + x(baz)y(foo)bar »+[f,g](x) -> f(x) + g(x) «+[f,g](x) -> f(x) + g(x) »+[f,g,h](x,y) -> f(x)g(y) + f(y)g(x) ``` Let it be known that: * The direction will *always* be given * The operator is *optional* * The `[]` denoting the functions will always be present, but will not always contain functions * The `()` denoting the variables will always be present, but will not always contain variables * Functions can be outputted in any order just as long as the expressions are in order (`cosAsinB - sinAsinB` can be written as `sinBcosA - sinBsinA` but not as `sinAsinB - cosAsinB`) * Variable names can be of any length * The `«` and `»` can be taken as `<` and `>` if wanted (`«` and `»` are preferred however) Therefore, if no functions/variables are present, then an empty output is required. Whitespacing within the answer doesn't matter (i.e. newlines/extra spaces don't invalidate outputs). Input can also be taken as: ``` [direction, operator, [functions], [variables]] ``` In which case, `direction` will be a string, `operator` will be either an empty string or an operator, `functions` will be a (sometimes empty) list of strings, as will variables. Score ----- This is code golf, so fewest bytes wins. Standard loopholes are forbidden. Leaderboards ------------ Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ```js var QUESTION_ID=194719; var OVERRIDE_USER=8478; var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}} ``` ```css body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> ```
2019/10/22
[ "https://codegolf.stackexchange.com/questions/194719", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/78850/" ]
JavaScript (ES6), ~~174~~ 171 bytes =================================== ```javascript (d,o,f,v,g=(f,V=v)=>f?V.map(v=>f+`(${v})`):V)=>f+f&&v+v?(d<'»'?f[1]?f.map(f=>g(f).join``):g(f[0]):v.map((_,i)=>v.map((_,j)=>g(f[j],[v[i++%v.length]])).join``)).join(o):'' ``` [Try it online!](https://tio.run/##nZJdboMwDMffewoUbSUeKd1eq1Fu0ReEVmgbBuqSalQRMO1EO0LfejHmJFtXVdCPITmxZfuX8HeKRCXl4j3fbEdCLlctD1q6ZJJxplgWUM5mgYJgysOZ/5ZsqELXm9O7D/UJc5jMdMrjw6HyVEiXz@5@54Y8eopDbsp5MM0oB7@QuZhjPQbRYwwTZbL0heUIOAQFmPKoiFmkotzz7pW/Xols@xrHcIBYh0qYuG67kKKU65W/lthIyf6LMId4uERkIUvCSJkLEuswwSAlyHGc8djBJE1Aryk4noNVGOo1hcEpc3cT00KQaeGWPOi8JxpCuGVVyKrRGjRxYHJaAac1WoMmekD2chdBeCnNMltjt0tERjJDNZijD4mEdCv18P/W0UnrscA/rRzVzLTAI3RTdJOegVlxMwTwPpZutpAUeO@UrBTbRHRiDAiT2I6CaufsC@pG3KzL34yP55vhcBsjTI1@A5XxG/QrqLt/bnwd@fcJOlo0e5A@4Myz7pr85R@9qrX9Bg "JavaScript (Node.js) – Try It Online") ### Commented ```javascript ( d, // d = direction o, // o = operator f, // f[] = list of functions v, // v[] = list of variables g = (f, V = v) => // g = helper function taking (f, V[]) f ? // if f is defined: V.map(v => // for each variable v in V[]: f + `(${v})` // return f, followed by '(v)' ) // : // else: V // just return V[] as-is ) => // f + f && v + v ? // if both f[] and v[] are non-empty: ( d < '»' ? // if the direction is '«': f[1] ? // if there are at least 2 functions: f.map(f => // for each function f_i in f[]: g(f).join`` // return 'f_i(v_0)f_i(v_1)...' ) // end of map() : // else: g(f[0]) // return [ 'f_0(v_0)', 'f_0(v_1)', ... ] : // else (the direction is '»'): v.map((_, i) => // for each variable at position i: v.map((_, j) => // for each variable at position j: g( // return [ 'f_j(v_k)' ] f[j], // where k = i mod v.length [v[i++ % v.length]] // and increment i ) // ).join`` // end of inner map(); join the list ) // end of outer map() ).join(o) // join the final list with the operator : // else: '' // just return an empty string ```
[C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 177 bytes ================================================================================================================= ```cs (d,o,f,v)=>string.Join(o=="*"?"":o,d<61?f.Select(l=>v.Aggregate("",(a,b)=>a+l+$"({b})")):v.Select((x,y)=>string.Concat(v.Select((i,o)=>o>=f.Count?i:f[(y+o)%f.Count]+$"({i})")))) ``` [Try it online!](https://tio.run/##fZJPb5wwEMXvfIqp1YpxmKUlhxx2MaiqVClVpBy2Ug6IgxfMxhLCEXjRplE@@9b8SXdDpB4Qmvfm/cyMKbpV0enTz0NTxMWjbKmzrW72dHunOxtPRbKo5nclTliSoYp6LpJJDH8Z3aARgl2xlLG1oTK@idIq3KpaFRZrkfTh9/2@VXtpFTJGKGnn4jKog88MX3avnHG@7t8CeKTnM/2HaQpp8exqMs41iaicd2hsqtdVhs@B4V9mJR@xesRyftp4vdElWNVZnKAgObx4AL1sodQtCJDZt3wzK@ZpFKIchAA/8yEFxmA9SuFvsx0RyId2OXSG28Nu4uIQFUN3CpFLXPM3ZuWWbbVpukUgIlfeNqU63lfo5z6HFUQ83D7V2qJP/giYGe7RclerJeMCgA4QwHsoH6GLpsUp4cOjahUeQSRwhE/DCNyNOvwC06APrbbqTjcKK3QbI7ckOg9F52/jfAPeqzcum8VBVpiOOt3kw6XSH3cjm9lLshwvy6v/tK7eeZfOvwPIyg9u/PVjzjv9BQ "C# (Visual C# Interactive Compiler) – Try It Online")
194,719
I was doing some investigation into trig functions using compound angles recently, and noticed that the results are really long and tedious to write: $$ \cos(A+B) = \cos A \cos B - \sin A \sin B \\ \cos(A-B) = \cos A \cos B + \sin A \sin B \\ \sin(A+B) = \sin A \cos B + \sin B \cos A \\ \sin(A-B) = \sin A \cos B - \sin B \cos A \\ $$ $$ \tan(A+B) = \frac{\tan A + \tan B}{1 - \tan A \tan B} $$ $$ \tan(A-B) = \frac{\tan A - \tan B}{1 + \tan A \tan B} $$ Realising this, I devised a shorter, golfier way, of writing such expressions: ``` <direction><operator>[functions](variables) ``` Where `direction` is either `«` or `»` and `operator` is in the string `+-*/` --- Also, when there is more variables than functions, the variables are, in a sense, left shifted through the functions, with unused variables simply being concatenated to the expression: ``` »-[f,g](x,y,z) ``` Turns into: $$ f(x)g(y)z - f(y)g(z)x - f(z)g(x)y $$ *Note that the variables `x`, `y` and `z` are left shifting through the functions* --- Note that when there is only one function given, it is applied as if the expression was an algebraic expansion. For example: ``` «+[cos](a,b) ``` Turns into $$ cos(a) + cos(b) $$ --- For an expression like `«+[f, g, h](foo, bar, baz)`, each function in the function list (`f, g, h`) is applied to every variable, as if the expression was being algebraically expanded: ``` f(foo)f(bar)f(baz) g(foo)g(bar)g(baz) h(foo)h(bar)h(baz) ``` These expressions are then concatenated with the provided operator (when the operator is `*`, the expressions are simply concatenated without any symbols): ``` f(foo)f(bar)f(baz) + g(foo)g(bar)g(baz) + h(foo)h(bar)h(baz) ``` --- For an expression like `»+[f, g, h](foo, bar, baz)`, each function in the function list (`f, g, h`) is applied to the variables in sequence, as if the variables were "shifting" through the functions: ``` f(foo)g(bar)h(baz) f(bar)g(baz)h(foo) f(baz)g(foo)h(bar) ``` These expressions are once again concatenated using the above method: ``` f(foo)g(bar)h(baz) + f(bar)g(baz)h(foo) + f(baz)g(foo)h(bar) ``` Some Clarifications ------------------- When the direction is `»` and there are more variables than functions , the following method is applied: ``` FOR j = 0 TO length of functions FOR i = 0 TO length of variables IF i >= length of functions - 1 THEN Result += variables[i] ELSE Result += Functions[i] + "(" + variables[i] + ")" NEXT i Left shift variables Result += operator NEXT j ``` Given the expression `»-[f,g](x,y,z)`, this would turn into: ``` f(x)g(y)z - f(y)g(z)x - f(z)g(x)y ``` Empty function lists should return an empty expression, as should empty variable lists. When there are more functions than variables and the direction is `»`, simply ignore the functions in the functions list whose index is greater than the length of the variables list. For example, given `»+[f,g,h](x,y)`: ``` f(x)g(y) + f(y)g(x) ``` The Challenge ------------- Given a shorthanded string as described above, output the expanded expression Test Cases ---------- ``` Input -> Output «+[cos,sin](a,b) -> cos(a)cos(b) + sin(a)sin(b) »+[cos,sin](a,b) -> cos(a)sin(b) + cos(b)sin(a) «[f](x,y,z,n) -> f(x)f(y)f(z)f(n) «+[f](x,y,z,n) -> f(x) + f(y) + f(z) + f(n) «+[f,g]() -> »*[f,g]() -> »-[f,g](a,b) -> f(a)g(b) - f(b)g(a) »[g,f](a,b) -> g(a)f(b)g(b)f(a) «+[tan](a,b) -> tan(a) + tan(b) »+[](a,b) -> »-[f,g](x,y,z) -> f(x)g(y)z - f(y)g(z)x - f(z)g(x)y «/[f,g](x,y,z) -> f(x)f(y)f(z) / g(x)g(y)g(z) «[]() -> »[]() -> »+[x,y](foo,bar,baz) -> x(foo)y(bar)baz + x(bar)y(baz)foo + x(baz)y(foo)bar »+[f,g](x) -> f(x) + g(x) «+[f,g](x) -> f(x) + g(x) »+[f,g,h](x,y) -> f(x)g(y) + f(y)g(x) ``` Let it be known that: * The direction will *always* be given * The operator is *optional* * The `[]` denoting the functions will always be present, but will not always contain functions * The `()` denoting the variables will always be present, but will not always contain variables * Functions can be outputted in any order just as long as the expressions are in order (`cosAsinB - sinAsinB` can be written as `sinBcosA - sinBsinA` but not as `sinAsinB - cosAsinB`) * Variable names can be of any length * The `«` and `»` can be taken as `<` and `>` if wanted (`«` and `»` are preferred however) Therefore, if no functions/variables are present, then an empty output is required. Whitespacing within the answer doesn't matter (i.e. newlines/extra spaces don't invalidate outputs). Input can also be taken as: ``` [direction, operator, [functions], [variables]] ``` In which case, `direction` will be a string, `operator` will be either an empty string or an operator, `functions` will be a (sometimes empty) list of strings, as will variables. Score ----- This is code golf, so fewest bytes wins. Standard loopholes are forbidden. Leaderboards ------------ Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ```js var QUESTION_ID=194719; var OVERRIDE_USER=8478; var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}} ``` ```css body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> ```
2019/10/22
[ "https://codegolf.stackexchange.com/questions/194719", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/78850/" ]
[05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 63 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ============================================================================================================================ ``` UÇ`θiVεY€…(ÿ)«}ëDg©DIgα+>∍Œ®ùεζεðK'(ýyðå≠i')«]Dg≠iJ}¸˜Xý³gIg*Ā× ``` Four loose inputs in the order `operator, direction, [variables], [functions]`. [Try it online](https://tio.run/##yy9OTMpM/f8/9HB7wrkdmWHntkY@alrzqGGZxuH9modW1x5e7ZJ@aKWLZ/q5jdp2jzp6j046tO7wznNbz207t/XwBm91jcN7Kw9vOLz0UeeCTHWghliXdBDTq/bQjtNzIg7vPbQ53TNd60jD4en//2tzHdrNFa1UUaGko1RZqRQLZKcBmcn5xUqxAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@pw6XkX1oC5IJ5LqfbghL@hx5uTzi3IzPs3NbIR01rHjUs0zi8X/PQ6trDq13SD610ObQeKJt@bqO23aOO3qOTDq07vPPcVrBg8blt57Ye3uCtrnF4b@XhDYeXPupckKkO0goELukgnlftoR2n50Qc3gvUYHR4RTrEMK0jDYen/9c5tM3@0Jb/0dFK2ko6SodWK@lEKyUCWUlKsUBWcn4xkF2cmacUG6ujAFWzG78auDEVQFYlEFcBcR5YaRqyMcSqgQjqKKVDJbRgbkCX0MXiOGR5LNLpQBamoxDyJYl4fI5uK8Iv6DbrY/EvNtdBvYvqXLgAwglp@fkgRyQWgUmIWRCT0VVWYNiDHPZY5ZD8gpDXUcpAD8UKsBqwZxC@ASWG2NhYAA). **Explanation:** ```python U # Pop and store the 1st (implicit) input `operator` in variable `X` Ç # Convert the 2nd (implicit) input `direction` to a list of codepoint ` # Push this codepoint to the stack θ # Only leave its last digit i # If this digit is 1 (so the direction is "«"): V # Pop and store the 3rd (implicit) input `variables` in variable `Y` ε } # Map over the 4th (implicit) input `functions`: Y # Push the `variable`-list from variable `Y` €…(ÿ) # Surround each variable with parenthesis « # And append it to the current `function` we're mapping ë # Else (so the direction is "»" instead): D # Duplicate the 3rd (implicit) input `variables` g # Pop and push the length to get the amount of `variables` © # Store it in variable `®` (without popping) D # Duplicate this length I # Push the fourth input `functions` g # Pop and take its length as well α # Take the absolute difference between the two amounts + # And add it to the duplicated amount of `variables` > # And increase it by 1 ∍ # Then extend the duplicated `variables` list to that length Œ # Get all sublists of this list ®ù # Only leave the sublists of a length equal to variable `®` ε # Map each remaining sublist to: ζ # Create pairs with the 4th (implicit) input `functions`, # with a default space as filler character if the lengths differ ε # Map each pair: ðK # Remove the spaces '(ý '# Join the pair with a ")" delimiter yðå≠i # If the current pair did NOT contain a space: ')« '# Append a ")" ] # Close all open if-statements and maps D # Duplicate the resulting list g≠i } # Pop and if its length is NOT 1: J # Join the inner-most list together to a string ¸ # Then wrap it into a list (in case it wasn't a list yet) ˜ # And deep flatten the list Xý # Join it by the operator we stores in variable `X` ³g # Get the length of the 3rd input-list `variables` Ig # And the length of the 4th input-list `functions` * # Multiply them with each other Ā # Truthify it (0 remains 0; everything else becomes 1) × # And repeat the string that many times # (so it becomes an empty string if either list was empty, # or remains unchanged otherwise) # (after which this is output implicitly as result) ```
[Python 2](https://docs.python.org/2/), ~~179~~ ~~190~~ 194 bytes ================================================================= ```python lambda d,o,F,V,S='%s(%s)':(o*(o>'*')).join([(''.join(S%(u,v)for v in V)for u in F if V),(''.join(map(lambda u,v:v and u and S%(u,v)or v or'',F,(V+V)[i:i+len(V)]))for i in range(len(V)))][d>'<']) ``` [Try it online!](https://tio.run/##lVTBbsIwDD23X5ELckLDNu1YAZdJ/ABSL10PgbaQCRLUFDT4@c4JHZTRQqdKrp28vOc4cXbHcq3Ve5VPPquN2C5SQVKu@YxHfD6BgaEDwyCkekj1FIbA2MuXlorGFODszQd0zw8s1wU5EKlI5Ny9dWdE5hjzC3YrdrQWwTXhgQiVItTamsax6AIAM6BRELFYhjLYZIpGLGGOWlrqQqhVRs/jjCVxOoUxJKwqM1N@CJMZMiGx73kUhzmBAE0MS21sYKSCxMbCRgtcxh1y2ht55XSz3zY8WnOyRt0yOsIceiCDf0If48a9Kd@4@9rWobtyi2/Uhx2zXUSPq92cRbNsT8vhR3@FW1kdaGW9/MnxQSme3oXu@ftsmhW@UXvtA20p32997vbXWfVG5rWEk8u1djsQxfl3ar96zfyShxfiCrhL294Ph7WHAGuEY0ehlzY1H4F8L/F92@v1U2Q7/tLZoe/hs5KGZFdIVZI00AHENr/6kZmxABLaGIhwgJERaua0JkSFbGOymsOvfgA "Python 2 – Try It Online") 11 bytes lost to fixing a bug. A function that takes a direction, an operator, a list of functions, and a list of variables. For direction, uses `<,>` instead of `«,»` because utf-x reasons. This assumes that if the direction is `>`, and there are more functions than variables, that we ignore the excess function(s); e.g., `>*[f,g,h],[c,d]) => f(c)g(d)*f(d)g(c)`
194,719
I was doing some investigation into trig functions using compound angles recently, and noticed that the results are really long and tedious to write: $$ \cos(A+B) = \cos A \cos B - \sin A \sin B \\ \cos(A-B) = \cos A \cos B + \sin A \sin B \\ \sin(A+B) = \sin A \cos B + \sin B \cos A \\ \sin(A-B) = \sin A \cos B - \sin B \cos A \\ $$ $$ \tan(A+B) = \frac{\tan A + \tan B}{1 - \tan A \tan B} $$ $$ \tan(A-B) = \frac{\tan A - \tan B}{1 + \tan A \tan B} $$ Realising this, I devised a shorter, golfier way, of writing such expressions: ``` <direction><operator>[functions](variables) ``` Where `direction` is either `«` or `»` and `operator` is in the string `+-*/` --- Also, when there is more variables than functions, the variables are, in a sense, left shifted through the functions, with unused variables simply being concatenated to the expression: ``` »-[f,g](x,y,z) ``` Turns into: $$ f(x)g(y)z - f(y)g(z)x - f(z)g(x)y $$ *Note that the variables `x`, `y` and `z` are left shifting through the functions* --- Note that when there is only one function given, it is applied as if the expression was an algebraic expansion. For example: ``` «+[cos](a,b) ``` Turns into $$ cos(a) + cos(b) $$ --- For an expression like `«+[f, g, h](foo, bar, baz)`, each function in the function list (`f, g, h`) is applied to every variable, as if the expression was being algebraically expanded: ``` f(foo)f(bar)f(baz) g(foo)g(bar)g(baz) h(foo)h(bar)h(baz) ``` These expressions are then concatenated with the provided operator (when the operator is `*`, the expressions are simply concatenated without any symbols): ``` f(foo)f(bar)f(baz) + g(foo)g(bar)g(baz) + h(foo)h(bar)h(baz) ``` --- For an expression like `»+[f, g, h](foo, bar, baz)`, each function in the function list (`f, g, h`) is applied to the variables in sequence, as if the variables were "shifting" through the functions: ``` f(foo)g(bar)h(baz) f(bar)g(baz)h(foo) f(baz)g(foo)h(bar) ``` These expressions are once again concatenated using the above method: ``` f(foo)g(bar)h(baz) + f(bar)g(baz)h(foo) + f(baz)g(foo)h(bar) ``` Some Clarifications ------------------- When the direction is `»` and there are more variables than functions , the following method is applied: ``` FOR j = 0 TO length of functions FOR i = 0 TO length of variables IF i >= length of functions - 1 THEN Result += variables[i] ELSE Result += Functions[i] + "(" + variables[i] + ")" NEXT i Left shift variables Result += operator NEXT j ``` Given the expression `»-[f,g](x,y,z)`, this would turn into: ``` f(x)g(y)z - f(y)g(z)x - f(z)g(x)y ``` Empty function lists should return an empty expression, as should empty variable lists. When there are more functions than variables and the direction is `»`, simply ignore the functions in the functions list whose index is greater than the length of the variables list. For example, given `»+[f,g,h](x,y)`: ``` f(x)g(y) + f(y)g(x) ``` The Challenge ------------- Given a shorthanded string as described above, output the expanded expression Test Cases ---------- ``` Input -> Output «+[cos,sin](a,b) -> cos(a)cos(b) + sin(a)sin(b) »+[cos,sin](a,b) -> cos(a)sin(b) + cos(b)sin(a) «[f](x,y,z,n) -> f(x)f(y)f(z)f(n) «+[f](x,y,z,n) -> f(x) + f(y) + f(z) + f(n) «+[f,g]() -> »*[f,g]() -> »-[f,g](a,b) -> f(a)g(b) - f(b)g(a) »[g,f](a,b) -> g(a)f(b)g(b)f(a) «+[tan](a,b) -> tan(a) + tan(b) »+[](a,b) -> »-[f,g](x,y,z) -> f(x)g(y)z - f(y)g(z)x - f(z)g(x)y «/[f,g](x,y,z) -> f(x)f(y)f(z) / g(x)g(y)g(z) «[]() -> »[]() -> »+[x,y](foo,bar,baz) -> x(foo)y(bar)baz + x(bar)y(baz)foo + x(baz)y(foo)bar »+[f,g](x) -> f(x) + g(x) «+[f,g](x) -> f(x) + g(x) »+[f,g,h](x,y) -> f(x)g(y) + f(y)g(x) ``` Let it be known that: * The direction will *always* be given * The operator is *optional* * The `[]` denoting the functions will always be present, but will not always contain functions * The `()` denoting the variables will always be present, but will not always contain variables * Functions can be outputted in any order just as long as the expressions are in order (`cosAsinB - sinAsinB` can be written as `sinBcosA - sinBsinA` but not as `sinAsinB - cosAsinB`) * Variable names can be of any length * The `«` and `»` can be taken as `<` and `>` if wanted (`«` and `»` are preferred however) Therefore, if no functions/variables are present, then an empty output is required. Whitespacing within the answer doesn't matter (i.e. newlines/extra spaces don't invalidate outputs). Input can also be taken as: ``` [direction, operator, [functions], [variables]] ``` In which case, `direction` will be a string, `operator` will be either an empty string or an operator, `functions` will be a (sometimes empty) list of strings, as will variables. Score ----- This is code golf, so fewest bytes wins. Standard loopholes are forbidden. Leaderboards ------------ Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ```js var QUESTION_ID=194719; var OVERRIDE_USER=8478; var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}} ``` ```css body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> ```
2019/10/22
[ "https://codegolf.stackexchange.com/questions/194719", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/78850/" ]
[05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 63 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ============================================================================================================================ ``` UÇ`θiVεY€…(ÿ)«}ëDg©DIgα+>∍Œ®ùεζεðK'(ýyðå≠i')«]Dg≠iJ}¸˜Xý³gIg*Ā× ``` Four loose inputs in the order `operator, direction, [variables], [functions]`. [Try it online](https://tio.run/##yy9OTMpM/f8/9HB7wrkdmWHntkY@alrzqGGZxuH9modW1x5e7ZJ@aKWLZ/q5jdp2jzp6j046tO7wznNbz207t/XwBm91jcN7Kw9vOLz0UeeCTHWghliXdBDTq/bQjtNzIg7vPbQ53TNd60jD4en//2tzHdrNFa1UUaGko1RZqRQLZKcBmcn5xUqxAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@pw6XkX1oC5IJ5LqfbghL@hx5uTzi3IzPs3NbIR01rHjUs0zi8X/PQ6trDq13SD610ObQeKJt@bqO23aOO3qOTDq07vPPcVrBg8blt57Ye3uCtrnF4b@XhDYeXPupckKkO0goELukgnlftoR2n50Qc3gvUYHR4RTrEMK0jDYen/9c5tM3@0Jb/0dFK2ko6SodWK@lEKyUCWUlKsUBWcn4xkF2cmacUG6ujAFWzG78auDEVQFYlEFcBcR5YaRqyMcSqgQjqKKVDJbRgbkCX0MXiOGR5LNLpQBamoxDyJYl4fI5uK8Iv6DbrY/EvNtdBvYvqXLgAwglp@fkgRyQWgUmIWRCT0VVWYNiDHPZY5ZD8gpDXUcpAD8UKsBqwZxC@ASWG2NhYAA). **Explanation:** ```python U # Pop and store the 1st (implicit) input `operator` in variable `X` Ç # Convert the 2nd (implicit) input `direction` to a list of codepoint ` # Push this codepoint to the stack θ # Only leave its last digit i # If this digit is 1 (so the direction is "«"): V # Pop and store the 3rd (implicit) input `variables` in variable `Y` ε } # Map over the 4th (implicit) input `functions`: Y # Push the `variable`-list from variable `Y` €…(ÿ) # Surround each variable with parenthesis « # And append it to the current `function` we're mapping ë # Else (so the direction is "»" instead): D # Duplicate the 3rd (implicit) input `variables` g # Pop and push the length to get the amount of `variables` © # Store it in variable `®` (without popping) D # Duplicate this length I # Push the fourth input `functions` g # Pop and take its length as well α # Take the absolute difference between the two amounts + # And add it to the duplicated amount of `variables` > # And increase it by 1 ∍ # Then extend the duplicated `variables` list to that length Œ # Get all sublists of this list ®ù # Only leave the sublists of a length equal to variable `®` ε # Map each remaining sublist to: ζ # Create pairs with the 4th (implicit) input `functions`, # with a default space as filler character if the lengths differ ε # Map each pair: ðK # Remove the spaces '(ý '# Join the pair with a ")" delimiter yðå≠i # If the current pair did NOT contain a space: ')« '# Append a ")" ] # Close all open if-statements and maps D # Duplicate the resulting list g≠i } # Pop and if its length is NOT 1: J # Join the inner-most list together to a string ¸ # Then wrap it into a list (in case it wasn't a list yet) ˜ # And deep flatten the list Xý # Join it by the operator we stores in variable `X` ³g # Get the length of the 3rd input-list `variables` Ig # And the length of the 4th input-list `functions` * # Multiply them with each other Ā # Truthify it (0 remains 0; everything else becomes 1) × # And repeat the string that many times # (so it becomes an empty string if either list was empty, # or remains unchanged otherwise) # (after which this is output implicitly as result) ```
[C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 177 bytes ================================================================================================================= ```cs (d,o,f,v)=>string.Join(o=="*"?"":o,d<61?f.Select(l=>v.Aggregate("",(a,b)=>a+l+$"({b})")):v.Select((x,y)=>string.Concat(v.Select((i,o)=>o>=f.Count?i:f[(y+o)%f.Count]+$"({i})")))) ``` [Try it online!](https://tio.run/##fZJPb5wwEMXvfIqp1YpxmKUlhxx2MaiqVClVpBy2Ug6IgxfMxhLCEXjRplE@@9b8SXdDpB4Qmvfm/cyMKbpV0enTz0NTxMWjbKmzrW72dHunOxtPRbKo5nclTliSoYp6LpJJDH8Z3aARgl2xlLG1oTK@idIq3KpaFRZrkfTh9/2@VXtpFTJGKGnn4jKog88MX3avnHG@7t8CeKTnM/2HaQpp8exqMs41iaicd2hsqtdVhs@B4V9mJR@xesRyftp4vdElWNVZnKAgObx4AL1sodQtCJDZt3wzK@ZpFKIchAA/8yEFxmA9SuFvsx0RyId2OXSG28Nu4uIQFUN3CpFLXPM3ZuWWbbVpukUgIlfeNqU63lfo5z6HFUQ83D7V2qJP/giYGe7RclerJeMCgA4QwHsoH6GLpsUp4cOjahUeQSRwhE/DCNyNOvwC06APrbbqTjcKK3QbI7ckOg9F52/jfAPeqzcum8VBVpiOOt3kw6XSH3cjm9lLshwvy6v/tK7eeZfOvwPIyg9u/PVjzjv9BQ "C# (Visual C# Interactive Compiler) – Try It Online")
5,727,640
I am using SharedPreference to store the state of checkboxes but even i am storing true in it , its still retrieving false. Here is my code - ``` @Override public void onPause() { super.onPause(); saveState(); } @Override public void onResume() { super.onResume(); loadState(); } @Override public void onRestart() { super.onRestart(); loadState(); } public void saveState() { SharedPreferences sp = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); for(int i = 0; i < itemCheck.length; i++) { Boolean b = itemCheck[i]; Log.e(TAG, b.toString()); editor.putBoolean(i+"", itemCheck[i]); } } public void loadState() { SharedPreferences sp = getPreferences(Context.MODE_PRIVATE); for(int i = 0; i < itemCheck.length; i++) { itemCheck[i] = sp.getBoolean(i+"", false); Boolean b = itemCheck[i]; Log.e(TAG, b.toString()); } for(int i = 0; i < itemCheck.length; i++) { lv.setItemChecked(i, itemCheck[i]); } } ``` Its giving me false because i set false as a default value in getBoolean which should be returned in the absence of predefined key. Please take a look and tell me what i did wrong. Thanks
2011/04/20
[ "https://Stackoverflow.com/questions/5727640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/664512/" ]
I did something similar a while back. Assuming that you want your images displayed in image\_id order you could do the following. On the "next" link, you make a call to your PHP script with parameters that identify the category and the id and the direction you want to move.. eg myserver.com/myapp/images.php?action=next&cat=holidaypics&image\_id=111 Then you can do a query to find the next highest image\_id with the same category by doing something like "select min(image\_id) from images where category\_id="holidaypics" and image\_id > 111" If you're going in reverse you'd change the action to "prev" and do a query like this... "select max(image\_id) from images where category\_id="holidaypics" and image\_id < 111" Does that help?
Use sessions <http://ru2.php.net/manual/en/book.session.php> or pass all variables your need every time you ask server.
5,727,640
I am using SharedPreference to store the state of checkboxes but even i am storing true in it , its still retrieving false. Here is my code - ``` @Override public void onPause() { super.onPause(); saveState(); } @Override public void onResume() { super.onResume(); loadState(); } @Override public void onRestart() { super.onRestart(); loadState(); } public void saveState() { SharedPreferences sp = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); for(int i = 0; i < itemCheck.length; i++) { Boolean b = itemCheck[i]; Log.e(TAG, b.toString()); editor.putBoolean(i+"", itemCheck[i]); } } public void loadState() { SharedPreferences sp = getPreferences(Context.MODE_PRIVATE); for(int i = 0; i < itemCheck.length; i++) { itemCheck[i] = sp.getBoolean(i+"", false); Boolean b = itemCheck[i]; Log.e(TAG, b.toString()); } for(int i = 0; i < itemCheck.length; i++) { lv.setItemChecked(i, itemCheck[i]); } } ``` Its giving me false because i set false as a default value in getBoolean which should be returned in the absence of predefined key. Please take a look and tell me what i did wrong. Thanks
2011/04/20
[ "https://Stackoverflow.com/questions/5727640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/664512/" ]
I did something similar a while back. Assuming that you want your images displayed in image\_id order you could do the following. On the "next" link, you make a call to your PHP script with parameters that identify the category and the id and the direction you want to move.. eg myserver.com/myapp/images.php?action=next&cat=holidaypics&image\_id=111 Then you can do a query to find the next highest image\_id with the same category by doing something like "select min(image\_id) from images where category\_id="holidaypics" and image\_id > 111" If you're going in reverse you'd change the action to "prev" and do a query like this... "select max(image\_id) from images where category\_id="holidaypics" and image\_id < 111" Does that help?
Consider Ajax to load your container with images of a particular category. It is as simple as saying HI
5,191,062
What is the equivalent javascript code for `mysql_real_escape_string()`?
2011/03/04
[ "https://Stackoverflow.com/questions/5191062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66143/" ]
There isn't any, because strings that come from JavaScript are still considered 'user input' and **should never be inserted in your database directly**. Your server-side has to do additional validation. There are functions to encode URLs and stuff like that. What are you trying to do?
I think we can use escape() methode
5,191,062
What is the equivalent javascript code for `mysql_real_escape_string()`?
2011/03/04
[ "https://Stackoverflow.com/questions/5191062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66143/" ]
A good tip when you're looking for javascript equivalent versions of popular PHP functions is [phpjs.org](http://phpjs.org) However your probably looking for the wrong functionality. mysql\_real\_escape\_string() can only be used if a mysql database connection is active (More details about this can be read on the [mysqli real\_escape page](http://php.net/manual/en/mysqli.real-escape-string.php). I.e mysql\_real\_escape\_string() isn't really a PHP implementation, but more MySQL. If used without database connection it will just leave you with an empty variable. You might have looked for a function that adds slashes and removes newlines? You can check the phpjs.org on how they implemented the add\_slashes function. Removing newlines can be done with a custom replace function I guess. Maybe explain in what environment you require this function to work in javascript, so we could push you in the right direction (i.e talk you out of using mysql\_real\_escape\_string in javascript but provide tips on which function(s) you really need)
There isn't any, because strings that come from JavaScript are still considered 'user input' and **should never be inserted in your database directly**. Your server-side has to do additional validation. There are functions to encode URLs and stuff like that. What are you trying to do?
5,191,062
What is the equivalent javascript code for `mysql_real_escape_string()`?
2011/03/04
[ "https://Stackoverflow.com/questions/5191062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66143/" ]
Based on the [PHP documentation](http://php.net/manual/en/function.mysql-real-escape-string.php) of the method this would do roughly the same thing. The method mysql\_real\_escape\_string in PHP is deprecated however. ``` function mysqlEscape(stringToEscape){ return stringToEscape .replace("\\", "\\\\") .replace("\'", "\\\'") .replace("\"", "\\\"") .replace("\n", "\\\n") .replace("\r", "\\\r") .replace("\x00", "\\\x00") .replace("\x1a", "\\\x1a"); } ``` Unfortunately that's not exactly what mysql\_real\_escape\_string does according to the [5.6 mysql API docs](http://dev.mysql.com/doc/refman/5.6/en/mysql-real-escape-string.html). It doesn't take into account character encodings among other things. The above method will likely do what you're looking for even if you only use the first 2 replaces like so. ``` function mysqlEscape(stringToEscape){ return stringToEscape .replace("\\", "\\\\") .replace("\'", "\\\'"); } ``` According to the mysql docs. > > MySQL requires only that backslash and the quote character used to quote the string in the query be escaped. mysql\_real\_escape\_string() quotes the other characters to make them easier to read in log files > > >
There isn't any, because strings that come from JavaScript are still considered 'user input' and **should never be inserted in your database directly**. Your server-side has to do additional validation. There are functions to encode URLs and stuff like that. What are you trying to do?
5,191,062
What is the equivalent javascript code for `mysql_real_escape_string()`?
2011/03/04
[ "https://Stackoverflow.com/questions/5191062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66143/" ]
I've had an use case where I need to escape my own data (not from user input) in order to use it within a node.js script. I've fixed the code from @majinnaibu answer, because it was only escaping the first occurrence of the special symbol. ``` function mysqlEscape(stringToEscape){ if(stringToEscape == '') { return stringToEscape; } return stringToEscape .replace(/\\/g, "\\\\") .replace(/\'/g, "\\\'") .replace(/\"/g, "\\\"") .replace(/\n/g, "\\\n") .replace(/\r/g, "\\\r") .replace(/\x00/g, "\\\x00") .replace(/\x1a/g, "\\\x1a"); } ``` Hope this helps someone else.
There isn't any, because strings that come from JavaScript are still considered 'user input' and **should never be inserted in your database directly**. Your server-side has to do additional validation. There are functions to encode URLs and stuff like that. What are you trying to do?
5,191,062
What is the equivalent javascript code for `mysql_real_escape_string()`?
2011/03/04
[ "https://Stackoverflow.com/questions/5191062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66143/" ]
A good tip when you're looking for javascript equivalent versions of popular PHP functions is [phpjs.org](http://phpjs.org) However your probably looking for the wrong functionality. mysql\_real\_escape\_string() can only be used if a mysql database connection is active (More details about this can be read on the [mysqli real\_escape page](http://php.net/manual/en/mysqli.real-escape-string.php). I.e mysql\_real\_escape\_string() isn't really a PHP implementation, but more MySQL. If used without database connection it will just leave you with an empty variable. You might have looked for a function that adds slashes and removes newlines? You can check the phpjs.org on how they implemented the add\_slashes function. Removing newlines can be done with a custom replace function I guess. Maybe explain in what environment you require this function to work in javascript, so we could push you in the right direction (i.e talk you out of using mysql\_real\_escape\_string in javascript but provide tips on which function(s) you really need)
I think we can use escape() methode
5,191,062
What is the equivalent javascript code for `mysql_real_escape_string()`?
2011/03/04
[ "https://Stackoverflow.com/questions/5191062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66143/" ]
Based on the [PHP documentation](http://php.net/manual/en/function.mysql-real-escape-string.php) of the method this would do roughly the same thing. The method mysql\_real\_escape\_string in PHP is deprecated however. ``` function mysqlEscape(stringToEscape){ return stringToEscape .replace("\\", "\\\\") .replace("\'", "\\\'") .replace("\"", "\\\"") .replace("\n", "\\\n") .replace("\r", "\\\r") .replace("\x00", "\\\x00") .replace("\x1a", "\\\x1a"); } ``` Unfortunately that's not exactly what mysql\_real\_escape\_string does according to the [5.6 mysql API docs](http://dev.mysql.com/doc/refman/5.6/en/mysql-real-escape-string.html). It doesn't take into account character encodings among other things. The above method will likely do what you're looking for even if you only use the first 2 replaces like so. ``` function mysqlEscape(stringToEscape){ return stringToEscape .replace("\\", "\\\\") .replace("\'", "\\\'"); } ``` According to the mysql docs. > > MySQL requires only that backslash and the quote character used to quote the string in the query be escaped. mysql\_real\_escape\_string() quotes the other characters to make them easier to read in log files > > >
I think we can use escape() methode
5,191,062
What is the equivalent javascript code for `mysql_real_escape_string()`?
2011/03/04
[ "https://Stackoverflow.com/questions/5191062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66143/" ]
I've had an use case where I need to escape my own data (not from user input) in order to use it within a node.js script. I've fixed the code from @majinnaibu answer, because it was only escaping the first occurrence of the special symbol. ``` function mysqlEscape(stringToEscape){ if(stringToEscape == '') { return stringToEscape; } return stringToEscape .replace(/\\/g, "\\\\") .replace(/\'/g, "\\\'") .replace(/\"/g, "\\\"") .replace(/\n/g, "\\\n") .replace(/\r/g, "\\\r") .replace(/\x00/g, "\\\x00") .replace(/\x1a/g, "\\\x1a"); } ``` Hope this helps someone else.
I think we can use escape() methode
1,687,561
I was wondering how can I have my users pick their favorite food from a category of foods in my MySQL database. Will I need two different tables? If so what will my second table look like? Here is my MySQL food table structure. ``` id | parent_id | food | url ```
2009/11/06
[ "https://Stackoverflow.com/questions/1687561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/204839/" ]
You'll need 3 tables in total: 1. Food - holds food information 2. Users - holds users information 3. Users\_Food - holds user id + food id (and maybe a ranking) You should probably read up on [database normalization](http://en.wikipedia.org/wiki/Database_normalization).
You'd need to make a second table: `user_id | food_id` Make them both primary. Then you can use JOIN's to select the food: ``` SELECT f.food, f.url FROM user_food AS u INNER JOIN food AS f ON (f.id = u.food_id) WHERE u.user_id = {USER_ID} ``` This will give you a list of all favorite foods set by the user.
55,037
Last time I made a website using PHP, I didn't know of PDO, so someone dropped all my tables. I think I've made an improvement now. I'm sorry if there's a lot to go through, but I want to make sure its **safe** *(most importantly)* and also using the **best practices**. Here are some snippets: 1) ``` $form = $_POST; $name = $form[ 'name' ]; $desc = $form[ 'desc' ]; $link = $form[ 'link' ]; $tag = $form[ 'tag' ]; $category = $form[ 'category' ]; $sql = "INSERT INTO items ( `name`, `desc`, `link`, `tag`, `category` ) VALUES ( :name, :desc, :link, :tag, :category )"; $query = $db->prepare( $sql ); $query->execute( array( ':name'=>$name, ':desc'=>$desc, ':link'=>$link, ':tag'=>$tag, ':category'=>$category ) ); ``` 2) ``` $db = new PDO('mysql:host=mywebsite.com;dbname=thisdb;charset=utf8','root', ''); ``` 3) ``` if (isset($_GET['search'])) { $searchStmt = $db->prepare('SELECT * FROM items WHERE tag LIKE :usersearch'); $searchStmt->execute(['usersearch' => "%".$_GET['search']."%"]); foreach ($searchStmt as $row) { ?> <?php include('includes/results-layout.php'); ?> <?php }} else { header('Location: http://localhost/photo'); } if ($_GET['search'] == "") { header('Location: http://mywebsite.com/photo'); } if ($searchStmt->rowCount() === 0) { echo "Sorry, your search for <i>\"".$_GET['search']."\"</i> was not found..."; } ``` 4) ``` $page1Stmt = $db->query("SELECT * FROM items WHERE category = 1 ORDER BY id DESC"); ``` 5) ``` $downloadStmt = $db->prepare('SELECT * FROM items WHERE id = :downloadID'); $downloadStmt->execute(['downloadID' => $_GET['id']]); ?> $tags = explode(" ",$row['tag']); foreach($tags as $tag) {echo "<a href='search.php?search=".$tag."'><span class='itemTag'>".$tag."</span></a>";} $relatedStmt = $db->prepare("SELECT * FROM items WHERE tag = (select tag from items where id = :downloadID)"); $relatedStmt->execute(['downloadID' => $_GET['id']]); ?> ``` 6) ``` $pageStmt = $db->query("SELECT * FROM items ORDER BY id DESC"); foreach ($pageStmt as $row) { ?> <?php include('includes/results-layout.php'); ?> <?php } ?> ```
2014/06/23
[ "https://codereview.stackexchange.com/questions/55037", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/46959/" ]
Just a couple of quick-at-first-glance issues that need addressing: * Horrid, and I mean truly horrid, coding style. Please [subscribe to the standards](http://www.php-fig.org). ASAP. They are unofficial, but all major players subscribe to them, as should you. * If a file contains nothing but PHP code, the closing tag should be omitted, as [the official docs clearly state](http://www.php.net//manual/en/language.basic-syntax.phptags.php): *"If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file"* * Use the fourth constructor argument for `PDO`, which allows you to configure the actual connection (see below) * Think about encoding issues: `SET NAMES 'UTF8'`. Multi-byte chars are going to be processed as ASCII chars if you don't tell MySQL you're using the UTF-8 charset. * Never trust the network. Don't blindly trust prepared statements, and don't blindly trust user-supplied data, ***especially*** when it's coming from `$_GET`. The `$_SESSION` super-global is the closest you can get to the *gray area* of user data you can trust (because you set it). `$_POST` and `$_GET` are right out. I've been quite vocal on the fourth argument of the `PDO` constructor, and on the UTF-8 business, just recently. Instead of copy-pasting my previous answer, [here's a link](https://codereview.stackexchange.com/a/55011/16133). Basically, what I'd recommend you do is this: ``` $db = new PDO( 'mysql:host=127.0.0.1;port=3306;dbname=myDb;charset=UTF8', $userName, $pass, array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, //production only - read warning below, though PDO::ATTR_EMULATE_PREPARES => false, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'" ) ); ``` Why only disable emulate prepares in production code: because debugging is probably something you do on your local machine, or using a VBox + vagrant. Emulating prepared statements is a good way to spot malformed queries without having to burden your DB server. Still, once you go live: use real prepared statements, though. ***Warning:*** don't just go ahead and switch to native prepared statements and push to production, of course. Always make sure your queries still work, and produce the same results as before! There are [differences and gotcha's to keep in mind](https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string/12118602#12118602) What do I mean by *"never trust the network"*? I mean you really ought to sanitize, validate and check the user input you are using in your code. Take snippet 3 for example - I'll apply some critiques I gave both here, and on the linked review ``` //proper indentation, whitespace is your friend $searchStmt = $db->prepare( 'SELECT * FROM items WHERE tag LIKE :usersearch' ); $searchStmt->execute( [ 'usersearch' => "%".$_GET['search']."%" ] ); ``` Now suppose `$_GET['search']`'s value was either one of the MySQL wildcards (`_` , or `%` for example). They are perfectly valid strings, so they won't be escaped, resulting in a query not unlike ``` SELECT * FROM items WHERE tag LIKE '%%%'; //or SELECT * FROM items WHERE tag LIKE '%_%'; ``` Both of which equate to a slower version of this query: ``` SELECT * FROM items; ``` ie: you might end up selecting everything, and are most likely performing a full table scan whenever this query is executed. That's bad. But a few lines *later*, you seem to have realized that the value of `$_GET['search']` might just be an empty string: ``` if ($_GET['search'] == "") { header('Location: http://mywebsite.com/photo'); } ``` But why perform the query first? Why not check the value, and prevent performing a full table select? There are a couple of other issues, like `foreach + include`? Why not pour that code you need a couple of times into a function, `include` or `require` that file once, and call that function? I mean: it's less disk access, and less IO means better performance. You also have the bad habit of re-assigning things without good reason: ``` $form = $_POST; $name = $form[ 'name' ]; $desc = $form[ 'desc' ]; $link = $form[ 'link' ]; $tag = $form[ 'tag' ]; $category = $form[ 'category' ]; $sql = "INSERT INTO items ( `name`, `desc`, `link`, `tag`, `category` ) VALUES ( :name, :desc, :link, :tag, :category )"; $query = $db->prepare( $sql ); $query->execute( array( ':name'=>$name, ':desc'=>$desc, ':link'=>$link, ':tag'=>$tag, ':category'=>$category ) ); ``` So you assign `$_POST` to `$form`, for *every* parameter, you create a new variable. Then you create a string and assign that to a variable called `$sql`, then, from that string, you create a `PDOStatement` instance, and assign that to yet another variable called `$query`, on which you call the `execute` method, constructing a new array using the variables you just extracting from an array?? Doesn't that seem a bit silly? Why not write the code like this: ``` $stmt = $db->prepare( 'INSERT INTO items ( `name`, `desc`, `link`, `tag`, `category` ) VALUES ( :name, :desc, :link, :tag, :category )' ); $stmt->execute( array( ':name' => $_POST['name'], ':desc' => $_POST['desc'], ':link' => $_POST['link'], ':tag' => $_POST['tag'], ':category' => $_POST['category'], ) ); ``` Not only does that look a hell of a lot tidier, it's actually more efficient, too. But there still is a problem with this code: I'm missing the `isset` checks. Now I could use a bunch of `if`'s or ternaries here. Depending on what you want. If and which values are missing, you could then redirect, or use `null` as a default value. But a basic loop could work here, too: ``` /** * Wrap the code in a function, so you can re-use it easily * @param array $data the data to bind * @param array $keys the keys which contain the values we need * @return array */ function extractBind(array $data, array $keys) { $bind = array();//the return array foreach ($keys as $key) $bind[':'.$key] = isset($data[$key]) ? $data[$key] : null; return $bind; } //in your case, this would be how you use this function $stmt = $db->prepare( 'INSERT INTO items ( `name`, `desc`, `link`, `tag`, `category` ) VALUES ( :name, :desc, :link, :tag, :category )' ); $stmt->execute( extractBind( $_POST, array( 'name', 'desc', 'tag', 'category' ) ) ); ``` Now I'm not saying you should use this code, but I'm just pointing out ways to make your life easier. You can use the function I wrote here, but you shouldn't pass the array it returns to the `$stmt->execute` call right away. Remember: *never trust the network*: The values in the bind array should still be sanitized and validated. Check my profile on this site, and read through a couple of my *"sanitize"* and *"validate"* answers, I've also posted a couple of answers on XSS vulnerabilities, which might interest you, too...
Okay All of them ----------- * Don't have multiple statements on the same line like that. * Use either spaces or tabs, don't use both. * `<?php something; ?> <?php somethingElse; ?>` is pointless. Don't do that. * Be consistent. Sometimes you're doing `funcName( $param )` and sometimes `funcName($param)`. Pick one and stick with it. 1) -- * Looks good security wise. See above **All of them** for improving. 2) -- * Looks good, but too little information to know. If you haven't already, set `PDO::ATTR_ERRMODE` to `PDO::ERRMODE_EXCEPTION` and `PDO::ATTR_EMULATE_PREPARES` to `false`. See **[`PDO::setAttribute()](http://www.php.net//manual/en/pdo.setattribute.php)**. 3) -- * Sometimes you are redirecting to `localhost`, sometimes to `mywebsite`. Use a variable. See **[`$_SERVER`](http://il1.php.net/reserved.variables.server.php)**. * `}}` is horrible. 4) -- * Very good. Queries that don't use parameters don't need to be prepared. Note however that there's a very fine line! Every time you need a variable inside of a query, you want a prepared statement. 5) -- * You are vulnerable to XSS attacks on your tags. This can be prevented by **[escaping your tags for HTML output](http://il1.php.net/htmlspecialchars)**. 6) -- * Look at the **all of them** list for details on how to improve. --- All in all, you *must* improve your code-style. Your code is extremely unreadable and will be hard to maintain in the future. Aside from that one XSS vulnerability, it looks good to me, but again, it's hard to tell just with the code you've given.
55,037
Last time I made a website using PHP, I didn't know of PDO, so someone dropped all my tables. I think I've made an improvement now. I'm sorry if there's a lot to go through, but I want to make sure its **safe** *(most importantly)* and also using the **best practices**. Here are some snippets: 1) ``` $form = $_POST; $name = $form[ 'name' ]; $desc = $form[ 'desc' ]; $link = $form[ 'link' ]; $tag = $form[ 'tag' ]; $category = $form[ 'category' ]; $sql = "INSERT INTO items ( `name`, `desc`, `link`, `tag`, `category` ) VALUES ( :name, :desc, :link, :tag, :category )"; $query = $db->prepare( $sql ); $query->execute( array( ':name'=>$name, ':desc'=>$desc, ':link'=>$link, ':tag'=>$tag, ':category'=>$category ) ); ``` 2) ``` $db = new PDO('mysql:host=mywebsite.com;dbname=thisdb;charset=utf8','root', ''); ``` 3) ``` if (isset($_GET['search'])) { $searchStmt = $db->prepare('SELECT * FROM items WHERE tag LIKE :usersearch'); $searchStmt->execute(['usersearch' => "%".$_GET['search']."%"]); foreach ($searchStmt as $row) { ?> <?php include('includes/results-layout.php'); ?> <?php }} else { header('Location: http://localhost/photo'); } if ($_GET['search'] == "") { header('Location: http://mywebsite.com/photo'); } if ($searchStmt->rowCount() === 0) { echo "Sorry, your search for <i>\"".$_GET['search']."\"</i> was not found..."; } ``` 4) ``` $page1Stmt = $db->query("SELECT * FROM items WHERE category = 1 ORDER BY id DESC"); ``` 5) ``` $downloadStmt = $db->prepare('SELECT * FROM items WHERE id = :downloadID'); $downloadStmt->execute(['downloadID' => $_GET['id']]); ?> $tags = explode(" ",$row['tag']); foreach($tags as $tag) {echo "<a href='search.php?search=".$tag."'><span class='itemTag'>".$tag."</span></a>";} $relatedStmt = $db->prepare("SELECT * FROM items WHERE tag = (select tag from items where id = :downloadID)"); $relatedStmt->execute(['downloadID' => $_GET['id']]); ?> ``` 6) ``` $pageStmt = $db->query("SELECT * FROM items ORDER BY id DESC"); foreach ($pageStmt as $row) { ?> <?php include('includes/results-layout.php'); ?> <?php } ?> ```
2014/06/23
[ "https://codereview.stackexchange.com/questions/55037", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/46959/" ]
Okay All of them ----------- * Don't have multiple statements on the same line like that. * Use either spaces or tabs, don't use both. * `<?php something; ?> <?php somethingElse; ?>` is pointless. Don't do that. * Be consistent. Sometimes you're doing `funcName( $param )` and sometimes `funcName($param)`. Pick one and stick with it. 1) -- * Looks good security wise. See above **All of them** for improving. 2) -- * Looks good, but too little information to know. If you haven't already, set `PDO::ATTR_ERRMODE` to `PDO::ERRMODE_EXCEPTION` and `PDO::ATTR_EMULATE_PREPARES` to `false`. See **[`PDO::setAttribute()](http://www.php.net//manual/en/pdo.setattribute.php)**. 3) -- * Sometimes you are redirecting to `localhost`, sometimes to `mywebsite`. Use a variable. See **[`$_SERVER`](http://il1.php.net/reserved.variables.server.php)**. * `}}` is horrible. 4) -- * Very good. Queries that don't use parameters don't need to be prepared. Note however that there's a very fine line! Every time you need a variable inside of a query, you want a prepared statement. 5) -- * You are vulnerable to XSS attacks on your tags. This can be prevented by **[escaping your tags for HTML output](http://il1.php.net/htmlspecialchars)**. 6) -- * Look at the **all of them** list for details on how to improve. --- All in all, you *must* improve your code-style. Your code is extremely unreadable and will be hard to maintain in the future. Aside from that one XSS vulnerability, it looks good to me, but again, it's hard to tell just with the code you've given.
First off a general comment about your formatting, I would suggest one statement per line. Program your fingers to type `;<cr>`. This will not only make it easier for you to find the statement you want to change later, but it will also make it easier for you and others (like say, users of codereview.stackexchange.com) to read. Also, if you use VC (you are aren't you?), one statement per line makes it easier to determine what has changed when reviewing diffs. That said, this code does appear to be safe from SQL injection through your use of PDO and parameterized statements. Onto the nitpicking :). 1. Other than the one statement per line thing I mentioned above nothing really wrong here. One thing that took me a long time to learn is that PDO doesn't actually require the `:` prefix on the array keys, so your array could be written as: `[ 'name' => ..., ... ]` 2. I'm not sure if you're using the `root` user here as an example or not, but if this is your actual setup I would recommend creating a database user with only the permissions needed by your app and disable remote access for the root user. 3. There are a couple of issues with this block of code. First off, the indentation is inconsistent. It's difficult to understand what this code is doing despite being a relatively short piece. Also, there is no need to drop out of PHP to include another PHP file in the foreach. Aside from the this, the overall flow is not optimal. If the search parameter is the empty string, this code will perform a DB query and process the results before discarding everything and redirecting to another page. The last if statement belongs **inside** the initial if s$tatement. Also, using rowCount() on the result of a SELECT statement will not return consistent results for different database drivers.This entire block should be restructured, e.g.: ``` if (isset($_GET['search']) && !empty($_GET['search'])) { $searchStmt = $db->prepare('SELECT * FROM items WHERE tag LIKE :usersearch'); $searchStmt->execute([ 'usersearch' => "%".$_GET['search']."%" ]); $count = 0; foreach ($searchStmt as $row) { include '...'; $count++; } if ($count === 0) { echo "Sorry, your search for <i>\"".$_GET['search']."\"</i> was not found..."; } } else { header('Location: http://mywebsite.com/photo'); } ``` 4. Nothing to say here, looks fine to me. 5. Other than the issues I've already covered, there appears to be phantom closing PHP tag. I'm guessing this is a copy page error. Also, nothing is being done with the results of the related tags query. If this just because it has not been included in the posted segment? Also, if tags can be created by users, they should be URL/HTML encoded before output to avoid subjecting your users to XSS attacks. 6. Same comment about dropping out of PHP to include a file. Finally, a general comment about code styles, try and be consistent in your use of syntax. Some snippets use `array(...)` syntax while others use the array shorthand `[ ... ]`. I would suggest following a published PHP style guide. [PHP-FIG](http://www.php-fig.org) offers a couple of levels of guide. [PSR-1](http://www.php-fig.org/psr/psr-1/) defines how to organize code into different files and how to name some elements. [PSR-2](http://www.php-fig.org/psr/psr-2/) is much more comprehensive and covers things like how much and where to use whitespace.
55,037
Last time I made a website using PHP, I didn't know of PDO, so someone dropped all my tables. I think I've made an improvement now. I'm sorry if there's a lot to go through, but I want to make sure its **safe** *(most importantly)* and also using the **best practices**. Here are some snippets: 1) ``` $form = $_POST; $name = $form[ 'name' ]; $desc = $form[ 'desc' ]; $link = $form[ 'link' ]; $tag = $form[ 'tag' ]; $category = $form[ 'category' ]; $sql = "INSERT INTO items ( `name`, `desc`, `link`, `tag`, `category` ) VALUES ( :name, :desc, :link, :tag, :category )"; $query = $db->prepare( $sql ); $query->execute( array( ':name'=>$name, ':desc'=>$desc, ':link'=>$link, ':tag'=>$tag, ':category'=>$category ) ); ``` 2) ``` $db = new PDO('mysql:host=mywebsite.com;dbname=thisdb;charset=utf8','root', ''); ``` 3) ``` if (isset($_GET['search'])) { $searchStmt = $db->prepare('SELECT * FROM items WHERE tag LIKE :usersearch'); $searchStmt->execute(['usersearch' => "%".$_GET['search']."%"]); foreach ($searchStmt as $row) { ?> <?php include('includes/results-layout.php'); ?> <?php }} else { header('Location: http://localhost/photo'); } if ($_GET['search'] == "") { header('Location: http://mywebsite.com/photo'); } if ($searchStmt->rowCount() === 0) { echo "Sorry, your search for <i>\"".$_GET['search']."\"</i> was not found..."; } ``` 4) ``` $page1Stmt = $db->query("SELECT * FROM items WHERE category = 1 ORDER BY id DESC"); ``` 5) ``` $downloadStmt = $db->prepare('SELECT * FROM items WHERE id = :downloadID'); $downloadStmt->execute(['downloadID' => $_GET['id']]); ?> $tags = explode(" ",$row['tag']); foreach($tags as $tag) {echo "<a href='search.php?search=".$tag."'><span class='itemTag'>".$tag."</span></a>";} $relatedStmt = $db->prepare("SELECT * FROM items WHERE tag = (select tag from items where id = :downloadID)"); $relatedStmt->execute(['downloadID' => $_GET['id']]); ?> ``` 6) ``` $pageStmt = $db->query("SELECT * FROM items ORDER BY id DESC"); foreach ($pageStmt as $row) { ?> <?php include('includes/results-layout.php'); ?> <?php } ?> ```
2014/06/23
[ "https://codereview.stackexchange.com/questions/55037", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/46959/" ]
Just a couple of quick-at-first-glance issues that need addressing: * Horrid, and I mean truly horrid, coding style. Please [subscribe to the standards](http://www.php-fig.org). ASAP. They are unofficial, but all major players subscribe to them, as should you. * If a file contains nothing but PHP code, the closing tag should be omitted, as [the official docs clearly state](http://www.php.net//manual/en/language.basic-syntax.phptags.php): *"If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file"* * Use the fourth constructor argument for `PDO`, which allows you to configure the actual connection (see below) * Think about encoding issues: `SET NAMES 'UTF8'`. Multi-byte chars are going to be processed as ASCII chars if you don't tell MySQL you're using the UTF-8 charset. * Never trust the network. Don't blindly trust prepared statements, and don't blindly trust user-supplied data, ***especially*** when it's coming from `$_GET`. The `$_SESSION` super-global is the closest you can get to the *gray area* of user data you can trust (because you set it). `$_POST` and `$_GET` are right out. I've been quite vocal on the fourth argument of the `PDO` constructor, and on the UTF-8 business, just recently. Instead of copy-pasting my previous answer, [here's a link](https://codereview.stackexchange.com/a/55011/16133). Basically, what I'd recommend you do is this: ``` $db = new PDO( 'mysql:host=127.0.0.1;port=3306;dbname=myDb;charset=UTF8', $userName, $pass, array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, //production only - read warning below, though PDO::ATTR_EMULATE_PREPARES => false, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'" ) ); ``` Why only disable emulate prepares in production code: because debugging is probably something you do on your local machine, or using a VBox + vagrant. Emulating prepared statements is a good way to spot malformed queries without having to burden your DB server. Still, once you go live: use real prepared statements, though. ***Warning:*** don't just go ahead and switch to native prepared statements and push to production, of course. Always make sure your queries still work, and produce the same results as before! There are [differences and gotcha's to keep in mind](https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string/12118602#12118602) What do I mean by *"never trust the network"*? I mean you really ought to sanitize, validate and check the user input you are using in your code. Take snippet 3 for example - I'll apply some critiques I gave both here, and on the linked review ``` //proper indentation, whitespace is your friend $searchStmt = $db->prepare( 'SELECT * FROM items WHERE tag LIKE :usersearch' ); $searchStmt->execute( [ 'usersearch' => "%".$_GET['search']."%" ] ); ``` Now suppose `$_GET['search']`'s value was either one of the MySQL wildcards (`_` , or `%` for example). They are perfectly valid strings, so they won't be escaped, resulting in a query not unlike ``` SELECT * FROM items WHERE tag LIKE '%%%'; //or SELECT * FROM items WHERE tag LIKE '%_%'; ``` Both of which equate to a slower version of this query: ``` SELECT * FROM items; ``` ie: you might end up selecting everything, and are most likely performing a full table scan whenever this query is executed. That's bad. But a few lines *later*, you seem to have realized that the value of `$_GET['search']` might just be an empty string: ``` if ($_GET['search'] == "") { header('Location: http://mywebsite.com/photo'); } ``` But why perform the query first? Why not check the value, and prevent performing a full table select? There are a couple of other issues, like `foreach + include`? Why not pour that code you need a couple of times into a function, `include` or `require` that file once, and call that function? I mean: it's less disk access, and less IO means better performance. You also have the bad habit of re-assigning things without good reason: ``` $form = $_POST; $name = $form[ 'name' ]; $desc = $form[ 'desc' ]; $link = $form[ 'link' ]; $tag = $form[ 'tag' ]; $category = $form[ 'category' ]; $sql = "INSERT INTO items ( `name`, `desc`, `link`, `tag`, `category` ) VALUES ( :name, :desc, :link, :tag, :category )"; $query = $db->prepare( $sql ); $query->execute( array( ':name'=>$name, ':desc'=>$desc, ':link'=>$link, ':tag'=>$tag, ':category'=>$category ) ); ``` So you assign `$_POST` to `$form`, for *every* parameter, you create a new variable. Then you create a string and assign that to a variable called `$sql`, then, from that string, you create a `PDOStatement` instance, and assign that to yet another variable called `$query`, on which you call the `execute` method, constructing a new array using the variables you just extracting from an array?? Doesn't that seem a bit silly? Why not write the code like this: ``` $stmt = $db->prepare( 'INSERT INTO items ( `name`, `desc`, `link`, `tag`, `category` ) VALUES ( :name, :desc, :link, :tag, :category )' ); $stmt->execute( array( ':name' => $_POST['name'], ':desc' => $_POST['desc'], ':link' => $_POST['link'], ':tag' => $_POST['tag'], ':category' => $_POST['category'], ) ); ``` Not only does that look a hell of a lot tidier, it's actually more efficient, too. But there still is a problem with this code: I'm missing the `isset` checks. Now I could use a bunch of `if`'s or ternaries here. Depending on what you want. If and which values are missing, you could then redirect, or use `null` as a default value. But a basic loop could work here, too: ``` /** * Wrap the code in a function, so you can re-use it easily * @param array $data the data to bind * @param array $keys the keys which contain the values we need * @return array */ function extractBind(array $data, array $keys) { $bind = array();//the return array foreach ($keys as $key) $bind[':'.$key] = isset($data[$key]) ? $data[$key] : null; return $bind; } //in your case, this would be how you use this function $stmt = $db->prepare( 'INSERT INTO items ( `name`, `desc`, `link`, `tag`, `category` ) VALUES ( :name, :desc, :link, :tag, :category )' ); $stmt->execute( extractBind( $_POST, array( 'name', 'desc', 'tag', 'category' ) ) ); ``` Now I'm not saying you should use this code, but I'm just pointing out ways to make your life easier. You can use the function I wrote here, but you shouldn't pass the array it returns to the `$stmt->execute` call right away. Remember: *never trust the network*: The values in the bind array should still be sanitized and validated. Check my profile on this site, and read through a couple of my *"sanitize"* and *"validate"* answers, I've also posted a couple of answers on XSS vulnerabilities, which might interest you, too...
First off a general comment about your formatting, I would suggest one statement per line. Program your fingers to type `;<cr>`. This will not only make it easier for you to find the statement you want to change later, but it will also make it easier for you and others (like say, users of codereview.stackexchange.com) to read. Also, if you use VC (you are aren't you?), one statement per line makes it easier to determine what has changed when reviewing diffs. That said, this code does appear to be safe from SQL injection through your use of PDO and parameterized statements. Onto the nitpicking :). 1. Other than the one statement per line thing I mentioned above nothing really wrong here. One thing that took me a long time to learn is that PDO doesn't actually require the `:` prefix on the array keys, so your array could be written as: `[ 'name' => ..., ... ]` 2. I'm not sure if you're using the `root` user here as an example or not, but if this is your actual setup I would recommend creating a database user with only the permissions needed by your app and disable remote access for the root user. 3. There are a couple of issues with this block of code. First off, the indentation is inconsistent. It's difficult to understand what this code is doing despite being a relatively short piece. Also, there is no need to drop out of PHP to include another PHP file in the foreach. Aside from the this, the overall flow is not optimal. If the search parameter is the empty string, this code will perform a DB query and process the results before discarding everything and redirecting to another page. The last if statement belongs **inside** the initial if s$tatement. Also, using rowCount() on the result of a SELECT statement will not return consistent results for different database drivers.This entire block should be restructured, e.g.: ``` if (isset($_GET['search']) && !empty($_GET['search'])) { $searchStmt = $db->prepare('SELECT * FROM items WHERE tag LIKE :usersearch'); $searchStmt->execute([ 'usersearch' => "%".$_GET['search']."%" ]); $count = 0; foreach ($searchStmt as $row) { include '...'; $count++; } if ($count === 0) { echo "Sorry, your search for <i>\"".$_GET['search']."\"</i> was not found..."; } } else { header('Location: http://mywebsite.com/photo'); } ``` 4. Nothing to say here, looks fine to me. 5. Other than the issues I've already covered, there appears to be phantom closing PHP tag. I'm guessing this is a copy page error. Also, nothing is being done with the results of the related tags query. If this just because it has not been included in the posted segment? Also, if tags can be created by users, they should be URL/HTML encoded before output to avoid subjecting your users to XSS attacks. 6. Same comment about dropping out of PHP to include a file. Finally, a general comment about code styles, try and be consistent in your use of syntax. Some snippets use `array(...)` syntax while others use the array shorthand `[ ... ]`. I would suggest following a published PHP style guide. [PHP-FIG](http://www.php-fig.org) offers a couple of levels of guide. [PSR-1](http://www.php-fig.org/psr/psr-1/) defines how to organize code into different files and how to name some elements. [PSR-2](http://www.php-fig.org/psr/psr-2/) is much more comprehensive and covers things like how much and where to use whitespace.
694,883
Consider the function $f(x)=[x]$ on the interval $[0,2]$ where $[x]$ denotes the largest integer less than or equal to x. Is this function continuous? I cant find a reason for it not to be, although im not sure.
2014/03/01
[ "https://math.stackexchange.com/questions/694883", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
If you're familiar with the properties of continuous functions, another way to see it is that $f^{-1}(1)=[0,1)$, which is not a closed subset of $[0,2]$.
**Hint:** Proof the negation of $$ (\forall \epsilon >0)(\exists \delta >0) \Big( (\forall x)(|x-1|<\delta \implies |f(x)-f(1)|<\epsilon)\Big), $$ that is $$ (\exists \epsilon >0)(\forall \delta >0) \Big( (\exists x)(|x-1|<\delta \mbox{ and } |f(x)-f(1)|>\epsilon)\Big) $$
694,883
Consider the function $f(x)=[x]$ on the interval $[0,2]$ where $[x]$ denotes the largest integer less than or equal to x. Is this function continuous? I cant find a reason for it not to be, although im not sure.
2014/03/01
[ "https://math.stackexchange.com/questions/694883", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
![enter image description here](https://i.stack.imgur.com/gkImo.png) You can surely see that the function is not continuous at integral points. To illustrate it compute $\lim\_{x\rightarrow 1^+}[x]$ and $\lim\_{x\rightarrow 1^-}[x]$ show that the limit does not exist at $x = 1$. Hence the function cannot be continuous.
Another characterisation of a function $f$ being continous at an argument value $x$ is, that it has a value $f(x)$ there which is equal to its limit value there. This requires an existing limit value. That last requirement is not valid for your function at $x = 1$: If you arrive from the left, the limit at $x = 1$ is $0$, $$ \lim\_{x \to 1 \atop x < 1} \left[ x \right] = \lim\_{x \to 1 \atop 0 < x < 1} \left[ x \right] = \lim\_{x \to 1 \atop 0 < x < 1} 0 = 0 $$ but if you arrive from the right, the limit value is $1$, $$ \lim\_{x \to 1 \atop x > 1} \left[ x \right] = \lim\_{x \to 1 \atop 2 > x > 1} \left[ x \right] = \lim\_{x \to 1 \atop 2 > x > 1} 1 = 1 $$ So the limit is not defined at $x = 1$, but $f$ is defined there. It is not continous there.
694,883
Consider the function $f(x)=[x]$ on the interval $[0,2]$ where $[x]$ denotes the largest integer less than or equal to x. Is this function continuous? I cant find a reason for it not to be, although im not sure.
2014/03/01
[ "https://math.stackexchange.com/questions/694883", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
The function $\lfloor x \rfloor$ is not continuous at interior points that are integers. In this case it at $x=1$. It is also discontinuous at $x=2$ If you are looking for a formal argument here is one. If a function $f(x)$ is continuous at $x=a$ then for every $\varepsilon>0$ there exist an $\delta>0$ such that $$|x-a|<\delta \Rightarrow |f(x)-f(a)| < \varepsilon $$ So if the function is continuous at $x=1$ then for $\varepsilon=\frac12$ there should be a $\delta$. If there is a delta at points such that $1-\delta<x<1+\delta$ the inequality $|f(x)-1| < \frac12 \, \, \star$ should be satisfied. Now our job is reduced to show that whatever $\delta$ we choose there is a point for which $\star$ do not hold. So if we choose a $\delta < 1$ the point $0<1-\frac\delta2<1$ and $f(x)=0$ at all such regions implying that $|f(x)-1|=|0-1|=1>\frac12$.
Another characterisation of a function $f$ being continous at an argument value $x$ is, that it has a value $f(x)$ there which is equal to its limit value there. This requires an existing limit value. That last requirement is not valid for your function at $x = 1$: If you arrive from the left, the limit at $x = 1$ is $0$, $$ \lim\_{x \to 1 \atop x < 1} \left[ x \right] = \lim\_{x \to 1 \atop 0 < x < 1} \left[ x \right] = \lim\_{x \to 1 \atop 0 < x < 1} 0 = 0 $$ but if you arrive from the right, the limit value is $1$, $$ \lim\_{x \to 1 \atop x > 1} \left[ x \right] = \lim\_{x \to 1 \atop 2 > x > 1} \left[ x \right] = \lim\_{x \to 1 \atop 2 > x > 1} 1 = 1 $$ So the limit is not defined at $x = 1$, but $f$ is defined there. It is not continous there.
694,883
Consider the function $f(x)=[x]$ on the interval $[0,2]$ where $[x]$ denotes the largest integer less than or equal to x. Is this function continuous? I cant find a reason for it not to be, although im not sure.
2014/03/01
[ "https://math.stackexchange.com/questions/694883", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
**Hint:** Proof the negation of $$ (\forall \epsilon >0)(\exists \delta >0) \Big( (\forall x)(|x-1|<\delta \implies |f(x)-f(1)|<\epsilon)\Big), $$ that is $$ (\exists \epsilon >0)(\forall \delta >0) \Big( (\exists x)(|x-1|<\delta \mbox{ and } |f(x)-f(1)|>\epsilon)\Big) $$
Another characterisation of a function $f$ being continous at an argument value $x$ is, that it has a value $f(x)$ there which is equal to its limit value there. This requires an existing limit value. That last requirement is not valid for your function at $x = 1$: If you arrive from the left, the limit at $x = 1$ is $0$, $$ \lim\_{x \to 1 \atop x < 1} \left[ x \right] = \lim\_{x \to 1 \atop 0 < x < 1} \left[ x \right] = \lim\_{x \to 1 \atop 0 < x < 1} 0 = 0 $$ but if you arrive from the right, the limit value is $1$, $$ \lim\_{x \to 1 \atop x > 1} \left[ x \right] = \lim\_{x \to 1 \atop 2 > x > 1} \left[ x \right] = \lim\_{x \to 1 \atop 2 > x > 1} 1 = 1 $$ So the limit is not defined at $x = 1$, but $f$ is defined there. It is not continous there.
694,883
Consider the function $f(x)=[x]$ on the interval $[0,2]$ where $[x]$ denotes the largest integer less than or equal to x. Is this function continuous? I cant find a reason for it not to be, although im not sure.
2014/03/01
[ "https://math.stackexchange.com/questions/694883", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
The function $\lfloor x \rfloor$ is not continuous at interior points that are integers. In this case it at $x=1$. It is also discontinuous at $x=2$ If you are looking for a formal argument here is one. If a function $f(x)$ is continuous at $x=a$ then for every $\varepsilon>0$ there exist an $\delta>0$ such that $$|x-a|<\delta \Rightarrow |f(x)-f(a)| < \varepsilon $$ So if the function is continuous at $x=1$ then for $\varepsilon=\frac12$ there should be a $\delta$. If there is a delta at points such that $1-\delta<x<1+\delta$ the inequality $|f(x)-1| < \frac12 \, \, \star$ should be satisfied. Now our job is reduced to show that whatever $\delta$ we choose there is a point for which $\star$ do not hold. So if we choose a $\delta < 1$ the point $0<1-\frac\delta2<1$ and $f(x)=0$ at all such regions implying that $|f(x)-1|=|0-1|=1>\frac12$.
It is not continous. To see that, consider for example that $f(1) = 1$, but $f(1 - \epsilon) = 0$ for any $\epsilon>0$. There is a 'jump' from $f=0$ to $f=1$ without any values inbetween, regardless of the size of $\epsilon$.
694,883
Consider the function $f(x)=[x]$ on the interval $[0,2]$ where $[x]$ denotes the largest integer less than or equal to x. Is this function continuous? I cant find a reason for it not to be, although im not sure.
2014/03/01
[ "https://math.stackexchange.com/questions/694883", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
It is not continous. To see that, consider for example that $f(1) = 1$, but $f(1 - \epsilon) = 0$ for any $\epsilon>0$. There is a 'jump' from $f=0$ to $f=1$ without any values inbetween, regardless of the size of $\epsilon$.
Another characterisation of a function $f$ being continous at an argument value $x$ is, that it has a value $f(x)$ there which is equal to its limit value there. This requires an existing limit value. That last requirement is not valid for your function at $x = 1$: If you arrive from the left, the limit at $x = 1$ is $0$, $$ \lim\_{x \to 1 \atop x < 1} \left[ x \right] = \lim\_{x \to 1 \atop 0 < x < 1} \left[ x \right] = \lim\_{x \to 1 \atop 0 < x < 1} 0 = 0 $$ but if you arrive from the right, the limit value is $1$, $$ \lim\_{x \to 1 \atop x > 1} \left[ x \right] = \lim\_{x \to 1 \atop 2 > x > 1} \left[ x \right] = \lim\_{x \to 1 \atop 2 > x > 1} 1 = 1 $$ So the limit is not defined at $x = 1$, but $f$ is defined there. It is not continous there.
694,883
Consider the function $f(x)=[x]$ on the interval $[0,2]$ where $[x]$ denotes the largest integer less than or equal to x. Is this function continuous? I cant find a reason for it not to be, although im not sure.
2014/03/01
[ "https://math.stackexchange.com/questions/694883", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
If you're familiar with the properties of continuous functions, another way to see it is that $f^{-1}(1)=[0,1)$, which is not a closed subset of $[0,2]$.
Another characterisation of a function $f$ being continous at an argument value $x$ is, that it has a value $f(x)$ there which is equal to its limit value there. This requires an existing limit value. That last requirement is not valid for your function at $x = 1$: If you arrive from the left, the limit at $x = 1$ is $0$, $$ \lim\_{x \to 1 \atop x < 1} \left[ x \right] = \lim\_{x \to 1 \atop 0 < x < 1} \left[ x \right] = \lim\_{x \to 1 \atop 0 < x < 1} 0 = 0 $$ but if you arrive from the right, the limit value is $1$, $$ \lim\_{x \to 1 \atop x > 1} \left[ x \right] = \lim\_{x \to 1 \atop 2 > x > 1} \left[ x \right] = \lim\_{x \to 1 \atop 2 > x > 1} 1 = 1 $$ So the limit is not defined at $x = 1$, but $f$ is defined there. It is not continous there.
694,883
Consider the function $f(x)=[x]$ on the interval $[0,2]$ where $[x]$ denotes the largest integer less than or equal to x. Is this function continuous? I cant find a reason for it not to be, although im not sure.
2014/03/01
[ "https://math.stackexchange.com/questions/694883", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
It is not continous. To see that, consider for example that $f(1) = 1$, but $f(1 - \epsilon) = 0$ for any $\epsilon>0$. There is a 'jump' from $f=0$ to $f=1$ without any values inbetween, regardless of the size of $\epsilon$.
**Hint:** Proof the negation of $$ (\forall \epsilon >0)(\exists \delta >0) \Big( (\forall x)(|x-1|<\delta \implies |f(x)-f(1)|<\epsilon)\Big), $$ that is $$ (\exists \epsilon >0)(\forall \delta >0) \Big( (\exists x)(|x-1|<\delta \mbox{ and } |f(x)-f(1)|>\epsilon)\Big) $$
694,883
Consider the function $f(x)=[x]$ on the interval $[0,2]$ where $[x]$ denotes the largest integer less than or equal to x. Is this function continuous? I cant find a reason for it not to be, although im not sure.
2014/03/01
[ "https://math.stackexchange.com/questions/694883", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
The function $\lfloor x \rfloor$ is not continuous at interior points that are integers. In this case it at $x=1$. It is also discontinuous at $x=2$ If you are looking for a formal argument here is one. If a function $f(x)$ is continuous at $x=a$ then for every $\varepsilon>0$ there exist an $\delta>0$ such that $$|x-a|<\delta \Rightarrow |f(x)-f(a)| < \varepsilon $$ So if the function is continuous at $x=1$ then for $\varepsilon=\frac12$ there should be a $\delta$. If there is a delta at points such that $1-\delta<x<1+\delta$ the inequality $|f(x)-1| < \frac12 \, \, \star$ should be satisfied. Now our job is reduced to show that whatever $\delta$ we choose there is a point for which $\star$ do not hold. So if we choose a $\delta < 1$ the point $0<1-\frac\delta2<1$ and $f(x)=0$ at all such regions implying that $|f(x)-1|=|0-1|=1>\frac12$.
If you're familiar with the properties of continuous functions, another way to see it is that $f^{-1}(1)=[0,1)$, which is not a closed subset of $[0,2]$.
694,883
Consider the function $f(x)=[x]$ on the interval $[0,2]$ where $[x]$ denotes the largest integer less than or equal to x. Is this function continuous? I cant find a reason for it not to be, although im not sure.
2014/03/01
[ "https://math.stackexchange.com/questions/694883", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
![enter image description here](https://i.stack.imgur.com/gkImo.png) You can surely see that the function is not continuous at integral points. To illustrate it compute $\lim\_{x\rightarrow 1^+}[x]$ and $\lim\_{x\rightarrow 1^-}[x]$ show that the limit does not exist at $x = 1$. Hence the function cannot be continuous.
**Hint:** Proof the negation of $$ (\forall \epsilon >0)(\exists \delta >0) \Big( (\forall x)(|x-1|<\delta \implies |f(x)-f(1)|<\epsilon)\Big), $$ that is $$ (\exists \epsilon >0)(\forall \delta >0) \Big( (\exists x)(|x-1|<\delta \mbox{ and } |f(x)-f(1)|>\epsilon)\Big) $$
8
В цьому питанні я сам створив відповідь. Це є wiki-відповідь (спільна відповідь, community wiki) — **її може редагувати кожен**. Ви можете додавати інші джерела: редагуючи ту відповідь або створювати окремі відповіді. * [Загальне](/a/9) / General * [Словники](/a/287) / Dictionaries * [Корпуси](/a/286) / Corporas * [Правописи](/a/119) / Spelling * [Пошук у локалізаціях програм](/a/56) / Search in software localizations * [Перелік ресурсів](/a/100) / List of sourses * Wikipedia, Wiktionary: [Джерела](/a/130) / Sources * [Учба](/a/190) / Learning * [Здоровий глузд](/a/152) / Common sense --- In this question I created an answer myself. It's a wiki-answer (community answer, community wiki) — **everyone can edit it**. You're welcome to add other sources: by editing that (wiki) answer or by creating new ones.
2017/02/07
[ "https://ukrainian.meta.stackexchange.com/questions/8", "https://ukrainian.meta.stackexchange.com", "https://ukrainian.meta.stackexchange.com/users/4/" ]
(це недописана стаття, яка вимагає переформатування і, можливо, категоризації) --- Список джерел, які вважають поважними наші колеги з [Wikipedia](https://uk.wikipedia.org/wiki/%D0%9E%D0%B1%D0%B3%D0%BE%D0%B2%D0%BE%D1%80%D0%B5%D0%BD%D0%BD%D1%8F_%D0%92%D1%96%D0%BA%D1%96%D0%BF%D0%B5%D0%B4%D1%96%D1%97:%D0%9F%D1%80%D0%BE%D0%B5%D0%BA%D1%82:%D0%93%D1%80%D0%B0%D0%BC%D0%BE%D1%82%D0%BD%D1%96%D1%81%D1%82%D1%8C/%D0%90%D0%B2%D1%82%D0%BE%D1%80%D0%B8%D1%82%D0%B5%D1%82%D0%BD%D1%96_%D0%B4%D0%B6%D0%B5%D1%80%D0%B5%D0%BB%D0%B0) ============================================================================================================================================================================================================================================================================================================================================================================================================================================== Словники і довідники, які можна використовувати для перевірки відповідності до сучасної української літературної норми ### Для перевірки наголосу * [Складні випадки наголошування слів](http://www.twirpx.com/file/300334/) ### Для перевірки написання (орфографії) \* ### Тлумачні словники * **Сучасний тлумачний словник української мови: 60 000 слів / За заг. ред. д-ра філол. наук, проф. В. В. Дубічинського. — Харків: ВД «ШКОЛА», 2007. — 832 с.** — доволі місткий та зручний тлумачний словник української мови. Як зазначають автори словника, в ньому вводиться сучасна лексика та сленг, серед застарілих слів — слова іх художньої літератури, а також добірка слів з усіх галузей знань. Словник рекомендований Міністерством освіти і науки. * [ВТССУМ](http://Lingvo.ua) * [Словник української мови в 11-ти томах. К.: Наукова думка, 1970–1980.](http://sum.in.ua/) ### Велика чи мала літера * **В. В. Жайворонок. Велика чи мала літера? Словник-довідник. — К.: Наук. думка, 2004.** — словник рекомендований до друку вченою радою Інституту мовознавства ім. О. О. Потебні НАН України, автор — відомий авторитетний український мовознавець, доктор філологічних наук, [[Жайворонок Віталій Вікторович]]. Входить до серії „Наукове видання «Словники України»“. Окрім того, зручний тим, що [доступний онлайн](http://velyka-chy-mala-litera.wikidot.com/) ### Довідники з культури мови * [Словник-довідник з культури української мови](http://ukrknyga.at.ua/load/slovnik_dovidnik_z_kulturi_ukrajinskoji_movi/4-1-0-265) * [Словник-довідник з українського літературного слововживання](http://www.twirpx.com/file/103521/) ### Перекладні Російсько-українські * [Російсько-українські словники](http://r2u.org.ua/) * [Російсько-український словник сталих виразів](http://stalivyrazy.org.ua/) * [Російсько-український словник фізичних термінів](http://ukrknyga.at.ua/load/rosijsko_ukrajinskij_slovnik_fizichnikh_terminiv_za_red_o_b_liskovicha/38-1-0-361) * [Російсько-український словник. Термінологічна лексика](http://freelib.in.ua/load/92-1-0-1776) * Російсько-український словник складної лексики С. Караванського ### Підручники і посібники з пунктуації \* ### Топоніміка * [Топонімічний словник України](http://www.toponymic-dictionary.in.ua/) Фразеологія =========== * [Словник фразеологічних синонімів](http://www.rozum.org.ua/index.php?a=index&d=24) * [Словник фразеологічних антонімів](http://sovremennik.ws/2008/07/03/slovnik_frazeologchnikh_antonmv_ukransko_movi.html) ### Галузеві словники * [Фінансовий словник](http://www.twirpx.com/file/459498/) * [Словник соціологічних і політологічних термінів](http://ukrknyga.at.ua/load/slovnik_sociologichnikh_i_politologichnikh_terminiv_za_red_v_astakhovoji_v_danilenka_a_panova/2-1-0-430) --- Список словників, які поважають наші колеги з [Wiktionary](https://uk.wiktionary.org/wiki/%D0%94%D0%BE%D0%B4%D0%B0%D1%82%D0%BE%D0%BA:%D0%A1%D0%BF%D0%B8%D1%81%D0%BE%D0%BA_%D1%81%D0%BB%D0%BE%D0%B2%D0%BD%D0%B8%D0%BA%D1%96%D0%B2) =================================================================================================================================================================================================================================
Загальний здоровий глузд ======================== * [Illustrated book of bad arguments](https://bookofbadarguments.com/) - на жаль, перекладу на українську ще немає. Ця книга показує, як саме люди схильні помилятися у своїй арґументації --- Common sense ============ * [Illustrated book of bad arguments](https://bookofbadarguments.com/) - Unfortunately it hasn't been translated to Ukrainian yet. This book shows how people tend to fail in their argumentation
8
В цьому питанні я сам створив відповідь. Це є wiki-відповідь (спільна відповідь, community wiki) — **її може редагувати кожен**. Ви можете додавати інші джерела: редагуючи ту відповідь або створювати окремі відповіді. * [Загальне](/a/9) / General * [Словники](/a/287) / Dictionaries * [Корпуси](/a/286) / Corporas * [Правописи](/a/119) / Spelling * [Пошук у локалізаціях програм](/a/56) / Search in software localizations * [Перелік ресурсів](/a/100) / List of sourses * Wikipedia, Wiktionary: [Джерела](/a/130) / Sources * [Учба](/a/190) / Learning * [Здоровий глузд](/a/152) / Common sense --- In this question I created an answer myself. It's a wiki-answer (community answer, community wiki) — **everyone can edit it**. You're welcome to add other sources: by editing that (wiki) answer or by creating new ones.
2017/02/07
[ "https://ukrainian.meta.stackexchange.com/questions/8", "https://ukrainian.meta.stackexchange.com", "https://ukrainian.meta.stackexchange.com/users/4/" ]
Пошук у локалізаціях програмного забезпечення ============================================= Позначення: — можна шукати онлайн. Microsoft --------- [Мовний портал](https://www.microsoft.com/Language/en-us/Search.aspx?sString=&langID=uk-ua) (також можна [стягувати у форматі XML](https://www.microsoft.com/en-us/language/terminology)). Google Chromium --------------- [Сторінка перекладів на launchpad](https://translations.launchpad.net/chromium-browser/translations/+lang/uk) дозволяє шукати лише в кожній секції окремо, але секцій небагато, найбільші з них: [chromium-browser](https://translations.launchpad.net/chromium-browser/translations/+pots/chromium-browser/uk/+translate), [generated-resources](https://translations.launchpad.net/chromium-browser/translations/+pots/generated-resources/uk/+translate). KDE --- [Сторінка перекладів](https://l10n.kde.org/team-infos.php?teamcode=uk) не дозволяє шукати онлайн, але можна: * стягувати відразу всі файли локалізації через Subversion, наприклад: ``` svn co svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/uk/messages svn co svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/uk/docmessages ``` * переглядати файли локалізації онлайн, але лише один за одним (що, враховуючи їх кількість, незручно). Ubuntu ------ [Сторінка перекладів на launchpad](https://translations.launchpad.net/ubuntu) не дозволяє шукати всюди, але дозволяє шукати в кожному пакеті окремо (для зручості можна відсортувати пакети за зменшенням кількості рядків). Drupal ------ [Пошук уже перекладених рядків](https://localize.drupal.org/translate/languages/uk/translate?search=test&status=2&limit=50). Translation Project ------------------- [Сторінка команди українських перекладачів](http://translationproject.org/team/uk.html) не дозволяє шукати всюди, але дозволяє: * переглядати локалізації для кожного пакету окремо; * [стягувати щомісячний tar-архів з локалізаціями всіх пакетів](http://translationproject.org/backups/last/uk.tgz). Хотілося б знайти переклади --------------------------- * Google * Apple * Gnome
(це недописана стаття, яка вимагає переформатування і, можливо, категоризації) --- Список джерел, які вважають поважними наші колеги з [Wikipedia](https://uk.wikipedia.org/wiki/%D0%9E%D0%B1%D0%B3%D0%BE%D0%B2%D0%BE%D1%80%D0%B5%D0%BD%D0%BD%D1%8F_%D0%92%D1%96%D0%BA%D1%96%D0%BF%D0%B5%D0%B4%D1%96%D1%97:%D0%9F%D1%80%D0%BE%D0%B5%D0%BA%D1%82:%D0%93%D1%80%D0%B0%D0%BC%D0%BE%D1%82%D0%BD%D1%96%D1%81%D1%82%D1%8C/%D0%90%D0%B2%D1%82%D0%BE%D1%80%D0%B8%D1%82%D0%B5%D1%82%D0%BD%D1%96_%D0%B4%D0%B6%D0%B5%D1%80%D0%B5%D0%BB%D0%B0) ============================================================================================================================================================================================================================================================================================================================================================================================================================================== Словники і довідники, які можна використовувати для перевірки відповідності до сучасної української літературної норми ### Для перевірки наголосу * [Складні випадки наголошування слів](http://www.twirpx.com/file/300334/) ### Для перевірки написання (орфографії) \* ### Тлумачні словники * **Сучасний тлумачний словник української мови: 60 000 слів / За заг. ред. д-ра філол. наук, проф. В. В. Дубічинського. — Харків: ВД «ШКОЛА», 2007. — 832 с.** — доволі місткий та зручний тлумачний словник української мови. Як зазначають автори словника, в ньому вводиться сучасна лексика та сленг, серед застарілих слів — слова іх художньої літератури, а також добірка слів з усіх галузей знань. Словник рекомендований Міністерством освіти і науки. * [ВТССУМ](http://Lingvo.ua) * [Словник української мови в 11-ти томах. К.: Наукова думка, 1970–1980.](http://sum.in.ua/) ### Велика чи мала літера * **В. В. Жайворонок. Велика чи мала літера? Словник-довідник. — К.: Наук. думка, 2004.** — словник рекомендований до друку вченою радою Інституту мовознавства ім. О. О. Потебні НАН України, автор — відомий авторитетний український мовознавець, доктор філологічних наук, [[Жайворонок Віталій Вікторович]]. Входить до серії „Наукове видання «Словники України»“. Окрім того, зручний тим, що [доступний онлайн](http://velyka-chy-mala-litera.wikidot.com/) ### Довідники з культури мови * [Словник-довідник з культури української мови](http://ukrknyga.at.ua/load/slovnik_dovidnik_z_kulturi_ukrajinskoji_movi/4-1-0-265) * [Словник-довідник з українського літературного слововживання](http://www.twirpx.com/file/103521/) ### Перекладні Російсько-українські * [Російсько-українські словники](http://r2u.org.ua/) * [Російсько-український словник сталих виразів](http://stalivyrazy.org.ua/) * [Російсько-український словник фізичних термінів](http://ukrknyga.at.ua/load/rosijsko_ukrajinskij_slovnik_fizichnikh_terminiv_za_red_o_b_liskovicha/38-1-0-361) * [Російсько-український словник. Термінологічна лексика](http://freelib.in.ua/load/92-1-0-1776) * Російсько-український словник складної лексики С. Караванського ### Підручники і посібники з пунктуації \* ### Топоніміка * [Топонімічний словник України](http://www.toponymic-dictionary.in.ua/) Фразеологія =========== * [Словник фразеологічних синонімів](http://www.rozum.org.ua/index.php?a=index&d=24) * [Словник фразеологічних антонімів](http://sovremennik.ws/2008/07/03/slovnik_frazeologchnikh_antonmv_ukransko_movi.html) ### Галузеві словники * [Фінансовий словник](http://www.twirpx.com/file/459498/) * [Словник соціологічних і політологічних термінів](http://ukrknyga.at.ua/load/slovnik_sociologichnikh_i_politologichnikh_terminiv_za_red_v_astakhovoji_v_danilenka_a_panova/2-1-0-430) --- Список словників, які поважають наші колеги з [Wiktionary](https://uk.wiktionary.org/wiki/%D0%94%D0%BE%D0%B4%D0%B0%D1%82%D0%BE%D0%BA:%D0%A1%D0%BF%D0%B8%D1%81%D0%BE%D0%BA_%D1%81%D0%BB%D0%BE%D0%B2%D0%BD%D0%B8%D0%BA%D1%96%D0%B2) =================================================================================================================================================================================================================================
8
В цьому питанні я сам створив відповідь. Це є wiki-відповідь (спільна відповідь, community wiki) — **її може редагувати кожен**. Ви можете додавати інші джерела: редагуючи ту відповідь або створювати окремі відповіді. * [Загальне](/a/9) / General * [Словники](/a/287) / Dictionaries * [Корпуси](/a/286) / Corporas * [Правописи](/a/119) / Spelling * [Пошук у локалізаціях програм](/a/56) / Search in software localizations * [Перелік ресурсів](/a/100) / List of sourses * Wikipedia, Wiktionary: [Джерела](/a/130) / Sources * [Учба](/a/190) / Learning * [Здоровий глузд](/a/152) / Common sense --- In this question I created an answer myself. It's a wiki-answer (community answer, community wiki) — **everyone can edit it**. You're welcome to add other sources: by editing that (wiki) answer or by creating new ones.
2017/02/07
[ "https://ukrainian.meta.stackexchange.com/questions/8", "https://ukrainian.meta.stackexchange.com", "https://ukrainian.meta.stackexchange.com/users/4/" ]
Ресурси для вивчення українскої =============================== * [Ukrainian Lessons Podcast](http://ukrainianlessons.com/) - безкоштовна серія подкастів розмовною українською для новачків. Оновлюється щотижня. * [Підбірка](//redd.it/r2oa4y "Редит r/Ukrainian") учбових матеріялів від r/WantDebianThanks. --- Ukrainian language learning resources ===================================== * [Ukrainian Lessons Podcast](http://ukrainianlessons.com/) - is a free series of podcasts in conversational Ukrainian for beginners. Updated weekly. * [A collection](//redd.it/r2oa4y "Редит r/Ukrainian") of study from r/WantDebianThanks.
Загальний здоровий глузд ======================== * [Illustrated book of bad arguments](https://bookofbadarguments.com/) - на жаль, перекладу на українську ще немає. Ця книга показує, як саме люди схильні помилятися у своїй арґументації --- Common sense ============ * [Illustrated book of bad arguments](https://bookofbadarguments.com/) - Unfortunately it hasn't been translated to Ukrainian yet. This book shows how people tend to fail in their argumentation
8
В цьому питанні я сам створив відповідь. Це є wiki-відповідь (спільна відповідь, community wiki) — **її може редагувати кожен**. Ви можете додавати інші джерела: редагуючи ту відповідь або створювати окремі відповіді. * [Загальне](/a/9) / General * [Словники](/a/287) / Dictionaries * [Корпуси](/a/286) / Corporas * [Правописи](/a/119) / Spelling * [Пошук у локалізаціях програм](/a/56) / Search in software localizations * [Перелік ресурсів](/a/100) / List of sourses * Wikipedia, Wiktionary: [Джерела](/a/130) / Sources * [Учба](/a/190) / Learning * [Здоровий глузд](/a/152) / Common sense --- In this question I created an answer myself. It's a wiki-answer (community answer, community wiki) — **everyone can edit it**. You're welcome to add other sources: by editing that (wiki) answer or by creating new ones.
2017/02/07
[ "https://ukrainian.meta.stackexchange.com/questions/8", "https://ukrainian.meta.stackexchange.com", "https://ukrainian.meta.stackexchange.com/users/4/" ]
Перелік ресурсів взято [тут](http://www.mova.info/links.aspx?l1=82). Вашій увазі пропонуються сайти, безпосередньо пов'язані з різними аспектами функціонування української мови у світах реальному та віртуальному, мовні ресурси від освітянсько-новинних до розважальних. * [Інтелектуальна кнайпа «Чудова Мова».](http://chumova.com/) Ми створили місце в укрнеті, яке має надавати питво та їжу для розуму, - інтелектуальну кнайпу. Виходячи з назви - "Чудова мова" - зрозуміло, що основна тематика обговорення в кнайпі - це мова. У всіх її найширших проявах, включаючи математику, адже математика - це мова науки. Особлива увага надається зникаючим мовам та мовним технологіям. * [Хронологія мовних подій в Україні: зовнішня історія української мови.](http://movahistory.org.ua/) Метою сайту є дати користувачеві якомога точнішу й надійнішу інформацію про зовнішню історію української мови. Подано посилання на різнопланові джерела, здебільшого наявні в Інтернеті. Сайт містить також бібліотеку. * [Повний перелік українських іменників.](http://www.senyk.poltava.ua/projs/ukr_dict.html) Для створення та розв'язування кросвордів. * [КіберМова.](http://www.cybermova.com/) Ресурси і програми для письмової та усної української мови * [ІЗБОРНИК.](http://litopys.org.ua/) Першоджерела та інтерпретації — проект електронної бібліотеки давньої української літератури. * [ProLing Office.](http://www.prolingoffice.com/) Сайт представляє останні версії таких відомих систем, як перевірка українського та російського правопису РУТА, російсько-український і україно-російський перекладач ПЛАЙ, російсько-український і україно-російський електронний словник УЛІС, розробником яки (?) * [БРАМА.](http://www.brama.com/) Одна з найвідоміших інформаційних пошукових систем, що концентрує увагу на розвиток українства у всьому світі. Система об‘єднує широке коло Інтернет-ресурсів. Сайт має розгалужений рубрикатор і систему пошуку. * [Український Центр.](http://www.ukrcenter.com/) Освітньо-інформаційний ресурс. На сайті є такі рубрики: українська електронна бібліотека, в цей день, обговорення, українське радіо, новини.
Загальний здоровий глузд ======================== * [Illustrated book of bad arguments](https://bookofbadarguments.com/) - на жаль, перекладу на українську ще немає. Ця книга показує, як саме люди схильні помилятися у своїй арґументації --- Common sense ============ * [Illustrated book of bad arguments](https://bookofbadarguments.com/) - Unfortunately it hasn't been translated to Ukrainian yet. This book shows how people tend to fail in their argumentation
8
В цьому питанні я сам створив відповідь. Це є wiki-відповідь (спільна відповідь, community wiki) — **її може редагувати кожен**. Ви можете додавати інші джерела: редагуючи ту відповідь або створювати окремі відповіді. * [Загальне](/a/9) / General * [Словники](/a/287) / Dictionaries * [Корпуси](/a/286) / Corporas * [Правописи](/a/119) / Spelling * [Пошук у локалізаціях програм](/a/56) / Search in software localizations * [Перелік ресурсів](/a/100) / List of sourses * Wikipedia, Wiktionary: [Джерела](/a/130) / Sources * [Учба](/a/190) / Learning * [Здоровий глузд](/a/152) / Common sense --- In this question I created an answer myself. It's a wiki-answer (community answer, community wiki) — **everyone can edit it**. You're welcome to add other sources: by editing that (wiki) answer or by creating new ones.
2017/02/07
[ "https://ukrainian.meta.stackexchange.com/questions/8", "https://ukrainian.meta.stackexchange.com", "https://ukrainian.meta.stackexchange.com/users/4/" ]
Пошук у локалізаціях програмного забезпечення ============================================= Позначення: — можна шукати онлайн. Microsoft --------- [Мовний портал](https://www.microsoft.com/Language/en-us/Search.aspx?sString=&langID=uk-ua) (також можна [стягувати у форматі XML](https://www.microsoft.com/en-us/language/terminology)). Google Chromium --------------- [Сторінка перекладів на launchpad](https://translations.launchpad.net/chromium-browser/translations/+lang/uk) дозволяє шукати лише в кожній секції окремо, але секцій небагато, найбільші з них: [chromium-browser](https://translations.launchpad.net/chromium-browser/translations/+pots/chromium-browser/uk/+translate), [generated-resources](https://translations.launchpad.net/chromium-browser/translations/+pots/generated-resources/uk/+translate). KDE --- [Сторінка перекладів](https://l10n.kde.org/team-infos.php?teamcode=uk) не дозволяє шукати онлайн, але можна: * стягувати відразу всі файли локалізації через Subversion, наприклад: ``` svn co svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/uk/messages svn co svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/uk/docmessages ``` * переглядати файли локалізації онлайн, але лише один за одним (що, враховуючи їх кількість, незручно). Ubuntu ------ [Сторінка перекладів на launchpad](https://translations.launchpad.net/ubuntu) не дозволяє шукати всюди, але дозволяє шукати в кожному пакеті окремо (для зручості можна відсортувати пакети за зменшенням кількості рядків). Drupal ------ [Пошук уже перекладених рядків](https://localize.drupal.org/translate/languages/uk/translate?search=test&status=2&limit=50). Translation Project ------------------- [Сторінка команди українських перекладачів](http://translationproject.org/team/uk.html) не дозволяє шукати всюди, але дозволяє: * переглядати локалізації для кожного пакету окремо; * [стягувати щомісячний tar-архів з локалізаціями всіх пакетів](http://translationproject.org/backups/last/uk.tgz). Хотілося б знайти переклади --------------------------- * Google * Apple * Gnome
Ресурси для вивчення українскої =============================== * [Ukrainian Lessons Podcast](http://ukrainianlessons.com/) - безкоштовна серія подкастів розмовною українською для новачків. Оновлюється щотижня. * [Підбірка](//redd.it/r2oa4y "Редит r/Ukrainian") учбових матеріялів від r/WantDebianThanks. --- Ukrainian language learning resources ===================================== * [Ukrainian Lessons Podcast](http://ukrainianlessons.com/) - is a free series of podcasts in conversational Ukrainian for beginners. Updated weekly. * [A collection](//redd.it/r2oa4y "Редит r/Ukrainian") of study from r/WantDebianThanks.
8
В цьому питанні я сам створив відповідь. Це є wiki-відповідь (спільна відповідь, community wiki) — **її може редагувати кожен**. Ви можете додавати інші джерела: редагуючи ту відповідь або створювати окремі відповіді. * [Загальне](/a/9) / General * [Словники](/a/287) / Dictionaries * [Корпуси](/a/286) / Corporas * [Правописи](/a/119) / Spelling * [Пошук у локалізаціях програм](/a/56) / Search in software localizations * [Перелік ресурсів](/a/100) / List of sourses * Wikipedia, Wiktionary: [Джерела](/a/130) / Sources * [Учба](/a/190) / Learning * [Здоровий глузд](/a/152) / Common sense --- In this question I created an answer myself. It's a wiki-answer (community answer, community wiki) — **everyone can edit it**. You're welcome to add other sources: by editing that (wiki) answer or by creating new ones.
2017/02/07
[ "https://ukrainian.meta.stackexchange.com/questions/8", "https://ukrainian.meta.stackexchange.com", "https://ukrainian.meta.stackexchange.com/users/4/" ]
Перелік ресурсів взято [тут](http://www.mova.info/links.aspx?l1=82). Вашій увазі пропонуються сайти, безпосередньо пов'язані з різними аспектами функціонування української мови у світах реальному та віртуальному, мовні ресурси від освітянсько-новинних до розважальних. * [Інтелектуальна кнайпа «Чудова Мова».](http://chumova.com/) Ми створили місце в укрнеті, яке має надавати питво та їжу для розуму, - інтелектуальну кнайпу. Виходячи з назви - "Чудова мова" - зрозуміло, що основна тематика обговорення в кнайпі - це мова. У всіх її найширших проявах, включаючи математику, адже математика - це мова науки. Особлива увага надається зникаючим мовам та мовним технологіям. * [Хронологія мовних подій в Україні: зовнішня історія української мови.](http://movahistory.org.ua/) Метою сайту є дати користувачеві якомога точнішу й надійнішу інформацію про зовнішню історію української мови. Подано посилання на різнопланові джерела, здебільшого наявні в Інтернеті. Сайт містить також бібліотеку. * [Повний перелік українських іменників.](http://www.senyk.poltava.ua/projs/ukr_dict.html) Для створення та розв'язування кросвордів. * [КіберМова.](http://www.cybermova.com/) Ресурси і програми для письмової та усної української мови * [ІЗБОРНИК.](http://litopys.org.ua/) Першоджерела та інтерпретації — проект електронної бібліотеки давньої української літератури. * [ProLing Office.](http://www.prolingoffice.com/) Сайт представляє останні версії таких відомих систем, як перевірка українського та російського правопису РУТА, російсько-український і україно-російський перекладач ПЛАЙ, російсько-український і україно-російський електронний словник УЛІС, розробником яки (?) * [БРАМА.](http://www.brama.com/) Одна з найвідоміших інформаційних пошукових систем, що концентрує увагу на розвиток українства у всьому світі. Система об‘єднує широке коло Інтернет-ресурсів. Сайт має розгалужений рубрикатор і систему пошуку. * [Український Центр.](http://www.ukrcenter.com/) Освітньо-інформаційний ресурс. На сайті є такі рубрики: українська електронна бібліотека, в цей день, обговорення, українське радіо, новини.
Словники ======== 1. Словник української мови в 11 книгах (СУМ-11: [inmo.org.ua](http://www.inmo.org.ua/sum.html), [sum.in.ua](http://sum.in.ua/), [ukrlit.org](http://ukrlit.org/slovnyk/slovnyk_ukrainskoi_movy_v_11_tomakh), [slovnyk.ua](https://www.slovnyk.ua/). 2. Словник української мови в 20 книгах (СУМ-20). Від [УЛІФ](https://services.ulif.org.ua/expl/Entry/). 3. Український мовно-інформаційний фонд (УМІФ) надає [словника](http://lcorp.ulif.org.ua/dictua/). 4. [r2u](https://r2u.org.ua/) має такі словники чи збірки: Російсько-український академічний словник (А. Кримський, С. Єфремов), Російсько-український словник (О. Ізюмов), Російсько-український фразеологічний словник (В. Підмогильний, Є. Плужник), Російсько-український словник технічної термінології (І. Шелудько, Т. Садовський), Російсько-український словник ділової мови (М. Дорошенко, М. Станиславський, В. Страшкевич), Російсько-український словник сталих виразів (І. О. Вирган, М. М. Пилинська), Словарь росийсько-український (М.Уманець, А.Спілка.), Російсько-український народний (сучасний) словник, Російсько-український словник військової термінології (С. та О. Якубські), Словник українських наукових і народних назв судинних рослин (Ю. Кобів), Практичний російсько-український словник приказок (Г. Млодзинський, М. Йогансена), Російсько-український словник з інженерних технологій (М. Ганіткевич, Б. Кінаш.), Російсько-український словник складної лексики (С. Караванський), Правописний словник (Г. Голоскевич), Словарь української мови (Б.Грінченко), Словник української мови (Б.Грінченко, за ред. С. Єфремова, А. Ніковського), Словник українсько-російський (А. Ніковський), Тлумачно-стилістичний народний словник, Словник української мови (Д.І.Яворницький), Український стилістичний словник (Огієнко І.), Українська лексикографія XIII—XX ст.djvu (6,7Мб), Список слів з літерою «Ґ» у академічному словнику, Список слів з позначкою «руссизм», Список слів з позначкою «полонизм», Пошук за іншими термінами та скороченнями, Частотний показник українських слів академічного словника (архів 1МБ), 5. [e2u](https://e2u.org.ua/) має такі словники чи збірки: Загальний народний англійсько-український словник, Великий англо-український словник (Є.І. Гороть, Л.М. Коцюк, Л.К. Малімон, А.Б. Павлюк.), Новий українсько-англійський словник (Є.І. Гороть, С.В. Гончарук, Л.К. Малімон, О.О. Рогач.), Фразлекс (англо-український фразеологічний словник) (Василь Старко), Довідник англійських, німецьких та українських ідіом і виразів (Шерік А.Д., Савічук В.Я., Старко В.Ф.), Англійсько-український словник сучасних термінів з ІТ (linux.org.ua), Англійсько-український словник з математики та інформатики (Є. Мейнарович, М. Кратко), Англійсько-українсько-англійський словник наукової мови (фізика та споріднені науки). Частина І англійсько-українська (О. Кочерга, Є. Мейнарович), Англійсько-українсько-англійський словник наукової мови (фізика та споріднені науки). Частина ІІ українсько-англійська (О. Кочерга, Є. Мейнарович), Англійсько-французько-німецько-український словник термінології Європейського Союзу (“Лабораторія наукового перекладу”), Українсько-англійський словник (К.Андрусишин, Я.Крет), Українсько-англійський словник ділової людини (Є. І. Гороть, О. В. Василенко, Н. В. Єфремова [та ін.]), Українсько-англійський словник з прав людини (Лесь Герасимчук), Англо-український тлумачний словник економічної лексики (А. Шимків), Англійсько-український словник-довідник інженерії довкілля (Тимотей Балабан), Глосарій термінів з хімії (Й.Опейда, О.Швайка), Українсько-англійський словник з радіоелектроніки (Богдан Рицар, Леонід Сніцарук, Роман Мисак), Українсько-англійський словник лінгвістичної термінології (Л.В. Коломієць, O.Л. Паламарчук, Г.П. Стрельчук, М.В. Шевченко). 6. [Словопедія](http://slovopedia.org.ua/) має такі словники чи збірки: Великий тлумачний словник (ВТС) сучасної української мови, УСЕ (Універсальний словник-енциклопедія), Орфографічний словник української мови, Фразеологічний словник української мови, Українсько-російський словник, Словник синонімів Полюги, Словник іншомовних слів Мельничука, Словник англіцизмів, Eкономічна енциклопедія, Неправильно — правильно. Волощак, Уроки державної мови (з газети «Хрещатик»), Літературне слововживання, «Як ми говоримо» Антоненка-Давидовича, Український правопис, Економічний словник, Словник мови Стуса, Крилаті вислови, Словник іншомовник слів, Стилістичні терміни, Словник іншомовних соціокультурних термінів, Енциклопедія політичної думки, Словник синонімів Караванського, СЦОТ (Словник церковно-обрядової термінології), Архітектура і монументальне мистецтво, Словник-антисуржик, Словник термінів, уживаних у чинному Законодавстві України, Словник бюджетної термінології, Термінологічний словник з економіки праці, Глосарій термінів Фондового ринку, Моделювання економіки, Власні імена людей, Словар українського сленгу, Музичні терміни, Тлумачний словник з інформатики та інформаційних систем для економістів (Л. С. Козловська, Н. М. Поліщук), Термінологічно-правописний порадник для богословів та редакторів богословських текстів (Інститут богословської термінології та перекладів), Управління якістю (Вакуленко А.В.), Гірничий енциклопедичний словник, 100 видатних iмен України, Словник церковно-обрядової термінології, Словник із соціальної роботи, Словник лемківскої говірки, Словник галицьких говірок, Лексикон львівський, Короткий словник вільномулярських назв, термінів і знаків, Укр. літ. мова на Буковині, Філософський енциклопедичний словник. 7. [Грінченко](http://hrinchenko.com/) ([від УМІФ](http://services.ulif.org.ua/grinch)). 8. [ABBYY Lingvo](https://www.lingvolive.com/en-us). 9. [linguisto](http://linguisto.eu/) (англійсько-, німецько-, французько-українські й частотний). Неавторитетні ------------- 1. [вікісловник](http://uk.wiktionary.org/). 2. [WorldwideDictionary](https://uk.worldwidedictionary.org/). 3. [slovnyk.ua](http://slovnyk.ua/). 4. [yenotes](http://yenotes.com). 5. [goroh.pp.ua](https://goroh.pp.ua/). 6. [slovnychok.com.ua](http://slovnychok.com.ua/). 7. [rozum](http://www.rozum.org.ua). 8. [dictionaries24](https://www.dictionaries24.com/uk/). 9. [ABCThesaurus](http://ukrainian.abcthesaurus.com/). 10. [синоніми.укр](https://xn--h1aaldafs6o.xn--j1amh/). 11. [Словник скорочень української мови](http://ukrskor.info/). 12. [Російсько-український словник сталих виразів](http://stalivyrazy.org.ua/). Виргана та Пилинської, призначений для літературних перекладачів, налічує понад 6000 фразеологічних одиниць та сталих виразів. --- Dictionaries ============ 1. SUM-11: [inmo.org.ua](http://www.inmo.org.ua/sum.html), [sum.in.ua](http://sum.in.ua/), [ukrlit.org](http://ukrlit.org/slovnyk/slovnyk_ukrainskoi_movy_v_11_tomakh), [slovnyk.ua](https://www.slovnyk.ua/). 2. SUM-22 on [ULIF](https://services.ulif.org.ua/expl/Entry/). 3. [ULIF](http://lcorp.ulif.org.ua/dictua/). 4. [r2u](https://r2u.org.ua/). 5. [e2u](https://e2u.org.ua/). 6. [slovopedia](http://slovopedia.org.ua/). 7. [Hrinchenko](http://hrinchenko.com/) ([from ULIF](http://services.ulif.org.ua/grinch)). 8. [ABBYY Lingvo](https://www.lingvolive.com/en-us). 9. [linguisto](http://linguisto.eu/) (English-, German-, French-Ukrainian and frequency). Non-authoritative: ------------------ 1. [wiktionary](http://uk.wiktionary.org/). 2. [WorldwideDictionary](https://uk.worldwidedictionary.org/). 3. [slovnyk.ua](http://slovnyk.ua/). 4. [yenotes](http://yenotes.com). 5. [goroh.pp.ua](https://goroh.pp.ua/). 6. [slovnychok.com.ua](http://slovnychok.com.ua/). 7. [rozum](http://www.rozum.org.ua). 8. [dictionaries24](https://www.dictionaries24.com/uk/). 9. [ABCThesaurus](http://ukrainian.abcthesaurus.com/). 10. [синоніми.укр](https://xn--h1aaldafs6o.xn--j1amh/). 11. [Dictionarie of abbrs](http://ukrskor.info/) 12. [Russian-Ukrainian phrase dictionary](http://stalivyrazy.org.ua/).
8
В цьому питанні я сам створив відповідь. Це є wiki-відповідь (спільна відповідь, community wiki) — **її може редагувати кожен**. Ви можете додавати інші джерела: редагуючи ту відповідь або створювати окремі відповіді. * [Загальне](/a/9) / General * [Словники](/a/287) / Dictionaries * [Корпуси](/a/286) / Corporas * [Правописи](/a/119) / Spelling * [Пошук у локалізаціях програм](/a/56) / Search in software localizations * [Перелік ресурсів](/a/100) / List of sourses * Wikipedia, Wiktionary: [Джерела](/a/130) / Sources * [Учба](/a/190) / Learning * [Здоровий глузд](/a/152) / Common sense --- In this question I created an answer myself. It's a wiki-answer (community answer, community wiki) — **everyone can edit it**. You're welcome to add other sources: by editing that (wiki) answer or by creating new ones.
2017/02/07
[ "https://ukrainian.meta.stackexchange.com/questions/8", "https://ukrainian.meta.stackexchange.com", "https://ukrainian.meta.stackexchange.com/users/4/" ]
Пошук у локалізаціях програмного забезпечення ============================================= Позначення: — можна шукати онлайн. Microsoft --------- [Мовний портал](https://www.microsoft.com/Language/en-us/Search.aspx?sString=&langID=uk-ua) (також можна [стягувати у форматі XML](https://www.microsoft.com/en-us/language/terminology)). Google Chromium --------------- [Сторінка перекладів на launchpad](https://translations.launchpad.net/chromium-browser/translations/+lang/uk) дозволяє шукати лише в кожній секції окремо, але секцій небагато, найбільші з них: [chromium-browser](https://translations.launchpad.net/chromium-browser/translations/+pots/chromium-browser/uk/+translate), [generated-resources](https://translations.launchpad.net/chromium-browser/translations/+pots/generated-resources/uk/+translate). KDE --- [Сторінка перекладів](https://l10n.kde.org/team-infos.php?teamcode=uk) не дозволяє шукати онлайн, але можна: * стягувати відразу всі файли локалізації через Subversion, наприклад: ``` svn co svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/uk/messages svn co svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/uk/docmessages ``` * переглядати файли локалізації онлайн, але лише один за одним (що, враховуючи їх кількість, незручно). Ubuntu ------ [Сторінка перекладів на launchpad](https://translations.launchpad.net/ubuntu) не дозволяє шукати всюди, але дозволяє шукати в кожному пакеті окремо (для зручості можна відсортувати пакети за зменшенням кількості рядків). Drupal ------ [Пошук уже перекладених рядків](https://localize.drupal.org/translate/languages/uk/translate?search=test&status=2&limit=50). Translation Project ------------------- [Сторінка команди українських перекладачів](http://translationproject.org/team/uk.html) не дозволяє шукати всюди, але дозволяє: * переглядати локалізації для кожного пакету окремо; * [стягувати щомісячний tar-архів з локалізаціями всіх пакетів](http://translationproject.org/backups/last/uk.tgz). Хотілося б знайти переклади --------------------------- * Google * Apple * Gnome
Словники ======== 1. Словник української мови в 11 книгах (СУМ-11: [inmo.org.ua](http://www.inmo.org.ua/sum.html), [sum.in.ua](http://sum.in.ua/), [ukrlit.org](http://ukrlit.org/slovnyk/slovnyk_ukrainskoi_movy_v_11_tomakh), [slovnyk.ua](https://www.slovnyk.ua/). 2. Словник української мови в 20 книгах (СУМ-20). Від [УЛІФ](https://services.ulif.org.ua/expl/Entry/). 3. Український мовно-інформаційний фонд (УМІФ) надає [словника](http://lcorp.ulif.org.ua/dictua/). 4. [r2u](https://r2u.org.ua/) має такі словники чи збірки: Російсько-український академічний словник (А. Кримський, С. Єфремов), Російсько-український словник (О. Ізюмов), Російсько-український фразеологічний словник (В. Підмогильний, Є. Плужник), Російсько-український словник технічної термінології (І. Шелудько, Т. Садовський), Російсько-український словник ділової мови (М. Дорошенко, М. Станиславський, В. Страшкевич), Російсько-український словник сталих виразів (І. О. Вирган, М. М. Пилинська), Словарь росийсько-український (М.Уманець, А.Спілка.), Російсько-український народний (сучасний) словник, Російсько-український словник військової термінології (С. та О. Якубські), Словник українських наукових і народних назв судинних рослин (Ю. Кобів), Практичний російсько-український словник приказок (Г. Млодзинський, М. Йогансена), Російсько-український словник з інженерних технологій (М. Ганіткевич, Б. Кінаш.), Російсько-український словник складної лексики (С. Караванський), Правописний словник (Г. Голоскевич), Словарь української мови (Б.Грінченко), Словник української мови (Б.Грінченко, за ред. С. Єфремова, А. Ніковського), Словник українсько-російський (А. Ніковський), Тлумачно-стилістичний народний словник, Словник української мови (Д.І.Яворницький), Український стилістичний словник (Огієнко І.), Українська лексикографія XIII—XX ст.djvu (6,7Мб), Список слів з літерою «Ґ» у академічному словнику, Список слів з позначкою «руссизм», Список слів з позначкою «полонизм», Пошук за іншими термінами та скороченнями, Частотний показник українських слів академічного словника (архів 1МБ), 5. [e2u](https://e2u.org.ua/) має такі словники чи збірки: Загальний народний англійсько-український словник, Великий англо-український словник (Є.І. Гороть, Л.М. Коцюк, Л.К. Малімон, А.Б. Павлюк.), Новий українсько-англійський словник (Є.І. Гороть, С.В. Гончарук, Л.К. Малімон, О.О. Рогач.), Фразлекс (англо-український фразеологічний словник) (Василь Старко), Довідник англійських, німецьких та українських ідіом і виразів (Шерік А.Д., Савічук В.Я., Старко В.Ф.), Англійсько-український словник сучасних термінів з ІТ (linux.org.ua), Англійсько-український словник з математики та інформатики (Є. Мейнарович, М. Кратко), Англійсько-українсько-англійський словник наукової мови (фізика та споріднені науки). Частина І англійсько-українська (О. Кочерга, Є. Мейнарович), Англійсько-українсько-англійський словник наукової мови (фізика та споріднені науки). Частина ІІ українсько-англійська (О. Кочерга, Є. Мейнарович), Англійсько-французько-німецько-український словник термінології Європейського Союзу (“Лабораторія наукового перекладу”), Українсько-англійський словник (К.Андрусишин, Я.Крет), Українсько-англійський словник ділової людини (Є. І. Гороть, О. В. Василенко, Н. В. Єфремова [та ін.]), Українсько-англійський словник з прав людини (Лесь Герасимчук), Англо-український тлумачний словник економічної лексики (А. Шимків), Англійсько-український словник-довідник інженерії довкілля (Тимотей Балабан), Глосарій термінів з хімії (Й.Опейда, О.Швайка), Українсько-англійський словник з радіоелектроніки (Богдан Рицар, Леонід Сніцарук, Роман Мисак), Українсько-англійський словник лінгвістичної термінології (Л.В. Коломієць, O.Л. Паламарчук, Г.П. Стрельчук, М.В. Шевченко). 6. [Словопедія](http://slovopedia.org.ua/) має такі словники чи збірки: Великий тлумачний словник (ВТС) сучасної української мови, УСЕ (Універсальний словник-енциклопедія), Орфографічний словник української мови, Фразеологічний словник української мови, Українсько-російський словник, Словник синонімів Полюги, Словник іншомовних слів Мельничука, Словник англіцизмів, Eкономічна енциклопедія, Неправильно — правильно. Волощак, Уроки державної мови (з газети «Хрещатик»), Літературне слововживання, «Як ми говоримо» Антоненка-Давидовича, Український правопис, Економічний словник, Словник мови Стуса, Крилаті вислови, Словник іншомовник слів, Стилістичні терміни, Словник іншомовних соціокультурних термінів, Енциклопедія політичної думки, Словник синонімів Караванського, СЦОТ (Словник церковно-обрядової термінології), Архітектура і монументальне мистецтво, Словник-антисуржик, Словник термінів, уживаних у чинному Законодавстві України, Словник бюджетної термінології, Термінологічний словник з економіки праці, Глосарій термінів Фондового ринку, Моделювання економіки, Власні імена людей, Словар українського сленгу, Музичні терміни, Тлумачний словник з інформатики та інформаційних систем для економістів (Л. С. Козловська, Н. М. Поліщук), Термінологічно-правописний порадник для богословів та редакторів богословських текстів (Інститут богословської термінології та перекладів), Управління якістю (Вакуленко А.В.), Гірничий енциклопедичний словник, 100 видатних iмен України, Словник церковно-обрядової термінології, Словник із соціальної роботи, Словник лемківскої говірки, Словник галицьких говірок, Лексикон львівський, Короткий словник вільномулярських назв, термінів і знаків, Укр. літ. мова на Буковині, Філософський енциклопедичний словник. 7. [Грінченко](http://hrinchenko.com/) ([від УМІФ](http://services.ulif.org.ua/grinch)). 8. [ABBYY Lingvo](https://www.lingvolive.com/en-us). 9. [linguisto](http://linguisto.eu/) (англійсько-, німецько-, французько-українські й частотний). Неавторитетні ------------- 1. [вікісловник](http://uk.wiktionary.org/). 2. [WorldwideDictionary](https://uk.worldwidedictionary.org/). 3. [slovnyk.ua](http://slovnyk.ua/). 4. [yenotes](http://yenotes.com). 5. [goroh.pp.ua](https://goroh.pp.ua/). 6. [slovnychok.com.ua](http://slovnychok.com.ua/). 7. [rozum](http://www.rozum.org.ua). 8. [dictionaries24](https://www.dictionaries24.com/uk/). 9. [ABCThesaurus](http://ukrainian.abcthesaurus.com/). 10. [синоніми.укр](https://xn--h1aaldafs6o.xn--j1amh/). 11. [Словник скорочень української мови](http://ukrskor.info/). 12. [Російсько-український словник сталих виразів](http://stalivyrazy.org.ua/). Виргана та Пилинської, призначений для літературних перекладачів, налічує понад 6000 фразеологічних одиниць та сталих виразів. --- Dictionaries ============ 1. SUM-11: [inmo.org.ua](http://www.inmo.org.ua/sum.html), [sum.in.ua](http://sum.in.ua/), [ukrlit.org](http://ukrlit.org/slovnyk/slovnyk_ukrainskoi_movy_v_11_tomakh), [slovnyk.ua](https://www.slovnyk.ua/). 2. SUM-22 on [ULIF](https://services.ulif.org.ua/expl/Entry/). 3. [ULIF](http://lcorp.ulif.org.ua/dictua/). 4. [r2u](https://r2u.org.ua/). 5. [e2u](https://e2u.org.ua/). 6. [slovopedia](http://slovopedia.org.ua/). 7. [Hrinchenko](http://hrinchenko.com/) ([from ULIF](http://services.ulif.org.ua/grinch)). 8. [ABBYY Lingvo](https://www.lingvolive.com/en-us). 9. [linguisto](http://linguisto.eu/) (English-, German-, French-Ukrainian and frequency). Non-authoritative: ------------------ 1. [wiktionary](http://uk.wiktionary.org/). 2. [WorldwideDictionary](https://uk.worldwidedictionary.org/). 3. [slovnyk.ua](http://slovnyk.ua/). 4. [yenotes](http://yenotes.com). 5. [goroh.pp.ua](https://goroh.pp.ua/). 6. [slovnychok.com.ua](http://slovnychok.com.ua/). 7. [rozum](http://www.rozum.org.ua). 8. [dictionaries24](https://www.dictionaries24.com/uk/). 9. [ABCThesaurus](http://ukrainian.abcthesaurus.com/). 10. [синоніми.укр](https://xn--h1aaldafs6o.xn--j1amh/). 11. [Dictionarie of abbrs](http://ukrskor.info/) 12. [Russian-Ukrainian phrase dictionary](http://stalivyrazy.org.ua/).
8
В цьому питанні я сам створив відповідь. Це є wiki-відповідь (спільна відповідь, community wiki) — **її може редагувати кожен**. Ви можете додавати інші джерела: редагуючи ту відповідь або створювати окремі відповіді. * [Загальне](/a/9) / General * [Словники](/a/287) / Dictionaries * [Корпуси](/a/286) / Corporas * [Правописи](/a/119) / Spelling * [Пошук у локалізаціях програм](/a/56) / Search in software localizations * [Перелік ресурсів](/a/100) / List of sourses * Wikipedia, Wiktionary: [Джерела](/a/130) / Sources * [Учба](/a/190) / Learning * [Здоровий глузд](/a/152) / Common sense --- In this question I created an answer myself. It's a wiki-answer (community answer, community wiki) — **everyone can edit it**. You're welcome to add other sources: by editing that (wiki) answer or by creating new ones.
2017/02/07
[ "https://ukrainian.meta.stackexchange.com/questions/8", "https://ukrainian.meta.stackexchange.com", "https://ukrainian.meta.stackexchange.com/users/4/" ]
Правописи ========= Позначення: — оригінал-макет або скан (точна копія); — результат розпізнавання або переформатування (можливі невеликі неточності); — приблизний опис чи переказ; ~~закреслення~~ — джерело вже зникло. 18 -- * 1798, Котляревський: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%9F%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81_%D0%9A%D0%BE%D1%82%D0%BB%D1%8F%D1%80%D0%B5%D0%B2%D1%81%D1%8C%D0%BA%D0%BE%D0%B3%D0%BE). 19 -- * 1893, Смаль-Стоцький і Ґартнер, «Руска граматика»: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%A0%D1%83%D1%81%D1%8C%D0%BA%D0%B0_%D0%B3%D1%80%D0%B0%D0%BC%D0%B0%D1%82%D0%B8%D0%BA%D0%B0_1893_%D1%80%D0%BE%D0%BA%D1%83), [Збруч](//zbruc.eu/node/66463). 20 -- * 1914, Смаль-Стоцький і Ґартнер, «Граматика руської мови»: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%93%D1%80%D0%B0%D0%BC%D0%B0%D1%82%D0%B8%D0%BA%D0%B0_%D1%80%D1%83%D1%81%D1%8C%D0%BA%D0%BE%D1%97_%D0%BC%D0%BE%D0%B2%D0%B8), [Internet Archive](//archive.org/details/hramatykarusko00smal), [Чтиво](//chtyvo.org.ua/authors/Smal-Stotskyi_Stepan/Hramatyka_ruskoi_movy) ([2](//chtyvo.org.ua/authors/Smal-Stotskyi_Stepan/Hramatyka_ruskoi_movy_vyd_1914)). * 1917, «Коротенька українська правопись» часопису «Рідне Слово»: [Культура України](//elib.nlu.org.ua/view.html?id=11914), [Diasporiana](//diasporiana.org.ua/movoznavstvo/korotka-ukrayinska-pravopys). * 1917, «Граматична термінологія і правопись, ухвалені комісією мови при Українському товаристві шкільної освіти в Київі (1917)» Української Центральної Ради: [Google Docs (DjVu)](//docs.google.com/file/d/0Bx3rm-9lOt18aFYyenNDNzl2MHc). * 1919, Смаль-Стоцький і Ґартнер, «Руска правопись зі словарцем», 3-тє видання: [Internet Archive](//archive.org/details/ruskapravopyszis00smal) ([2](//archive.org/details/cihm_76668)). * 1919, Смаль-Стоцький і Ґартнер, «Українська граматика»: [Internet Archive](//archive.org/details/ukranskahramatyk00smal) ([2](//archive.org/details/ukranskahramatyk00smal_0), [3](//archive.org/details/cihm_77796)), [Чтиво](//chtyvo.org.ua/authors/Smal-Stotskyi_Stepan/Ukrainska_hramatyka). * 1921, «Найголовніші правила українського правопису»: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81_1921_%D1%80%D0%BE%D0%BA%D1%83), [Культура України](//elib.nlu.org.ua/view.html?id=9634), [Чтиво](//chtyvo.org.ua/authors/Krymskyi_Ahatanhel/Naiholovnishi_pravyla_ukrainskoho_pravopysu/). * 1922, «Головніші правила українського правопису»: [Культура України](//elib.nlu.org.ua/view.html?id=10541), [Diasporiana](//diasporiana.org.ua/movoznavstvo/golovnishi-pravyla-ukrayinskogo-pravopysu). * 1922, «Правописні правила, приняті Науковим товариством імени Шевченка у Львові»: [Культура України](//elib.nlu.org.ua/view.html?id=10577). * 1925, Огієнко: [Культура України](//elib.nlu.org.ua/view.html?id=11911). * 1926, «Харківський», проєкт: [movahistory](http://movahistory.org.ua/index.php/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81._(%D0%9F%D1%80%D0%BE%D1%94%D0%BA%D1%82)._1926_%D1%80.). * 1928, «Харківський», проєкт: [movahistory](http://movahistory.org.ua/index.php/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81._(%D0%9F%D1%80%D0%BE%D1%94%D0%BA%D1%82)._1928_%D1%80.). * 1928/1929, «Харківський»: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%A5%D0%B0%D1%80%D0%BA%D1%96%D0%B2%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81), [R2U](//r2u.org.ua/node/181) ([2](//r2u.org.ua/data/other/%D0%9F%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81-1928.pdf)), [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0009938), [movahistory](http://movahistory.org.ua/index.php/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81._1928_%D1%80.), [Мечнікова](http://rarebook.onu.edu.ua:8081/handle/123456789/9765). Див. також: + 1929 Гладкий, «Новий український правопис»: [Культура України](//elib.nlu.org.ua/view.html?id=9416). + 1929, Грунський, «Основи нового українського правопису»: [Культура України](//elib.nlu.org.ua/view.html?id=9425). + 1929(?), Наконечний, «Про новий правопис український»: [Культура України](//elib.nlu.org.ua/view.html?id=9981). + 1929, Синявський, «Найголовніші правила української мови (за новим правописом)»: [Україніка](http://irbis-nbuv.gov.ua/ulib/item/0001537). Друге видання: [Культура України](//elib.nlu.org.ua/view.html?id=10659). * 1933, Хвиля: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81_1933_%D1%80%D0%BE%D0%BA%D1%83), [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0009919), [movahistory](http://movahistory.org.ua/index.php/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81._1933_%D1%80.). Див. також: + 1935, «Словник-покажчик до…»: [Культура України](//elib.nlu.org.ua/view.html?id=10744). * 1934, [Український правопис / А. Хвиля. – 2-ге вид.](http://escriptorium.univer.kharkov.ua/handle/1237075002/10591) * 1938, Грунський, проєкт: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%9F%D1%80%D0%BE%D1%94%D0%BA%D1%82_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81%D1%83_1939_%D1%80%D0%BE%D0%BA%D1%83), [movahistory](http://movahistory.org.ua/index.php/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81._(%D0%9F%D1%80%D0%BE%D0%B5%D0%BA%D1%82_%D0%B2%D0%B8%D0%B4%D0%B0%D0%BD%D0%BD%D1%8F_%D1%87%D0%B5%D1%82%D0%B2%D0%B5%D1%80%D1%82%D0%BE%D0%B3%D0%BE)._1938%D1%80). * 1940, Грунський, проєкт: [movahistory](http://movahistory.org.ua/index.php/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81._(%D0%9F%D1%80%D0%BE%D0%B5%D0%BA%D1%82_%D0%B2%D0%B8%D0%B4%D0%B0%D0%BD%D0%BD%D1%8F_%D1%87%D0%B5%D1%82%D0%B2%D0%B5%D1%80%D1%82%D0%BE%D0%B3%D0%BE)._1940_%D1%80.). * 1941, Синявський, «Норми української літературної мови»: [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0001032), [R2U](//r2u.org.ua/guides/synyavsky/zmist), [частково на Вікіджерелах](//uk.wikisource.org/wiki/%D0%9E%D0%BB%D0%B5%D0%BA%D1%81%D0%B0_%D0%A1%D0%B8%D0%BD%D1%8F%D0%B2%D1%81%D1%8C%D0%BA%D0%B8%D0%B9._%D0%9D%D0%BE%D1%80%D0%BC%D0%B8_%D1%83%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%BE%D1%97_%D0%BB%D1%96%D1%82%D0%B5%D1%80%D0%B0%D1%82%D1%83%D1%80%D0%BD%D0%BE%D1%97_%D0%BC%D0%BE%D0%B2%D0%B8). Редакція Телемка з додатками: [R2U](//r2u.org.ua/data/other/%D0%9D%D0%BE%D1%80%D0%BC%D0%B8%20%D1%83%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%BE%D1%97%20%D0%BB%D1%96%D1%82%D0%B5%D1%80%D0%B0%D1%82%D1%83%D1%80%D0%BD%D0%BE%D1%97%20%D0%BC%D0%BE%D0%B2%D0%B8,%20%D0%A1%D0%B8%D0%BD%D1%8F%D0%B2%D1%81%D1%8C%D0%BA%D0%B8%D0%B9%20(1941).pdf), [Чтиво](//chtyvo.org.ua/authors/Syniavskyi_Oleksa/Normy_ukrainskoi_literaturnoi_movy), [Український Центр](http://www.ukrcenter.com/%D0%9B%D1%96%D1%82%D0%B5%D1%80%D0%B0%D1%82%D1%83%D1%80%D0%B0/%D0%9E%D0%BB%D0%B5%D0%BA%D1%81%D0%B0-%D0%A1%D0%B8%D0%BD%D1%8F%D0%B2%D1%81%D1%8C%D0%BA%D0%B8%D0%B9/54944/%D0%9D%D0%BE%D1%80%D0%BC%D0%B8-%D1%83%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%BE%D1%97-%D0%BB%D1%96%D1%82%D0%B5%D1%80%D0%B0%D1%82%D1%83%D1%80%D0%BD%D0%BE%D1%97-%D0%BC%D0%BE%D0%B2%D0%B8). * 1942, Зілинський, 2-ге видання: [Культура України](//elib.nlu.org.ua/view.html?id=10748). * 1943, Зілинський, 3-те видання: [Культура України](//elib.nlu.org.ua/view.html?id=12064), [Diasporiana](//diasporiana.org.ua/movoznavstvo/15486-ukrayinskiy-pravopis), [movahistory](http://movahistory.org.ua/index.php/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81._%D0%A3%D0%BF%D0%BE%D1%80%D1%8F%D0%B4%D0%BA%D1%83%D0%B2%D0%B0%D0%B2_%D0%86%D0%B2%D0%B0%D0%BD_%D0%97%D0%B5%D0%BB%D0%B8%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9). * 1943, Зілинський, 4-те видання: [Культура України](//elib.nlu.org.ua/view.html?id=12092). * 1945/1946, Ⅰ: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81_1946_%D1%80%D0%BE%D0%BA%D1%83), [Internet Archive](//archive.org/details/ukrainian_pravopys_1945), [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0010302), [Культура України](//elib.nlu.org.ua/view.html?id=10274), [шматок на movahistory](http://movahistory.org.ua/index.php/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81._1946_%D1%80.). * 1946, Шерех: [Культура України](//elib.nlu.org.ua/view.html?id=11909), [Diasporiana](//diasporiana.org.ua/movoznavstvo/2837-shereh-yu-golovni-pravila-ukrayinskogo-pravopisu). * 1946, Ковалів: [Культура України](//elib.nlu.org.ua/view.html?id=11915). * 1949, Рудницький: [Diasporiana](//diasporiana.org.ua/movoznavstvo/17387-rudnitskiy-ya-ukrayinskiy-pravopis/). * 1960, Ⅱ: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81_1960_%D1%80%D0%BE%D0%BA%D1%83), [Internet Archive](//archive.org/details/up-1960), [§ 41–42 на CTAN](http://mirrors.ctan.org/language/hyphenation/ukrhyph/rules60.pdf). * 1977, Ковалів: [Diasporiana](//diasporiana.org.ua/movoznavstvo/3485-kovaliv-p-ukrayinskiy-pravopis), [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0010216). * 1990, Ⅲ: ???. * 1993/1994, Ⅳ: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81_1993_%D1%80%D0%BE%D0%BA%D1%83), [Google Books](http://google.com/books?id=WKzqAAAAMAAJ), ~~[коледж НАУ](http://flightcollege.com.ua/library/8%20%D0%A4%D0%98%D0%9B%D0%9E%D0%9B%D0%9E%D0%93%D0%98%D0%A7%D0%95%D0%A1%D0%9A%D0%98%D0%95%20%D0%9D%D0%90%D0%A3%D0%9A%D0%98/81%20%D0%AF%D0%97%D0%AB%D0%9A%D0%9E%D0%97%D0%9D%D0%90%D0%9D%D0%98%D0%95/81.2%20%D0%A3%D0%9A%D0%A0/%D0%94%D0%BE%D0%B2%D1%96%D0%B4%D0%BD%D0%B8%D0%BA%D0%B8/%D0%A3%D0%BA%D1%80%D0%B0%D0%B8%D0%BD%D1%81%D0%BA%D0%B8%D0%B9%20%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D1%8B%D1%81%201994.djvu)~~. * 1996, Ⅴ: ???. * 1997, Ⅵ: [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0009746). * 1998, Ⅶ: [§ 41–42 на CTAN](http://mirrors.ctan.org/language/hyphenation/ukrhyph/rules90.pdf). * 1999, Німчук, проєкт: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%9F%D1%80%D0%BE%D1%94%D0%BA%D1%82_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81%D1%83_1999_%D1%80%D0%BE%D0%BA%D1%83), [R2U](//r2u.org.ua/pravopys/pravXXI/zmist.htm#proekt), [vlada.kiev.ua через Internet Archive](//web.archive.org/web/20120604210430/http://www.vlada.kiev.ua/pravopys/pravXXI/zmist.htm#proekt) ([2](//web.archive.org/web/20100913013850/http://pravopys.vlada.kiev.ua/pravopys/pravXXI/zmist.htm#proekt)). * 2000: ~~[коледж НАУ](http://flightcollege.com.ua/library/8%20%D0%A4%D0%98%D0%9B%D0%9E%D0%9B%D0%9E%D0%93%D0%98%D0%A7%D0%95%D0%A1%D0%9A%D0%98%D0%95%20%D0%9D%D0%90%D0%A3%D0%9A%D0%98/81%20%D0%AF%D0%97%D0%AB%D0%9A%D0%9E%D0%97%D0%9D%D0%90%D0%9D%D0%98%D0%95/81.2%20%D0%A3%D0%9A%D0%A0/%D0%94%D0%BE%D0%B2%D1%96%D0%B4%D0%BD%D0%B8%D0%BA%D0%B8/%D0%A3%D0%BA%D1%80%D0%B0%D0%B8%D0%BD%D1%81%D0%BA%D0%B8%D0%B9%20%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D1%8B%D1%81%20%202000.djvu)~~. 21 -- * 2002: ???. * 2003, В. Русанівський, проєкт: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%9F%D1%80%D0%BE%D1%94%D0%BA%D1%82_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81%D1%83_2003_%D1%80%D0%BE%D0%BA%D1%83), [Ізборник](http://litopys.org.ua/pdf/proekt_2003.pdf) ([2](http://izbornyk.org.ua/pdf/proekt_2003.pdf)), [ДУТ](http://www.dut.edu.ua/ua/lib/1/category/96/view/848), [Google Books](//google.com/books?id=XLdiAAAAMAAJ). * 2003: [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0009469). * 2004: ???. * 2005: ???. * 2007: [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0001517), ~~[коледж НАУ](http://flightcollege.com.ua/library/8%20%D0%A4%D0%98%D0%9B%D0%9E%D0%9B%D0%9E%D0%93%D0%98%D0%A7%D0%95%D0%A1%D0%9A%D0%98%D0%95%20%D0%9D%D0%90%D0%A3%D0%9A%D0%98/81%20%D0%AF%D0%97%D0%AB%D0%9A%D0%9E%D0%97%D0%9D%D0%90%D0%9D%D0%98%D0%95/81.2%20%D0%A3%D0%9A%D0%A0/%D0%94%D0%BE%D0%B2%D1%96%D0%B4%D0%BD%D0%B8%D0%BA%D0%B8/%D0%A3%D0%BA%D1%80%D0%B0%D0%B8%D0%BD%D1%81%D0%BA%D0%B8%D0%B9%20%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D1%8B%D1%81%202007.djvu), [коледж НАУ](http://flightcollege.com.ua/library/8%20%D0%A4%D0%98%D0%9B%D0%9E%D0%9B%D0%9E%D0%93%D0%98%D0%A7%D0%95%D0%A1%D0%9A%D0%98%D0%95%20%D0%9D%D0%90%D0%A3%D0%9A%D0%98/81%20%D0%AF%D0%97%D0%AB%D0%9A%D0%9E%D0%97%D0%9D%D0%90%D0%9D%D0%98%D0%95/81.2%20%D0%A3%D0%9A%D0%A0/%D0%94%D0%BE%D0%B2%D1%96%D0%B4%D0%BD%D0%B8%D0%BA%D0%B8/%D0%A3%D0%BA%D1%80%D0%B0%D0%B8%D0%BD%D1%81%D0%BA%D0%B8%D0%B9%20%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D1%8B%D1%81%202007.doc), [коледж ЧНУ](https://www.college-chnu.cv.ua/images/Books/pravopys.pdf)~~. * 2008, Ющук, проєкт: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%9F%D1%80%D0%BE%D1%94%D0%BA%D1%82_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81%D1%83_%D0%86%D0%B2%D0%B0%D0%BD%D0%B0_%D0%AE%D1%89%D1%83%D0%BA%D0%B0_(2008)), [Культура України](//elib.nlu.org.ua/view.html?id=8816). * 2010: ???. * 2012: [УМІФ](http://spelling.ulif.org.ua/), [Ізборник](http://litopys.org.ua/pravopys/pravopys2012.htm) ([2](http://izbornyk.org.ua/pravopys/pravopys2012.htm)), [Ізборник](http://litopys.org.ua/pdf/pravopys2012.pdf) ([2](http://izbornyk.org.ua/pdf/pravopys2012.pdf)), [Україніка](http://irbis-nbuv.gov.ua/ulib/item/ukr0010414). * 2015: [Ізборник](http://litopys.org.ua/pravopys/pravopys2015.htm) ([2](http://izbornyk.org.ua/pravopys/pravopys2015.htm)), [Ізборник](http://litopys.org.ua/pdf/pravopys2015.pdf) ([2](http://izbornyk.org.ua/pdf/pravopys2015.pdf)), [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0009360). * 2019: [Вікіпедія](https://uk.wikipedia.org/wiki/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81_2019_%D1%80%D0%BE%D0%BA%D1%83), [УМІФ](https://www.ulif.org.ua/system/files/pravopus-new.pdf), [ІнМо](https://drive.google.com/file/d/1p0moU61Yrg4RskpJYTljxkiAa5vrd0mM/view) ([звідси](http://www.inmo.org.ua/news/%D1%83%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9-%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81.-%D0%B5%D0%BB%D0%B5%D0%BA%D1%82%D1%80%D0%BE%D0%BD%D0%BD%D0%B0-%D0%B2%D0%B5%D1%80%D1%81%D1%96%D1%8F-%D0%BE%D1%84%D1%96%D1%86%D1%96%D0%B9%D0%BD%D0%BE%D0%B3%D0%BE-%D0%B2%D0%B8%D0%B4%D0%B0%D0%BD%D0%BD%D1%8F.html)); також старіші версії: [НАНУ](https://files.nas.gov.ua/PublicMessages/Documents/0/2021/01/210118223223523-1428.pdf), [МОН](https://mon.gov.ua/ua/osvita/zagalna-serednya-osvita/navchalni-programi/ukrayinskij-pravopis-2019). ### Огляди * Огієнко, «Нариси з історії української мови: система українського правопису», 1927, Варшава: [Культура України](//elib.nlu.org.ua/object.html?id=9635). Передрук, 1990, Вінніпеґ: [Diasporiana](//diasporiana.org.ua/movoznavstvo/3606-ogiyenko-i-narisi-z-istoriyi-ukrayinskoyi-movi-sistema-ukrayinskogo-pravopisu). * Огієнко, «Історія української літературної мови», 1949, Вінніпег. Переживання/передруки: + 2001, Київ: [Ізборник](http://litopys.org.ua/ohukr/ohu.htm) ([2](http://izbornyk.org.ua/ohukr/ohu.htm)). + 2-ге вид., випр., 2004, Київ: [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0001364), [Чтиво](//chtyvo.org.ua/authors/Ohiyenko_Ivan/Istoriya_ukrainskoi_literaturnoi_movy). * Німчук, «Проблеми українського правопису ⅩⅩ — початку ⅩⅩⅠ ст. ст.», 2002, Київ: [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0008884), [movahistory](http://movahistory.org.ua/index.php/%D0%9D%D1%96%D0%BC%D1%87%D1%83%D0%BA_%D0%92._%D0%9F%D1%80%D0%BE%D0%B1%D0%BB%D0%B5%D0%BC%D0%B8_%D1%83%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%BE%D0%B3%D0%BE_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81%D1%83_%D0%B2_XX-XXI_%D1%81%D1%82._%D1%81%D1%82.), [без додатків на R2U](//r2u.org.ua/node/126), [без додатків на vlada.kiev.ua через Internet Archive](//web.archive.org/web/20120605003228/http://www.vlada.kiev.ua/pravopys/1.html) ([2](//web.archive.org/web/20100921132422/http://pravopys.vlada.kiev.ua/pravopys/1.html)). * Німчук, «Історія українського правопису: ⅩⅥ–ⅩⅩ століття», 2004, Київ: [movahistory](http://movahistory.org.ua/index.php/%D0%86%D1%81%D1%82%D0%BE%D1%80%D1%96%D1%8F_%D1%83%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%BE%D0%B3%D0%BE_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81%D1%83:_XVI%E2%80%94XX_%D1%81%D1%82%D0%BE%D0%BB%D1%96%D1%82%D1%82%D1%8F._%D0%A5%D1%80%D0%B5%D1%81%D1%82%D0%BE%D0%BC%D0%B0%D1%82%D1%96%D1%8F), [Інститут історії України](http://resource.history.org.ua/item/0007903). * Кацімон, «Загальні уваги до граматик української мови С. Смаль-Стоцького і Ф. Гартнера (1893, 1907, 1914 рр.)», 2013, Київ: [Вернадського](http://nbuv.gov.ua/UJRN/Nznuoaf_2013_35_45). Ґенеалоґія чинного правописа, тому желехівка, ярижка ітд не додані. Джерело: фейсбукова ґрупа [Історія українського правопису](//fb.com/groups/375320239720280/posts/1210098496242446/), [Павло Литвинчук](//%D1%84%D0%B1.com/pavlberg). --- [![Ґенеалоґія чинного правописа](https://i.stack.imgur.com/xyPwe.png)](https://i.stack.imgur.com/xyPwe.png) * [Порівняльні таблиці](//uk.wikipedia.org/wiki/%D0%9F%D0%BE%D1%80%D1%96%D0%B2%D0%BD%D1%8F%D0%BD%D0%BD%D1%8F_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81%D1%96%D0%B2_%D1%83%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%BE%D1%97_%D0%BC%D0%BE%D0%B2%D0%B8) правописів на Вікіпедії. * Спільнота [Український правопис-2018](//fb.com/groups/177824792769309/) на Фейсбуці.
Словники ======== 1. Словник української мови в 11 книгах (СУМ-11: [inmo.org.ua](http://www.inmo.org.ua/sum.html), [sum.in.ua](http://sum.in.ua/), [ukrlit.org](http://ukrlit.org/slovnyk/slovnyk_ukrainskoi_movy_v_11_tomakh), [slovnyk.ua](https://www.slovnyk.ua/). 2. Словник української мови в 20 книгах (СУМ-20). Від [УЛІФ](https://services.ulif.org.ua/expl/Entry/). 3. Український мовно-інформаційний фонд (УМІФ) надає [словника](http://lcorp.ulif.org.ua/dictua/). 4. [r2u](https://r2u.org.ua/) має такі словники чи збірки: Російсько-український академічний словник (А. Кримський, С. Єфремов), Російсько-український словник (О. Ізюмов), Російсько-український фразеологічний словник (В. Підмогильний, Є. Плужник), Російсько-український словник технічної термінології (І. Шелудько, Т. Садовський), Російсько-український словник ділової мови (М. Дорошенко, М. Станиславський, В. Страшкевич), Російсько-український словник сталих виразів (І. О. Вирган, М. М. Пилинська), Словарь росийсько-український (М.Уманець, А.Спілка.), Російсько-український народний (сучасний) словник, Російсько-український словник військової термінології (С. та О. Якубські), Словник українських наукових і народних назв судинних рослин (Ю. Кобів), Практичний російсько-український словник приказок (Г. Млодзинський, М. Йогансена), Російсько-український словник з інженерних технологій (М. Ганіткевич, Б. Кінаш.), Російсько-український словник складної лексики (С. Караванський), Правописний словник (Г. Голоскевич), Словарь української мови (Б.Грінченко), Словник української мови (Б.Грінченко, за ред. С. Єфремова, А. Ніковського), Словник українсько-російський (А. Ніковський), Тлумачно-стилістичний народний словник, Словник української мови (Д.І.Яворницький), Український стилістичний словник (Огієнко І.), Українська лексикографія XIII—XX ст.djvu (6,7Мб), Список слів з літерою «Ґ» у академічному словнику, Список слів з позначкою «руссизм», Список слів з позначкою «полонизм», Пошук за іншими термінами та скороченнями, Частотний показник українських слів академічного словника (архів 1МБ), 5. [e2u](https://e2u.org.ua/) має такі словники чи збірки: Загальний народний англійсько-український словник, Великий англо-український словник (Є.І. Гороть, Л.М. Коцюк, Л.К. Малімон, А.Б. Павлюк.), Новий українсько-англійський словник (Є.І. Гороть, С.В. Гончарук, Л.К. Малімон, О.О. Рогач.), Фразлекс (англо-український фразеологічний словник) (Василь Старко), Довідник англійських, німецьких та українських ідіом і виразів (Шерік А.Д., Савічук В.Я., Старко В.Ф.), Англійсько-український словник сучасних термінів з ІТ (linux.org.ua), Англійсько-український словник з математики та інформатики (Є. Мейнарович, М. Кратко), Англійсько-українсько-англійський словник наукової мови (фізика та споріднені науки). Частина І англійсько-українська (О. Кочерга, Є. Мейнарович), Англійсько-українсько-англійський словник наукової мови (фізика та споріднені науки). Частина ІІ українсько-англійська (О. Кочерга, Є. Мейнарович), Англійсько-французько-німецько-український словник термінології Європейського Союзу (“Лабораторія наукового перекладу”), Українсько-англійський словник (К.Андрусишин, Я.Крет), Українсько-англійський словник ділової людини (Є. І. Гороть, О. В. Василенко, Н. В. Єфремова [та ін.]), Українсько-англійський словник з прав людини (Лесь Герасимчук), Англо-український тлумачний словник економічної лексики (А. Шимків), Англійсько-український словник-довідник інженерії довкілля (Тимотей Балабан), Глосарій термінів з хімії (Й.Опейда, О.Швайка), Українсько-англійський словник з радіоелектроніки (Богдан Рицар, Леонід Сніцарук, Роман Мисак), Українсько-англійський словник лінгвістичної термінології (Л.В. Коломієць, O.Л. Паламарчук, Г.П. Стрельчук, М.В. Шевченко). 6. [Словопедія](http://slovopedia.org.ua/) має такі словники чи збірки: Великий тлумачний словник (ВТС) сучасної української мови, УСЕ (Універсальний словник-енциклопедія), Орфографічний словник української мови, Фразеологічний словник української мови, Українсько-російський словник, Словник синонімів Полюги, Словник іншомовних слів Мельничука, Словник англіцизмів, Eкономічна енциклопедія, Неправильно — правильно. Волощак, Уроки державної мови (з газети «Хрещатик»), Літературне слововживання, «Як ми говоримо» Антоненка-Давидовича, Український правопис, Економічний словник, Словник мови Стуса, Крилаті вислови, Словник іншомовник слів, Стилістичні терміни, Словник іншомовних соціокультурних термінів, Енциклопедія політичної думки, Словник синонімів Караванського, СЦОТ (Словник церковно-обрядової термінології), Архітектура і монументальне мистецтво, Словник-антисуржик, Словник термінів, уживаних у чинному Законодавстві України, Словник бюджетної термінології, Термінологічний словник з економіки праці, Глосарій термінів Фондового ринку, Моделювання економіки, Власні імена людей, Словар українського сленгу, Музичні терміни, Тлумачний словник з інформатики та інформаційних систем для економістів (Л. С. Козловська, Н. М. Поліщук), Термінологічно-правописний порадник для богословів та редакторів богословських текстів (Інститут богословської термінології та перекладів), Управління якістю (Вакуленко А.В.), Гірничий енциклопедичний словник, 100 видатних iмен України, Словник церковно-обрядової термінології, Словник із соціальної роботи, Словник лемківскої говірки, Словник галицьких говірок, Лексикон львівський, Короткий словник вільномулярських назв, термінів і знаків, Укр. літ. мова на Буковині, Філософський енциклопедичний словник. 7. [Грінченко](http://hrinchenko.com/) ([від УМІФ](http://services.ulif.org.ua/grinch)). 8. [ABBYY Lingvo](https://www.lingvolive.com/en-us). 9. [linguisto](http://linguisto.eu/) (англійсько-, німецько-, французько-українські й частотний). Неавторитетні ------------- 1. [вікісловник](http://uk.wiktionary.org/). 2. [WorldwideDictionary](https://uk.worldwidedictionary.org/). 3. [slovnyk.ua](http://slovnyk.ua/). 4. [yenotes](http://yenotes.com). 5. [goroh.pp.ua](https://goroh.pp.ua/). 6. [slovnychok.com.ua](http://slovnychok.com.ua/). 7. [rozum](http://www.rozum.org.ua). 8. [dictionaries24](https://www.dictionaries24.com/uk/). 9. [ABCThesaurus](http://ukrainian.abcthesaurus.com/). 10. [синоніми.укр](https://xn--h1aaldafs6o.xn--j1amh/). 11. [Словник скорочень української мови](http://ukrskor.info/). 12. [Російсько-український словник сталих виразів](http://stalivyrazy.org.ua/). Виргана та Пилинської, призначений для літературних перекладачів, налічує понад 6000 фразеологічних одиниць та сталих виразів. --- Dictionaries ============ 1. SUM-11: [inmo.org.ua](http://www.inmo.org.ua/sum.html), [sum.in.ua](http://sum.in.ua/), [ukrlit.org](http://ukrlit.org/slovnyk/slovnyk_ukrainskoi_movy_v_11_tomakh), [slovnyk.ua](https://www.slovnyk.ua/). 2. SUM-22 on [ULIF](https://services.ulif.org.ua/expl/Entry/). 3. [ULIF](http://lcorp.ulif.org.ua/dictua/). 4. [r2u](https://r2u.org.ua/). 5. [e2u](https://e2u.org.ua/). 6. [slovopedia](http://slovopedia.org.ua/). 7. [Hrinchenko](http://hrinchenko.com/) ([from ULIF](http://services.ulif.org.ua/grinch)). 8. [ABBYY Lingvo](https://www.lingvolive.com/en-us). 9. [linguisto](http://linguisto.eu/) (English-, German-, French-Ukrainian and frequency). Non-authoritative: ------------------ 1. [wiktionary](http://uk.wiktionary.org/). 2. [WorldwideDictionary](https://uk.worldwidedictionary.org/). 3. [slovnyk.ua](http://slovnyk.ua/). 4. [yenotes](http://yenotes.com). 5. [goroh.pp.ua](https://goroh.pp.ua/). 6. [slovnychok.com.ua](http://slovnychok.com.ua/). 7. [rozum](http://www.rozum.org.ua). 8. [dictionaries24](https://www.dictionaries24.com/uk/). 9. [ABCThesaurus](http://ukrainian.abcthesaurus.com/). 10. [синоніми.укр](https://xn--h1aaldafs6o.xn--j1amh/). 11. [Dictionarie of abbrs](http://ukrskor.info/) 12. [Russian-Ukrainian phrase dictionary](http://stalivyrazy.org.ua/).
8
В цьому питанні я сам створив відповідь. Це є wiki-відповідь (спільна відповідь, community wiki) — **її може редагувати кожен**. Ви можете додавати інші джерела: редагуючи ту відповідь або створювати окремі відповіді. * [Загальне](/a/9) / General * [Словники](/a/287) / Dictionaries * [Корпуси](/a/286) / Corporas * [Правописи](/a/119) / Spelling * [Пошук у локалізаціях програм](/a/56) / Search in software localizations * [Перелік ресурсів](/a/100) / List of sourses * Wikipedia, Wiktionary: [Джерела](/a/130) / Sources * [Учба](/a/190) / Learning * [Здоровий глузд](/a/152) / Common sense --- In this question I created an answer myself. It's a wiki-answer (community answer, community wiki) — **everyone can edit it**. You're welcome to add other sources: by editing that (wiki) answer or by creating new ones.
2017/02/07
[ "https://ukrainian.meta.stackexchange.com/questions/8", "https://ukrainian.meta.stackexchange.com", "https://ukrainian.meta.stackexchange.com/users/4/" ]
Правописи ========= Позначення: — оригінал-макет або скан (точна копія); — результат розпізнавання або переформатування (можливі невеликі неточності); — приблизний опис чи переказ; ~~закреслення~~ — джерело вже зникло. 18 -- * 1798, Котляревський: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%9F%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81_%D0%9A%D0%BE%D1%82%D0%BB%D1%8F%D1%80%D0%B5%D0%B2%D1%81%D1%8C%D0%BA%D0%BE%D0%B3%D0%BE). 19 -- * 1893, Смаль-Стоцький і Ґартнер, «Руска граматика»: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%A0%D1%83%D1%81%D1%8C%D0%BA%D0%B0_%D0%B3%D1%80%D0%B0%D0%BC%D0%B0%D1%82%D0%B8%D0%BA%D0%B0_1893_%D1%80%D0%BE%D0%BA%D1%83), [Збруч](//zbruc.eu/node/66463). 20 -- * 1914, Смаль-Стоцький і Ґартнер, «Граматика руської мови»: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%93%D1%80%D0%B0%D0%BC%D0%B0%D1%82%D0%B8%D0%BA%D0%B0_%D1%80%D1%83%D1%81%D1%8C%D0%BA%D0%BE%D1%97_%D0%BC%D0%BE%D0%B2%D0%B8), [Internet Archive](//archive.org/details/hramatykarusko00smal), [Чтиво](//chtyvo.org.ua/authors/Smal-Stotskyi_Stepan/Hramatyka_ruskoi_movy) ([2](//chtyvo.org.ua/authors/Smal-Stotskyi_Stepan/Hramatyka_ruskoi_movy_vyd_1914)). * 1917, «Коротенька українська правопись» часопису «Рідне Слово»: [Культура України](//elib.nlu.org.ua/view.html?id=11914), [Diasporiana](//diasporiana.org.ua/movoznavstvo/korotka-ukrayinska-pravopys). * 1917, «Граматична термінологія і правопись, ухвалені комісією мови при Українському товаристві шкільної освіти в Київі (1917)» Української Центральної Ради: [Google Docs (DjVu)](//docs.google.com/file/d/0Bx3rm-9lOt18aFYyenNDNzl2MHc). * 1919, Смаль-Стоцький і Ґартнер, «Руска правопись зі словарцем», 3-тє видання: [Internet Archive](//archive.org/details/ruskapravopyszis00smal) ([2](//archive.org/details/cihm_76668)). * 1919, Смаль-Стоцький і Ґартнер, «Українська граматика»: [Internet Archive](//archive.org/details/ukranskahramatyk00smal) ([2](//archive.org/details/ukranskahramatyk00smal_0), [3](//archive.org/details/cihm_77796)), [Чтиво](//chtyvo.org.ua/authors/Smal-Stotskyi_Stepan/Ukrainska_hramatyka). * 1921, «Найголовніші правила українського правопису»: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81_1921_%D1%80%D0%BE%D0%BA%D1%83), [Культура України](//elib.nlu.org.ua/view.html?id=9634), [Чтиво](//chtyvo.org.ua/authors/Krymskyi_Ahatanhel/Naiholovnishi_pravyla_ukrainskoho_pravopysu/). * 1922, «Головніші правила українського правопису»: [Культура України](//elib.nlu.org.ua/view.html?id=10541), [Diasporiana](//diasporiana.org.ua/movoznavstvo/golovnishi-pravyla-ukrayinskogo-pravopysu). * 1922, «Правописні правила, приняті Науковим товариством імени Шевченка у Львові»: [Культура України](//elib.nlu.org.ua/view.html?id=10577). * 1925, Огієнко: [Культура України](//elib.nlu.org.ua/view.html?id=11911). * 1926, «Харківський», проєкт: [movahistory](http://movahistory.org.ua/index.php/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81._(%D0%9F%D1%80%D0%BE%D1%94%D0%BA%D1%82)._1926_%D1%80.). * 1928, «Харківський», проєкт: [movahistory](http://movahistory.org.ua/index.php/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81._(%D0%9F%D1%80%D0%BE%D1%94%D0%BA%D1%82)._1928_%D1%80.). * 1928/1929, «Харківський»: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%A5%D0%B0%D1%80%D0%BA%D1%96%D0%B2%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81), [R2U](//r2u.org.ua/node/181) ([2](//r2u.org.ua/data/other/%D0%9F%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81-1928.pdf)), [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0009938), [movahistory](http://movahistory.org.ua/index.php/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81._1928_%D1%80.), [Мечнікова](http://rarebook.onu.edu.ua:8081/handle/123456789/9765). Див. також: + 1929 Гладкий, «Новий український правопис»: [Культура України](//elib.nlu.org.ua/view.html?id=9416). + 1929, Грунський, «Основи нового українського правопису»: [Культура України](//elib.nlu.org.ua/view.html?id=9425). + 1929(?), Наконечний, «Про новий правопис український»: [Культура України](//elib.nlu.org.ua/view.html?id=9981). + 1929, Синявський, «Найголовніші правила української мови (за новим правописом)»: [Україніка](http://irbis-nbuv.gov.ua/ulib/item/0001537). Друге видання: [Культура України](//elib.nlu.org.ua/view.html?id=10659). * 1933, Хвиля: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81_1933_%D1%80%D0%BE%D0%BA%D1%83), [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0009919), [movahistory](http://movahistory.org.ua/index.php/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81._1933_%D1%80.). Див. також: + 1935, «Словник-покажчик до…»: [Культура України](//elib.nlu.org.ua/view.html?id=10744). * 1934, [Український правопис / А. Хвиля. – 2-ге вид.](http://escriptorium.univer.kharkov.ua/handle/1237075002/10591) * 1938, Грунський, проєкт: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%9F%D1%80%D0%BE%D1%94%D0%BA%D1%82_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81%D1%83_1939_%D1%80%D0%BE%D0%BA%D1%83), [movahistory](http://movahistory.org.ua/index.php/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81._(%D0%9F%D1%80%D0%BE%D0%B5%D0%BA%D1%82_%D0%B2%D0%B8%D0%B4%D0%B0%D0%BD%D0%BD%D1%8F_%D1%87%D0%B5%D1%82%D0%B2%D0%B5%D1%80%D1%82%D0%BE%D0%B3%D0%BE)._1938%D1%80). * 1940, Грунський, проєкт: [movahistory](http://movahistory.org.ua/index.php/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81._(%D0%9F%D1%80%D0%BE%D0%B5%D0%BA%D1%82_%D0%B2%D0%B8%D0%B4%D0%B0%D0%BD%D0%BD%D1%8F_%D1%87%D0%B5%D1%82%D0%B2%D0%B5%D1%80%D1%82%D0%BE%D0%B3%D0%BE)._1940_%D1%80.). * 1941, Синявський, «Норми української літературної мови»: [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0001032), [R2U](//r2u.org.ua/guides/synyavsky/zmist), [частково на Вікіджерелах](//uk.wikisource.org/wiki/%D0%9E%D0%BB%D0%B5%D0%BA%D1%81%D0%B0_%D0%A1%D0%B8%D0%BD%D1%8F%D0%B2%D1%81%D1%8C%D0%BA%D0%B8%D0%B9._%D0%9D%D0%BE%D1%80%D0%BC%D0%B8_%D1%83%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%BE%D1%97_%D0%BB%D1%96%D1%82%D0%B5%D1%80%D0%B0%D1%82%D1%83%D1%80%D0%BD%D0%BE%D1%97_%D0%BC%D0%BE%D0%B2%D0%B8). Редакція Телемка з додатками: [R2U](//r2u.org.ua/data/other/%D0%9D%D0%BE%D1%80%D0%BC%D0%B8%20%D1%83%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%BE%D1%97%20%D0%BB%D1%96%D1%82%D0%B5%D1%80%D0%B0%D1%82%D1%83%D1%80%D0%BD%D0%BE%D1%97%20%D0%BC%D0%BE%D0%B2%D0%B8,%20%D0%A1%D0%B8%D0%BD%D1%8F%D0%B2%D1%81%D1%8C%D0%BA%D0%B8%D0%B9%20(1941).pdf), [Чтиво](//chtyvo.org.ua/authors/Syniavskyi_Oleksa/Normy_ukrainskoi_literaturnoi_movy), [Український Центр](http://www.ukrcenter.com/%D0%9B%D1%96%D1%82%D0%B5%D1%80%D0%B0%D1%82%D1%83%D1%80%D0%B0/%D0%9E%D0%BB%D0%B5%D0%BA%D1%81%D0%B0-%D0%A1%D0%B8%D0%BD%D1%8F%D0%B2%D1%81%D1%8C%D0%BA%D0%B8%D0%B9/54944/%D0%9D%D0%BE%D1%80%D0%BC%D0%B8-%D1%83%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%BE%D1%97-%D0%BB%D1%96%D1%82%D0%B5%D1%80%D0%B0%D1%82%D1%83%D1%80%D0%BD%D0%BE%D1%97-%D0%BC%D0%BE%D0%B2%D0%B8). * 1942, Зілинський, 2-ге видання: [Культура України](//elib.nlu.org.ua/view.html?id=10748). * 1943, Зілинський, 3-те видання: [Культура України](//elib.nlu.org.ua/view.html?id=12064), [Diasporiana](//diasporiana.org.ua/movoznavstvo/15486-ukrayinskiy-pravopis), [movahistory](http://movahistory.org.ua/index.php/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81._%D0%A3%D0%BF%D0%BE%D1%80%D1%8F%D0%B4%D0%BA%D1%83%D0%B2%D0%B0%D0%B2_%D0%86%D0%B2%D0%B0%D0%BD_%D0%97%D0%B5%D0%BB%D0%B8%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9). * 1943, Зілинський, 4-те видання: [Культура України](//elib.nlu.org.ua/view.html?id=12092). * 1945/1946, Ⅰ: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81_1946_%D1%80%D0%BE%D0%BA%D1%83), [Internet Archive](//archive.org/details/ukrainian_pravopys_1945), [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0010302), [Культура України](//elib.nlu.org.ua/view.html?id=10274), [шматок на movahistory](http://movahistory.org.ua/index.php/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81._1946_%D1%80.). * 1946, Шерех: [Культура України](//elib.nlu.org.ua/view.html?id=11909), [Diasporiana](//diasporiana.org.ua/movoznavstvo/2837-shereh-yu-golovni-pravila-ukrayinskogo-pravopisu). * 1946, Ковалів: [Культура України](//elib.nlu.org.ua/view.html?id=11915). * 1949, Рудницький: [Diasporiana](//diasporiana.org.ua/movoznavstvo/17387-rudnitskiy-ya-ukrayinskiy-pravopis/). * 1960, Ⅱ: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81_1960_%D1%80%D0%BE%D0%BA%D1%83), [Internet Archive](//archive.org/details/up-1960), [§ 41–42 на CTAN](http://mirrors.ctan.org/language/hyphenation/ukrhyph/rules60.pdf). * 1977, Ковалів: [Diasporiana](//diasporiana.org.ua/movoznavstvo/3485-kovaliv-p-ukrayinskiy-pravopis), [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0010216). * 1990, Ⅲ: ???. * 1993/1994, Ⅳ: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81_1993_%D1%80%D0%BE%D0%BA%D1%83), [Google Books](http://google.com/books?id=WKzqAAAAMAAJ), ~~[коледж НАУ](http://flightcollege.com.ua/library/8%20%D0%A4%D0%98%D0%9B%D0%9E%D0%9B%D0%9E%D0%93%D0%98%D0%A7%D0%95%D0%A1%D0%9A%D0%98%D0%95%20%D0%9D%D0%90%D0%A3%D0%9A%D0%98/81%20%D0%AF%D0%97%D0%AB%D0%9A%D0%9E%D0%97%D0%9D%D0%90%D0%9D%D0%98%D0%95/81.2%20%D0%A3%D0%9A%D0%A0/%D0%94%D0%BE%D0%B2%D1%96%D0%B4%D0%BD%D0%B8%D0%BA%D0%B8/%D0%A3%D0%BA%D1%80%D0%B0%D0%B8%D0%BD%D1%81%D0%BA%D0%B8%D0%B9%20%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D1%8B%D1%81%201994.djvu)~~. * 1996, Ⅴ: ???. * 1997, Ⅵ: [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0009746). * 1998, Ⅶ: [§ 41–42 на CTAN](http://mirrors.ctan.org/language/hyphenation/ukrhyph/rules90.pdf). * 1999, Німчук, проєкт: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%9F%D1%80%D0%BE%D1%94%D0%BA%D1%82_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81%D1%83_1999_%D1%80%D0%BE%D0%BA%D1%83), [R2U](//r2u.org.ua/pravopys/pravXXI/zmist.htm#proekt), [vlada.kiev.ua через Internet Archive](//web.archive.org/web/20120604210430/http://www.vlada.kiev.ua/pravopys/pravXXI/zmist.htm#proekt) ([2](//web.archive.org/web/20100913013850/http://pravopys.vlada.kiev.ua/pravopys/pravXXI/zmist.htm#proekt)). * 2000: ~~[коледж НАУ](http://flightcollege.com.ua/library/8%20%D0%A4%D0%98%D0%9B%D0%9E%D0%9B%D0%9E%D0%93%D0%98%D0%A7%D0%95%D0%A1%D0%9A%D0%98%D0%95%20%D0%9D%D0%90%D0%A3%D0%9A%D0%98/81%20%D0%AF%D0%97%D0%AB%D0%9A%D0%9E%D0%97%D0%9D%D0%90%D0%9D%D0%98%D0%95/81.2%20%D0%A3%D0%9A%D0%A0/%D0%94%D0%BE%D0%B2%D1%96%D0%B4%D0%BD%D0%B8%D0%BA%D0%B8/%D0%A3%D0%BA%D1%80%D0%B0%D0%B8%D0%BD%D1%81%D0%BA%D0%B8%D0%B9%20%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D1%8B%D1%81%20%202000.djvu)~~. 21 -- * 2002: ???. * 2003, В. Русанівський, проєкт: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%9F%D1%80%D0%BE%D1%94%D0%BA%D1%82_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81%D1%83_2003_%D1%80%D0%BE%D0%BA%D1%83), [Ізборник](http://litopys.org.ua/pdf/proekt_2003.pdf) ([2](http://izbornyk.org.ua/pdf/proekt_2003.pdf)), [ДУТ](http://www.dut.edu.ua/ua/lib/1/category/96/view/848), [Google Books](//google.com/books?id=XLdiAAAAMAAJ). * 2003: [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0009469). * 2004: ???. * 2005: ???. * 2007: [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0001517), ~~[коледж НАУ](http://flightcollege.com.ua/library/8%20%D0%A4%D0%98%D0%9B%D0%9E%D0%9B%D0%9E%D0%93%D0%98%D0%A7%D0%95%D0%A1%D0%9A%D0%98%D0%95%20%D0%9D%D0%90%D0%A3%D0%9A%D0%98/81%20%D0%AF%D0%97%D0%AB%D0%9A%D0%9E%D0%97%D0%9D%D0%90%D0%9D%D0%98%D0%95/81.2%20%D0%A3%D0%9A%D0%A0/%D0%94%D0%BE%D0%B2%D1%96%D0%B4%D0%BD%D0%B8%D0%BA%D0%B8/%D0%A3%D0%BA%D1%80%D0%B0%D0%B8%D0%BD%D1%81%D0%BA%D0%B8%D0%B9%20%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D1%8B%D1%81%202007.djvu), [коледж НАУ](http://flightcollege.com.ua/library/8%20%D0%A4%D0%98%D0%9B%D0%9E%D0%9B%D0%9E%D0%93%D0%98%D0%A7%D0%95%D0%A1%D0%9A%D0%98%D0%95%20%D0%9D%D0%90%D0%A3%D0%9A%D0%98/81%20%D0%AF%D0%97%D0%AB%D0%9A%D0%9E%D0%97%D0%9D%D0%90%D0%9D%D0%98%D0%95/81.2%20%D0%A3%D0%9A%D0%A0/%D0%94%D0%BE%D0%B2%D1%96%D0%B4%D0%BD%D0%B8%D0%BA%D0%B8/%D0%A3%D0%BA%D1%80%D0%B0%D0%B8%D0%BD%D1%81%D0%BA%D0%B8%D0%B9%20%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D1%8B%D1%81%202007.doc), [коледж ЧНУ](https://www.college-chnu.cv.ua/images/Books/pravopys.pdf)~~. * 2008, Ющук, проєкт: [Вікіпедія](//uk.wikipedia.org/wiki/%D0%9F%D1%80%D0%BE%D1%94%D0%BA%D1%82_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81%D1%83_%D0%86%D0%B2%D0%B0%D0%BD%D0%B0_%D0%AE%D1%89%D1%83%D0%BA%D0%B0_(2008)), [Культура України](//elib.nlu.org.ua/view.html?id=8816). * 2010: ???. * 2012: [УМІФ](http://spelling.ulif.org.ua/), [Ізборник](http://litopys.org.ua/pravopys/pravopys2012.htm) ([2](http://izbornyk.org.ua/pravopys/pravopys2012.htm)), [Ізборник](http://litopys.org.ua/pdf/pravopys2012.pdf) ([2](http://izbornyk.org.ua/pdf/pravopys2012.pdf)), [Україніка](http://irbis-nbuv.gov.ua/ulib/item/ukr0010414). * 2015: [Ізборник](http://litopys.org.ua/pravopys/pravopys2015.htm) ([2](http://izbornyk.org.ua/pravopys/pravopys2015.htm)), [Ізборник](http://litopys.org.ua/pdf/pravopys2015.pdf) ([2](http://izbornyk.org.ua/pdf/pravopys2015.pdf)), [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0009360). * 2019: [Вікіпедія](https://uk.wikipedia.org/wiki/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81_2019_%D1%80%D0%BE%D0%BA%D1%83), [УМІФ](https://www.ulif.org.ua/system/files/pravopus-new.pdf), [ІнМо](https://drive.google.com/file/d/1p0moU61Yrg4RskpJYTljxkiAa5vrd0mM/view) ([звідси](http://www.inmo.org.ua/news/%D1%83%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B8%D0%B9-%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81.-%D0%B5%D0%BB%D0%B5%D0%BA%D1%82%D1%80%D0%BE%D0%BD%D0%BD%D0%B0-%D0%B2%D0%B5%D1%80%D1%81%D1%96%D1%8F-%D0%BE%D1%84%D1%96%D1%86%D1%96%D0%B9%D0%BD%D0%BE%D0%B3%D0%BE-%D0%B2%D0%B8%D0%B4%D0%B0%D0%BD%D0%BD%D1%8F.html)); також старіші версії: [НАНУ](https://files.nas.gov.ua/PublicMessages/Documents/0/2021/01/210118223223523-1428.pdf), [МОН](https://mon.gov.ua/ua/osvita/zagalna-serednya-osvita/navchalni-programi/ukrayinskij-pravopis-2019). ### Огляди * Огієнко, «Нариси з історії української мови: система українського правопису», 1927, Варшава: [Культура України](//elib.nlu.org.ua/object.html?id=9635). Передрук, 1990, Вінніпеґ: [Diasporiana](//diasporiana.org.ua/movoznavstvo/3606-ogiyenko-i-narisi-z-istoriyi-ukrayinskoyi-movi-sistema-ukrayinskogo-pravopisu). * Огієнко, «Історія української літературної мови», 1949, Вінніпег. Переживання/передруки: + 2001, Київ: [Ізборник](http://litopys.org.ua/ohukr/ohu.htm) ([2](http://izbornyk.org.ua/ohukr/ohu.htm)). + 2-ге вид., випр., 2004, Київ: [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0001364), [Чтиво](//chtyvo.org.ua/authors/Ohiyenko_Ivan/Istoriya_ukrainskoi_literaturnoi_movy). * Німчук, «Проблеми українського правопису ⅩⅩ — початку ⅩⅩⅠ ст. ст.», 2002, Київ: [Україніка](http://irbis-nbuv.gov.ua/ulib/item/UKR0008884), [movahistory](http://movahistory.org.ua/index.php/%D0%9D%D1%96%D0%BC%D1%87%D1%83%D0%BA_%D0%92._%D0%9F%D1%80%D0%BE%D0%B1%D0%BB%D0%B5%D0%BC%D0%B8_%D1%83%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%BE%D0%B3%D0%BE_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81%D1%83_%D0%B2_XX-XXI_%D1%81%D1%82._%D1%81%D1%82.), [без додатків на R2U](//r2u.org.ua/node/126), [без додатків на vlada.kiev.ua через Internet Archive](//web.archive.org/web/20120605003228/http://www.vlada.kiev.ua/pravopys/1.html) ([2](//web.archive.org/web/20100921132422/http://pravopys.vlada.kiev.ua/pravopys/1.html)). * Німчук, «Історія українського правопису: ⅩⅥ–ⅩⅩ століття», 2004, Київ: [movahistory](http://movahistory.org.ua/index.php/%D0%86%D1%81%D1%82%D0%BE%D1%80%D1%96%D1%8F_%D1%83%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%BE%D0%B3%D0%BE_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81%D1%83:_XVI%E2%80%94XX_%D1%81%D1%82%D0%BE%D0%BB%D1%96%D1%82%D1%82%D1%8F._%D0%A5%D1%80%D0%B5%D1%81%D1%82%D0%BE%D0%BC%D0%B0%D1%82%D1%96%D1%8F), [Інститут історії України](http://resource.history.org.ua/item/0007903). * Кацімон, «Загальні уваги до граматик української мови С. Смаль-Стоцького і Ф. Гартнера (1893, 1907, 1914 рр.)», 2013, Київ: [Вернадського](http://nbuv.gov.ua/UJRN/Nznuoaf_2013_35_45). Ґенеалоґія чинного правописа, тому желехівка, ярижка ітд не додані. Джерело: фейсбукова ґрупа [Історія українського правопису](//fb.com/groups/375320239720280/posts/1210098496242446/), [Павло Литвинчук](//%D1%84%D0%B1.com/pavlberg). --- [![Ґенеалоґія чинного правописа](https://i.stack.imgur.com/xyPwe.png)](https://i.stack.imgur.com/xyPwe.png) * [Порівняльні таблиці](//uk.wikipedia.org/wiki/%D0%9F%D0%BE%D1%80%D1%96%D0%B2%D0%BD%D1%8F%D0%BD%D0%BD%D1%8F_%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%BF%D0%B8%D1%81%D1%96%D0%B2_%D1%83%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%BE%D1%97_%D0%BC%D0%BE%D0%B2%D0%B8) правописів на Вікіпедії. * Спільнота [Український правопис-2018](//fb.com/groups/177824792769309/) на Фейсбуці.
(це недописана стаття, яка вимагає переформатування і, можливо, категоризації) --- Список джерел, які вважають поважними наші колеги з [Wikipedia](https://uk.wikipedia.org/wiki/%D0%9E%D0%B1%D0%B3%D0%BE%D0%B2%D0%BE%D1%80%D0%B5%D0%BD%D0%BD%D1%8F_%D0%92%D1%96%D0%BA%D1%96%D0%BF%D0%B5%D0%B4%D1%96%D1%97:%D0%9F%D1%80%D0%BE%D0%B5%D0%BA%D1%82:%D0%93%D1%80%D0%B0%D0%BC%D0%BE%D1%82%D0%BD%D1%96%D1%81%D1%82%D1%8C/%D0%90%D0%B2%D1%82%D0%BE%D1%80%D0%B8%D1%82%D0%B5%D1%82%D0%BD%D1%96_%D0%B4%D0%B6%D0%B5%D1%80%D0%B5%D0%BB%D0%B0) ============================================================================================================================================================================================================================================================================================================================================================================================================================================== Словники і довідники, які можна використовувати для перевірки відповідності до сучасної української літературної норми ### Для перевірки наголосу * [Складні випадки наголошування слів](http://www.twirpx.com/file/300334/) ### Для перевірки написання (орфографії) \* ### Тлумачні словники * **Сучасний тлумачний словник української мови: 60 000 слів / За заг. ред. д-ра філол. наук, проф. В. В. Дубічинського. — Харків: ВД «ШКОЛА», 2007. — 832 с.** — доволі місткий та зручний тлумачний словник української мови. Як зазначають автори словника, в ньому вводиться сучасна лексика та сленг, серед застарілих слів — слова іх художньої літератури, а також добірка слів з усіх галузей знань. Словник рекомендований Міністерством освіти і науки. * [ВТССУМ](http://Lingvo.ua) * [Словник української мови в 11-ти томах. К.: Наукова думка, 1970–1980.](http://sum.in.ua/) ### Велика чи мала літера * **В. В. Жайворонок. Велика чи мала літера? Словник-довідник. — К.: Наук. думка, 2004.** — словник рекомендований до друку вченою радою Інституту мовознавства ім. О. О. Потебні НАН України, автор — відомий авторитетний український мовознавець, доктор філологічних наук, [[Жайворонок Віталій Вікторович]]. Входить до серії „Наукове видання «Словники України»“. Окрім того, зручний тим, що [доступний онлайн](http://velyka-chy-mala-litera.wikidot.com/) ### Довідники з культури мови * [Словник-довідник з культури української мови](http://ukrknyga.at.ua/load/slovnik_dovidnik_z_kulturi_ukrajinskoji_movi/4-1-0-265) * [Словник-довідник з українського літературного слововживання](http://www.twirpx.com/file/103521/) ### Перекладні Російсько-українські * [Російсько-українські словники](http://r2u.org.ua/) * [Російсько-український словник сталих виразів](http://stalivyrazy.org.ua/) * [Російсько-український словник фізичних термінів](http://ukrknyga.at.ua/load/rosijsko_ukrajinskij_slovnik_fizichnikh_terminiv_za_red_o_b_liskovicha/38-1-0-361) * [Російсько-український словник. Термінологічна лексика](http://freelib.in.ua/load/92-1-0-1776) * Російсько-український словник складної лексики С. Караванського ### Підручники і посібники з пунктуації \* ### Топоніміка * [Топонімічний словник України](http://www.toponymic-dictionary.in.ua/) Фразеологія =========== * [Словник фразеологічних синонімів](http://www.rozum.org.ua/index.php?a=index&d=24) * [Словник фразеологічних антонімів](http://sovremennik.ws/2008/07/03/slovnik_frazeologchnikh_antonmv_ukransko_movi.html) ### Галузеві словники * [Фінансовий словник](http://www.twirpx.com/file/459498/) * [Словник соціологічних і політологічних термінів](http://ukrknyga.at.ua/load/slovnik_sociologichnikh_i_politologichnikh_terminiv_za_red_v_astakhovoji_v_danilenka_a_panova/2-1-0-430) --- Список словників, які поважають наші колеги з [Wiktionary](https://uk.wiktionary.org/wiki/%D0%94%D0%BE%D0%B4%D0%B0%D1%82%D0%BE%D0%BA:%D0%A1%D0%BF%D0%B8%D1%81%D0%BE%D0%BA_%D1%81%D0%BB%D0%BE%D0%B2%D0%BD%D0%B8%D0%BA%D1%96%D0%B2) =================================================================================================================================================================================================================================
8
В цьому питанні я сам створив відповідь. Це є wiki-відповідь (спільна відповідь, community wiki) — **її може редагувати кожен**. Ви можете додавати інші джерела: редагуючи ту відповідь або створювати окремі відповіді. * [Загальне](/a/9) / General * [Словники](/a/287) / Dictionaries * [Корпуси](/a/286) / Corporas * [Правописи](/a/119) / Spelling * [Пошук у локалізаціях програм](/a/56) / Search in software localizations * [Перелік ресурсів](/a/100) / List of sourses * Wikipedia, Wiktionary: [Джерела](/a/130) / Sources * [Учба](/a/190) / Learning * [Здоровий глузд](/a/152) / Common sense --- In this question I created an answer myself. It's a wiki-answer (community answer, community wiki) — **everyone can edit it**. You're welcome to add other sources: by editing that (wiki) answer or by creating new ones.
2017/02/07
[ "https://ukrainian.meta.stackexchange.com/questions/8", "https://ukrainian.meta.stackexchange.com", "https://ukrainian.meta.stackexchange.com/users/4/" ]
1. Поради мовознавців: [«Як ми говоримо» Б. Антоненка-Давидовича](http://yak-my-hovorymo.wikidot.com/), [«Культура слова» О. Пономаріва](http://ponomariv-kultura-slova.wikidot.com/), [блог О. Пономаріва на BBC](http://www.bbc.com/ukrainian/topics/ponomariv), [«Уроки державної мови» (в газеті «Хрещатик») Б. Рогози](http://mova.kreschatic.kiev.ua/index.html) (мовознавці іноді помиляються), [відеоуроки О. Авраменка](http://xn--80aafnzkijm.xn--j1amh/11/12) (також [аудіоуроки](http://xn--80aafnzkijm.xn--j1amh/11/13)) (чи він мовознавець?). Неавторитетні поради: [список найтиповіших мовних помилок у Вікіпедії](http://uk.wikipedia.org/wiki/%D0%92%D1%96%D0%BA%D1%96%D0%BF%D0%B5%D0%B4%D1%96%D1%8F:%D0%A1%D0%BF%D0%B8%D1%81%D0%BE%D0%BA_%D0%BD%D0%B0%D0%B9%D1%82%D0%B8%D0%BF%D0%BE%D0%B2%D1%96%D1%88%D0%B8%D1%85_%D0%BC%D0%BE%D0%B2%D0%BD%D0%B8%D1%85_%D0%BF%D0%BE%D0%BC%D0%B8%D0%BB%D0%BE%D0%BA#cite_ref-dzvonadzvonu_1-0). 2. Інші спільноти: [Чиста мова](https://www.facebook.com/chystamova/), Мова – ДНК нації ([сторінка Facebook](https://www.facebook.com/mova.ukr), [сайт](https://ukr-mova.in.ua/)), [СловОпис](https://www.facebook.com/slovopys/), [ua-etymology](http://ua-etymology.livejournal.com/), [моволюбам](http://l-ponomar.com/), [movakrapka](http://movakrapka.blogspot.com/), [MOVA.info Q&A](http://www.mova.info/dovidka.aspx), [лінгвофорум](http://lingvoforum.net/index.php?board=101.0), [r2u мовні консультації](http://r2u.org.ua/forum/viewforum.php?f=6), [словопедія форум](http://www.slovopedia.com/forum/viewforum.php?f=12). 3. Підручники: [підготовка до ЗНО](http://zno.academia.in.ua/course/view.php?id=8), [від ІФ КНУ](http://www.linguist.univ.kiev.ua/WINS/pidruchn/), [на Phoenicis](https://www.phoenicis.com.ua/ukrainian-language.html) 4. Адаптація іноземних слів: правопис, [правила транслітерації ДСІВ](http://sips.gov.ua/ua/transliteruvannja.html), [правила транслітерації Укркартографії](http://ukrmap.com.ua/services/kodeksi-ustalenoji-praktiki/). Неавторитетне джерело неологізмів: [Словотвір](http://slovotvir.org.ua/). 5. Для іноземців: [Speak Ukrainian](https://speakukraine.net/). --- 1. Linguists' advices : [“How do we speak” of B. Antonenko-Davydovych](http://yak-my-hovorymo.wikidot.com/), [“Culture of word” of O. Ponomariv](http://ponomariv-kultura-slova.wikidot.com/), [O. Ponomariv's blog at BBC](http://www.bbc.com/ukrainian/topics/ponomariv), [“Lessons of the state language” (in the newspaper “Khreshchatyk”) of B. Rohoza](http://mova.kreschatic.kiev.ua/index.html) (linguists sometimes make mistakes too), [O. Avramenko's video-lessons](http://xn--80aafnzkijm.xn--j1amh/11/12) (also [radio-lessons](http://xn--80aafnzkijm.xn--j1amh/11/13))(is he a linguist?). Non-authoritative advices: [list of the most common lingual mistakes in Wikipedia](http://uk.wikipedia.org/wiki/%D0%92%D1%96%D0%BA%D1%96%D0%BF%D0%B5%D0%B4%D1%96%D1%8F:%D0%A1%D0%BF%D0%B8%D1%81%D0%BE%D0%BA_%D0%BD%D0%B0%D0%B9%D1%82%D0%B8%D0%BF%D0%BE%D0%B2%D1%96%D1%88%D0%B8%D1%85_%D0%BC%D0%BE%D0%B2%D0%BD%D0%B8%D1%85_%D0%BF%D0%BE%D0%BC%D0%B8%D0%BB%D0%BE%D0%BA#cite_ref-dzvonadzvonu_1-0). 2. Other communities: [Chysta mova](https://www.facebook.com/chystamova/), Mova a.k.a. mova.ukr ([Facebook page](https://www.facebook.com/mova.ukr), [site](https://ukr-mova.in.ua/)), [SlovOpys](https://www.facebook.com/slovopys/), [ua-etymology](http://ua-etymology.livejournal.com/), [l-ponomar](http://l-ponomar.com/), [movakrapka](http://movakrapka.blogspot.com/), [MOVA.info Q&A](http://www.mova.info/dovidka.aspx), [lingvoforum](http://lingvoforum.net/index.php?board=101.0), [r2u lingual consultations](http://r2u.org.ua/forum/viewforum.php?f=6), [slovopedia forum](http://www.slovopedia.com/forum/viewforum.php?f=12). 3. Textbooks: [preparation to EIT](http://zno.academia.in.ua/course/view.php?id=8), [from IP of KNU](http://www.linguist.univ.kiev.ua/WINS/pidruchn/), [on Phoenicis](https://www.phoenicis.com.ua/ukrainian-language.html). 4. Foreign words adaptation: orthography, [SIPS transliteration rules](http://sips.gov.ua/ua/transliteruvannja.html), [Ukrmap transliteration rules](http://ukrmap.com.ua/services/kodeksi-ustalenoji-praktiki/). Non-authoritative neologism source: [Словотвір](http://slovotvir.org.ua/). 5. For foreigners: [Speak Ukrainian](https://speakukraine.net/).
Загальний здоровий глузд ======================== * [Illustrated book of bad arguments](https://bookofbadarguments.com/) - на жаль, перекладу на українську ще немає. Ця книга показує, як саме люди схильні помилятися у своїй арґументації --- Common sense ============ * [Illustrated book of bad arguments](https://bookofbadarguments.com/) - Unfortunately it hasn't been translated to Ukrainian yet. This book shows how people tend to fail in their argumentation
23,106,821
here is my code it will give following error. The variable name '@sno' has already been declared. Variable names must be unique within a query batch or stored procedure. ``` private void btnBatchInsert_Click(ArrayList data) { // Get the DataTable with Rows State as RowState.Added SqlCommand command = new SqlCommand(); sqlcon.Open(); for (int j = 0; j < data.Count; j++) { string[] arr = data[j].ToString().Split('#'); // Set the Parameter with appropriate Source Column Name command.Parameters.Add("@sno", arr[0].ToString()); command.Parameters.Add("@IMECode", arr[1].ToString()); command.Parameters.Add("@rcptno", arr[2].ToString()); command.Parameters.Add("@InvoiceNo", arr[3].ToString() ); command.Parameters.Add("@CSSNo", arr[4].ToString()); command.Parameters.Add("@Invoicedate", arr[5].ToString()); command.Parameters.Add("@Name", arr[6].ToString()); command.Parameters.Add("@PlanNo", planMode(arr[7].ToString()) ); command.Parameters.Add("@Mode", PlanType(arr[8].ToString())); command.Parameters.Add("@Installamount", Convert.ToDouble(arr[9].ToString().Equals("") ? "0" : arr[9].ToString()).ToString()); command.Parameters.Add("@Spotcommi", Convert.ToDouble(arr[10].ToString().Equals("") ? "0" : arr[10].ToString()).ToString() ); command.Parameters.Add("@Applicationfee", Convert.ToDouble(arr[11].ToString().Equals("") ? "0" : arr[11].ToString()).ToString()); command.Parameters.Add("@Netamount", (Convert.ToDouble(arr[12].ToString().Equals("") ? "0" : arr[12].ToString()) + Convert.ToDouble(arr[11].ToString().Equals("") ? "0" : arr[11].ToString())).ToString() ); command.Parameters.Add("@Adjmount", Convert.ToDouble(arr[13].ToString().Equals("") ? "0" : arr[13].ToString()).ToString() ); command.Parameters.Add("@csc_name", arr[14].ToString()); command.Connection = sqlcon; //cmd.CommandText = "Insert into [Personal_information_ofcandidat](User_id,Name,MName,LName,Exam_date,Exam_id,College_Name,Email_id,Phone_no) values('" + userid + "','" + uname + "','" + muname + "','" + luname + "','" + DateTime.Now + "','" + examid + "','" + collegname + "','" + email + "','" + mobile + "')"; command.CommandText = "insert into tempforagreementlist(sno,IMECode,rcptno,InvoiceNo,CSSNo,Invoicedate,Name,PlanNo,Mode,Installamount,Spotcommi,Applicationfee,Netamount,Adjmount,csc_name) values(@sno,@IMECode,@rcptno,@InvoiceNo,@CSSNo,@Invoicedate,@Name,@PlanNo,@Mode,@Installamount,@Spotcommi,@Applicationfee,@Netamount,@Adjmount,@csc_name)"; command.CommandType = CommandType.Text; int a = command.ExecuteNonQuery(); } } ```
2014/04/16
[ "https://Stackoverflow.com/questions/23106821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3226562/" ]
You are adding parameters inside a loop. The second, third, forth, etc iterations through the loop: yes, you will be adding duplicates. Either: * clear the parameters between iterations * overwrite the values rather than adding new parameters
You're adding all variables more than once.. because you're doing it in a loop. ``` SqlCommand command = new SqlCommand(); // command that lasts // across all iterations of loop for (int j = 0; j < data.Count; j++) { // adding all parameters each time. ``` Add the parameters first.. then give them a value on each iteration (instead of doing both).
23,106,821
here is my code it will give following error. The variable name '@sno' has already been declared. Variable names must be unique within a query batch or stored procedure. ``` private void btnBatchInsert_Click(ArrayList data) { // Get the DataTable with Rows State as RowState.Added SqlCommand command = new SqlCommand(); sqlcon.Open(); for (int j = 0; j < data.Count; j++) { string[] arr = data[j].ToString().Split('#'); // Set the Parameter with appropriate Source Column Name command.Parameters.Add("@sno", arr[0].ToString()); command.Parameters.Add("@IMECode", arr[1].ToString()); command.Parameters.Add("@rcptno", arr[2].ToString()); command.Parameters.Add("@InvoiceNo", arr[3].ToString() ); command.Parameters.Add("@CSSNo", arr[4].ToString()); command.Parameters.Add("@Invoicedate", arr[5].ToString()); command.Parameters.Add("@Name", arr[6].ToString()); command.Parameters.Add("@PlanNo", planMode(arr[7].ToString()) ); command.Parameters.Add("@Mode", PlanType(arr[8].ToString())); command.Parameters.Add("@Installamount", Convert.ToDouble(arr[9].ToString().Equals("") ? "0" : arr[9].ToString()).ToString()); command.Parameters.Add("@Spotcommi", Convert.ToDouble(arr[10].ToString().Equals("") ? "0" : arr[10].ToString()).ToString() ); command.Parameters.Add("@Applicationfee", Convert.ToDouble(arr[11].ToString().Equals("") ? "0" : arr[11].ToString()).ToString()); command.Parameters.Add("@Netamount", (Convert.ToDouble(arr[12].ToString().Equals("") ? "0" : arr[12].ToString()) + Convert.ToDouble(arr[11].ToString().Equals("") ? "0" : arr[11].ToString())).ToString() ); command.Parameters.Add("@Adjmount", Convert.ToDouble(arr[13].ToString().Equals("") ? "0" : arr[13].ToString()).ToString() ); command.Parameters.Add("@csc_name", arr[14].ToString()); command.Connection = sqlcon; //cmd.CommandText = "Insert into [Personal_information_ofcandidat](User_id,Name,MName,LName,Exam_date,Exam_id,College_Name,Email_id,Phone_no) values('" + userid + "','" + uname + "','" + muname + "','" + luname + "','" + DateTime.Now + "','" + examid + "','" + collegname + "','" + email + "','" + mobile + "')"; command.CommandText = "insert into tempforagreementlist(sno,IMECode,rcptno,InvoiceNo,CSSNo,Invoicedate,Name,PlanNo,Mode,Installamount,Spotcommi,Applicationfee,Netamount,Adjmount,csc_name) values(@sno,@IMECode,@rcptno,@InvoiceNo,@CSSNo,@Invoicedate,@Name,@PlanNo,@Mode,@Installamount,@Spotcommi,@Applicationfee,@Netamount,@Adjmount,@csc_name)"; command.CommandType = CommandType.Text; int a = command.ExecuteNonQuery(); } } ```
2014/04/16
[ "https://Stackoverflow.com/questions/23106821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3226562/" ]
You are adding parameters inside a loop. The second, third, forth, etc iterations through the loop: yes, you will be adding duplicates. Either: * clear the parameters between iterations * overwrite the values rather than adding new parameters
On each iteration, you would need to create a new instance of SqlCommand and assign it to command for it to remove the parameters that you previously added. ``` for (int j = 0; j < data.Count; j++) { command = new SqlCommand(); string[] arr = data[j].ToString().Split('#'); ```
23,106,821
here is my code it will give following error. The variable name '@sno' has already been declared. Variable names must be unique within a query batch or stored procedure. ``` private void btnBatchInsert_Click(ArrayList data) { // Get the DataTable with Rows State as RowState.Added SqlCommand command = new SqlCommand(); sqlcon.Open(); for (int j = 0; j < data.Count; j++) { string[] arr = data[j].ToString().Split('#'); // Set the Parameter with appropriate Source Column Name command.Parameters.Add("@sno", arr[0].ToString()); command.Parameters.Add("@IMECode", arr[1].ToString()); command.Parameters.Add("@rcptno", arr[2].ToString()); command.Parameters.Add("@InvoiceNo", arr[3].ToString() ); command.Parameters.Add("@CSSNo", arr[4].ToString()); command.Parameters.Add("@Invoicedate", arr[5].ToString()); command.Parameters.Add("@Name", arr[6].ToString()); command.Parameters.Add("@PlanNo", planMode(arr[7].ToString()) ); command.Parameters.Add("@Mode", PlanType(arr[8].ToString())); command.Parameters.Add("@Installamount", Convert.ToDouble(arr[9].ToString().Equals("") ? "0" : arr[9].ToString()).ToString()); command.Parameters.Add("@Spotcommi", Convert.ToDouble(arr[10].ToString().Equals("") ? "0" : arr[10].ToString()).ToString() ); command.Parameters.Add("@Applicationfee", Convert.ToDouble(arr[11].ToString().Equals("") ? "0" : arr[11].ToString()).ToString()); command.Parameters.Add("@Netamount", (Convert.ToDouble(arr[12].ToString().Equals("") ? "0" : arr[12].ToString()) + Convert.ToDouble(arr[11].ToString().Equals("") ? "0" : arr[11].ToString())).ToString() ); command.Parameters.Add("@Adjmount", Convert.ToDouble(arr[13].ToString().Equals("") ? "0" : arr[13].ToString()).ToString() ); command.Parameters.Add("@csc_name", arr[14].ToString()); command.Connection = sqlcon; //cmd.CommandText = "Insert into [Personal_information_ofcandidat](User_id,Name,MName,LName,Exam_date,Exam_id,College_Name,Email_id,Phone_no) values('" + userid + "','" + uname + "','" + muname + "','" + luname + "','" + DateTime.Now + "','" + examid + "','" + collegname + "','" + email + "','" + mobile + "')"; command.CommandText = "insert into tempforagreementlist(sno,IMECode,rcptno,InvoiceNo,CSSNo,Invoicedate,Name,PlanNo,Mode,Installamount,Spotcommi,Applicationfee,Netamount,Adjmount,csc_name) values(@sno,@IMECode,@rcptno,@InvoiceNo,@CSSNo,@Invoicedate,@Name,@PlanNo,@Mode,@Installamount,@Spotcommi,@Applicationfee,@Netamount,@Adjmount,@csc_name)"; command.CommandType = CommandType.Text; int a = command.ExecuteNonQuery(); } } ```
2014/04/16
[ "https://Stackoverflow.com/questions/23106821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3226562/" ]
You are adding parameters inside a loop. The second, third, forth, etc iterations through the loop: yes, you will be adding duplicates. Either: * clear the parameters between iterations * overwrite the values rather than adding new parameters
The most simple solution is to define the parameters outside the loop adding them to the Parameters collection. Inside the loop you change only the value and execute the command Also try to be very specific with the Parameter type and size because in that way you allow the database engine to store the query plan and reuse it at every loop. This could be important in term of performances. ``` private void btnBatchInsert_Click(ArrayList data) { sqlcon.Open(); SqlCommand command = new SqlCommand(); command.Connection = sqlcon; // Add to the parameters collection a specific parameter with appropriate type and size command.Parameters.Add(new SqlParameter("@sno", SqlDbType.NVarChar, 32)); .... for (int j = 0; j < data.Count; j++) { command.Parameters["@sno"].Value = arr[0].ToString(); .... command.ExecuteNonQuery(); } } ```
2,396,324
I am trying to find out the density of the product $XY$ of two independent Gamma random variables $X \sim \mathrm{Gamma}(k\_1, \theta\_1)$ and $Y \sim \mathrm{Gamma}(k\_2, \theta\_2)$, where $k\_i$'s are the shape parameters and $\theta\_i$'s are the scale parameters. I know the formula for the density of the product of two independent RV <https://en.wikipedia.org/wiki/Product_distribution>, but I couldn't evaluate the integral. I know the resulting density will involve Meijer G-functions, and I found this paper: <http://epubs.siam.org/doi/abs/10.1137/0118065>, but the Gamma distribution density in this paper is given as $$f\_i(x\_i)=\frac{1}{\Gamma{\left(b\_i\right)}} x\_i^{b\_i-1} e^{-x\_i}$$ with unity scale parameter. Is there a formula to find the density of the product of two independent Gamma random variables with arbitrary shape and scale parameters? Any help is highly appreciated.
2017/08/17
[ "https://math.stackexchange.com/questions/2396324", "https://math.stackexchange.com", "https://math.stackexchange.com/users/330947/" ]
Let $X \sim \text{Gamma}(a,b)$ with pdf $f(x)$: [![enter image description here](https://i.stack.imgur.com/woBp2.png)](https://i.stack.imgur.com/woBp2.png) and $Y \sim \text{Gamma}(\alpha,\beta)$ be independent with pdf $g(y)$: [![enter image description here](https://i.stack.imgur.com/n74Aw.png)](https://i.stack.imgur.com/n74Aw.png) Then, the pdf of the product $Z = X Y$ can be obtained as $h(z)$: [![enter image description here](https://i.stack.imgur.com/Pdj1d.png)](https://i.stack.imgur.com/Pdj1d.png) where I am using the `TransformProduct` function from *mathStatica/Mathematica* to do the nitty-gritties, and `BesselK[n,z]` denotes the modified Bessel function of the second kind. This is much simpler than requiring MeijerG functions. I should note that I am one of the authors of the software function used. **Quick Monte Carlo check** * against theoretical solution derived above when $a =2$, $b = 3$, $\alpha = 4$, and $\beta = 1.1$ [![enter image description here](https://i.stack.imgur.com/P1aXG.png)](https://i.stack.imgur.com/P1aXG.png) Looks fine :)
In order to provide an analytical derivation and confirm the result, it is possible to proceed as follows: Let's start by defining independent gamma product $Z\_{2}=XY$, $X=Z\_{1}$ and $Y=\frac{Z\_{2}}{Z\_{1}}$. Then we can write joint density using jacobian, \begin{equation} f(z\_{1},z\_{2})=f\_{x}(z\_{1})f\_{y}(z\_{2})|J| \end{equation} where jacobian $|J|$ is, \begin{bmatrix}\frac{\partial x }{\partial z\_{1}}&\frac{\partial x }{\partial z\_{2}}\\\frac{\partial y }{\partial z\_{1}}&\frac{\partial y }{\partial z\_{2}}\end{bmatrix} \begin{bmatrix}1&0\\\frac{-z\_{2}}{z\_{1}^{2}}&\frac{1}{z\_{1}}\end{bmatrix} Then this equals, \begin{equation} f(z\_{1},z\_{2})=f\_{x}(z\_{1})f\_{y}(z\_{2})\frac{1}{z\_{1}} \end{equation} \begin{equation} f(z\_{1},z\_{2})=\frac{\beta\_{x}^{-\alpha\_{x}}z\_{1}^{\alpha\_{x}-1}e^{\frac{-z\_{1}}{\beta\_{x}}}}{\Gamma(\beta\_{x})}\frac{\beta\_{y}^{-\alpha\_{y}}(\frac{z\_{2}}{z\_{1}})^{\alpha\_{y}-1}e^{\frac{-z\_{2}/z\_{1}}{\beta\_{y}}}}{\Gamma(\beta\_{y})} \end{equation} In order to get marginal density of $Z\_{2}=XY$ the product, we integrate out the joint density we wrote over $Z\_{1}$ \begin{equation} f(z\_{2})=\beta\_{x}^{-\alpha\_{x}}\beta\_{y}^{-\alpha\_{y}}z\_{2}^{\alpha\_{y}-1}\int\_{0}^{\infty}\left[\frac{z\_{1}^{\alpha\_{x}-\alpha\_{y}-1}e^{\frac{-z\_{1}}{\beta\_{x}}}e^{\frac{-z\_{2}/z\_{1}}{\beta\_{y}}}}{\Gamma(\beta\_{x})\Gamma(\beta\_{y})}dz\_{1}\right] \end{equation} Using the fact that, \begin{equation} \int\_{0}^{\infty}x^{\alpha-1}\exp(-ax-bx^{-1})dx=2\left(\frac{b}{a}\right)^{\alpha/2}K\_{\alpha}\left(2\sqrt{ab} \right) \end{equation} We will have, \begin{equation} f\left(z\_{2}=xy\right)=\frac{z\_{2}^{\alpha\_{y}-1}\beta\_{x}^{-\alpha\_{x}}\beta\_{y}^{-\alpha\_{y}}2\left(\frac{z\_{2}\beta\_{x}}{\beta\_{y}}\right)^{\frac{\left(\alpha\_{x}-\alpha\_{y}\right)}{2}}K\_{\alpha\_{x}-\alpha\_{y}}\left(2\sqrt{\frac{z\_{2}}{\beta\_{x}\beta\_{y}}} \right)}{\Gamma(\alpha\_{x})\Gamma(\alpha\_{y})} \end{equation} Another Monte-Carlo check confirms @wolfies nice result above, [![GammaProductPlot](https://i.stack.imgur.com/A4zD5.png)](https://i.stack.imgur.com/A4zD5.png) Plus an integral on the pdf confirms the accuracy of it to be the correct density. After integrating in R we obtain, > > integrate(gamprod,lower = 0.,upper = Inf,ax = 2,bx = 3,ay = 4,by = 1.1) > 1 with absolute error < 6.8e-05 > > >
33,147,896
This is definitely a rookie question but I'm not finding an answer for this (maybe because of my wording) so here goes: I'm reading a data frame into R studio (csv file) that has 24 columns with headers. There are only numbers in these columns (they're essentially concentrations of several chemicals). It's called all. I need to use them as numeric vectors. When I read them in and type ``` is.numeric(all[,1]) ``` I get ``` TRUE ``` When I type ``` is.numeric(all[1]) ``` I get ``` FALSE ``` I think this is because R interprets the header as a factor. I also tried reading in a table without headers and with `headers=FALSE`, but R renames it to V1, V2 etc so the result ends up being the same. I need to work with functions where I invoke something like `all[2:24]`. How can I go about to make R either "not see" the header or remove it altogether? Thanks for the answers! PS: the dataframe I am using (without headers - if it had headers, it would just have names instead of V1, V2, etc) is something like this: [![data](https://i.stack.imgur.com/8PbnT.jpg)](https://i.stack.imgur.com/8PbnT.jpg)
2015/10/15
[ "https://Stackoverflow.com/questions/33147896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4425170/" ]
As easy as that: ``` var url = document.getElementById("id of element").href; url = url.substring(0, url.length-1); url = url + "1"; document.getElementById("id of element").href = url; ``` Probably google first about string functions before asking...
If the pattern of the url stays the same (the parameter `dl=0`) then you can simply use the [`.replace()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)-function: ``` var url = 'https://www.dropbox.com/sh/wbc1ewhfg1jttpr/AADLfZKlfOBs5e_ueAkzffKRa/SamplePDFDownload.pdf?dl=0'; url = url.replace('dl=0', 'dl=1'); ```
19,604,852
Is it required to make foreign key column in a table as NOT NULL, If we not written explicitly foreign key column as not null what it will be? Can it contain null values? And what is the Difference between following two statements: ``` [PhoneId] [int] NOT NULL FOREIGN KEY REFERENCES [dbo].[tbl_PhoneNumber](PhoneNumberId) [PhoneId] [int] FOREIGN KEY REFERENCES [dbo].[tbl_PhoneNumber](PhoneNumberId) ```
2013/10/26
[ "https://Stackoverflow.com/questions/19604852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2349008/" ]
> > Is it required to make foreign key column in a table as NOT NULL, > > > No it is not required. MSDN says that:- > > When a value other than NULL is entered into the column of a FOREIGN > KEY constraint, the value must exist in the referenced column; > otherwise, a foreign key violation error message is returned. To make > sure that all values of a composite foreign key constraint are > verified, specify NOT NULL on all the participating columns. > > > So the simple answer to your question is NO IT IS NOT REQUIRED. A foreign key attribute can contain NULL values as well. Your second definition will allow `Nulls` in the column. From [here](http://blog.sqlauthority.com/2008/09/08/sql-server-%E2%80%93-2008-creating-primary-key-foreign-key-and-default-constraint/):- > > When a FOREIGN KEY constraint is added to an existing column or > columns in the table SQL Server, by default checks the existing data > in the columns to ensure that all values, except NULL, exist in the > column(s) of the referenced PRIMARY KEY or UNIQUE constraint. > > > Also check **[Foreign Key Constraints](http://technet.microsoft.com/en-us/library/ms189049.aspx)**
It is not required. A foreign key attribute without `NOT NULL` can contain `NULL` values, and this can be used to indicate that no such tuple in the referenced relation is applicable.
19,604,852
Is it required to make foreign key column in a table as NOT NULL, If we not written explicitly foreign key column as not null what it will be? Can it contain null values? And what is the Difference between following two statements: ``` [PhoneId] [int] NOT NULL FOREIGN KEY REFERENCES [dbo].[tbl_PhoneNumber](PhoneNumberId) [PhoneId] [int] FOREIGN KEY REFERENCES [dbo].[tbl_PhoneNumber](PhoneNumberId) ```
2013/10/26
[ "https://Stackoverflow.com/questions/19604852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2349008/" ]
According to sql normalization rule foreign key value must be equal to primary key value or NULL, so it will contain either NULL value of one value from primary key table row.
It is not required. A foreign key attribute without `NOT NULL` can contain `NULL` values, and this can be used to indicate that no such tuple in the referenced relation is applicable.
19,604,852
Is it required to make foreign key column in a table as NOT NULL, If we not written explicitly foreign key column as not null what it will be? Can it contain null values? And what is the Difference between following two statements: ``` [PhoneId] [int] NOT NULL FOREIGN KEY REFERENCES [dbo].[tbl_PhoneNumber](PhoneNumberId) [PhoneId] [int] FOREIGN KEY REFERENCES [dbo].[tbl_PhoneNumber](PhoneNumberId) ```
2013/10/26
[ "https://Stackoverflow.com/questions/19604852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2349008/" ]
> > Is it required to make foreign key column in a table as NOT NULL, > > > No it is not required. MSDN says that:- > > When a value other than NULL is entered into the column of a FOREIGN > KEY constraint, the value must exist in the referenced column; > otherwise, a foreign key violation error message is returned. To make > sure that all values of a composite foreign key constraint are > verified, specify NOT NULL on all the participating columns. > > > So the simple answer to your question is NO IT IS NOT REQUIRED. A foreign key attribute can contain NULL values as well. Your second definition will allow `Nulls` in the column. From [here](http://blog.sqlauthority.com/2008/09/08/sql-server-%E2%80%93-2008-creating-primary-key-foreign-key-and-default-constraint/):- > > When a FOREIGN KEY constraint is added to an existing column or > columns in the table SQL Server, by default checks the existing data > in the columns to ensure that all values, except NULL, exist in the > column(s) of the referenced PRIMARY KEY or UNIQUE constraint. > > > Also check **[Foreign Key Constraints](http://technet.microsoft.com/en-us/library/ms189049.aspx)**
According to sql normalization rule foreign key value must be equal to primary key value or NULL, so it will contain either NULL value of one value from primary key table row.
34,872
can anyone please explain me what is meant by salesforce? and what is meant by Partner portal? i tried to figure it out but there is no use could any one help me out..
2014/05/12
[ "https://salesforce.stackexchange.com/questions/34872", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/8316/" ]
Salesforce in it's core is a combination of features (clouds) that are focused on CRM, suppored by a platform that will also allow you to extend these features, or build entirly independant functionality. It's oriented to be used by internal users of a company. The partner portal or partner community is a feature of salesforce that allows giving access to users in companies your company works together with, so that collaboration can be done within your CRM system. The benefit is that both your internal as external partner users can work directly on the same data, which is a huge benefit. Partner community can for instance be used to give access to re-sellers or offshore support teams (as part of another organisation).
You can find more information on partner portal at <https://help.salesforce.com/HTViewHelpDoc?id=partner_portal_about.htm&language=en_US> As explained at that link, partner portal is no longer offered to new customers. They have been replaced by Communities. You can find more information about them at <http://help.salesforce.com/help/pdfs/en/salesforce_communities_implementation.pdf> You can use full-blown SalesForce internally to deal with leads, customer accounts, customer support, and then leverage Communities to deal with partners for sales and support.
7,886,024
I have two List. first list element `Name Age Sex` and second list element `test 10 female`. I want to insert this data into database. In first list having `MySQL Column` and in second `MySQL Column Values`.I'm trying to make this query. `INSERT INTO (LIST1) VALUES (List2)` =>`INSERT INTO table (name,age,sex) values (test,10,female)` Is it possible? thanks
2011/10/25
[ "https://Stackoverflow.com/questions/7886024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/559744/" ]
How about this? ``` >>> query = 'INSERT INTO (%s) VALUES (%s)' % (','.join([str(i) for i in list1]), ','.join([str(i) for i in list2])) >>> print query INSERT INTO (name,age,sex) VALUES (test,10,female) ``` The `str` is needed because that way, numbers are allowed to be in the list. Edit: I feel like you could add some effort into this yourself, but anyway. To add quotes, I'd change it to this: ``` >>> list1 = ['name', 'age', 'sex'] >>> list2 = ['test', 10, 'female'] >>> f = lambda l: ','.join(["'%s'" % str(s) for s in l]) >>> print 'INSERT INTO (%s) VALUES (%s)' % (f(list1), f(list2)) INSERT INTO ('name','age','sex') VALUES ('test','10','female') ```
Try getting this to work using the MySQL gui. Once that works properly, then you can try to get it to work with Python using the SQL statements that worked in MySQL.
6,510,985
I have the code below to query a table which retrieves arrays. The parameter $idList could have several values and may therefore produce duplicates. I am only interested in inserting one unique memalertid. Any advice on how to remove the duplicates would be much appreciated. ``` $sql = mysql_query("SELECT memalertid from memlist where listID IN ($idList) AND (emailyes = '1') "); while ($info = mysql_fetch_array($sql)){ $insert_query = "insert into subsalerts (memalertid, idMembers, emailid) VALUES('".$info['memalertid']."','$idMembers','$emailid')"; $insert_buffer = mysql_query($insert_query); ``` Thanks very much
2011/06/28
[ "https://Stackoverflow.com/questions/6510985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/468908/" ]
Simply use `SELECT DISTINCT` to select distinct rows. ``` SELECT DISTINCT memalertid FROM memlist WHERE listID IN ($idList) AND (emailyes = '1') ``` You could also `GROUP BY memalertid` instead. ``` SELECT memalertid FROM memlist WHERE listID IN ($idList) AND (emailyes = '1') GROUP BY memalertid ``` For more information: <http://dev.mysql.com/doc/refman/5.5/en/select.html>.
``` $newArray = array_unique($yourArray); ``` This will create a new array only with unique values; excluding any duplicates.
6,510,985
I have the code below to query a table which retrieves arrays. The parameter $idList could have several values and may therefore produce duplicates. I am only interested in inserting one unique memalertid. Any advice on how to remove the duplicates would be much appreciated. ``` $sql = mysql_query("SELECT memalertid from memlist where listID IN ($idList) AND (emailyes = '1') "); while ($info = mysql_fetch_array($sql)){ $insert_query = "insert into subsalerts (memalertid, idMembers, emailid) VALUES('".$info['memalertid']."','$idMembers','$emailid')"; $insert_buffer = mysql_query($insert_query); ``` Thanks very much
2011/06/28
[ "https://Stackoverflow.com/questions/6510985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/468908/" ]
``` $newArray = array_unique($yourArray); ``` This will create a new array only with unique values; excluding any duplicates.
No need to get PHP involved. Just `SELECT` using `GROUP BY`. ``` INSERT INTO subsalerts (memalertid, idMembers, emailid) SELECT memalertid, $idMembers, $emailid FROM memlist WHERE listID IN ($idList) AND emailyes = 1 GROUP BY memalertid; ```
6,510,985
I have the code below to query a table which retrieves arrays. The parameter $idList could have several values and may therefore produce duplicates. I am only interested in inserting one unique memalertid. Any advice on how to remove the duplicates would be much appreciated. ``` $sql = mysql_query("SELECT memalertid from memlist where listID IN ($idList) AND (emailyes = '1') "); while ($info = mysql_fetch_array($sql)){ $insert_query = "insert into subsalerts (memalertid, idMembers, emailid) VALUES('".$info['memalertid']."','$idMembers','$emailid')"; $insert_buffer = mysql_query($insert_query); ``` Thanks very much
2011/06/28
[ "https://Stackoverflow.com/questions/6510985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/468908/" ]
Simply use `SELECT DISTINCT` to select distinct rows. ``` SELECT DISTINCT memalertid FROM memlist WHERE listID IN ($idList) AND (emailyes = '1') ``` You could also `GROUP BY memalertid` instead. ``` SELECT memalertid FROM memlist WHERE listID IN ($idList) AND (emailyes = '1') GROUP BY memalertid ``` For more information: <http://dev.mysql.com/doc/refman/5.5/en/select.html>.
You can use [group by](http://dev.mysql.com/doc/refman/5.1/en/select.html) clause to group the results with the same id, so that you'll get only unique ids
6,510,985
I have the code below to query a table which retrieves arrays. The parameter $idList could have several values and may therefore produce duplicates. I am only interested in inserting one unique memalertid. Any advice on how to remove the duplicates would be much appreciated. ``` $sql = mysql_query("SELECT memalertid from memlist where listID IN ($idList) AND (emailyes = '1') "); while ($info = mysql_fetch_array($sql)){ $insert_query = "insert into subsalerts (memalertid, idMembers, emailid) VALUES('".$info['memalertid']."','$idMembers','$emailid')"; $insert_buffer = mysql_query($insert_query); ``` Thanks very much
2011/06/28
[ "https://Stackoverflow.com/questions/6510985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/468908/" ]
Simply use `SELECT DISTINCT` to select distinct rows. ``` SELECT DISTINCT memalertid FROM memlist WHERE listID IN ($idList) AND (emailyes = '1') ``` You could also `GROUP BY memalertid` instead. ``` SELECT memalertid FROM memlist WHERE listID IN ($idList) AND (emailyes = '1') GROUP BY memalertid ``` For more information: <http://dev.mysql.com/doc/refman/5.5/en/select.html>.
No need to get PHP involved. Just `SELECT` using `GROUP BY`. ``` INSERT INTO subsalerts (memalertid, idMembers, emailid) SELECT memalertid, $idMembers, $emailid FROM memlist WHERE listID IN ($idList) AND emailyes = 1 GROUP BY memalertid; ```
6,510,985
I have the code below to query a table which retrieves arrays. The parameter $idList could have several values and may therefore produce duplicates. I am only interested in inserting one unique memalertid. Any advice on how to remove the duplicates would be much appreciated. ``` $sql = mysql_query("SELECT memalertid from memlist where listID IN ($idList) AND (emailyes = '1') "); while ($info = mysql_fetch_array($sql)){ $insert_query = "insert into subsalerts (memalertid, idMembers, emailid) VALUES('".$info['memalertid']."','$idMembers','$emailid')"; $insert_buffer = mysql_query($insert_query); ``` Thanks very much
2011/06/28
[ "https://Stackoverflow.com/questions/6510985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/468908/" ]
You can use [group by](http://dev.mysql.com/doc/refman/5.1/en/select.html) clause to group the results with the same id, so that you'll get only unique ids
No need to get PHP involved. Just `SELECT` using `GROUP BY`. ``` INSERT INTO subsalerts (memalertid, idMembers, emailid) SELECT memalertid, $idMembers, $emailid FROM memlist WHERE listID IN ($idList) AND emailyes = 1 GROUP BY memalertid; ```
91,828
I have a (nonlinear) function which takes as input 4 parameters and produces a real number as output. It is quite complex to compute the function value given a set of parameters (as it requires a very big summation). I'd like to answer queries on this function efficiently so I was thinking of trying to use some interpolation methods. I have used Chebyshev polynomials to interpolate univariate functions, but I haven't been able to find (or understand) anything on interpolating multivariate functions. I'm not set on using Chebyshev polynomials, I have just had some exposure to them and know they tend to be efficient (in terms of # of necessary coefficients and interpolation error). I was wondering if anyone could give me (an engineer) any pointers for how to go about interpolating a multi-variate function? Simple examples or sample code would be awesome, but I'll take any attempts to explain how interpolation would work in higher dimensions, including (readable) references.
2011/12/15
[ "https://math.stackexchange.com/questions/91828", "https://math.stackexchange.com", "https://math.stackexchange.com/users/9420/" ]
Since nobody's answered yet, I throw this out there (I'm no expert in multivariate interpolation, hopefully someone with expertise will eventually weigh in). I imagine you've already looked at the [Wikipedia Article on Multivariate Interpolation](http://en.wikipedia.org/wiki/Multivariate_interpolation). There's a lot of stuff out there. However, if you just want a "quick fix", I'd go with some sort of linear regression. (1) Pick your favorite template function, say, $f(x,y,z,t) = Ax^2t+B\sin(y+z)+Cxyz$ (2) Plug-in some "known" values, so something like: * $w\_1 = f(x\_1,y\_1,z\_1,t\_1) = Ax\_1^2t\_1+B\sin(y\_1+z\_1)+Cx\_1y\_1z\_1$ * $w\_2 = f(x\_2,y\_2,z\_2,t\_2) = Ax\_2^2t\_2+B\sin(y\_2+z\_2)+Cx\_2y\_2z\_2$ * $w\_3 = f(x\_3,y\_3,z\_3,t\_3) = Ax\_3^2t\_3+B\sin(y\_3+z\_3)+Cx\_3y\_3z\_3$ * $w\_4 = f(x\_4,y\_4,z\_4,t\_4) = Ax\_4^2t\_4+B\sin(y\_4+z\_4)+Cx\_4y\_4z\_4$ (3) Translate to a linear system: $${\bf w} = \begin{bmatrix} w\_1 \\ w\_2 \\ w\_3 \\ w\_4 \end{bmatrix} = \begin{bmatrix} x\_1^2t\_1 & \sin(y\_1+z\_1) & x\_1y\_1z\_1 \\ x\_2^2t\_2 & \sin(y\_2+z\_2) & x\_2y\_2z\_2 \\ x\_3^2t\_3 & \sin(y\_3+z\_3) & x\_3y\_3z\_3 \\ x\_4^2t\_4 & \sin(y\_4+z\_4) & x\_4y\_4z\_4 \end{bmatrix} \begin{bmatrix} A \\ B \\ C \end{bmatrix} = M {\bf x} $$ (4) Solve the [Normal Equations](http://en.wikipedia.org/wiki/Normal_equations): $M^T M {\bf x} = M^T {\bf w}$ to find the solution which best fits your data. Of course, if you pick a general enough function $f$ to begin with, the system from (3) will be consistent and you'll be able to solve ${\bf w} = M{\bf x}$ directly. I imagine finding error bounds is quite daunting. But if you used a general multivariate polynomial of fairly high degree, is ought to do the trick. Even something like: $f(x,y,z,t) = Ax^3+By^3+Cz^3+Dt^3+Ex^2y+Fxy^2+Gxyz+\cdots+Hx+Iy+Jz+K$ ought to do a decent job.
I would suggest taking a look at [Moving Least Squares](http://en.wikipedia.org/wiki/Moving_least_squares) (MLS), which can generate quite smooth interpolators using low-order functions. One benefit of MLS is that it can easily work with scattered data, which means you can sample your expensive function at relevant locations only. If you want to perform uniform sampling of your function you can look at the simplicial lattice described in [1], which is a nice alternative to the standard regular grid. [1] [Fast High-Dimensional Filtering Using the Permutohedral Lattice](http://graphics.stanford.edu/papers/permutohedral/). Adams et al. Eurographics 2010.
71,323,490
I am generating class Objects and putting them into std::vector. Before adding, I need to check if they intersect with the already generated objects. As I plan to have millions of them, I need to parallelize this function as it takes a lot of time (The function must check each new object against all previously generated). Unfortunately, the speed increase is not significant. The profiler also shows very low efficiency (all overhead). Any advise would be appreciated. ``` bool Generator::_check_cube (std::vector<Cube> &cubes, const cube &cube) { auto ptr_cube = &cube; auto npol = cubes.size(); auto ptr_cubes = cubes.data(); const auto nthreads = omp_get_max_threads(); bool check = false; #pragma omp parallel shared (ptr_cube, ptr_cubes, npol, check) { #pragma omp single nowait { const auto batch_size = npol / nthreads; for (int32_t i = 0; i < nthreads; i++) { const auto bstart = batch_size * i; const auto bend = ((bstart + batch_size) > npol) ? npol : bstart + batch_size; #pragma omp task firstprivate(i, bstart, bend) shared (check) { struct bd bd1{}, bd2{}; bd1 = allocate_bd(); bd2 = allocate_bd(); for (auto j = bstart; j < bend; j++) { bool loc_check; #pragma omp atomic read loc_check = check; if (loc_check) break; if (ptr_cube->cube_intersecting(ptr_cubes[j], &bd1, &bd2)) { #pragma omp atomic write check = true; break; } } free_bd(&bd1); free_bd(&bd2); } } } } return check; } ``` UPDATE: The Cube is actually made of smaller objects Cuboids, each of them have size (L, W, H), position coordinates and rotation. The intersect function: ``` bool Cube::cube_intersecting(Cube &other, struct bd *bd1, struct bd *bd2) const { const auto nom = number_of_cuboids(); const auto onom = other.number_of_cuboids(); for (int32_t i = 0; i < nom; i++) { get_mcoord(i, bd1); for (int32_t j = 0; j < onom; j++) { other.get_mcoord(j, bd2); if (check_gjk_intersection(bd1, bd2)) { return true; } } } return false; } ``` //get\_mcoord calculates vertices of the cuboids ``` void Cube::get_mcoord(int32_t index, struct bd *bd) const { for (int32_t i = 0; i < 8; i++) { for (int32_t j = 0; j < 3; j++) { bd->coord[i][j] = _cuboids[index].get_coord(i)[j]; } } } inline struct bd allocate_bd() { struct bd bd{}; bd.numpoints = 8; bd.coord = (double **) malloc(8 * sizeof(double *)); for (int32_t i = 0; i < 8; i++) { bd.coord[i] = (double *) malloc(3 * sizeof(double)); } return bd; } ``` Typical values: npol > 1 million, threads 32, and each npol Cube consists of 1 - 3 smaller cuboids which are directly checked against other if intersect. [![enter image description here](https://i.stack.imgur.com/VA7XC.png)](https://i.stack.imgur.com/VA7XC.png)
2022/03/02
[ "https://Stackoverflow.com/questions/71323490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12948072/" ]
> > `Starting ChromeDriver 99.0.4844.51` > > > > > `Current browser version is 98.0.4758.102` > > > Your chrome driver is for chrome version, which is not out yet. You have several solutions: * You can download actual ChromeDriver 98.0.4758.102 from [here](https://chromedriver.chromium.org/downloads) and use it. * You can download **Chrome Beta** (currently 99.0.4844.51) or **Chrome Dev** (currently 100.0.4896.12), where you have access to newer versions. * If you are using **WebDriverManager** from `io.github.bonigarcia`, you have to set correctly browserVersion and driverVersion: ``` WebDriverManager.chromedriver().browserVersion("98.0.4758.102").setup(); WebDriverManager.chromedriver().driverVersion("98.0.4758.102").setup(); ```
This error message... ``` Starting ChromeDriver 99.0.4844.51 (d537ec02474b5afe23684e7963d538896c63ac77-refs/branch-heads/4844@{#875}) on port 59895 . Exception in thread "Thread-4" org.openqa.selenium.SessionNotCreatedException: Could not start a new session. Response code 500. Message: session not created: This version of ChromeDriver only supports Chrome version 99 Current browser version is 98.0.4758.102 with binary path C:\Program Files\Google\Chrome\Application\chrome.exe ``` ...implies that the [ChromeDriver](https://stackoverflow.com/a/59927747/7429447) was unable to initiate/spawn a new *Browsing Context* i.e. [google-chrome](/questions/tagged/google-chrome "show questions tagged 'google-chrome'") session. Your main issue is the **incompatibility** between the version of the binaries you are using as follows: * You are using *chrome=98.0* * Release Notes of [*ChromeDriver v98.0*](https://chromedriver.storage.googleapis.com/index.html?path=98.0.4758.48/) clearly mentions the following : > > Supports Chrome version 98 > > > * But you are using *chromedriver=99.0* * Release Notes of [*chromedriver=99.0*](https://chromedriver.storage.googleapis.com/99.0.4844.51/notes.txt) clearly mentions the following : > > Supports Chrome version 99 > > > So there is a clear mismatch between *chromedriver=91.0* and the *chrome=96.0.4664.45* --- Solution -------- Ensure that: * *ChromeDriver* is updated to current [ChromeDriver v99.0](https://chromedriver.storage.googleapis.com/index.html?path=99.0.4844.51/) level. * *Chrome Browser* is updated to current *chrome=99* (as per [chromedriver=99.0.4844.51 release notes](https://chromedriver.storage.googleapis.com/99.0.4844.51/notes.txt)). ![Chrome v99](https://i.stack.imgur.com/52g1y.png)
37,958,457
I have a problem. I need to use the first row of the **txt** as my string and then look in the same **txt** the occurrences and print the number, but I have a problem, for example; if my **txt** is like: `wordwordword` and my string is word, it only counts the first word, it does´t print the counter: 3, print the counter: 1. How can I solve this? Demo.java --------- ``` import java.io.*; import java.util.*; public class Demo { public static void main(String args[]) throws java.io.IOException { BufferedReader in = new BufferedReader(new FileReader("c.txt")); Scanner sc = new Scanner(System.in); String s1; s1 = in.readLine(); String Word; Word = s1; String line = in.readLine(); int count = 0; String s[]; do { s = line.split(" "); for (int i = 0; i < s.length; i++) { String a = s[i]; if (a.contains(Word)) count++; } line = in.readLine(); } while (line != null); System.out.println("first line: " + s1); System.out.print("There are " + count + " occurences of " + Word + " in "); java.io.File file = new java.io.File("c.txt"); Scanner input = new Scanner(file); while (input.hasNext()) { String word = input.nextLine(); System.out.print(word); } } } ``` **txt:** > > GAGCATAGA > CGAGAGCATATAGGAGCATATCTTGAGCATACCGAGCATATGAGCATAATATACCCGTCCGAGAGCATACACTGAGCATAAAGGAGCATAGAGCATACAACTGAGAATGGAGCATAGAGCATACGGAGCATAAGAGCATAGAGCATAGAGCATACGGAGCATAGAGCATAGAGCATAGCCGATGGGGAGCATACTGTTACGTAGAGCATACGAGCATAGCGCAAGAGCATAAAGAGCATAGAGCATATGAGCATATAGAGCATACGAGCATACAAGATCCGGGGAGCATAGCGAGGTAATAGTCGGAGCATAGAGCATAGAGCATATGAGCATACGGGAGCATAAATGAGCATAAGGAGCATAGAGCATAGAGCATAAGAGCATATCTCGAGCATAAGCGAGCATAGAGCATAAAAATCAATCACGTTGAGCATATGAGCATAAATACTGGAGCATAGATCGAGCATAGTAGAGCATACGAGCATAGAGCATAGGAGCATAAGAGCATATGAGCATATTGAGCATATGAAGGAGCATAAAAATGAGCATAAGGAGCATACCATCGTTGAGCATAATCCGAGCATAGGAGCATAGAATAGAGCATAGACAGGAGTTTTTGGAGCATATGAGCATAGAGCATAGAGCATAGAGCATAGAGCATAGAGCATAGAGCATATTCGAGCATAATTGAGCATATGAGCATAGAGCATATGGAGCATAGGCTGAGCATACCGAGCATAGCAATTAGAGCATAATCCTAGGGAGCATAGGAGCATACGTGAGCATAGCTGAGCATAGAGCATAGAGCATAGTGTTCGAGCATAGAGCATAGAGCATATGAGCATAGAGCATACTTGAGCATATGGTACGAGCATAGGAGCATATAAGGAGGAGCATATCGAGCATAGAGCATAGGCCTGGCCAGAGCATATAACCGAGCATAGGGTTGGAGCATAAGGCCGGAGCATACGAGCATACGAGCATATGAAATGAGCATAATGTGAGCATAGAGCATATCGAGCATATGAGCATAGGAGCATA > > > in this example with the txt, the program should print the counter= 21
2016/06/22
[ "https://Stackoverflow.com/questions/37958457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4917789/" ]
You are asking for one line of leading context by using the `-B1` option. This means grep will display both the line which matched and the line directly before it. Each match will be separated by `--` on a line by itself as shown below: ``` $ man grep | grep -B1 context -A num, --after-context=num Print num lines of trailing context after each match. See also -- -B num, --before-context=num Print num lines of leading context before each match. See also -- -C[num, --context=num] Print num lines of leading and trailing context surrounding each -- --context[=num] Print num lines of leading and trailing context. The default is ``` The reason you aren't seeing `--` between every match is that the context is only displayed above a sequence of consecutive matches. So see the following example: ``` seq 13 | grep -B1 1 1 -- 9 10 11 12 13 ``` The seq command produces all the numbers between 1 and 13. Only the first line and the lines from 10 on contain a 1, so you see the 1 in its own group, then `--`, then the one line context, then the group of consecutive matching lines.
`GREP_COLORS` section of the grep manpage says : > > Specifies the colors and other attributes used to highlight various > parts of the output. Its value is a colon-separated list > of capabilities that defaults to > ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and > ne boolean capabilities omitted (i.e., false). > > > and > > se=36 > SGR substring for separators that are inserted between > selected line fields (:), between context line fields, (-), and > between groups of adjacent lines when nonzero context is > specified (--). The default is a cyan text foreground over the > terminal's default background. > > > Consider file sample.txt : ``` $cat sample.txt ABBB AAB AAB S S S AABB ABAA BAA CCC $grep -B2 'AAB' sample.txt ABBB AAB AAB -- S S AABB ``` Here `--` is the way of `grep` to tell you that `AAB` before `--` and `S` after `--` are not adjacent lines in the actual file.
50,027,640
I'm very new to AS3 and I'm trying to learn by experimenting in flash, by making a simple 2D farming game with very simple code. I've made one crop field out of 6 that works, which is a movieclip with different frames for each fruit growing. For example, frame 1-5 is a strawberry growing where frame 5 is when it's ready to be picked, and then 6-10 is of carrots, etc Is there a way for me to make it so that I don't have to write the exact same code for the next crop field, and instead change the variables in this code depending on which crop field you click on? Here's an example of the code ``` if (field1.currentFrame == 1) { field1.nextFrame(); infoText.text = "You've watered the crop. Let's wait and see how it turns out!"; function plantStrawberry():void { field1.nextFrame(); if (field1.currentFrame == 5) { clearInterval(strawberryInterval); } } var strawberryInterval = setInterval(plantStrawberry,5000); } ``` pls no judgerino, as said, I'm very new to AS3, lol.
2018/04/25
[ "https://Stackoverflow.com/questions/50027640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3492677/" ]
There are a few ways to go about being DRY (don't repeat yourself) with your code in this scenario. The best way, would be to learn to use classes. Classes are blueprints, and are made for these very scenarios. Here is an example of a simple class to do what you'd like. In Flash/Animate, go to *file*, then *new*, then '*ActionScript 3.0 Class*' - give it a name of `Crop`. In the document that comes up, there should be some basic boilerplate code. Everything should wrapped in a package. The package tells flash where to find this class - so this example, leave it as is (just `package {`) and save this file in the same folder as your `.fla`. All functions need to be wrapped in a class declaration, this should be generated for you based off the name you put in (`Crop`). Next you'll see one function, that has the same name as the class. This is called a constructor, and this function runs whenever you create a new instance of this class. Since classes are blueprints, you create instances of them that are objects - those objects then get all the code you put in this class. So, to start, you should have this: ``` package { public class Crop { public function Crop() { // constructor code } } } ``` Let's go ahead and put your code in. See the code comments for details: ``` package { //imports should go here import flash.display.MovieClip; import flash.events.Event; import flash.events.TimerEvent; import flash.utils.Timer; //lets make this class extend MovieClip - that means it will be a MovieClip in addition to everything else you add below public class Crop extends MovieClip { //instead of setInterval, use a timer - it's easier to manage and cleanup //in class files, variables and functions have access modifiers, that's what the public and private words are about //private means only this class can ever use the var/function private var timer:Timer; public function Crop() { //initialize the timer - have it tick every 5 seconds, and repeat 4 times (to move you from frame 1 - 5) timer = new Timer(5000, 4); //listen for the TIMER event (which is the tick) and call the function 'grow' when the timer ticks timer.addEventListener(TimerEvent.TIMER, grow); } //a function that starts the timer ticking public function startGrowing():void { timer.start(); } //this function is called every timer tick. private function grow(e:Event):void { this.nextFrame(); //go to the next frame of your crop } } } ``` Save the file. Now that you have this class, you need to attach it to your library assets so they all get this functionality. In the library panel, for each of your crop objects, right click (or ctrl+click on Mac) and go to `properties`. In the properties, click `advanced`, and give it a unique class name (for instance `Strawberry`). Then in the base class field, put `Crop` (the class we just made). Repeat for the others. [![enter image description here](https://i.stack.imgur.com/jgmVO.jpg)](https://i.stack.imgur.com/jgmVO.jpg) Now on your timeline, when you want a crop to start growing, you can do: ``` field1.startGrowing(); //assuming your instance `field1` is one of the crops that you assigned the base class `Crop` to ``` Hopefully this gives an entry point into the power of classes. You can add more functionality into this one and it automatically apply to all the crops you attached it to.
Although [**BFAT**'s tutorial](https://stackoverflow.com/a/50028490/4687633) is absolutely correct, it is not the only way to do things, moreover, if you ever move from Flash and AS3 to something else, or even try **Starling** (a framework that allows to build fast and non-laggy mobile applications in Flash/AS3), you'll find that concept not applicable. It is very Flash-y and I applause to it though. Instead of making each field subclass the abstract (means, it is never instantiated by itself) **Crop** class, you can make the **Crop** class take 1 of these 6 fields as an argument on creation (or later). Basically, you tell "I want to make crop field with wheat graphics". So, let me redo that class a bit. ``` package { // Imports. import flash.display.Sprite; import flash.display.MovieClip; import flash.utils.Timer; import flash.events.Event; import flash.events.TimerEvent; public class Crop extends Sprite { // I agree with the use of Timer. private var timer:Timer; // Visuals go here. private var field:MovieClip; // Class constructor. public function Crop(FieldClass:Class) { // With "new" keyword you can omit () // if there are no mandatory arguments. field = new FieldClass; field.stop(); addChild(field); } // A function that starts the timer ticking. public function startGrowing():void { timer = new Timer(5000, 4); timer.addEventListener(TimerEvent.TIMER, grow); timer.start(); } // This function is called every timer tick. private function grow(e:Event):void { // Command the graphics to go to the next frame. field.nextFrame(); } } } ``` Then, the usage. When you create fields, you need to set AS3 classes to them to have access, leaving base class as is, Flash will automatically set it to non-specific **MovieClip**. Lessay, you have **crops.Wheat** field and **crops.Barley** field. ``` import Crop; import crops.Wheat; import crops.Barley; var W:Crop = new Crop(Wheat); var B:Crop = new Crop(Barley); addChild(W); addChild(B); B.x = 100; W.startGrowing(); B.startGrowing(); ```
25,987,405
I have 2 Forms, in Form1 , there are a lot of transaction to be done, so i have used the BackgroundWorker. so during the action to be taken i want the form2 to be opened and shows the progressbar ( the progress of the actions ) so I have done like this: This is Form1 ``` public partial class Form1 : Form { Form2 form2 = new Form2(); public Form1() { InitializeComponent(); Shown += new EventHandler(Form1_Shown); // To report progress from the background worker we need to set this property backgroundWorker1.WorkerReportsProgress = true; // This event will be raised on the worker thread when the worker starts backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork); // This event will be raised when we call ReportProgress backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged); } void Form1_Shown(object sender, EventArgs e) { form2.Show(); // Start the background worker backgroundWorker1.RunWorkerAsync(); } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { // Your background task goes here for (int i = 0; i <= 100; i++) { // Report progress to 'UI' thread backgroundWorker1.ReportProgress(i); // Simulate long task System.Threading.Thread.Sleep(100); } form2.Close(); } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { // The progress percentage is a property of e form2.progressBar1.Value = e.ProgressPercentage; } } ``` I have a Progressbar in form2 which its modifier is public. the problem is that when the actions would be accompilshed the form2 ( which contans the progress bar) should be closed , So i used ``` form2.Close(); ``` but i get this error message ``` Cross-thread operation not valid: Control 'Form2' accessed from a thread other than the thread it was created on ``` how can i solve this problem?
2014/09/23
[ "https://Stackoverflow.com/questions/25987405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1379478/" ]
Use delegate to make it thread safe ``` if(form2.InvokeRequired) { form2.Invoke(new MethodInvoker(delegate { form2.Close() })); } ```
The problem is the control just can be accessed by the thread that create it. Check this: <http://msdn.microsoft.com/en-us/library/ms171728.aspx> And this : [Cross-thread operation not valid: Control 'Form2' accessed from a thread other than the thread it was created on](https://stackoverflow.com/questions/25987405/cross-thread-operation-not-valid-control-form2-accessed-from-a-thread-other-t/25987470#25987470)
50,459,454
I am trying to implement a generic single linked list. So far I have everything done correctly but I cannot get my search function to work properly. It should print "yes"in the output but nothing happens. Here is my code: ``` #ifndef LinkedList_hpp #define LinkedList_hpp #include <iostream> template<class T> struct Node { T data; Node<T>* next; }; template<class T> class SingleLinkedList { private: Node<T>* head; Node<T>* tail; public: SingleLinkedList() { head = nullptr; tail = nullptr; } void createNode(const T& theData) { Node<T>* temp = new Node<T>; temp->data = theData; temp->next = nullptr; if(head == nullptr) { head = temp; tail = temp; temp = nullptr; } else { tail->next = temp; tail = temp; } } void display() { Node<T>* temp = new Node<T>; temp = head; while(temp != nullptr) { std::cout << temp->data << "\t"; temp = temp->next; } } void insert_start(const T& theData) { Node<T>* temp = new Node<T>; temp->data = theData; temp->next = head; head = temp; } void insert_position(int pos, const T& theData) { Node<T>* previous = new Node<T>; Node<T>* current = new Node<T>; Node<T>* temp = new Node<T>; current = head; for(int i = 1; i < pos; i++) { previous = current; current = current->next; } temp->data = theData; previous->next = temp; temp->next = current; } void delete_first() { Node<T>* temp = new Node<T>; temp = head; head = head->next; delete temp; } void delete_last() { Node<T>* previous = new Node<T>; Node<T>* current = new Node<T>; current = head; while(current->next != nullptr) { previous = current; current = current->next; } tail = previous; previous->next = nullptr; delete current; } void delete_position(int pos) { Node<T>* previous = new Node<T>; Node<T>* current = new Node<T>; current = head; for(int i = 1; i < pos; i++) { previous = current; current = current->next; } previous->next = current->next; } bool search(Node<T>* head, int x) { struct Node<T>* current = head; while (current != NULL) { if (current->data == x) return true; current = current->next; } return false; } }; #endif /* LinkedList_hpp */ ``` Here is the main.cpp: ``` #include <iostream> #include "LinkedList.hpp" int main(int argc, const char * argv[]) { SingleLinkedList<int> obj; obj.createNode(2); obj.createNode(4); obj.createNode(6); obj.createNode(8); obj.createNode(10); std::cout<<"\n--------------------------------------------------\n"; std::cout<<"---------------Displaying All nodes---------------"; std::cout<<"\n--------------------------------------------------\n"; obj.display(); std::cout<<"\n--------------------------------------------------\n"; std::cout<<"-----------------Inserting At End-----------------"; std::cout<<"\n--------------------------------------------------\n"; obj.createNode(55); obj.display(); std::cout<<"\n--------------------------------------------------\n"; std::cout<<"----------------Inserting At Start----------------"; std::cout<<"\n--------------------------------------------------\n"; obj.insert_start(50); obj.display(); std::cout<<"\n--------------------------------------------------\n"; std::cout<<"-------------Inserting At Particular--------------"; std::cout<<"\n--------------------------------------------------\n"; obj.insert_position(5,60); obj.display(); std::cout<<"\n--------------------------------------------------\n"; std::cout<<"----------------Deleting At Start-----------------"; std::cout<<"\n--------------------------------------------------\n"; obj.delete_first(); obj.display(); std::cout<<"\n--------------------------------------------------\n"; std::cout<<"-----------------Deleing At End-------------------"; std::cout<<"\n--------------------------------------------------\n"; obj.delete_last(); obj.display(); std::cout<<"\n--------------------------------------------------\n"; std::cout<<"--------------Deleting At Particular--------------"; std::cout<<"\n--------------------------------------------------\n"; obj.delete_position(4); obj.display(); std::cout<<"\n--------------------------------------------------\n"; system("pause"); Node<int>* head = NULL; obj.search(head, 8) ? printf("Yes") : printf("No"); return 0; } ``` You can see that I search for the value 8 and it should print yes since 8 is still in the linked list.
2018/05/22
[ "https://Stackoverflow.com/questions/50459454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This is your `search` function: ``` bool search(Node<T>* head, int x) { struct Node<T>* current = head; while (current != NULL) { if (current->data == x) return true; current = current->next; } return false; } ``` It uses the argument `head` passed into as the first argument, instead of the `SingleLinkedList<T>::head` member variable. And since you call it passing a null pointer as the first argument, you will not find anything. Simple fix: Remove the first argument from the `search` function: ``` bool search(T x) { ... } ``` As you see I also changed the argument of the value you search for to the template type.
This line: ``` Node<int>* head = NULL; ``` mean you are passing NULL into your search method. Your search method should not take a head parameter at all - `head` is already a member of your class. Also note: you have lots of memory leaks like this: ``` Node<T>* temp = new Node<T>; temp = head; ``` You don't need to allocate memory for a pointer that you are just going to overwrite with a new value, just use ``` Node<T>* temp = head; ```
7,912,335
I have a page I have to update, it has 3 frames (top bar, side bar and main content. If i click something in the main content frame i want to update a list in the side bar frame. how do i do this (i use jquery or javascript for button clicks).
2011/10/27
[ "https://Stackoverflow.com/questions/7912335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/930584/" ]
*Q: multiplexing allows to reduce overhead of creating new connections to FCGI clients effectively interweaving requests chunks* A: True. But keep-alive is also reducing new connections. *Q: and at the same time enabling "keep-alive" model to connection* A: Multiplexing is not required for keep-alive. *Q: Latter allows sending several requests over a single connection* A: keep-alive allows several requests after each other. Multiplexing allows several requests in parallel. There is no widely used FastCGI capable web server supporting multiplexing. But nginx supports FastCGI keep-alive. FastCGI multiplexing is generally a bad idea, because FastCGI doesn't support flow control. That means: If a FastCGI backend sends data, but the http client can't receive data fast enough, the web server has to save all those data, until they can be sent to the client. When not using multiplexing, the web server could just not read data from the fastcgi backend if the http client is too slow effectively backlogging the fastcgi backend. When using multiplexing the web server needs to read all data from the fastcgi backend, even though one of the clients isn't receiving data fast enough.
I don't know if some server implement FASTCGI multiplexing (which I believe you understood correctly, but the details are in the FASTCTI protocol specifications), and I would not bother. You will very probably use FASTCGI thru an [existing FASTCGI library](http://www.fastcgi.com/drupal/node/5) (e.g. [Ocamlnet](http://projects.camlcity.org/projects/ocamlnet.html) if you code in Ocaml, etc.). And that library would do the multiplexing, if it does it. From your point of view (of that library user) you should not really care, unless you are coding such a library yourself. If FASTCGI multiplexing bothers you, you might use the [SCGI](http://en.wikipedia.org/wiki/Simple_Common_Gateway_Interface) protocol, which offers similar functionality, but is simpler, a bit less efficient, and non-multiplexing.
7,912,335
I have a page I have to update, it has 3 frames (top bar, side bar and main content. If i click something in the main content frame i want to update a list in the side bar frame. how do i do this (i use jquery or javascript for button clicks).
2011/10/27
[ "https://Stackoverflow.com/questions/7912335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/930584/" ]
Trying to state the answers above more precisely (and correct some parts)... > > *multiplexing allows to reduce overhead of creating new connections to FCGI clients effectively interweaving requests chunks* > > > In opposite to keep-alive it reduces new connections drastically, especially on high-load servers or if micro-servicing (a lot of micro requests) in usage. Futhermore it is almost required in case of balancing across network (so one cannot use unix-sockets anymore and the connection buildup process gaining more and more priority). > > *and at the same time enabling "keep-alive" model to connection* > > > Although the multiplexing is not required for keep-alive, but keep-alive is almost required for multiplexing (otherwise it would make little sense). > > *I've found there's no server that implements FCGI multiplexing* > > > There is few servers that supports multiplexing out of the box, but... I saw already several modules of other devs and I have own fcgi-module for nginx (as replacement) that supports FastCGI multiplex requests. It can show the real performance increase in the practice, especially if the upstreams are connected over the network. If someone needs it, I will try to find time and make it available on github etc. > > [*from answer above*] FastCGI multiplexing is generally a bad idea, because FastCGI doesn't support flow control. That means: If a FastCGI backend sends data, but the http client can't receive data fast enough, the web server has to save all those data, until they can be sent to the client. > > > This is not true. Normally the FastCGI handlers are fully asynchronous, pool of workers is separated from the delivering workers, etc. So each chunk gets a request-id, so if two or more upstream workers write to single connection simultaneously, the chunks that nginx will get are just smaller. That is the single cons. As regards the "the web server has to save all those data", it does this in any case (regardless multiplexing used or not), because otherwise one can get out-of-memory situation if too many pending data available for response. So either the backend should produce fewer data (or be thwarted) or the web-server should receive it as soon as possible and transmit it to client or save it to some interim storage (and for example nginx does this if pending data size exceeds the values configured with *fastcgi\_buffer\_size* and *fastcgi\_buffers* directives). > > [*from answer above*] When using multiplexing the web server needs to read all data from the fastcgi backend, even though one of the clients isn't receiving data fast enough. > > > Also this is false. The web-server has to read only the single chunk of response to the end, and good worker pools have "intelligent" handling, so automatically sends the chunks to the web-server as soon as possible (means if it gets available), so if multiple content-providers write to so-called "reflected" channels of the same real connection, the pending packets will be separated and chunks received from nginx as soon as the response data is available. Thereby almost only the throughput of the connection is crucial, and it does not matter at all how fast the clients will receive the data. And again, multiplexing saves vastly the time of the connection buildup, so reduces number of pending requests as well as the common request execution time (transaction rate).
I don't know if some server implement FASTCGI multiplexing (which I believe you understood correctly, but the details are in the FASTCTI protocol specifications), and I would not bother. You will very probably use FASTCGI thru an [existing FASTCGI library](http://www.fastcgi.com/drupal/node/5) (e.g. [Ocamlnet](http://projects.camlcity.org/projects/ocamlnet.html) if you code in Ocaml, etc.). And that library would do the multiplexing, if it does it. From your point of view (of that library user) you should not really care, unless you are coding such a library yourself. If FASTCGI multiplexing bothers you, you might use the [SCGI](http://en.wikipedia.org/wiki/Simple_Common_Gateway_Interface) protocol, which offers similar functionality, but is simpler, a bit less efficient, and non-multiplexing.
12,569,018
I am studying python, and although I think I get the whole concept and notion of Python, today I stumbled upon a piece of code that I did not fully understand: Say I have a class that is supposed to define Circles but lacks a body: ``` class Circle(): pass ``` Since I have not defined any attributes, how can I do this: ``` my_circle = Circle() my_circle.radius = 12 ``` The weird part is that Python accepts the above statement. I don't understand why Python doesn't raise an `undefined name error`. I do understand that via *dynamic typing* I just bind variables to objects whenever I want, but shouldn't an attribute `radius` exist in the `Circle` class to allow me to do this? **EDIT**: Lots of wonderful information in your answers! **Thank you everyone for all those fantastic answers!** It's a pity I only get to mark one as an answer.
2012/09/24
[ "https://Stackoverflow.com/questions/12569018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1426969/" ]
It creates a `radius` data member of `my_circle`. If you had asked it for `my_circle.radius` it would have thrown an exception: ``` >>> print my_circle.radius # AttributeError ``` Interestingly, this does not change the class; just that one instance. So: ``` >>> my_circle = Circle() >>> my_circle.radius = 5 >>> my_other_circle = Circle() >>> print my_other_circle.radius # AttributeError ```
How to prevent new attributes creation ? ======================================== Using class ----------- To control the creation of new attributes, you can overwrite the `__setattr__` method. It will be called every time `my_obj.x = 123` is called. See the [documentation](https://docs.python.org/3/reference/datamodel.html#object.__setattr__): ```py class A: def __init__(self): # Call object.__setattr__ to bypass the attribute checking super().__setattr__('x', 123) def __setattr__(self, name, value): # Cannot create new attributes if not hasattr(self, name): raise AttributeError('Cannot set new attributes') # Can update existing attributes super().__setattr__(name, value) a = A() a.x = 123 # Allowed a.y = 456 # raise AttributeError ``` Note that users can still bypass the checking if they call directly `object.__setattr__(a, 'attr_name', attr_value)`. Using dataclass --------------- With `dataclasses`, you can forbid the creation of new attributes with `frozen=True`. It will also prevent existing attributes to be updated. ``` @dataclasses.dataclass(frozen=True) class A: x: int a = A(x=123) a.y = 123 # Raise FrozenInstanceError a.x = 123 # Raise FrozenInstanceError ``` Note: `dataclasses.FrozenInstanceError` is a subclass of AttributeError
12,569,018
I am studying python, and although I think I get the whole concept and notion of Python, today I stumbled upon a piece of code that I did not fully understand: Say I have a class that is supposed to define Circles but lacks a body: ``` class Circle(): pass ``` Since I have not defined any attributes, how can I do this: ``` my_circle = Circle() my_circle.radius = 12 ``` The weird part is that Python accepts the above statement. I don't understand why Python doesn't raise an `undefined name error`. I do understand that via *dynamic typing* I just bind variables to objects whenever I want, but shouldn't an attribute `radius` exist in the `Circle` class to allow me to do this? **EDIT**: Lots of wonderful information in your answers! **Thank you everyone for all those fantastic answers!** It's a pity I only get to mark one as an answer.
2012/09/24
[ "https://Stackoverflow.com/questions/12569018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1426969/" ]
It creates a `radius` data member of `my_circle`. If you had asked it for `my_circle.radius` it would have thrown an exception: ``` >>> print my_circle.radius # AttributeError ``` Interestingly, this does not change the class; just that one instance. So: ``` >>> my_circle = Circle() >>> my_circle.radius = 5 >>> my_other_circle = Circle() >>> print my_other_circle.radius # AttributeError ```
There are two types of attributes in Python - `Class Data Attributes` and `Instance Data Attributes`. Python gives you flexibility of creating `Data Attributes` on the fly. Since an instance data attribute is related to an instance, you can also do that in `__init__` method or you can do it after you have created your instance.. ``` class Demo(object): classAttr = 30 def __init__(self): self.inInit = 10 demo = Demo() demo.outInit = 20 Demo.new_class_attr = 45; # You can also create class attribute here. print demo.classAttr # Can access it del demo.classAttr # Cannot do this.. Should delete only through class demo.classAttr = 67 # creates an instance attribute for this instance. del demo.classAttr # Now OK. print Demo.classAttr ``` So, you see that we have created two instance attributes, one inside `__init__` and one outside, after instance is created.. But a difference is that, the instance attribute created inside `__init__` will be set for all the instances, while if created outside, you can have different instance attributes for different isntances.. This is unlike Java, where each Instance of a Class have same set of Instance Variables.. * NOTE: - While you can access a class attribute through an instance, you cannot delete it.. Also, if you try to modify a class attribute through an instance, you actually create an instance attribute which shadows the class attribute..
12,569,018
I am studying python, and although I think I get the whole concept and notion of Python, today I stumbled upon a piece of code that I did not fully understand: Say I have a class that is supposed to define Circles but lacks a body: ``` class Circle(): pass ``` Since I have not defined any attributes, how can I do this: ``` my_circle = Circle() my_circle.radius = 12 ``` The weird part is that Python accepts the above statement. I don't understand why Python doesn't raise an `undefined name error`. I do understand that via *dynamic typing* I just bind variables to objects whenever I want, but shouldn't an attribute `radius` exist in the `Circle` class to allow me to do this? **EDIT**: Lots of wonderful information in your answers! **Thank you everyone for all those fantastic answers!** It's a pity I only get to mark one as an answer.
2012/09/24
[ "https://Stackoverflow.com/questions/12569018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1426969/" ]
To add to [Conchylicultor's answer](https://stackoverflow.com/a/59711821/1719931), Python 3.10 added a new parameter to `dataclass`. The `slots` parameter will create the `__slots__` attribute in the class, preventing creation of new attributes outside of `__init__`, but allowing assignments to existing attributes. If `slots=True`, assigning to an attribute that was not defined will throw an `AttributeError`. Here is an example with `slots` and with `frozen`: ```py from dataclasses import dataclass @dataclass class Data: x:float=0 y:float=0 @dataclass(frozen=True) class DataFrozen: x:float=0 y:float=0 @dataclass(slots=True) class DataSlots: x:float=0 y:float=0 p = Data(1,2) p.x = 5 # ok p.z = 8 # ok p = DataFrozen(1,2) p.x = 5 # FrozenInstanceError p.z = 8 # FrozenInstanceError p = DataSlots(1,2) p.x = 5 # ok p.z = 8 # AttributeError ```
As delnan said, you can obtain this behavior with the `__slots__` attribute. But the fact that it is a way to save memory space and access type does not discard the fact that it is (also) a/the mean to disable dynamic attributes. Disabling dynamic attributes is a reasonable thing to do, if only to prevent subtle bugs due to spelling mistakes. "Testing and discipline" is fine but relying on automated validation is certainly not wrong either – and not necessarily unpythonic either. Also, since the `attrs` library reached version 16 in 2016 (obviously way after the original question and answers), creating a closed class with slots has never been easier. ``` >>> import attr ... ... @attr.s(slots=True) ... class Circle: ... radius = attr.ib() ... ... f = Circle(radius=2) ... f.color = 'red' AttributeError: 'Circle' object has no attribute 'color' ```
12,569,018
I am studying python, and although I think I get the whole concept and notion of Python, today I stumbled upon a piece of code that I did not fully understand: Say I have a class that is supposed to define Circles but lacks a body: ``` class Circle(): pass ``` Since I have not defined any attributes, how can I do this: ``` my_circle = Circle() my_circle.radius = 12 ``` The weird part is that Python accepts the above statement. I don't understand why Python doesn't raise an `undefined name error`. I do understand that via *dynamic typing* I just bind variables to objects whenever I want, but shouldn't an attribute `radius` exist in the `Circle` class to allow me to do this? **EDIT**: Lots of wonderful information in your answers! **Thank you everyone for all those fantastic answers!** It's a pity I only get to mark one as an answer.
2012/09/24
[ "https://Stackoverflow.com/questions/12569018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1426969/" ]
Just to clarify some misunderstandings in the discussions here. This code: ``` class Foo(object): def __init__(self, bar): self.bar = bar foo = Foo(5) ``` And this code: ``` class Foo(object): pass foo = Foo() foo.bar = 5 ``` is *exactly equivalent*. There really is no difference. It does exactly the same thing. This difference is that in the first case it's encapsulated and it's clear that the bar attribute is a normal part of Foo-type objects. In the second case it is not clear that this is so. In the first case you can not create a Foo object that doesn't have the bar attribute (well, you probably can, but not easily), in the second case the Foo objects will not have a bar attribute unless you set it. So although the code is programatically equivalent, it's used in different cases.
How to prevent new attributes creation ? ======================================== Using class ----------- To control the creation of new attributes, you can overwrite the `__setattr__` method. It will be called every time `my_obj.x = 123` is called. See the [documentation](https://docs.python.org/3/reference/datamodel.html#object.__setattr__): ```py class A: def __init__(self): # Call object.__setattr__ to bypass the attribute checking super().__setattr__('x', 123) def __setattr__(self, name, value): # Cannot create new attributes if not hasattr(self, name): raise AttributeError('Cannot set new attributes') # Can update existing attributes super().__setattr__(name, value) a = A() a.x = 123 # Allowed a.y = 456 # raise AttributeError ``` Note that users can still bypass the checking if they call directly `object.__setattr__(a, 'attr_name', attr_value)`. Using dataclass --------------- With `dataclasses`, you can forbid the creation of new attributes with `frozen=True`. It will also prevent existing attributes to be updated. ``` @dataclasses.dataclass(frozen=True) class A: x: int a = A(x=123) a.y = 123 # Raise FrozenInstanceError a.x = 123 # Raise FrozenInstanceError ``` Note: `dataclasses.FrozenInstanceError` is a subclass of AttributeError
12,569,018
I am studying python, and although I think I get the whole concept and notion of Python, today I stumbled upon a piece of code that I did not fully understand: Say I have a class that is supposed to define Circles but lacks a body: ``` class Circle(): pass ``` Since I have not defined any attributes, how can I do this: ``` my_circle = Circle() my_circle.radius = 12 ``` The weird part is that Python accepts the above statement. I don't understand why Python doesn't raise an `undefined name error`. I do understand that via *dynamic typing* I just bind variables to objects whenever I want, but shouldn't an attribute `radius` exist in the `Circle` class to allow me to do this? **EDIT**: Lots of wonderful information in your answers! **Thank you everyone for all those fantastic answers!** It's a pity I only get to mark one as an answer.
2012/09/24
[ "https://Stackoverflow.com/questions/12569018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1426969/" ]
A leading principle is that *there is no such thing as a declaration*. That is, you never declare "this class has a method foo" or "instances of this class have an attribute bar", let alone making a statement about the types of objects to be stored there. You simply define a method, attribute, class, etc. and it's added. As JBernardo points out, any `__init__` method does the very same thing. It wouldn't make a lot of sense to arbitrarily restrict creation of new attributes to methods with the name `__init__`. And it's sometimes useful to store a function as `__init__` which don't actually have that name (e.g. decorators), and such a restriction would break that. Now, this isn't universally true. Builtin types omit this capability as an optimization. Via [`__slots__`](http://docs.python.org/reference/datamodel.html#slots), you can also prevent this on user-defined classes. But this is merely a space optimization (no need for a dictionary for every object), not a correctness thing. If you want a safety net, well, too bad. Python does not offer one, and you cannot reasonably add one, and most importantly, it would be shunned by Python programmers who embrace the language (read: almost all of those you want to work with). Testing and discipline, still go a long way to ensuring correctness. Don't use the liberty to make up attributes outside of `__init__` *if it can be avoided*, and do automated testing. I very rarely have an `AttributeError` or a logical error due to trickery like this, and of those that happen, almost all are caught by tests.
As delnan said, you can obtain this behavior with the `__slots__` attribute. But the fact that it is a way to save memory space and access type does not discard the fact that it is (also) a/the mean to disable dynamic attributes. Disabling dynamic attributes is a reasonable thing to do, if only to prevent subtle bugs due to spelling mistakes. "Testing and discipline" is fine but relying on automated validation is certainly not wrong either – and not necessarily unpythonic either. Also, since the `attrs` library reached version 16 in 2016 (obviously way after the original question and answers), creating a closed class with slots has never been easier. ``` >>> import attr ... ... @attr.s(slots=True) ... class Circle: ... radius = attr.ib() ... ... f = Circle(radius=2) ... f.color = 'red' AttributeError: 'Circle' object has no attribute 'color' ```
12,569,018
I am studying python, and although I think I get the whole concept and notion of Python, today I stumbled upon a piece of code that I did not fully understand: Say I have a class that is supposed to define Circles but lacks a body: ``` class Circle(): pass ``` Since I have not defined any attributes, how can I do this: ``` my_circle = Circle() my_circle.radius = 12 ``` The weird part is that Python accepts the above statement. I don't understand why Python doesn't raise an `undefined name error`. I do understand that via *dynamic typing* I just bind variables to objects whenever I want, but shouldn't an attribute `radius` exist in the `Circle` class to allow me to do this? **EDIT**: Lots of wonderful information in your answers! **Thank you everyone for all those fantastic answers!** It's a pity I only get to mark one as an answer.
2012/09/24
[ "https://Stackoverflow.com/questions/12569018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1426969/" ]
Just to clarify some misunderstandings in the discussions here. This code: ``` class Foo(object): def __init__(self, bar): self.bar = bar foo = Foo(5) ``` And this code: ``` class Foo(object): pass foo = Foo() foo.bar = 5 ``` is *exactly equivalent*. There really is no difference. It does exactly the same thing. This difference is that in the first case it's encapsulated and it's clear that the bar attribute is a normal part of Foo-type objects. In the second case it is not clear that this is so. In the first case you can not create a Foo object that doesn't have the bar attribute (well, you probably can, but not easily), in the second case the Foo objects will not have a bar attribute unless you set it. So although the code is programatically equivalent, it's used in different cases.
No, python is flexible like that, it does not enforce what attributes you can store on user-defined classes. There is a trick however, using the [`__slots__` attribute](http://docs.python.org/reference/datamodel.html#slots) on a class definition will prevent you from creating additional attributes not defined in the `__slots__` sequence: ``` >>> class Foo(object): ... __slots__ = () ... >>> f = Foo() >>> f.bar = 'spam' Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Foo' object has no attribute 'bar' >>> class Foo(object): ... __slots__ = ('bar',) ... >>> f = Foo() >>> f.bar Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: bar >>> f.bar = 'spam' ```
12,569,018
I am studying python, and although I think I get the whole concept and notion of Python, today I stumbled upon a piece of code that I did not fully understand: Say I have a class that is supposed to define Circles but lacks a body: ``` class Circle(): pass ``` Since I have not defined any attributes, how can I do this: ``` my_circle = Circle() my_circle.radius = 12 ``` The weird part is that Python accepts the above statement. I don't understand why Python doesn't raise an `undefined name error`. I do understand that via *dynamic typing* I just bind variables to objects whenever I want, but shouldn't an attribute `radius` exist in the `Circle` class to allow me to do this? **EDIT**: Lots of wonderful information in your answers! **Thank you everyone for all those fantastic answers!** It's a pity I only get to mark one as an answer.
2012/09/24
[ "https://Stackoverflow.com/questions/12569018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1426969/" ]
Python lets you store attributes of any name on virtually any instance (or class, for that matter). It's possible to block this either by writing the class in C, like the built-in types, or by using `__slots__` which allows only certain names. The reason it works is that most instances store their attributes in a dictionary. Yes, a regular Python dictionary like you'd define with `{}`. The dictionary is stored in an instance attribute called `__dict__`. In fact, some people say "classes are just syntactic sugar for dictionaries." That is, you can do everything you can do with a class with a dictionary; classes just make it easier. You're used to static languages where you must define all attributes at compile time. In Python, class definitions are *executed*, not compiled; classes are objects just like any other; and adding attributes is as easy as adding an item to a dictionary. This is why Python is considered a *dynamic* language.
To add to [Conchylicultor's answer](https://stackoverflow.com/a/59711821/1719931), Python 3.10 added a new parameter to `dataclass`. The `slots` parameter will create the `__slots__` attribute in the class, preventing creation of new attributes outside of `__init__`, but allowing assignments to existing attributes. If `slots=True`, assigning to an attribute that was not defined will throw an `AttributeError`. Here is an example with `slots` and with `frozen`: ```py from dataclasses import dataclass @dataclass class Data: x:float=0 y:float=0 @dataclass(frozen=True) class DataFrozen: x:float=0 y:float=0 @dataclass(slots=True) class DataSlots: x:float=0 y:float=0 p = Data(1,2) p.x = 5 # ok p.z = 8 # ok p = DataFrozen(1,2) p.x = 5 # FrozenInstanceError p.z = 8 # FrozenInstanceError p = DataSlots(1,2) p.x = 5 # ok p.z = 8 # AttributeError ```
12,569,018
I am studying python, and although I think I get the whole concept and notion of Python, today I stumbled upon a piece of code that I did not fully understand: Say I have a class that is supposed to define Circles but lacks a body: ``` class Circle(): pass ``` Since I have not defined any attributes, how can I do this: ``` my_circle = Circle() my_circle.radius = 12 ``` The weird part is that Python accepts the above statement. I don't understand why Python doesn't raise an `undefined name error`. I do understand that via *dynamic typing* I just bind variables to objects whenever I want, but shouldn't an attribute `radius` exist in the `Circle` class to allow me to do this? **EDIT**: Lots of wonderful information in your answers! **Thank you everyone for all those fantastic answers!** It's a pity I only get to mark one as an answer.
2012/09/24
[ "https://Stackoverflow.com/questions/12569018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1426969/" ]
A leading principle is that *there is no such thing as a declaration*. That is, you never declare "this class has a method foo" or "instances of this class have an attribute bar", let alone making a statement about the types of objects to be stored there. You simply define a method, attribute, class, etc. and it's added. As JBernardo points out, any `__init__` method does the very same thing. It wouldn't make a lot of sense to arbitrarily restrict creation of new attributes to methods with the name `__init__`. And it's sometimes useful to store a function as `__init__` which don't actually have that name (e.g. decorators), and such a restriction would break that. Now, this isn't universally true. Builtin types omit this capability as an optimization. Via [`__slots__`](http://docs.python.org/reference/datamodel.html#slots), you can also prevent this on user-defined classes. But this is merely a space optimization (no need for a dictionary for every object), not a correctness thing. If you want a safety net, well, too bad. Python does not offer one, and you cannot reasonably add one, and most importantly, it would be shunned by Python programmers who embrace the language (read: almost all of those you want to work with). Testing and discipline, still go a long way to ensuring correctness. Don't use the liberty to make up attributes outside of `__init__` *if it can be avoided*, and do automated testing. I very rarely have an `AttributeError` or a logical error due to trickery like this, and of those that happen, almost all are caught by tests.
There are two types of attributes in Python - `Class Data Attributes` and `Instance Data Attributes`. Python gives you flexibility of creating `Data Attributes` on the fly. Since an instance data attribute is related to an instance, you can also do that in `__init__` method or you can do it after you have created your instance.. ``` class Demo(object): classAttr = 30 def __init__(self): self.inInit = 10 demo = Demo() demo.outInit = 20 Demo.new_class_attr = 45; # You can also create class attribute here. print demo.classAttr # Can access it del demo.classAttr # Cannot do this.. Should delete only through class demo.classAttr = 67 # creates an instance attribute for this instance. del demo.classAttr # Now OK. print Demo.classAttr ``` So, you see that we have created two instance attributes, one inside `__init__` and one outside, after instance is created.. But a difference is that, the instance attribute created inside `__init__` will be set for all the instances, while if created outside, you can have different instance attributes for different isntances.. This is unlike Java, where each Instance of a Class have same set of Instance Variables.. * NOTE: - While you can access a class attribute through an instance, you cannot delete it.. Also, if you try to modify a class attribute through an instance, you actually create an instance attribute which shadows the class attribute..
12,569,018
I am studying python, and although I think I get the whole concept and notion of Python, today I stumbled upon a piece of code that I did not fully understand: Say I have a class that is supposed to define Circles but lacks a body: ``` class Circle(): pass ``` Since I have not defined any attributes, how can I do this: ``` my_circle = Circle() my_circle.radius = 12 ``` The weird part is that Python accepts the above statement. I don't understand why Python doesn't raise an `undefined name error`. I do understand that via *dynamic typing* I just bind variables to objects whenever I want, but shouldn't an attribute `radius` exist in the `Circle` class to allow me to do this? **EDIT**: Lots of wonderful information in your answers! **Thank you everyone for all those fantastic answers!** It's a pity I only get to mark one as an answer.
2012/09/24
[ "https://Stackoverflow.com/questions/12569018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1426969/" ]
No, python is flexible like that, it does not enforce what attributes you can store on user-defined classes. There is a trick however, using the [`__slots__` attribute](http://docs.python.org/reference/datamodel.html#slots) on a class definition will prevent you from creating additional attributes not defined in the `__slots__` sequence: ``` >>> class Foo(object): ... __slots__ = () ... >>> f = Foo() >>> f.bar = 'spam' Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Foo' object has no attribute 'bar' >>> class Foo(object): ... __slots__ = ('bar',) ... >>> f = Foo() >>> f.bar Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: bar >>> f.bar = 'spam' ```
To add to [Conchylicultor's answer](https://stackoverflow.com/a/59711821/1719931), Python 3.10 added a new parameter to `dataclass`. The `slots` parameter will create the `__slots__` attribute in the class, preventing creation of new attributes outside of `__init__`, but allowing assignments to existing attributes. If `slots=True`, assigning to an attribute that was not defined will throw an `AttributeError`. Here is an example with `slots` and with `frozen`: ```py from dataclasses import dataclass @dataclass class Data: x:float=0 y:float=0 @dataclass(frozen=True) class DataFrozen: x:float=0 y:float=0 @dataclass(slots=True) class DataSlots: x:float=0 y:float=0 p = Data(1,2) p.x = 5 # ok p.z = 8 # ok p = DataFrozen(1,2) p.x = 5 # FrozenInstanceError p.z = 8 # FrozenInstanceError p = DataSlots(1,2) p.x = 5 # ok p.z = 8 # AttributeError ```
12,569,018
I am studying python, and although I think I get the whole concept and notion of Python, today I stumbled upon a piece of code that I did not fully understand: Say I have a class that is supposed to define Circles but lacks a body: ``` class Circle(): pass ``` Since I have not defined any attributes, how can I do this: ``` my_circle = Circle() my_circle.radius = 12 ``` The weird part is that Python accepts the above statement. I don't understand why Python doesn't raise an `undefined name error`. I do understand that via *dynamic typing* I just bind variables to objects whenever I want, but shouldn't an attribute `radius` exist in the `Circle` class to allow me to do this? **EDIT**: Lots of wonderful information in your answers! **Thank you everyone for all those fantastic answers!** It's a pity I only get to mark one as an answer.
2012/09/24
[ "https://Stackoverflow.com/questions/12569018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1426969/" ]
No, python is flexible like that, it does not enforce what attributes you can store on user-defined classes. There is a trick however, using the [`__slots__` attribute](http://docs.python.org/reference/datamodel.html#slots) on a class definition will prevent you from creating additional attributes not defined in the `__slots__` sequence: ``` >>> class Foo(object): ... __slots__ = () ... >>> f = Foo() >>> f.bar = 'spam' Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Foo' object has no attribute 'bar' >>> class Foo(object): ... __slots__ = ('bar',) ... >>> f = Foo() >>> f.bar Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: bar >>> f.bar = 'spam' ```
It creates a `radius` data member of `my_circle`. If you had asked it for `my_circle.radius` it would have thrown an exception: ``` >>> print my_circle.radius # AttributeError ``` Interestingly, this does not change the class; just that one instance. So: ``` >>> my_circle = Circle() >>> my_circle.radius = 5 >>> my_other_circle = Circle() >>> print my_other_circle.radius # AttributeError ```
43,986,558
I have a panda data frame with several column of integers, as well as a corresponding dictionary of {column : {integer:string\_label}}. I am trying to create a dataframe in which the integers have been replaced by their labels. The closest I got is below, but the output is somewhat unexpected. **Code** ``` import pandas as pd import numpy as np df = pd.DataFrame({'a':[1,2,3,3,8],'b':[8,8,8,8,7]}) dic = {'a':{1:"label1",2:"label2",3:"label3"}, 'b':{8:'label8',7:'label7'}} converters = {column: lambda x: dic[column][x] if x in dic[column].keys() else np.nan for column in dic.keys()} new = pd.DataFrame.from_dict({col: series.apply(converters[col]) if col in converters else series for col, series in df.iteritems()}) print new #Output: # a b # 0 NaN label8 # 1 NaN label8 # 2 NaN label8 # 3 NaN label8 # 4 label8 label7 ```
2017/05/15
[ "https://Stackoverflow.com/questions/43986558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6255101/" ]
As Greg mentioned, the issue is your strings do not match your `levels`. They need to match exactly. To apply this, you could do the following: ``` #starting with user specific data and levels chr_string <- c("NEW.ENGLAND", "NEW.ENGLAND", "NEW.ENGLAND", "NEW.ENGLAND", "NEW.ENGLAND", "NEW.ENGLAND", "NEW.ENGLAND", "NEW.ENGLAND", "MIDDLE.ATLANTIC", "MIDDLE.ATLANTIC", "MIDDLE.ATLANTIC", "MIDDLE.ATLANTIC", "MIDDLE.ATLANTIC", "MIDDLE.ATLANTIC", "MIDDLE.ATLANTIC", "E..NOR..CENTRAL", "E..NOR..CENTRAL", "E..NOR..CENTRAL", "E..NOR..CENTRAL", "E..NOR..CENTRAL", "E..NOR..CENTRAL", "W..NOR..CENTRAL", "W..NOR..CENTRAL", "W..NOR..CENTRAL", "W..NOR..CENTRAL", "W..NOR..CENTRAL", "SOUTH.ATLANTIC", "SOUTH.ATLANTIC", "SOUTH.ATLANTIC", "SOUTH.ATLANTIC", "E..SOU..CENTRAL", "E..SOU..CENTRAL", "E..SOU..CENTRAL", "W..SOU..CENTRAL", "W..SOU..CENTRAL", "MOUNTAIN") levels <- c("NEW ENGLAND", "MIDDLE ATLANTIC", "E. NOR. CENTRAL", "W. NOR. CENTRAL", "SOUTH ATLANTIC", "E. SOU. CENTRAL", "W. SOU. CENTRAL", "MOUNTAIN", "PACIFIC") #regex to remove periods from your vector of strings chr_string <- sapply(chr_string, gsub, pattern = '[//.]', replacement = ' ') #remove double spaces and replace with '. ' string as required by levels chr_string <- sapply(chr_string, gsub, pattern = ' ', replacement = '. ') #removing names from the vector names(chr_string) <- NULL #as requested; expected result factor(chr_string, levels = levels) ``` Alternately, just change your `levels`.
The specified levels need to match the character strings. Your first element is "NEW.ENGLAND", but in the levels you have "NEW ENGLAND" (with a space instead of a dot), so R is not going to match them up. When creating the factor those need to match exactly, you can use the `labels` argument to change the level codes after the matching, or you can use a second step and call to `levels` to change the labels.
59,655,017
I have a dataframe like this with two date columns and a quamtity column : ``` start_date end_date qty 1 2018-01-01 2018-01-08 23 2 2018-01-08 2018-01-15 21 3 2018-01-15 2018-01-22 5 4 2018-01-22 2018-01-29 12 ``` I have a second dataframe with just column containing yearly holidays for a couple of years, like this: ``` holiday 1 2018-01-01 2 2018-01-27 3 2018-12-25 4 2018-12-26 ``` I would like to go through the first dataframe row by row and assign boolean value to a new column holidays if a date in the second data frame falls between the date values of the first date frame. The result would look like this: ``` start_date end_date qty holidays 1 2018-01-01 2018-01-08 23 True 2 2018-01-08 2018-01-15 21 False 3 2018-01-15 2018-01-22 5 False 4 2018-01-22 2018-01-29 12 True ``` When I try to do that with a for loop I get the following error: > > ValueError: Can only compare identically-labeled Series objects > > > An answer would be appreciated.
2020/01/08
[ "https://Stackoverflow.com/questions/59655017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1073962/" ]
If you want a fully-vectorized solution, consider using the underlying `numpy` arrays: ```py import numpy as np def holiday_arr(start, end, holidays): start = start.reshape((-1, 1)) end = end.reshape((-1, 1)) holidays = holidays.reshape((1, -1)) result = np.any( (start <= holiday) & (holiday <= end), axis=1 ) return result ``` If you have your dataframes as above (calling them `df1` and `df2`), you can obtain your desired result by running: ```py df1["contains_holiday"] = holiday_arr( df1["start_date"].to_numpy(), df1["end_date"].to_numpy(), df2["holiday"].to_numpy() ) ``` `df1` then looks like: ``` start_date end_date qty contains_holiday 1 2018-01-01 2018-01-08 23 True 2 2018-01-08 2018-01-15 21 False 3 2018-01-15 2018-01-22 5 False 4 2018-01-22 2018-01-29 12 True ```
try: ``` def _is_holiday(row, df2): return ((df2['holiday'] >= row['start_date']) & (df2['holiday'] <= row['end_date'])).any() df1.apply(lambda x: _is_holiday(x, df2), axis=1) ```
59,655,017
I have a dataframe like this with two date columns and a quamtity column : ``` start_date end_date qty 1 2018-01-01 2018-01-08 23 2 2018-01-08 2018-01-15 21 3 2018-01-15 2018-01-22 5 4 2018-01-22 2018-01-29 12 ``` I have a second dataframe with just column containing yearly holidays for a couple of years, like this: ``` holiday 1 2018-01-01 2 2018-01-27 3 2018-12-25 4 2018-12-26 ``` I would like to go through the first dataframe row by row and assign boolean value to a new column holidays if a date in the second data frame falls between the date values of the first date frame. The result would look like this: ``` start_date end_date qty holidays 1 2018-01-01 2018-01-08 23 True 2 2018-01-08 2018-01-15 21 False 3 2018-01-15 2018-01-22 5 False 4 2018-01-22 2018-01-29 12 True ``` When I try to do that with a for loop I get the following error: > > ValueError: Can only compare identically-labeled Series objects > > > An answer would be appreciated.
2020/01/08
[ "https://Stackoverflow.com/questions/59655017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1073962/" ]
If you want a fully-vectorized solution, consider using the underlying `numpy` arrays: ```py import numpy as np def holiday_arr(start, end, holidays): start = start.reshape((-1, 1)) end = end.reshape((-1, 1)) holidays = holidays.reshape((1, -1)) result = np.any( (start <= holiday) & (holiday <= end), axis=1 ) return result ``` If you have your dataframes as above (calling them `df1` and `df2`), you can obtain your desired result by running: ```py df1["contains_holiday"] = holiday_arr( df1["start_date"].to_numpy(), df1["end_date"].to_numpy(), df2["holiday"].to_numpy() ) ``` `df1` then looks like: ``` start_date end_date qty contains_holiday 1 2018-01-01 2018-01-08 23 True 2 2018-01-08 2018-01-15 21 False 3 2018-01-15 2018-01-22 5 False 4 2018-01-22 2018-01-29 12 True ```
I'm not sure why you would want to go row-by-row. But boolean comparisons would be way faster. ``` df['holiday'] = ((df2.holiday >= df.start_date) & (df2.holiday <= df.end_date)) ``` Time ``` >>> 1000 loops, best of 3: 1.05 ms per loop ``` Quoting @hchw solution (row-by-row) ``` def _is_holiday(row, df2): return ((df2['holiday'] >= row['start_date']) & (df2['holiday'] <= row['end_date'])).any() df.apply(lambda x: _is_holiday(x, df2), axis=1) ``` ``` >>> The slowest run took 4.89 times longer than the fastest. This could mean that an intermediate result is being cached. 100 loops, best of 3: 4.46 ms per loop ```
59,655,017
I have a dataframe like this with two date columns and a quamtity column : ``` start_date end_date qty 1 2018-01-01 2018-01-08 23 2 2018-01-08 2018-01-15 21 3 2018-01-15 2018-01-22 5 4 2018-01-22 2018-01-29 12 ``` I have a second dataframe with just column containing yearly holidays for a couple of years, like this: ``` holiday 1 2018-01-01 2 2018-01-27 3 2018-12-25 4 2018-12-26 ``` I would like to go through the first dataframe row by row and assign boolean value to a new column holidays if a date in the second data frame falls between the date values of the first date frame. The result would look like this: ``` start_date end_date qty holidays 1 2018-01-01 2018-01-08 23 True 2 2018-01-08 2018-01-15 21 False 3 2018-01-15 2018-01-22 5 False 4 2018-01-22 2018-01-29 12 True ``` When I try to do that with a for loop I get the following error: > > ValueError: Can only compare identically-labeled Series objects > > > An answer would be appreciated.
2020/01/08
[ "https://Stackoverflow.com/questions/59655017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1073962/" ]
If you want a fully-vectorized solution, consider using the underlying `numpy` arrays: ```py import numpy as np def holiday_arr(start, end, holidays): start = start.reshape((-1, 1)) end = end.reshape((-1, 1)) holidays = holidays.reshape((1, -1)) result = np.any( (start <= holiday) & (holiday <= end), axis=1 ) return result ``` If you have your dataframes as above (calling them `df1` and `df2`), you can obtain your desired result by running: ```py df1["contains_holiday"] = holiday_arr( df1["start_date"].to_numpy(), df1["end_date"].to_numpy(), df2["holiday"].to_numpy() ) ``` `df1` then looks like: ``` start_date end_date qty contains_holiday 1 2018-01-01 2018-01-08 23 True 2 2018-01-08 2018-01-15 21 False 3 2018-01-15 2018-01-22 5 False 4 2018-01-22 2018-01-29 12 True ```
Try `IntervalIndex.contains` with list comprehensiont and `np.sum` ``` iix = pd.IntervalIndex.from_arrays(df1.start_date, df1.end_date, closed='both') df1['holidays'] = np.sum([iix.contains(x) for x in df2.holiday], axis=0) >= 1 Out[812]: start_date end_date qty holidays 1 2018-01-01 2018-01-08 23 True 2 2018-01-08 2018-01-15 21 False 3 2018-01-15 2018-01-22 5 False 4 2018-01-22 2018-01-29 12 True ``` --- **Note**: I assume `start_date`, `end_date`, `holiday` columns are in datetime format. If they are not, you need to convert them before run above command as follows ``` df1.start_date = pd.to_datetime(df1.start_date) df1.end_date = pd.to_datetime(df1.end_date) df2.holiday = pd.to_datetime(df2.holiday) ```
3,238,457
How can I consume a JSON document without jQuery? Instead of calling the method `getJSON()`, I'd like to design my own. How do I do that?
2010/07/13
[ "https://Stackoverflow.com/questions/3238457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373213/" ]
If it's the same domain request then use window.XMLHttpRequest. If it's remote, then inject a script element, you can see how jQuery does it: ``` // If we're requesting a remote document // and trying to load JSON or Script with a GET if ( s.dataType === "script" && type === "GET" && remote ) { var head = document.getElementsByTagName("head")[0] || document.documentElement; var script = document.createElement("script"); script.src = s.url; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } // Handle Script loading if ( !jsonp ) { var done = false; // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) { done = true; success(); complete(); // Handle memory leak in IE script.onload = script.onreadystatechange = null; if ( head && script.parentNode ) { head.removeChild( script ); } } }; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); // We handle everything using the script element injection return undefined; } ``` Use a [JSON Parser](https://github.com/douglascrockford/JSON-js/blob/master/json2.js). You can also use `eval` but it's frowned upon in favor of a JSON parser. Here's jQuery's internal parseJSON method: ``` parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@") .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]") .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) { // Try to use the native JSON parser first return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); } else { jQuery.error( "Invalid JSON: " + data ); } }, ```
You would have to roll your own JSON/AJAX function. There are some examples [here](http://www.webreference.com/programming/javascript/rg5/). I am not sure how good they are.
44,378,973
So what I am trying to achieve is to return a pointer to a 2D array from the function so it could accessed in main(). I know there are some C++ libraries that does it for you like `std::vector` but I am trying to avoid dynamic memory allocation since I am working on embedded board (STM32) so I will stick to just normal pointers and arrays. (**ALSO for some reason I can't use `std::array` in KEIL uVision, which is also why I am forced to work with pointers/arrays**) In addition, I understand that returning a pointer to a local array `int arr[2][2]` defined inside the function is not a good idea since it will no longer be valid after the function returns, which is why I creating `test_array`, declaring it inside a class and defining it in a function (acting as a global variable) so I assume this shouldn't be a problem. What do you guys think? However, doing it this way gives an error **"Excess elements in scalar initializer"** ``` #include <iostream> #include "file.hpp" int main() { myClass class_object; class_object.value = class_object.foo(); } ``` --- ``` //file.hpp #include <stdio.h> class myClass{ int array[2][2]; int (*foo())[2]; int (*value)[2]; int test_array[2][2]; //declaring here! }; ``` --- ``` //file.cpp #include "file.hpp" int (*myClass::foo())[2]{ test_array[2][2]={ {10,20}, {30, 40} }; //defining here - ERROR!! int arr[2][2]= { {1, 10}, {20, 30} }; return arr; } ```
2017/06/05
[ "https://Stackoverflow.com/questions/44378973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8109229/" ]
The immediate problem: ``` test_array[2][2]={ {10,20}, {30, 40} }; //defining here - ERROR!! ``` is not defining. `test_array` was defined up in `myClass`. This is attempting to assign to a single element of `test_array`, specifically `[2][2]` which does not exist. What particularly offends the compiler is not the out of bounds access, but that `={ {10,20}, {30, 40} };` is trying to stuff an array into a single array element. The compiler is expecting a single number, so four numbers is definitely in excess. Unfortunately I don't know of a good way to do what you want to do. You can initialize an array with an initializer list, but you can't assign from one. So ``` class myClass{ public: myClass(); void foo(); int test_array[2][2]; //declaring here! }; // you can do this: myClass::myClass(): test_array{ {10,20}, {30, 40} } { } void myClass::foo() { // but you can't do this: test_array = { {10,20}, {30, 40} }; } ``` Depending on what you do with `test_array`, initializing in the constructor may work for you. If you have to reset the array on every call to `foo`, perhaps an Automatic variable is a better fit for you ``` void myClass::foo() { int temp_array[2][2] = { {10,20}, {30, 40} }; // use temp_array // maybe copy temp_array to test_array with good ol' memcpy here if you // need to carry the state for some reason. } ``` To silence the elephant in the room [and gain access to `std::array`, give this a try.](http://www.keil.com/support/docs/3696.htm) Note: I've never done this. It could be an utter freaking disaster for all I know, so take it with a grain of salt.
If you really want to work with C-Array, use typedef to have *normal* syntax: ``` class myClass{ public: using array2 = int[2][2]; myClass() { test_array[0][0] = 0; test_array[0][1] = 1; test_array[1][0] = 2; test_array[1][1] = 3; } const array2& getArray() const { return test_array; } array2& getArray() { return test_array; } private: array2 test_array; }; ```
27,902
In "some characteristic C is what distinguishes A from B", does characteristic C belongs to A but not to B, or to B but not to A? For example: > > Imposing restrictions on the available resources is what distinguishes computational complexity from computability theory. > > >
2011/05/31
[ "https://english.stackexchange.com/questions/27902", "https://english.stackexchange.com", "https://english.stackexchange.com/users/683/" ]
I think the word you are after is *listener* in everyday terminology. The speaker speaks to an *audience*. In the audience, you may find some very attentive *listeners*. Everybody in the room will hear the talk, so it might be argued that *hearer* is a possibility. It depends on the interest of the audience member, though. Hearing is something you cannot control. Your ears will pick up the sound and send it to your brain. So everyone who hears the sounds will be a *hearer*. Listening, though, is something that you can control. You can decide to tune out and not pay attention, or you can decide to lap up every sound or word. If you are interested and follow the talk, you will probably describe yourself as a *listener*. This also manifests in the set term *avid listener*. I'm not sure if such a construct exists for hearing.
**Edited Answer, see below.** Every time I've studied conversations patterns and rules of speaking, the other person has always been called either **hearer** or **addressee**. Here I'll quote an example from my notes: > > "Speakers and hearers constantly adjust their internal registry of deictics to keep up with the conversation." > > > or > > "Directives = Speech acts in which the words are aimed at making the hearer do something;" > > > I'm not really sure about *listener*, but honestly I can't recall using it. --- **EDIT:** Since I've been downvoted, I'll link a further reference which proves me right. The book, [Speech acts: an essay in the philosophy of language](http://books.google.it/books?id=t3_WhfknvF0C&printsec=frontcover&dq=searle%20acts&hl=it&ei=fsbkTY_AGtDm-gbqg6jQBg&sa=X&oi=book_result&ct=book-preview-link&resnum=1&ved=0CC4QuwUwAA#v=onepage&q=hearer&f=false), is written by John R. Searle, a rather known name in the Linguistics field and to whoever studied Linguistics in an academic setting. **Speech Acts** are utterances that don't simply convey information, but can also "perform actions" such as "*I hereby declare you company and wife.*" (This one, for example, is a **Declaration** according to Searle's classification of Speech Acts. If you search words in that book, there are **34 entries** for "hearer" and **0 entries** for "listener".
27,902
In "some characteristic C is what distinguishes A from B", does characteristic C belongs to A but not to B, or to B but not to A? For example: > > Imposing restrictions on the available resources is what distinguishes computational complexity from computability theory. > > >
2011/05/31
[ "https://english.stackexchange.com/questions/27902", "https://english.stackexchange.com", "https://english.stackexchange.com/users/683/" ]
I think the word you are after is *listener* in everyday terminology. The speaker speaks to an *audience*. In the audience, you may find some very attentive *listeners*. Everybody in the room will hear the talk, so it might be argued that *hearer* is a possibility. It depends on the interest of the audience member, though. Hearing is something you cannot control. Your ears will pick up the sound and send it to your brain. So everyone who hears the sounds will be a *hearer*. Listening, though, is something that you can control. You can decide to tune out and not pay attention, or you can decide to lap up every sound or word. If you are interested and follow the talk, you will probably describe yourself as a *listener*. This also manifests in the set term *avid listener*. I'm not sure if such a construct exists for hearing.
The answers given answer the title question of 'hearing equivalent for “speaker”'. However, the question is actually asked in reference to analysing a **conversation**. In that case, 'speakers' isn't really correct either. Those who speak in a conversation also plays the same listening role as those who do not speak. In the context of research, the groups would likely be labelled 'speaking participants' and 'non-speaking participants'. In a less formal context, you would talk about 'the people who spoke' and 'the people who didn't speak'.
27,902
In "some characteristic C is what distinguishes A from B", does characteristic C belongs to A but not to B, or to B but not to A? For example: > > Imposing restrictions on the available resources is what distinguishes computational complexity from computability theory. > > >
2011/05/31
[ "https://english.stackexchange.com/questions/27902", "https://english.stackexchange.com", "https://english.stackexchange.com/users/683/" ]
**Edited Answer, see below.** Every time I've studied conversations patterns and rules of speaking, the other person has always been called either **hearer** or **addressee**. Here I'll quote an example from my notes: > > "Speakers and hearers constantly adjust their internal registry of deictics to keep up with the conversation." > > > or > > "Directives = Speech acts in which the words are aimed at making the hearer do something;" > > > I'm not really sure about *listener*, but honestly I can't recall using it. --- **EDIT:** Since I've been downvoted, I'll link a further reference which proves me right. The book, [Speech acts: an essay in the philosophy of language](http://books.google.it/books?id=t3_WhfknvF0C&printsec=frontcover&dq=searle%20acts&hl=it&ei=fsbkTY_AGtDm-gbqg6jQBg&sa=X&oi=book_result&ct=book-preview-link&resnum=1&ved=0CC4QuwUwAA#v=onepage&q=hearer&f=false), is written by John R. Searle, a rather known name in the Linguistics field and to whoever studied Linguistics in an academic setting. **Speech Acts** are utterances that don't simply convey information, but can also "perform actions" such as "*I hereby declare you company and wife.*" (This one, for example, is a **Declaration** according to Searle's classification of Speech Acts. If you search words in that book, there are **34 entries** for "hearer" and **0 entries** for "listener".
The answers given answer the title question of 'hearing equivalent for “speaker”'. However, the question is actually asked in reference to analysing a **conversation**. In that case, 'speakers' isn't really correct either. Those who speak in a conversation also plays the same listening role as those who do not speak. In the context of research, the groups would likely be labelled 'speaking participants' and 'non-speaking participants'. In a less formal context, you would talk about 'the people who spoke' and 'the people who didn't speak'.
6,838,882
1.) I have an XSD file (I have no control over) that I converted to object model using JAXB 2.) I have a database extract in XML format. The XML element tag names are strictly the field names of the table 3.) I mapped the xml elements to the Java class using annotations. Question: Is there a way to maintain the element names in the XSD file, and JUST extract the value of the xml elements. JAXB annotated class: ``` @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Item", propOrder = { "code", "name", "price" }) @XmlRootElement(name="inventory") public class Item { @XmlElement(name="catalog_num", required = true) protected String code; @XmlElement(name="catalog_descrip", required = true) protected String name; @XmlElement(name="prod_price") protected double price; public String getCode() { return code; } //etc ``` An excerpt of the database xml file: ``` <?xml version="1.0"?> <inventory> <catalog_num>I001</catalog_num> <catalog_descrip>Descriptive Name of Product</catalog_descrip> <prod_price>11200</prod_price> </inventory> ``` The result I need to get after marshaling the above xml file is: ``` <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Item> <code>I001</code> <name>Descriptive Name of Product</name> <price>11200.0</price> </Item> ``` In the above code, I have tried annotating the methods instead of the fields, but I yield the same result. I just want the value extracted from the xml elements, but not change the element names. I hope I am making sense.
2011/07/27
[ "https://Stackoverflow.com/questions/6838882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/851133/" ]
Do it at the web server level. Since you tagged your question `.htaccess` I'm assuming that's Apache. ``` RewriteEngine On RewriteCond %{QUERY_STRING} file=(.*)&name=(.*)&sid=(.*) RewriteRule modules.php modules.php?name=%2&file=%1&sid=%3 [R=301,L] ``` I haven't tested that, does it work?
You could try something like this - ``` <?php if (preg_match ('/file=article\&name=Name/', $_SERVER['REQUEST_URI'])) { header ('HTTP/1.1 301 Moved Permanently'); header ('Location: ' . str_replace('file=article&name=Name', 'name=Name&file=article', $_SERVER['REQUEST_URI']); } ``` or for a more generic one ``` <?php if (preg_match ('/file=(.*)\&name=(.*)/', $_SERVER['REQUEST_URI'], $matches)) { header ('HTTP/1.1 301 Moved Permanently'); header ('Location: ' . preg_replace('/file=(.*)&name=([^&]*)/', 'file=${1}\&name=${2}', $_SERVER['REQUEST_URI'])); } ```
20,099,214
I'm having a tough time enabling javascript in chrome on my own webpage. Other websites seem to be able to do it pretty easily. Here's my prtty simple code but the start() function just wouldn't work. ``` <doctype html> <html> <head> <script type = "javascript"> function start() { alert("Hi"); } </script> </head> <body onload = "start()"> Hi </body> </html> ```
2013/11/20
[ "https://Stackoverflow.com/questions/20099214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1591730/" ]
You're using wrong [**`type`** Attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#Attributes), it should be ``` <script type="text/javascript"> ``` or simply ``` <script> </script> //by default is type is "text/javascript" ``` Also change `<!DOCTYPE html>`
``` <!doctype html> <html> <head> <script> function start() { alert("Hi"); } </script> </head> <body onload = "start()"> Hi </body> </html> ```
20,099,214
I'm having a tough time enabling javascript in chrome on my own webpage. Other websites seem to be able to do it pretty easily. Here's my prtty simple code but the start() function just wouldn't work. ``` <doctype html> <html> <head> <script type = "javascript"> function start() { alert("Hi"); } </script> </head> <body onload = "start()"> Hi </body> </html> ```
2013/11/20
[ "https://Stackoverflow.com/questions/20099214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1591730/" ]
The main problem is your type attribute. If you were to keep it, then it should be ``` <script type="text/javascript"></script> ``` However, you don't need it (See here: <http://javascript.crockford.com/script.html>). You can just use ``` <script></script> ``` That will fix your function. Although not directly hindering your function, your doctype is missing the '!' and should probably be updated ``` <!doctype html> ```
``` <!doctype html> <html> <head> <script> function start() { alert("Hi"); } </script> </head> <body onload = "start()"> Hi </body> </html> ```
20,833,084
I want to change guest VM's(Windows) IP address on ESXi. One way I have known is using RDP to connect to the guest OS and modifying the network configuration. However, I wish to make the process automated. Hence, does vCenter or ESXi contain similar functions or tools to perform this demand? (I have tried ovftool and vCLI but not work) Thanks for ur reply. Rocas
2013/12/30
[ "https://Stackoverflow.com/questions/20833084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3145174/" ]
**Why is `n` the exact same Object as `None`?** The C implementation keeps a singleton instance. `NoneType.__new__` is returning the singleton instance. **Why was the language designed such that n is the exact same Object as `None`?** If there was not a singleton instance, then you could not rely on the check `x is None` since the `is` operator is based on identity. Although `None == None` is also `True`, it's possible to have `x == None` be `True` when `x` is not actually `None`. See [this answer](https://stackoverflow.com/a/14247383/1464861) for an example. **How would one even implement this behavior in python?** You can implement this pattern by overridding `__new__`. Here's a basic example: ``` class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if Singleton._instance is None: Singleton._instance = object.__new__(cls, *args, **kwargs) return Singleton._instance if __name__ == '__main__': s1 = Singleton() s2 = Singleton() print 's1 is s2:', s1 is s2 print 'id(s1):', id(s1) print 'id(s2):', id(s2) ``` Output: > > s1 is s2: True > > id(s1): 4506243152 > > id(s2): 4506243152 > > > > Of course this simple example doesn't make it *impossible* to create a second instance.
1. The NoneType overrides `__new__` which always return the same singleton. The code is actually [written in C](http://hg.python.org/cpython/file/b35b204e5d0b/Objects/object.c#l1412) so `dis` cannot help, but conceptually it's just like this. 2. Having only one None instance is easier to deal with. They are all equal anyway. 3. By overriding `__new__`... e.g. ``` class MyNoneType(object): _common_none = 0 def __new__(cls): return cls._common_none MyNoneType._common_none = object.__new__(MyNoneType) m1 = MyNoneType() m2 = MyNoneType() print(m1 is m2) ```
20,833,084
I want to change guest VM's(Windows) IP address on ESXi. One way I have known is using RDP to connect to the guest OS and modifying the network configuration. However, I wish to make the process automated. Hence, does vCenter or ESXi contain similar functions or tools to perform this demand? (I have tried ovftool and vCLI but not work) Thanks for ur reply. Rocas
2013/12/30
[ "https://Stackoverflow.com/questions/20833084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3145174/" ]
> > Why is n the exact same Object as None? > > > Many immutable objects in Python are [interned](http://en.wikipedia.org/wiki/String_interning) including `None`, smaller ints, and many strings. Demo: ``` >>> s1='abc' >>> s2='def' >>> s3='abc' >>> id(s1) 4540177408 >>> id(s3) 4540177408 # Note: same as s1 >>> x=1 >>> y=2 >>> z=1 >>> id(x) 4538711696 >>> id(z) 4538711696 # Note: same as x ``` > > Why was the language designed > such that n is the exact same Object as None? > > > See above -- speed, efficiency, lack of ambiguity and memory usage among other reasons to intern immutable objects. > > How would one even > implement this behavior in python? > > > Among other ways, you can override `__new__` to return the same object: ``` class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__new__( cls, *args, **kwargs) return cls._instance ``` For strings, you can call [intern](http://docs.python.org/2/library/functions.html#intern) on Python 2 or [sys.intern](http://docs.python.org/3.3/library/sys.html#sys.intern) on Python 3
1. The NoneType overrides `__new__` which always return the same singleton. The code is actually [written in C](http://hg.python.org/cpython/file/b35b204e5d0b/Objects/object.c#l1412) so `dis` cannot help, but conceptually it's just like this. 2. Having only one None instance is easier to deal with. They are all equal anyway. 3. By overriding `__new__`... e.g. ``` class MyNoneType(object): _common_none = 0 def __new__(cls): return cls._common_none MyNoneType._common_none = object.__new__(MyNoneType) m1 = MyNoneType() m2 = MyNoneType() print(m1 is m2) ```
20,833,084
I want to change guest VM's(Windows) IP address on ESXi. One way I have known is using RDP to connect to the guest OS and modifying the network configuration. However, I wish to make the process automated. Hence, does vCenter or ESXi contain similar functions or tools to perform this demand? (I have tried ovftool and vCLI but not work) Thanks for ur reply. Rocas
2013/12/30
[ "https://Stackoverflow.com/questions/20833084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3145174/" ]
Other answers describe how to use `__new__` to implement a singleton, but that's not how None is actually implemented (in cPython at least, I haven't looked into other implementations). Trying to create an instance of None through `type(None)()` is special cased, and ends up calling the [following C function](http://hg.python.org/cpython/file/8b4d36d0c090/Objects/object.c#l1409): ``` static PyObject * none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) { if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) { PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments"); return NULL; } Py_RETURN_NONE; } ``` And `Py_RETURN_NONE` is [defined here](http://hg.python.org/cpython/file/8b4d36d0c090/Include/object.h#l837): ``` /* _Py_NoneStruct is an object of undefined type which can be used in contexts where NULL (nil) is not suitable (since NULL often means 'error'). Don't forget to apply Py_INCREF() when returning this value!!! */ PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */ #define Py_None (&_Py_NoneStruct) /* Macro for returning Py_None from a function */ #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None ``` Contrast this with the [function that creates a normal python object](http://hg.python.org/cpython/file/8b4d36d0c090/Objects/object.c#l237): ``` PyObject * _PyObject_New(PyTypeObject *tp) { PyObject *op; op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp)); if (op == NULL) return PyErr_NoMemory(); return PyObject_INIT(op, tp); } ``` When you create a normal object, memory for the object is allocated and initialized. When you try to create a new instance of `None`, all you get is a reference to the already existing `_Py_NoneStruct`. That's why, no matter what you do, every reference to `None` will be the exact same object.
1. The NoneType overrides `__new__` which always return the same singleton. The code is actually [written in C](http://hg.python.org/cpython/file/b35b204e5d0b/Objects/object.c#l1412) so `dis` cannot help, but conceptually it's just like this. 2. Having only one None instance is easier to deal with. They are all equal anyway. 3. By overriding `__new__`... e.g. ``` class MyNoneType(object): _common_none = 0 def __new__(cls): return cls._common_none MyNoneType._common_none = object.__new__(MyNoneType) m1 = MyNoneType() m2 = MyNoneType() print(m1 is m2) ```
20,833,084
I want to change guest VM's(Windows) IP address on ESXi. One way I have known is using RDP to connect to the guest OS and modifying the network configuration. However, I wish to make the process automated. Hence, does vCenter or ESXi contain similar functions or tools to perform this demand? (I have tried ovftool and vCLI but not work) Thanks for ur reply. Rocas
2013/12/30
[ "https://Stackoverflow.com/questions/20833084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3145174/" ]
**Why is `n` the exact same Object as `None`?** The C implementation keeps a singleton instance. `NoneType.__new__` is returning the singleton instance. **Why was the language designed such that n is the exact same Object as `None`?** If there was not a singleton instance, then you could not rely on the check `x is None` since the `is` operator is based on identity. Although `None == None` is also `True`, it's possible to have `x == None` be `True` when `x` is not actually `None`. See [this answer](https://stackoverflow.com/a/14247383/1464861) for an example. **How would one even implement this behavior in python?** You can implement this pattern by overridding `__new__`. Here's a basic example: ``` class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if Singleton._instance is None: Singleton._instance = object.__new__(cls, *args, **kwargs) return Singleton._instance if __name__ == '__main__': s1 = Singleton() s2 = Singleton() print 's1 is s2:', s1 is s2 print 'id(s1):', id(s1) print 'id(s2):', id(s2) ``` Output: > > s1 is s2: True > > id(s1): 4506243152 > > id(s2): 4506243152 > > > > Of course this simple example doesn't make it *impossible* to create a second instance.
> > Why is n the exact same Object as None? > > > Many immutable objects in Python are [interned](http://en.wikipedia.org/wiki/String_interning) including `None`, smaller ints, and many strings. Demo: ``` >>> s1='abc' >>> s2='def' >>> s3='abc' >>> id(s1) 4540177408 >>> id(s3) 4540177408 # Note: same as s1 >>> x=1 >>> y=2 >>> z=1 >>> id(x) 4538711696 >>> id(z) 4538711696 # Note: same as x ``` > > Why was the language designed > such that n is the exact same Object as None? > > > See above -- speed, efficiency, lack of ambiguity and memory usage among other reasons to intern immutable objects. > > How would one even > implement this behavior in python? > > > Among other ways, you can override `__new__` to return the same object: ``` class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__new__( cls, *args, **kwargs) return cls._instance ``` For strings, you can call [intern](http://docs.python.org/2/library/functions.html#intern) on Python 2 or [sys.intern](http://docs.python.org/3.3/library/sys.html#sys.intern) on Python 3
20,833,084
I want to change guest VM's(Windows) IP address on ESXi. One way I have known is using RDP to connect to the guest OS and modifying the network configuration. However, I wish to make the process automated. Hence, does vCenter or ESXi contain similar functions or tools to perform this demand? (I have tried ovftool and vCLI but not work) Thanks for ur reply. Rocas
2013/12/30
[ "https://Stackoverflow.com/questions/20833084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3145174/" ]
**Why is `n` the exact same Object as `None`?** The C implementation keeps a singleton instance. `NoneType.__new__` is returning the singleton instance. **Why was the language designed such that n is the exact same Object as `None`?** If there was not a singleton instance, then you could not rely on the check `x is None` since the `is` operator is based on identity. Although `None == None` is also `True`, it's possible to have `x == None` be `True` when `x` is not actually `None`. See [this answer](https://stackoverflow.com/a/14247383/1464861) for an example. **How would one even implement this behavior in python?** You can implement this pattern by overridding `__new__`. Here's a basic example: ``` class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if Singleton._instance is None: Singleton._instance = object.__new__(cls, *args, **kwargs) return Singleton._instance if __name__ == '__main__': s1 = Singleton() s2 = Singleton() print 's1 is s2:', s1 is s2 print 'id(s1):', id(s1) print 'id(s2):', id(s2) ``` Output: > > s1 is s2: True > > id(s1): 4506243152 > > id(s2): 4506243152 > > > > Of course this simple example doesn't make it *impossible* to create a second instance.
Other answers describe how to use `__new__` to implement a singleton, but that's not how None is actually implemented (in cPython at least, I haven't looked into other implementations). Trying to create an instance of None through `type(None)()` is special cased, and ends up calling the [following C function](http://hg.python.org/cpython/file/8b4d36d0c090/Objects/object.c#l1409): ``` static PyObject * none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) { if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) { PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments"); return NULL; } Py_RETURN_NONE; } ``` And `Py_RETURN_NONE` is [defined here](http://hg.python.org/cpython/file/8b4d36d0c090/Include/object.h#l837): ``` /* _Py_NoneStruct is an object of undefined type which can be used in contexts where NULL (nil) is not suitable (since NULL often means 'error'). Don't forget to apply Py_INCREF() when returning this value!!! */ PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */ #define Py_None (&_Py_NoneStruct) /* Macro for returning Py_None from a function */ #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None ``` Contrast this with the [function that creates a normal python object](http://hg.python.org/cpython/file/8b4d36d0c090/Objects/object.c#l237): ``` PyObject * _PyObject_New(PyTypeObject *tp) { PyObject *op; op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp)); if (op == NULL) return PyErr_NoMemory(); return PyObject_INIT(op, tp); } ``` When you create a normal object, memory for the object is allocated and initialized. When you try to create a new instance of `None`, all you get is a reference to the already existing `_Py_NoneStruct`. That's why, no matter what you do, every reference to `None` will be the exact same object.
20,833,084
I want to change guest VM's(Windows) IP address on ESXi. One way I have known is using RDP to connect to the guest OS and modifying the network configuration. However, I wish to make the process automated. Hence, does vCenter or ESXi contain similar functions or tools to perform this demand? (I have tried ovftool and vCLI but not work) Thanks for ur reply. Rocas
2013/12/30
[ "https://Stackoverflow.com/questions/20833084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3145174/" ]
Other answers describe how to use `__new__` to implement a singleton, but that's not how None is actually implemented (in cPython at least, I haven't looked into other implementations). Trying to create an instance of None through `type(None)()` is special cased, and ends up calling the [following C function](http://hg.python.org/cpython/file/8b4d36d0c090/Objects/object.c#l1409): ``` static PyObject * none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) { if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) { PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments"); return NULL; } Py_RETURN_NONE; } ``` And `Py_RETURN_NONE` is [defined here](http://hg.python.org/cpython/file/8b4d36d0c090/Include/object.h#l837): ``` /* _Py_NoneStruct is an object of undefined type which can be used in contexts where NULL (nil) is not suitable (since NULL often means 'error'). Don't forget to apply Py_INCREF() when returning this value!!! */ PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */ #define Py_None (&_Py_NoneStruct) /* Macro for returning Py_None from a function */ #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None ``` Contrast this with the [function that creates a normal python object](http://hg.python.org/cpython/file/8b4d36d0c090/Objects/object.c#l237): ``` PyObject * _PyObject_New(PyTypeObject *tp) { PyObject *op; op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp)); if (op == NULL) return PyErr_NoMemory(); return PyObject_INIT(op, tp); } ``` When you create a normal object, memory for the object is allocated and initialized. When you try to create a new instance of `None`, all you get is a reference to the already existing `_Py_NoneStruct`. That's why, no matter what you do, every reference to `None` will be the exact same object.
> > Why is n the exact same Object as None? > > > Many immutable objects in Python are [interned](http://en.wikipedia.org/wiki/String_interning) including `None`, smaller ints, and many strings. Demo: ``` >>> s1='abc' >>> s2='def' >>> s3='abc' >>> id(s1) 4540177408 >>> id(s3) 4540177408 # Note: same as s1 >>> x=1 >>> y=2 >>> z=1 >>> id(x) 4538711696 >>> id(z) 4538711696 # Note: same as x ``` > > Why was the language designed > such that n is the exact same Object as None? > > > See above -- speed, efficiency, lack of ambiguity and memory usage among other reasons to intern immutable objects. > > How would one even > implement this behavior in python? > > > Among other ways, you can override `__new__` to return the same object: ``` class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__new__( cls, *args, **kwargs) return cls._instance ``` For strings, you can call [intern](http://docs.python.org/2/library/functions.html#intern) on Python 2 or [sys.intern](http://docs.python.org/3.3/library/sys.html#sys.intern) on Python 3
28,899,747
I need to run the ffmpeg command in the PHP. But php-ffmpeg is no more supports the latest version and out of date. May i know alternate way to run the ffmpeg command in the webfile (PHP,Javascript,jQuery). I try the `exec()` and `shell_exec()` in the PHP file but gets the blank output. ``` echo shell_exec("/usr/local/bin/ffmpeg -i test.mp3 -codec:a libmp3lame -b:a 128k out.mp3"); ``` and ``` echo shell_exec("ffmpeg -i test.mp3 -codec:a libmp3lame -b:a 128k out.mp3"); ```
2015/03/06
[ "https://Stackoverflow.com/questions/28899747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3836660/" ]
ffmpeg outputs on stderr, so you need to redirect the output. Add `2>&1` to your command line: ``` echo shell_exec("/usr/local/bin/ffmpeg -i test.mp3 -codec:a libmp3lame -b:a 128k out.mp3 2>&1"); ``` Then you will see the output.
use **FFMpeg\FFMpeg**, you can install with composer: **"php-ffmpeg/php-ffmpeg"**: "0.5.\*@dev" ([FFMpeg\FFMpeg Git Repository](https://github.com/PHP-FFMpeg/PHP-FFMpeg)) **Or** use **Symfony Process**, you can install with composer: **"symfony/process" : "~2.0"** ([Symfony Process Documentation](http://symfony.com/doc/current/components/process.html)) **Or** use **proc\_open()** function. **FFMpeg\FFMpeg** used **Symfony Process** and **Symfony Process** used **proc\_open()** function :) I prefer to use Symfony Process: ``` require 'vendor/autoload.php'; use Symfony\Component\Process\Process; $process = new Process('ls -lsa'); $process->run(); ```
28,899,747
I need to run the ffmpeg command in the PHP. But php-ffmpeg is no more supports the latest version and out of date. May i know alternate way to run the ffmpeg command in the webfile (PHP,Javascript,jQuery). I try the `exec()` and `shell_exec()` in the PHP file but gets the blank output. ``` echo shell_exec("/usr/local/bin/ffmpeg -i test.mp3 -codec:a libmp3lame -b:a 128k out.mp3"); ``` and ``` echo shell_exec("ffmpeg -i test.mp3 -codec:a libmp3lame -b:a 128k out.mp3"); ```
2015/03/06
[ "https://Stackoverflow.com/questions/28899747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3836660/" ]
use **FFMpeg\FFMpeg**, you can install with composer: **"php-ffmpeg/php-ffmpeg"**: "0.5.\*@dev" ([FFMpeg\FFMpeg Git Repository](https://github.com/PHP-FFMpeg/PHP-FFMpeg)) **Or** use **Symfony Process**, you can install with composer: **"symfony/process" : "~2.0"** ([Symfony Process Documentation](http://symfony.com/doc/current/components/process.html)) **Or** use **proc\_open()** function. **FFMpeg\FFMpeg** used **Symfony Process** and **Symfony Process** used **proc\_open()** function :) I prefer to use Symfony Process: ``` require 'vendor/autoload.php'; use Symfony\Component\Process\Process; $process = new Process('ls -lsa'); $process->run(); ```
first you have to install ffmpeg library in your server. with out install ffmpeg in your server command will not run. the following link will help you <https://ffmpeg.org/> <https://www.resellerspanel.com/articles/dedicated-servers-articles/dedicated-servers-howtos/how-to-install-ffmpeg-on-a-dedicated-server/> then after run this command ``` exec("ffmpeg -i test.mp3 -codec:a libmp3lame -b:a 128k out.mp3"); ```
28,899,747
I need to run the ffmpeg command in the PHP. But php-ffmpeg is no more supports the latest version and out of date. May i know alternate way to run the ffmpeg command in the webfile (PHP,Javascript,jQuery). I try the `exec()` and `shell_exec()` in the PHP file but gets the blank output. ``` echo shell_exec("/usr/local/bin/ffmpeg -i test.mp3 -codec:a libmp3lame -b:a 128k out.mp3"); ``` and ``` echo shell_exec("ffmpeg -i test.mp3 -codec:a libmp3lame -b:a 128k out.mp3"); ```
2015/03/06
[ "https://Stackoverflow.com/questions/28899747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3836660/" ]
ffmpeg outputs on stderr, so you need to redirect the output. Add `2>&1` to your command line: ``` echo shell_exec("/usr/local/bin/ffmpeg -i test.mp3 -codec:a libmp3lame -b:a 128k out.mp3 2>&1"); ``` Then you will see the output.
first you have to install ffmpeg library in your server. with out install ffmpeg in your server command will not run. the following link will help you <https://ffmpeg.org/> <https://www.resellerspanel.com/articles/dedicated-servers-articles/dedicated-servers-howtos/how-to-install-ffmpeg-on-a-dedicated-server/> then after run this command ``` exec("ffmpeg -i test.mp3 -codec:a libmp3lame -b:a 128k out.mp3"); ```
32,116,167
I am using jquery validate for form validation. There is only one element in the form as of now.Others will be added later.The `form_email` field is required. here is my script with html ``` <form novalidate="novalidate" name="Emergency Contact Form" action="#" id="form_3" class="form-horizontal"> <div class="form-body"> <div class="form-group act"> <label class="control-label col-md-3">What is your email address? <span class="required">* </span></label> <div class="col-md-4"> <input id="18" name="form_email" class="form-control element" type="email"> </div> <br><br> <div class="col-md-offset-3 col-md-9"> <button type="button" id="btn18" class="btn green">Submit</button> </div> </div> </div> </form> <script> $(document).ready(function(){ $("#form_3").validate({ rules: { form_email: { required: true,email: true} }, messages: { form_email: { required:"We require your email address to proceed" } } }); $("#btn18").on("click",function(){ if($("#form_3").valid()){ getNextQuestion(elementVal); } }); }); </script> ``` The problem is that when I keep the email field empty and click the button it does not give the validation msg. But when I enter an invalid email address(asdf@ghjk.) and click the button it gives the validation msg('Please enter a valid email address.'). Why is it not giving validation msg when field is empty. These html elements are injected through ajax. Thanks in Advance!
2015/08/20
[ "https://Stackoverflow.com/questions/32116167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3710726/" ]
``` <div ng-repeat="x in names"> <div>{{x.name}} <span ng-repeat="y in usernames track by $index"> <input ng-model="y.assignedUserNames" ng-if="y.mgId==x.mgId "></input> </span> </div> </div> ``` Working [plunker](http://fiddle.jshell.net/7Ly6q14c/10/)
You can do something like this in code.. ```js var app = angular.module('app', []); app.controller('ctrl', function ($scope) { $scope.masterClausesList = [ { "Id":1, "ID":1, "Title":"Platform", "Desc":"Our Platform provides our users with a variety of resources to facilitate organizing of groups, (a \"Meetup\" or \"Meetup Group\"), and creating of a network (\"Meetup Everywhere\").", "Checked":null, "CCategory":"Company Contracts" }, { "Id":2, "ID":2, "Title":"Membership", "Desc":"Our Platform provides our users with a variety of resources to facilitate organizing of groups, (a \"Meetup\" or \"Meetup Group\"), and creating of a network (\"Meetup Everywhere\").", "Checked":null, "CCategory":"Company Contracts" }, { "Id":3, "ID":3, "Title":"Payment", "Desc":"Limited to 100 days", "Checked":null, "CCategory":"Company Contracts" } ]; $scope.selectedContract = []; $scope.selectedContract.clausesSelected = [ { "Id":1, "ID":1, "Title":"Platform", "SortId":null, "Desc":"Our Platform provides our users with a variety of resources to facilitate organizing of groups, (a \"Meetup\" or \"Meetup Group\"), and creating of a network (\"Meetup Everywhere\").", "CCategory":null, "CUSER":null, "CCONTRACTHDRID":"6", "CCLAUSEMSTID":"1" } ]; $scope.kk = '___'; var k2 = []; angular.forEach($scope.masterClausesList, function (value1,key1) { angular.forEach($scope.selectedContract.clausesSelected, function (value2,key2) { }); }); var log = []; angular.forEach($scope.masterClausesList, function(value) { angular.forEach($scope.selectedContract.clausesSelected, function (value2) { if(value2.CCLAUSEMSTID == value.Id){ value.Checked = true this.push(value); }else{ //this.push(value); } },log); }, log); $scope.kk = log; }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script> <body ng-app="app" ng-controller="ctrl"> {{kk}} </body> ```
1,941,044
> > $\mathbf{a}\times \mathbf{b}$ follows the right hand rule? Why not left hand rule? Why is it $a b \sin (x)$ times the perpendicular vector? Why is $\sin (x)$ used with the vectors but $\cos(x)$ is a scalar product? > > > So why is cross product defined in the way that it is? I am mainly interested in the right hand rule defintion too as it is out of reach?
2016/09/25
[ "https://math.stackexchange.com/questions/1941044", "https://math.stackexchange.com", "https://math.stackexchange.com/users/363952/" ]
Well, one can see the rule as is in order to agree with the standard orientation of $\mathbb{R}^3$ $(e\_1 \times e\_2=e\_3)$. Or just convention. There is a way to see how this can come up "naturally", though. Given $a,b \in \mathbb{R}^3$, $a \times b$ is the vector which comes out from Riesz representation theorem (a fancy way to say that $V \simeq V^\*$ using the isomorphism given by the inner product) applied to the linear functional $$\det(\cdot, a,b).$$ Computing the vector yields both the fact that it has its norm being what it should be and its direction also being what it should be. To get to the other direction, we would have to invert $a,b$, considering $a \times b$ to come from the vector corresponding to $\det(\cdot, b,a)$, an "unnatural" thing.
The real reason is because it is convention to use a right-handed coordinate system. If you switched to a left-handed coordinate system for some reason (I'm not sure why), then you would need to do your cross-products using a left-hand rule to get the same answers. That's really as simple as it gets. It's a result of our conventions in defining our coordinates the way we do.