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
25,388,825
Problem : There is a stack consisting of N bricks. You and your friend decide to play a game using this stack. In this game, one can alternatively remove 1/2/3 bricks from the top and the numbers on the bricks removed by the player is added to his score. You have to play in such a way that you obtain maximum possible score while it is given that your friend will also play optimally and you make the first move. Input Format First line will contain an integer T i.e. number of test cases. There will be two lines corresponding to each test case, first line will contain a number N i.e. number of element in stack and next line will contain N numbers i.e. numbers written on bricks from top to bottom. Output Format For each test case, print a single line containing your maximum score. I have tried with recursion but didn't work ``` int recurse(int length, int sequence[5], int i) { if(length - i < 3) { int sum = 0; for(i; i < length; i++) sum += sequence[i]; return sum; } else { int sum1 = 0; int sum2 = 0; int sum3 = 0; sum1 += recurse(length, sequence, i+1); sum2 += recurse(length, sequence, i+2); sum3 += recurse(length, sequence, i+3); return max(max(sum1,sum2),sum3); } } int main() { int sequence[] = {0, 0, 9, 1, 999}; int length = 5; cout << recurse(length, sequence, 0); return 0; } ```
2014/08/19
[ "https://Stackoverflow.com/questions/25388825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3005924/" ]
``` import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args){ Scanner sc=new Scanner(System.in); int noTest=sc.nextInt(); for(int i=0; i<noTest; i++){ int noBrick=sc.nextInt(); ArrayList<Integer> arr=new ArrayList<Integer>(); for (int j=0; j<noBrick; j++){ arr.add(sc.nextInt()); } long sum[]= new long[noBrick]; sum[noBrick-1]= arr.get(noBrick-1); for (int j=noBrick-2; j>=0; j--){ sum[j]= sum[j+1]+ arr.get(j); } long[] max=new long[noBrick]; if(noBrick>=1) max[noBrick-1]=arr.get(noBrick-1); if(noBrick>=2) max[noBrick-2]=(int)Math.max(arr.get(noBrick-2),max[noBrick-1]+arr.get(noBrick-2)); if(noBrick>=3) max[noBrick-3]=(int)Math.max(arr.get(noBrick-3),max[noBrick-2]+arr.get(noBrick-3)); if(noBrick>=4){ for (int j=noBrick-4; j>=0; j--){ long opt1= arr.get(j)+sum[j+1]-max[j+1]; long opt2= arr.get(j)+arr.get(j+1)+sum[j+2]-max[j+2]; long opt3= arr.get(j)+arr.get(j+1)+arr.get(j+2)+sum[j+3]-max[j+3]; max[j]= (long)Math.max(opt1,Math.max(opt2,opt3)); } } long cost= max[0]; System.out.println(cost); } } } ``` I tried this using Java, seems to work alright.
here a better solution that i found on the internet without recursion. ``` #include <iostream> #include <fstream> #include <algorithm> #define MAXINDEX 10001 using namespace std; long long maxResult(int a[MAXINDEX], int LENGTH){ long long prefixSum [MAXINDEX] = {0}; prefixSum[0] = a[0]; for(int i = 1; i < LENGTH; i++){ prefixSum[i] += prefixSum[i-1] + a[i]; } long long dp[MAXINDEX] = {0}; dp[0] = a[0]; dp[1] = dp[0] + a[1]; dp[2] = dp[1] + a[2]; for(int k = 3; k < LENGTH; k++){ long long x = prefixSum[k-1] + a[k] - dp[k-1]; long long y = prefixSum[k-2] + a[k] + a[k-1] - dp[k-2]; long long z = prefixSum[k-3] + a[k] + a[k-1] + a[k-2] - dp[k-3]; dp[k] = max(x,max(y,z)); } return dp[LENGTH-1]; } using namespace std; int main(){ int cases; int bricks[MAXINDEX]; ifstream fin("test.in"); fin >> cases; for (int i = 0; i < cases; i++){ long n; fin >> n; for(int j = 0; j < n; j++) fin >> bricks[j]; reverse(bricks, bricks+n); cout << maxResult(bricks, n)<< endl; } return 0; } ```
25,388,825
Problem : There is a stack consisting of N bricks. You and your friend decide to play a game using this stack. In this game, one can alternatively remove 1/2/3 bricks from the top and the numbers on the bricks removed by the player is added to his score. You have to play in such a way that you obtain maximum possible score while it is given that your friend will also play optimally and you make the first move. Input Format First line will contain an integer T i.e. number of test cases. There will be two lines corresponding to each test case, first line will contain a number N i.e. number of element in stack and next line will contain N numbers i.e. numbers written on bricks from top to bottom. Output Format For each test case, print a single line containing your maximum score. I have tried with recursion but didn't work ``` int recurse(int length, int sequence[5], int i) { if(length - i < 3) { int sum = 0; for(i; i < length; i++) sum += sequence[i]; return sum; } else { int sum1 = 0; int sum2 = 0; int sum3 = 0; sum1 += recurse(length, sequence, i+1); sum2 += recurse(length, sequence, i+2); sum3 += recurse(length, sequence, i+3); return max(max(sum1,sum2),sum3); } } int main() { int sequence[] = {0, 0, 9, 1, 999}; int length = 5; cout << recurse(length, sequence, 0); return 0; } ```
2014/08/19
[ "https://Stackoverflow.com/questions/25388825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3005924/" ]
My approach to solving this problem was as follows: ### Both players play optimally. So, the solution is to be built in a manner that need not take the player into account. This is because both players are going to pick the best choice available to them for any given state of the stack of bricks. ### The base cases: Either player, when left with the last one/two/three bricks, will choose to remove all bricks. For the sake of convenience, let's assume that the array is actually in reverse order (i.e. a[0] is the value of the bottom-most brick in the stack) (This can easily be incorporated by performing a reverse operation on the array.) So, the base cases are: ``` # Base Cases dp[0] = a[0] dp[1] = a[0]+a[1] dp[2] = a[0]+a[1]+a[2] ``` ### Building the final solution: Now, in each iteration, a player has 3 choices. 1. pick brick (i), or, 2. pick brick (i and i-1) , or, 3. pick brick (i,i-1 and i-2) If the player opted for choice 1, the following would result: * player secures a[i] points from the brick (i) (+a[i]) * will not be able to procure the points on the bricks removed by the opponent. This value is stored in dp[i-1] (which the opponent will end up scoring by virtue of this choice made by the player). * will surely procure the points on the bricks not removed by the opponent. (+ Sum of all the bricks up until brick (i-1) not removed by opponent ) A prefix array to store the partial sums of points of bricks can be computed as follows: ``` # build prefix sum array pre = [a[0]] for i in range(1,n): pre.append(pre[-1]+a[i]) ``` And, now, if player opted for choice 1, the score would be: ``` ans1 = a[i] + (pre[i-1] - dp[i-1]) ``` Similarly, for choices 2 and 3. So, we get: ``` ans1 = a[i]+ (pre[i-1] - dp[i-1]) # if we pick only ith brick ans2 = a[i]+a[i-1]+(pre[i-2] - dp[i-2]) # pick 2 bricks ans3 = a[i]+a[i-1]+a[i-2]+(pre[i-3] - dp[i-3]) # pick 3 bricks ``` Now, each player wants to maximize this value. So, in each iteration, we pick the maximum among ans1, ans2 and ans3. dp[i] = max(ans1, ans2, ans3) Now, all we have to do is to iterate from 3 through to n-1 to get the required solution. Here is the final snippet in python: ``` a = map(int, raw_input().split()) a.reverse() # so that a[0] is bottom brick of stack dp = [0 for x1 in xrange(n)] dp[0] = a[0] dp[1] = a[0]+a[1] dp[2] = a[0]+a[1]+a[2] # build prefix sum array pre = [a[0]] for i in range(1,n): pre.append(pre[-1]+a[i]) for i in xrange(3,n): # We can pick brick i, (i,i-1) or (i,i-1,i-2) ans1 = a[i]+ (pre[i-1] - dp[i-1]) # if we pick only ith brick ans2 = a[i]+a[i-1]+(pre[i-2] - dp[i-2]) # pick 2 ans3 = a[i]+a[i-1]+a[i-2]+(pre[i-3] - dp[i-3]) #pick 3 # both players maximise this value. Doesn't matter who is playing dp[i] = max(ans1, ans2, ans3) print dp[n-1] ```
here a better solution that i found on the internet without recursion. ``` #include <iostream> #include <fstream> #include <algorithm> #define MAXINDEX 10001 using namespace std; long long maxResult(int a[MAXINDEX], int LENGTH){ long long prefixSum [MAXINDEX] = {0}; prefixSum[0] = a[0]; for(int i = 1; i < LENGTH; i++){ prefixSum[i] += prefixSum[i-1] + a[i]; } long long dp[MAXINDEX] = {0}; dp[0] = a[0]; dp[1] = dp[0] + a[1]; dp[2] = dp[1] + a[2]; for(int k = 3; k < LENGTH; k++){ long long x = prefixSum[k-1] + a[k] - dp[k-1]; long long y = prefixSum[k-2] + a[k] + a[k-1] - dp[k-2]; long long z = prefixSum[k-3] + a[k] + a[k-1] + a[k-2] - dp[k-3]; dp[k] = max(x,max(y,z)); } return dp[LENGTH-1]; } using namespace std; int main(){ int cases; int bricks[MAXINDEX]; ifstream fin("test.in"); fin >> cases; for (int i = 0; i < cases; i++){ long n; fin >> n; for(int j = 0; j < n; j++) fin >> bricks[j]; reverse(bricks, bricks+n); cout << maxResult(bricks, n)<< endl; } return 0; } ```
25,388,825
Problem : There is a stack consisting of N bricks. You and your friend decide to play a game using this stack. In this game, one can alternatively remove 1/2/3 bricks from the top and the numbers on the bricks removed by the player is added to his score. You have to play in such a way that you obtain maximum possible score while it is given that your friend will also play optimally and you make the first move. Input Format First line will contain an integer T i.e. number of test cases. There will be two lines corresponding to each test case, first line will contain a number N i.e. number of element in stack and next line will contain N numbers i.e. numbers written on bricks from top to bottom. Output Format For each test case, print a single line containing your maximum score. I have tried with recursion but didn't work ``` int recurse(int length, int sequence[5], int i) { if(length - i < 3) { int sum = 0; for(i; i < length; i++) sum += sequence[i]; return sum; } else { int sum1 = 0; int sum2 = 0; int sum3 = 0; sum1 += recurse(length, sequence, i+1); sum2 += recurse(length, sequence, i+2); sum3 += recurse(length, sequence, i+3); return max(max(sum1,sum2),sum3); } } int main() { int sequence[] = {0, 0, 9, 1, 999}; int length = 5; cout << recurse(length, sequence, 0); return 0; } ```
2014/08/19
[ "https://Stackoverflow.com/questions/25388825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3005924/" ]
My approach to solving this problem was as follows: ### Both players play optimally. So, the solution is to be built in a manner that need not take the player into account. This is because both players are going to pick the best choice available to them for any given state of the stack of bricks. ### The base cases: Either player, when left with the last one/two/three bricks, will choose to remove all bricks. For the sake of convenience, let's assume that the array is actually in reverse order (i.e. a[0] is the value of the bottom-most brick in the stack) (This can easily be incorporated by performing a reverse operation on the array.) So, the base cases are: ``` # Base Cases dp[0] = a[0] dp[1] = a[0]+a[1] dp[2] = a[0]+a[1]+a[2] ``` ### Building the final solution: Now, in each iteration, a player has 3 choices. 1. pick brick (i), or, 2. pick brick (i and i-1) , or, 3. pick brick (i,i-1 and i-2) If the player opted for choice 1, the following would result: * player secures a[i] points from the brick (i) (+a[i]) * will not be able to procure the points on the bricks removed by the opponent. This value is stored in dp[i-1] (which the opponent will end up scoring by virtue of this choice made by the player). * will surely procure the points on the bricks not removed by the opponent. (+ Sum of all the bricks up until brick (i-1) not removed by opponent ) A prefix array to store the partial sums of points of bricks can be computed as follows: ``` # build prefix sum array pre = [a[0]] for i in range(1,n): pre.append(pre[-1]+a[i]) ``` And, now, if player opted for choice 1, the score would be: ``` ans1 = a[i] + (pre[i-1] - dp[i-1]) ``` Similarly, for choices 2 and 3. So, we get: ``` ans1 = a[i]+ (pre[i-1] - dp[i-1]) # if we pick only ith brick ans2 = a[i]+a[i-1]+(pre[i-2] - dp[i-2]) # pick 2 bricks ans3 = a[i]+a[i-1]+a[i-2]+(pre[i-3] - dp[i-3]) # pick 3 bricks ``` Now, each player wants to maximize this value. So, in each iteration, we pick the maximum among ans1, ans2 and ans3. dp[i] = max(ans1, ans2, ans3) Now, all we have to do is to iterate from 3 through to n-1 to get the required solution. Here is the final snippet in python: ``` a = map(int, raw_input().split()) a.reverse() # so that a[0] is bottom brick of stack dp = [0 for x1 in xrange(n)] dp[0] = a[0] dp[1] = a[0]+a[1] dp[2] = a[0]+a[1]+a[2] # build prefix sum array pre = [a[0]] for i in range(1,n): pre.append(pre[-1]+a[i]) for i in xrange(3,n): # We can pick brick i, (i,i-1) or (i,i-1,i-2) ans1 = a[i]+ (pre[i-1] - dp[i-1]) # if we pick only ith brick ans2 = a[i]+a[i-1]+(pre[i-2] - dp[i-2]) # pick 2 ans3 = a[i]+a[i-1]+a[i-2]+(pre[i-3] - dp[i-3]) #pick 3 # both players maximise this value. Doesn't matter who is playing dp[i] = max(ans1, ans2, ans3) print dp[n-1] ```
``` import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args){ Scanner sc=new Scanner(System.in); int noTest=sc.nextInt(); for(int i=0; i<noTest; i++){ int noBrick=sc.nextInt(); ArrayList<Integer> arr=new ArrayList<Integer>(); for (int j=0; j<noBrick; j++){ arr.add(sc.nextInt()); } long sum[]= new long[noBrick]; sum[noBrick-1]= arr.get(noBrick-1); for (int j=noBrick-2; j>=0; j--){ sum[j]= sum[j+1]+ arr.get(j); } long[] max=new long[noBrick]; if(noBrick>=1) max[noBrick-1]=arr.get(noBrick-1); if(noBrick>=2) max[noBrick-2]=(int)Math.max(arr.get(noBrick-2),max[noBrick-1]+arr.get(noBrick-2)); if(noBrick>=3) max[noBrick-3]=(int)Math.max(arr.get(noBrick-3),max[noBrick-2]+arr.get(noBrick-3)); if(noBrick>=4){ for (int j=noBrick-4; j>=0; j--){ long opt1= arr.get(j)+sum[j+1]-max[j+1]; long opt2= arr.get(j)+arr.get(j+1)+sum[j+2]-max[j+2]; long opt3= arr.get(j)+arr.get(j+1)+arr.get(j+2)+sum[j+3]-max[j+3]; max[j]= (long)Math.max(opt1,Math.max(opt2,opt3)); } } long cost= max[0]; System.out.println(cost); } } } ``` I tried this using Java, seems to work alright.
53,160,164
I am trying to select 'contractkey' after joining the two tables. All I can run now is "select \*" and then all columns are returned. Below is the query. It runs perfectly as long as I do not try to select a column. How can I select a specific column? do I need to to label the table after the INNER JOIN? ``` Select * FROM (SELECT attachmentdata.contractkey, requirementinfo.reqcode, requirementinfo.parentidkey as 'ReqInfoParentID', max(attachment.datecreated) as datecreated, applicationinfo.hocompletiondate FROM location1.attachment LEFT JOIN location1.attachmentdata on attachment.contractkey = attachmentdata.contractkey and attachment.id = attachmentdata.parentidkey --Links Attachment Type LEFT JOIN location1.requirementinfo on attachment.contractkey = requirementinfo.contractkey and attachment.parentidkey = requirementinfo.id --Links Attachment Type INNER JOIN location1.applicationinfo on attachment.contractkey = applicationinfo.contractkey and requirementinfo.parentidkey = applicationinfo.parentidkey --Links Policy Type where (requirementinfo.reqcode = 2) group by attachmentdata.contractkey,requirementinfo.reqcode, requirementinfo.parentidkey, applicationinfo.hocompletiondate) as table1 INNER JOIN (SELECT attachmentdata.contractkey, requirementinfo.reqcode, requirementinfo.parentidkey as 'ReqInfoParentID', attachment.datecreated, applicationinfo.hocompletiondate, attachmentdata.pcdata FROM location1.attachment LEFT JOIN location1.attachmentdata on attachment.contractkey = attachmentdata.contractkey and attachment.id = attachmentdata.parentidkey --Links Attachment Type LEFT JOIN location1.requirementinfo on attachment.contractkey = requirementinfo.contractkey and attachment.parentidkey = requirementinfo.id --Links Attachment Type INNER JOIN location1.applicationinfo on attachment.contractkey = applicationinfo.contractkey and requirementinfo.parentidkey = applicationinfo.parentidkey)table2 on table1.contractkey = table2.contractkey and table1.reqcode = table2.reqcode and table1.ReqInfoParentID = table2.ReqInfoParentID and table1.datecreated = table2.datecreated and table1.hocompletiondate = table2.hocompletiondate ```
2018/11/05
[ "https://Stackoverflow.com/questions/53160164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9381751/" ]
There are columns `contractkey` in both tables, so the system doesn't know which ones you want. So you will have to put tablename in front of it. `SELECT table1.contractkey, ...`
Add the following to the end of your outermost inner table selects: ``` SELECT contractkey FROM (SELECT attachmentdata.contractkey, etc... ) AS t(contractkey,reqcode,ReqInfoParentID,datecreated,hocompletiondate) ```
53,160,164
I am trying to select 'contractkey' after joining the two tables. All I can run now is "select \*" and then all columns are returned. Below is the query. It runs perfectly as long as I do not try to select a column. How can I select a specific column? do I need to to label the table after the INNER JOIN? ``` Select * FROM (SELECT attachmentdata.contractkey, requirementinfo.reqcode, requirementinfo.parentidkey as 'ReqInfoParentID', max(attachment.datecreated) as datecreated, applicationinfo.hocompletiondate FROM location1.attachment LEFT JOIN location1.attachmentdata on attachment.contractkey = attachmentdata.contractkey and attachment.id = attachmentdata.parentidkey --Links Attachment Type LEFT JOIN location1.requirementinfo on attachment.contractkey = requirementinfo.contractkey and attachment.parentidkey = requirementinfo.id --Links Attachment Type INNER JOIN location1.applicationinfo on attachment.contractkey = applicationinfo.contractkey and requirementinfo.parentidkey = applicationinfo.parentidkey --Links Policy Type where (requirementinfo.reqcode = 2) group by attachmentdata.contractkey,requirementinfo.reqcode, requirementinfo.parentidkey, applicationinfo.hocompletiondate) as table1 INNER JOIN (SELECT attachmentdata.contractkey, requirementinfo.reqcode, requirementinfo.parentidkey as 'ReqInfoParentID', attachment.datecreated, applicationinfo.hocompletiondate, attachmentdata.pcdata FROM location1.attachment LEFT JOIN location1.attachmentdata on attachment.contractkey = attachmentdata.contractkey and attachment.id = attachmentdata.parentidkey --Links Attachment Type LEFT JOIN location1.requirementinfo on attachment.contractkey = requirementinfo.contractkey and attachment.parentidkey = requirementinfo.id --Links Attachment Type INNER JOIN location1.applicationinfo on attachment.contractkey = applicationinfo.contractkey and requirementinfo.parentidkey = applicationinfo.parentidkey)table2 on table1.contractkey = table2.contractkey and table1.reqcode = table2.reqcode and table1.ReqInfoParentID = table2.ReqInfoParentID and table1.datecreated = table2.datecreated and table1.hocompletiondate = table2.hocompletiondate ```
2018/11/05
[ "https://Stackoverflow.com/questions/53160164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9381751/" ]
There are columns `contractkey` in both tables, so the system doesn't know which ones you want. So you will have to put tablename in front of it. `SELECT table1.contractkey, ...`
It is not required to "Label the table"(Alias). Use Case to make sure it won't put null for records that are not in the AttachmentData table as follow: ``` Select * FROM (SELECT case WHEN attachmentdata.contractkey IS NOT NULL THEN attachmentdata.contractkey else attachment.contractkey END AS contractkey, requirementinfo.reqcode, requirementinfo.parentidkey as 'ReqInfoParentID', max(attachment.datecreated) as datecreated, applicationinfo.hocompletiondat ... ```
12,108,495
Firstly apologies with my limited knowledge, I am just starting out in CF. So I am trying to send out an html email with cfmail when a form query is satisfied. The problem I am having is that the css I am embedding within the email head is either throwing up errors or just not formatting at all. Please could someone look at my code and tell me where I am going wrong. Incidentally when I take out the # tags in the css it seems to work but the email sends with no formatting!!! ``` <cfmail to="customer email" from="xxxxxxx@gmail.com" subject="Your order at has been shipped" type="html"> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Title</title> <style type="text/css"> body { color: #000000; font-family: Arial, Helvetica, sans-serif; } body, td, th, input, textarea, select, a { font-size: 12px; } p { margin-top: 0px; margin-bottom: 20px; } a, a:visited, a b { color: #378DC1; text-decoration: underline; cursor: pointer; } a:hover { text-decoration: none; } a img { border: none; } #container { width: 680px; } #logo { margin-bottom: 20px; } table.list { border-collapse: collapse; width: 100%; border-top: 1px solid #DDDDDD; border-left: 1px solid #DDDDDD; margin-bottom: 20px; } table.list td { border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; } table.list thead td { background-color: #EFEFEF; padding: 0px 5px; } table.list thead td a, .list thead td { text-decoration: none; color: #222222; font-weight: bold; } table.list tbody td a { text-decoration: underline; } table.list tbody td { vertical-align: top; padding: 0px 5px; } table.list .left { text-align: left; padding: 7px; } table.list .right { text-align: right; padding: 7px; } table.list .center { text-align: center; padding: 7px; } </style> </head> <body> <div id="container"> <p>Your Order has been Shipped</p> <table class="list"> <thead> <tr> <td class="left" colspan="2">text_order_detail;</td> </tr> </thead> <tbody> <tr> <td class="left"><b>text_order_id</b><br /> <b>text_date_added</b><br /> <b>text_payment_method</b><br /> <b>text_shipping_method</b> </td> <td class="left"><b>text_email</b><br /> <b>text_telephone</b><br /> <b>text_ip<br /></td> </tr> </tbody> </table> <table class="list"> <thead> <tr> <td class="left">text_instruction</td> </tr> </thead> <tbody> <tr> <td class="left">comment</td> </tr> </tbody> </table> <table class="list"> <thead> <tr> <td class="left">text_payment_address</td> <td class="left">text_shipping_address</td> </tr> </thead> <tbody> <tr> <td class="left">payment_address</td> <td class="left">shipping_address</td> </tr> </tbody> </table> <table class="list"> <thead> <tr> <td class="left">text_product</td> <td class="left">text_model</td> <td class="right">text_quantity</td> <td class="right">text_price</td> <td class="right">text_total</td> </tr> </thead> <tbody> <tr> <td class="left">product <br /> <small>option</small> </td> <td class="left">product['model']</td> <td class="right">product['quantity']</td> <td class="right">product['price']</td> <td class="right">product['total']</td> </tr> </tbody> <tfoot> <tr> <td colspan="4" class="right"><b>total['title']</b></td> <td class="right">total['text']</td> </tr> </tfoot> </table> <p>text_footer</p> <p>text_powered</p> </div> </body> </html> </cfmail> </cfif> ```
2012/08/24
[ "https://Stackoverflow.com/questions/12108495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1206585/" ]
You should stick to inline styles for HTML emails rather than having your styles presented the way you are doing. E.G. ``` <td style="padding:10px;"></td> ```
Two issues the first is you need to use `##` in your CSS instead of `#`, otherwise ColdFusion tries to process those as variables. The second is you have an erroneous `</cfif>` at the bottom of your page, but that was probably just from when you copy and pasted your code. I tested the code with `##` instead of `#` and the email sent correctly on CF 9.0.1
5,225,639
I hope you forgive me if I'm a little confused about this. Jrails rewrites all the helper methods for rjs otherwise in prototype. Jquery-rails overrides rails.js (so I taught the rjs helpers as well, but I see it's not) and the rest of the libraries in jquery instead of prototype. Does it means that with just Jquery-rails I can't use rjs at all? Then do these gems work well together and let me completely forget prototype? Is there any disadvantage in using them together? I read some complaining about the fact that jrails uses jq 1.5 and now there is 1.8, but jquery-rails gives me the last version (is there retro compatibility?), but how will this affect my development (using both the gems together)? I mean Have you got some examples of jquery-ui plugins I can't use, or I could have problems with latest versions? Any help is appreciated. Don't get me wrong, I'm not against prototype, just I keep on having conflicts over conflicts using both of them, and if I have to choose I pick Jquery.
2011/03/07
[ "https://Stackoverflow.com/questions/5225639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/465915/" ]
Yes, RJS requires jrails. Otherwise RJS generates `prototype` code. I just started using jrails and jquery-rails together and they work fine. I have to use jrails because my app has many RJS files. In general, people who switched to jQuery write pure JavaScript code. They do not use RJS at all so jrails is not needed. Instead of RJS, ERB templates are used. E.g. ``` $('#foo').html("<%= escape_javascript(render "bar") %>"); ```
Rails has the concept of a "javascript driver", which can be replaced with *any* javascript library. By dafault it uses prototype, but if you install jquery-rails, it removes the JS driver for prototype, and adds the jQuery driver. So you can still run rjs with jQuery, as the driver is different, and will output jQuery commands, rather than prototype. About the jQuery version, you're confusing jQuery with jQueryUI. The last version of jQuery is 1.5.1 (and I think jQuery-rails has 1.5), and the latest of jQueryUI is 1.8.10. jQuery UI is an extension of jQuery, which includes mouse interaction, more effects, themes and other goodies. If you're new to jQuery, I strongly suggest you to read [jQuery in Action](http://www.manning.com/bibeault2/). It's an amazing introduction to jQuery and jQueryUI.... definitely worth every penny.
40,320
How do i decide whether to sign someones PGP public key? I was looking at some contact pages and they have a request for people to sign their public key. How serious of a commitment is it to sign someones public key?
2013/08/09
[ "https://security.stackexchange.com/questions/40320", "https://security.stackexchange.com", "https://security.stackexchange.com/users/28403/" ]
You should really only sign someone's key if you actually know them, and you trust that the key is theirs. When you sign it, you are saying that you checked them out, that you know it's their key. You then figure out "would I trust this person to be as thorough as me in evaluating the identity of other people?" You might have friends who are careful, or people who you are acquainted with and hold a position of responsibility so you think they might be trustworthy, or they might be a complete stranger, so you wouldn't trust them with a burned out match. That's when you assign the level of trust. A web page begging you to sign it could be someone trying to build a sock puppet, false identity, or even stealing someone else's identity. Worse, they could be collecting the identities of people who are gullible enough to sign a random key with no validation process.
You need to verify their identity. Normally this would require them you to have them show you two forms of identity validation (for instance an ID card and a driver's license) and by making them show you a document which determines that they actually live at their listed address ( a bill for electricity or water for instance). For instance CAcert is a community driven certificate authority. They sometimes do signing parties: > > To create higher-trust certificates, users can participate in a web of > trust system whereby users physically meet and verify each other's > identities. CAcert maintains the number of assurance points for each > account. Assurance points can be gained through various means, > primarily by having one's identity physically verified by users > classified as "Assurers". Having more assurance points allows users > more privileges such as writing a name in the certificate and longer > expiration times on certificates. A user with at least 100 assurance > points is a Prospective Assurer, and may—after passing an Assurer > Challenge[5]—verify other users; more assurance points allow the > Assurer to assign more assurance points to others. > > >
54,281,820
Cannot add formatting for time. Should be displayed in 12 hours, AM PM format; I need this one for a subscription form for customers. The Date and Time I am using for schedule How to get 12 hours AM PM time format? ```js private weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; private monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; constructor(private router: Router) {} ngOnInit() { } getCurrentUrl() { return this.router.url.split('#')[0]; } formatDate(dt) { const _date = new Date(dt); const nameDay = this.weekday[_date.getDay()]; return nameDay + ', ' + _date.getDate() + ' ' + this.monthNames[_date.getMonth()] + ' ' + _date.getFullYear(); } getTime(dt) { const _date = new Date(dt); let _hour = _date.getHours().toString(); let _min = _date.getMinutes().toString(); _hour = _hour.length === 1 ? '0' + _hour.toString() : _hour; _min = _min.length === 1 ? '0' + _min.toString() : _min; return _hour + ':' + _min; ```
2019/01/20
[ "https://Stackoverflow.com/questions/54281820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9231814/" ]
I feel like I need more detail. But given what you have provided: <https://codepen.io/nstanard/pen/bzbdrJ> ``` let date = new Date(); function formatDate(dt) { // const _date = new Date(dt); // const nameDay = this.weekday[dt.getDay()]; // return nameDay + ', ' + dt.getDate() + ' ' + this.monthNames[dt.getMonth()] + ' ' + dt.getFullYear(); let normalizeHour = dt.getHours() >= 13 ? dt.getHours() - 12 : dt.getHours() return dt.getHours() >= 13 ? normalizeHour + 'PM' : normalizeHour + 'AM' } console.log(formatDate(date)) ``` Here is the hour of a date object formatted for AM and PM. Read more --------- **However,** if you are using TypeScript and Angular I suggest you take a look a the following example: <https://stackblitz.com/edit/angular-sc1ihu> 1. create a date object `dateNow : Date = new Date();` 2. Use the date format in the html. `{{dateNow | date:'short'}}` Using DatePipe is part of ng.common and IS best practice.
Instead of going to the hassle of creating your own date formatter, why don't you use the built-in datePipe? ``` constructor(private datePipe: DatePipe){ this.datePipe.transform(this._date, 'yyyy MM dd'); } ``` you can use all the built-in values of the DatePipe. Don't forget to add DatePipe to your providers array.
24,365,156
One day ago i created a project in netbeans. It is a simple database desktop application using mysql community edition. It was working fine.When I export this project to another machine and try to run it, it was not working. I didn't get what happen because I am new to java programming .Kindly help. my output log in NetBeans: ``` warning: [options] bootstrap class path not set in conjunction with -source 1.7 warning: Supported source version 'RELEASE_6' from annotation processor 'org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor' less than -source '1.7' warning: The following options were not recognized by any processor: '[eclipselink.canonicalmodel.use_static_factory]' 1 warning compile: run: [EL Info]: 2014-06-23 16:36:54.049--ServerSession(967343730)--EclipseLink, version: Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5 [EL Severe]: ejb: 2014-06-23 16:36:54.517--ServerSession(967343730)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: NO) Error Code: 1045 Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: NO) Error Code: 1045 at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:766) at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:766) at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:204) at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(EntityManagerFactoryDelegate.java:304) at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:336) at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:302) at select_record.SelectRecord.initComponents(SelectRecord.java:44) at select_record.SelectRecord.<init>(SelectRecord.java:23) at EmployeeInformation.<init>(EmployeeInformation.java:12) at EmployeeInformation.main(EmployeeInformation.java:243) Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: NO) Error Code: 1045 at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:331) at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:326) at org.eclipse.persistence.sessions.DefaultConnector.connect(DefaultConnector.java:138) at org.eclipse.persistence.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:162) at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.setOrDetectDatasource(DatabaseSessionImpl.java:204) at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:741) at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:239) at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:685) ... 8 more Caused by: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: NO) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:925) at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1704) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1250) at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2465) at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2498) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2283) at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:822) at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:408) at com.mysql.jdbc.Util.handleNewInstance(Util.java:411) at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:404) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:317) at java.sql.DriverManager.getConnection(DriverManager.java:664) at java.sql.DriverManager.getConnection(DriverManager.java:208) at org.eclipse.persistence.sessions.DefaultConnector.connect(DefaultConnector.java:98) ... 13 more Java Result: 1 BUILD SUCCESSFUL (total time: 16 seconds) ```
2014/06/23
[ "https://Stackoverflow.com/questions/24365156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3767255/" ]
Actually after reading the error stream, your error is somewhere here: ``` Access denied for user 'root'@'localhost' (using password: NO) Error Code: 1045 Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: NO) Error ``` Please do check on your database connection credential:
Change the password and username of DB class into new mysql server details.without that JAVA application unable to connect with mysql server.
21,445,701
How can I call the Zamkniecie() file Window1.cs not the new object as I showed in the method Window\_Closed(), but the object you are currently working with a file MainWindow.cs? Components of methods Zamkniecie() have been created in the file MainWindow.xaml ``` File: Window1.cs namespace AllSportsBets102 { public partial class Window1 : Window { public Window1(DataGrid zdg, List<Data2> dsx) { InitializeComponent(); } private void Window_Closed(object sender, EventArgs e) { MainWindow mw = new MainWindow(); mw.Zamkniecie(); } } } File: MainWindow.cs namespace AllSportsBets102 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } public void Zamkniecie() { InfoStackPanel.IsEnabled = true; KuponStackPanel1.IsEnabled = true; KuponStackPanel2.IsEnabled = true; FiltrStackPanel.IsEnabled = true; WszystkieZdarzeniaStackPanel1.IsEnabled = true; WszystkieZdarzeniaStackPanel2.IsEnabled = true; KuponLabel.IsEnabled = true; WszystkieLabel.IsEnabled = true; InfoLabel.IsEnabled = true; StackPanel1Copy.IsEnabled = true; StackPanel2Copy.IsEnabled = true; } } } ```
2014/01/30
[ "https://Stackoverflow.com/questions/21445701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2735729/" ]
Here are a few options: 1. Give Window1 a reference to MainWindow so it can call the Zamkniecie method. 2. Make the Zamkniecie method static. 3. Move the Zamkniecie method into Window1. 4. If there is only one instance of MainWindow, implement MainWindow as a singleton so you will have access to it from anywhere. 5. If MainWindow instantiates Window1, raise an event from Window1 that is handled on MainWindow. 6. If MainWindow does not instantiate Window1, implement the observer pattern. I prefer option 5, if it's possible because it more closely allow each class to manage itself. If you only want to call Zamkniecie when Window1 closes, you should be able to recognize that from MainWindow. Here's a code snippet that would go in MainWindow: ``` Window1 window1 = new Window1(); window1.ShowDialog(); Zamkniecie(); ``` Note: Which file these classes are in makes no difference as long as they are in the same namespace.
I know this might be redundant, but the quickest way would be to add an ``` using MainWindow.cs; ``` at the top of the Window1.cs file
60,008,180
I have a `pyspark.sql.dataframe.DataFrame` like the following ``` df.show() +--------------------+----+----+---------+----------+---------+----------+---------+ | ID|Code|bool| lat| lon| v1| v2| v3| +--------------------+----+----+---------+----------+---------+----------+---------+ |5ac52674ffff34c98...|IDFA| 1|42.377167| -71.06994|17.422535|1525319638|36.853622| |5ac52674ffff34c98...|IDFA| 1| 42.37747|-71.069824|17.683573|1525319639|36.853622| |5ac52674ffff34c98...|IDFA| 1| 42.37757| -71.06942|22.287935|1525319640|36.853622| |5ac52674ffff34c98...|IDFA| 1| 42.37761| -71.06943|19.110023|1525319641|36.853622| |5ac52674ffff34c98...|IDFA| 1|42.377243| -71.06952|18.904774|1525319642|36.853622| |5ac52674ffff34c98...|IDFA| 1|42.378254| -71.06948|20.772903|1525319643|36.853622| |5ac52674ffff34c98...|IDFA| 1| 42.37801| -71.06983|18.084948|1525319644|36.853622| |5ac52674ffff34c98...|IDFA| 1|42.378693| -71.07033| 15.64326|1525319645|36.853622| |5ac52674ffff34c98...|IDFA| 1|42.378723|-71.070335|21.093477|1525319646|36.853622| |5ac52674ffff34c98...|IDFA| 1| 42.37868| -71.07034|21.851894|1525319647|36.853622| |5ac52674ffff34c98...|IDFA| 1|42.378716| -71.07029|20.583202|1525319648|36.853622| |5ac52674ffff34c98...|IDFA| 1| 42.37872| -71.07067|19.738768|1525319649|36.853622| |5ac52674ffff34c98...|IDFA| 1|42.379112| -71.07097|20.480911|1525319650|36.853622| |5ac52674ffff34c98...|IDFA| 1| 42.37952| -71.0708|20.526752|1525319651| 44.93808| |5ac52674ffff34c98...|IDFA| 1| 42.37902| -71.07056|20.534052|1525319652| 44.93808| |5ac52674ffff34c98...|IDFA| 1|42.380203| -71.0709|19.921381|1525319653| 44.93808| |5ac52674ffff34c98...|IDFA| 1| 42.37968|-71.071144| 20.12599|1525319654| 44.93808| |5ac52674ffff34c98...|IDFA| 1|42.379696| -71.07114|18.760069|1525319655| 36.77853| |5ac52674ffff34c98...|IDFA| 1| 42.38011| -71.07123|19.155525|1525319656| 36.77853| |5ac52674ffff34c98...|IDFA| 1| 42.38022| -71.0712|16.978994|1525319657| 36.77853| +--------------------+----+----+---------+----------+---------+----------+---------+ only showing top 20 rows ``` If try to `count` ``` %%time df.count() CPU times: user 4 ms, sys: 0 ns, total: 4 ms Wall time: 28.1 s 30241272 ``` now if I take a subset of `df` the time to count is even longer. ``` id0 = df.first().ID ## First ID tmp = df.filter( (df['ID'] == id0) ) %%time tmp.count() CPU times: user 12 ms, sys: 0 ns, total: 12 ms Wall time: 1min 33s Out[6]: 3299 ```
2020/01/31
[ "https://Stackoverflow.com/questions/60008180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3590067/" ]
Your question is very ingesting and tricky.. I tested with a large dataset in order to reproduce your behavior. Problem Description ------------------- I tested the following two cases in a large dataset: ``` # Case 1 df.count() # Execution time: 37secs # Case 2 df.filter((df['ID'] == id0)).count() #Execution time: 1.39 min ``` Explaination ------------ Lets see the Physical Plan with only `.count()`: ``` == Physical Plan == *(2) HashAggregate(keys=[], functions=[count(1)], output=[count#38L]) +- Exchange SinglePartition +- *(1) HashAggregate(keys=[], functions=[partial_count(1)], output=[count#41L]) +- *(1) FileScan csv [] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:...], PartitionFilters: [], PushedFilters: [], ReadSchema: struct<> ``` Lets see the physical plan with `.filter()` and then `.count()`: ``` == Physical Plan == *(2) HashAggregate(keys=[], functions=[count(1)], output=[count#61L]) +- Exchange SinglePartition +- *(1) HashAggregate(keys=[], functions=[partial_count(1)], output=[count#64L]) +- *(1) Project +- *(1) Filter (isnotnull(ID#11) && (ID#11 = Muhammed MacIntyre)) +- *(1) FileScan csv [ID#11] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:...], PartitionFilters: [], PushedFilters: [IsNotNull(ID), EqualTo(ID,Muhammed MacIntyre)], ReadSchema: struct<_c1:string> ``` Generally, Spark when counts the number of rows maps the rows with count=1 and the reduce all the mappers to create the final number of rows. In the **Case 2** Spark has first to filter and then create the partial counts for every partition and then having another stage to sum those up together. So, for the same rows, in the second case the Spark doing also the filtering, something that affects the computation time in large datasets. Spark is a framework for distributed processing and doesn't have indexes like Pandas, which could do the filtering extremely fast without passing all the rows. Summary ------- In that simple case you can't do a lot of things to improve the execution time. You can try your application with different configuration settings (e.g # spark.sql.shuffle.partitions, `# spark.default.parallelism`, `# of executors`, `# executor memory` etc)
This is because spark is [lazily evaluated](https://data-flair.training/blogs/apache-spark-lazy-evaluation/). When you call tmp.count(), that is an action step. In other words, your timing of tmp.count also includes the filter time. If you want to truly compare the two counts, try the following: ``` %%time df.count() id0 = df.first().ID ## First ID tmp = df.filter( (df['ID'] == id0) ) tmp.persist().show() %%time tmp.count() ``` The important component here is the tmp.persist().show() *BEFORE* performing the count. This performs the filter and caches the result. That way, the tmp.count() only includes the actual count time.
24,032,470
i am currently developing an application written in Vb.Net. Is there any chance to tell all Chromecasts in the same network of the application to start a specific application ? I´ve searched the whole internet since months, and there is no SDK i can find for .Net. Anyone knows how to do this, or can point me to the right direction ? Cheers, Alex
2014/06/04
[ "https://Stackoverflow.com/questions/24032470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1864986/" ]
As far as I know there is no such implementation in .NET, but you can look into protocol implementations in Node.js ([V1](https://github.com/wearefractal/nodecast) [V2](https://github.com/vincentbernat/nodecastor)) and in java ([V1](https://github.com/entertailion/Caster) [V2](https://github.com/vitalidze/chromecast-java-api-v2)). I am implementing V2 in java. You should also take into account that V1 is retiring, and soon they will move to V2 for all applications.
First, there is no .Net sdk. Moreover, you need to be connected to each chromecast device individually to be able to communicate with them, hence no "broadcast" messaging.
24,032,470
i am currently developing an application written in Vb.Net. Is there any chance to tell all Chromecasts in the same network of the application to start a specific application ? I´ve searched the whole internet since months, and there is no SDK i can find for .Net. Anyone knows how to do this, or can point me to the right direction ? Cheers, Alex
2014/06/04
[ "https://Stackoverflow.com/questions/24032470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1864986/" ]
First, there is no .Net sdk. Moreover, you need to be connected to each chromecast device individually to be able to communicate with them, hence no "broadcast" messaging.
.Net development is possible using [Sharpcaster](https://github.com/Tapanila/SharpCaster). Also look at [GoogleCast](https://github.com/kakone/GoogleCast).
24,032,470
i am currently developing an application written in Vb.Net. Is there any chance to tell all Chromecasts in the same network of the application to start a specific application ? I´ve searched the whole internet since months, and there is no SDK i can find for .Net. Anyone knows how to do this, or can point me to the right direction ? Cheers, Alex
2014/06/04
[ "https://Stackoverflow.com/questions/24032470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1864986/" ]
As far as I know there is no such implementation in .NET, but you can look into protocol implementations in Node.js ([V1](https://github.com/wearefractal/nodecast) [V2](https://github.com/vincentbernat/nodecastor)) and in java ([V1](https://github.com/entertailion/Caster) [V2](https://github.com/vitalidze/chromecast-java-api-v2)). I am implementing V2 in java. You should also take into account that V1 is retiring, and soon they will move to V2 for all applications.
.Net development is possible using [Sharpcaster](https://github.com/Tapanila/SharpCaster). Also look at [GoogleCast](https://github.com/kakone/GoogleCast).
30,280,533
im trying to make it so that when a form is submitted, it would send an email. The database connecting/submitting is working so it's nothing from the database or form side hopefully. Here is my code: ``` <?php $mysql_host = "localhost"; $mysql_username = ""; $mysql_password = ""; $mysql_database = ""; $mysql_database2 = ""; $sub = $_POST['subject']; $mysqli2 = new Mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database2) or die(mysqli_error()); $head = $mysqli2->query("SELECT head FROM class WHERE subject = '$sub'")->fetch_object()->head; $status = 1; $mysqli = new Mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database) or die(mysqli_error()); $prepare = $mysqli->prepare("INSERT INTO `Overrides`(`name`,`mname`,`fname`,`sid`,`email`,`phone`,`sc`,`subject`,`section`,`semester`,`professor`,`status`,`dean`,`head`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $prepare->bind_param("ssssssssssssss", $_POST['name'], $_POST['mname'], $_POST['fname'], $_POST['sid'], $_POST['email'], $_POST['phone'], $_POST['Scolarship'], $_POST['subject'], $_POST['section'], $_POST['semester'], $_POST['professor'], $status, $_POST['dean'], $head); $prepare->execute(); $name = $_POST['name']; $mname= $_POST['mname']; $fname = $_POST['fname']; $email = $_POST['email']; $semester = $_POST['semester']; $sid = $_POST['sid']; $subject = $_POST['subject']; $section = $_POST['section']; $professor = $_POST['professor']; if(prepare) { $to = '$email'; //can receive notification $subject = 'Override Request'; $message = 'Dear $name<br /><br /> Your Following override request has been submitted.<br /><br /> Name: $name . $mname . $fname Student ID : $sid Semester : $semester Subject : $subject Section : $section Professor : $professor<br /><br /> Please note that the request is passed to different faculty members in order to be revised. You will be notified on each update'; $headers = 'From: system@auke.edu.kw' . "\r\n" . 'Reply-To: webmaster@ourcompany.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); echo 'Email Sent.'; } print 'Error : ('. $mysqli->errno .') '. $mysqli->error; ?> ``` It prints email sent but i get nothing on my mail. Thanks.
2015/05/16
[ "https://Stackoverflow.com/questions/30280533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4430274/" ]
``` $to = '$email'; ``` Have to be ``` $to = "$email"; ``` or - better: ``` $to = $email; ```
You should read this [Curly braces in string in PHP](https://stackoverflow.com/questions/2596837/curly-braces-in-string-in-php) In your code "Email sent" will be allways display. Try: ``` if ( mail($to, $subject, $message, $headers) ) echo "Sent"; else echo "Error"; ```
30,280,533
im trying to make it so that when a form is submitted, it would send an email. The database connecting/submitting is working so it's nothing from the database or form side hopefully. Here is my code: ``` <?php $mysql_host = "localhost"; $mysql_username = ""; $mysql_password = ""; $mysql_database = ""; $mysql_database2 = ""; $sub = $_POST['subject']; $mysqli2 = new Mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database2) or die(mysqli_error()); $head = $mysqli2->query("SELECT head FROM class WHERE subject = '$sub'")->fetch_object()->head; $status = 1; $mysqli = new Mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database) or die(mysqli_error()); $prepare = $mysqli->prepare("INSERT INTO `Overrides`(`name`,`mname`,`fname`,`sid`,`email`,`phone`,`sc`,`subject`,`section`,`semester`,`professor`,`status`,`dean`,`head`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $prepare->bind_param("ssssssssssssss", $_POST['name'], $_POST['mname'], $_POST['fname'], $_POST['sid'], $_POST['email'], $_POST['phone'], $_POST['Scolarship'], $_POST['subject'], $_POST['section'], $_POST['semester'], $_POST['professor'], $status, $_POST['dean'], $head); $prepare->execute(); $name = $_POST['name']; $mname= $_POST['mname']; $fname = $_POST['fname']; $email = $_POST['email']; $semester = $_POST['semester']; $sid = $_POST['sid']; $subject = $_POST['subject']; $section = $_POST['section']; $professor = $_POST['professor']; if(prepare) { $to = '$email'; //can receive notification $subject = 'Override Request'; $message = 'Dear $name<br /><br /> Your Following override request has been submitted.<br /><br /> Name: $name . $mname . $fname Student ID : $sid Semester : $semester Subject : $subject Section : $section Professor : $professor<br /><br /> Please note that the request is passed to different faculty members in order to be revised. You will be notified on each update'; $headers = 'From: system@auke.edu.kw' . "\r\n" . 'Reply-To: webmaster@ourcompany.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); echo 'Email Sent.'; } print 'Error : ('. $mysqli->errno .') '. $mysqli->error; ?> ``` It prints email sent but i get nothing on my mail. Thanks.
2015/05/16
[ "https://Stackoverflow.com/questions/30280533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4430274/" ]
``` $to = '$email'; ``` Have to be ``` $to = "$email"; ``` or - better: ``` $to = $email; ```
One of the problems is here ``` if(prepare) ``` `prepare` is treated as a [**constant**](http://php.net/manual/en/language.constants.php) rather than the intended variable `$prepare`. Do `if($prepare){...}` Also your variables need to be in double quotes. ``` $to = '$email'; ``` variables do not get interpolated in single quotes ``` $to = "$email"; ``` same for `$message = '...';` that should be `$message = "...";` You should also be doing and replacing `$prepare->execute();` with ``` if(!$prepare->execute()){ trigger_error("there was an error....".$mysqli->error, E_USER_WARNING); } ``` or ``` if(!$prepare->execute()){ trigger_error("there was an error....".$mysqli2->error, E_USER_WARNING); } ``` for your `SELECT` connection. to check for possible db errors. Also make sure your form uses a POST method and that all elements bear the proper name attributes. * Form will fail silently if the POST method is omitted. It also defaults to GET if omitted. I don't know what the form looks like, so you'll need to look into that. --- **Edit:** (adding PHPmailer information) Seeing as you may not have access to using `mail()`, you could try using PHPmailer and a Gmail account if you have one. Here is an example pulled from <https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps> Visit also their main page: <http://phpmailer.worxware.com/index.php> ``` <?php /** * This example shows settings to use when sending via Google's Gmail servers. */ //SMTP needs accurate times, and the PHP time zone MUST be set //This should be done in your php.ini, but this is how to do it if you don't have access to that date_default_timezone_set('Etc/UTC'); require '../PHPMailerAutoload.php'; //Create a new PHPMailer instance $mail = new PHPMailer; //Tell PHPMailer to use SMTP $mail->isSMTP(); //Enable SMTP debugging // 0 = off (for production use) // 1 = client messages // 2 = client and server messages $mail->SMTPDebug = 2; //Ask for HTML-friendly debug output $mail->Debugoutput = 'html'; //Set the hostname of the mail server $mail->Host = 'smtp.gmail.com'; //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission $mail->Port = 587; //Set the encryption system to use - ssl (deprecated) or tls $mail->SMTPSecure = 'tls'; //Whether to use SMTP authentication $mail->SMTPAuth = true; //Username to use for SMTP authentication - use full email address for gmail $mail->Username = "username@gmail.com"; //Password to use for SMTP authentication $mail->Password = "yourpassword"; //Set who the message is to be sent from $mail->setFrom('from@example.com', 'First Last'); //Set an alternative reply-to address $mail->addReplyTo('replyto@example.com', 'First Last'); //Set who the message is to be sent to $mail->addAddress('whoto@example.com', 'John Doe'); //Set the subject line $mail->Subject = 'PHPMailer GMail SMTP test'; //Read an HTML message body from an external file, convert referenced images to embedded, //convert HTML into a basic plain-text alternative body $mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__)); //Replace the plain text body with one created manually $mail->AltBody = 'This is a plain-text message body'; //Attach an image file $mail->addAttachment('images/phpmailer_mini.png'); //send the message, check for errors if (!$mail->send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message sent!"; } ```
490,432
We had a debate - cons and pros of having a factory per dto in order to test some service. The idea is that the service is being invoked with primitive types parameters (username, password, etc), but the service dependency should be leveraged using those primitives. The only way to test it was to inject into service an additional dependency, DtoFactory, and that way to ensure that primitive parameters are utilized the way we wanted. What worries me is the idea of "FactoryX per DtoX". What would be an alternative? Thanks
2009/01/29
[ "https://Stackoverflow.com/questions/490432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59563/" ]
It is most definitely not safe to ignore this message. If you hit this message, you've almost certainly created a real loader lock policy violation. This is a very serious error and can cause unpredictable behavior in a program (including deadlock). The best way to avoid this is to not access any other .Net Objects/Functions directly or indirectly inside of DLL main. For your case, it's probably best to use a different cache policy. Perhaps create a ref counted object to hold the .Net reference. That way the object will be released before DllMain is called for unload (the dll can't be unloaded until all of your objects are destroyed).
Don't ignore. I had a LoaderLock issue on startup of a C# app that used an unmanaged C++ DLL. In this case, some of the DLL code (ported from Linux) had statics that were accessing files on initialization during load. Once the statics were cleaned up, the LoaderLock issue was fixed. In a similar way, if you have C/C++ statics that access files during cleanup, this could be contributing to your LoaderLock.
1,866
Just for your entertainment: There is a guy, George Duckett, who webscraped most SE sites and "published" the content into "books". Now he also has one for Economics, and if you have answered some questions you will likely find yourself within! [Link to the Econ book](https://books.google.hu/books?id=bF1RDwAAQBAJ&pg=PT1213&lpg=PT1213&dq=%C3%9Cbel+Yildmar&source=bl&ots=JyVmwvMp9x&sig=xdYS_h8G0eal3dDbZP1HyoL9Im4&hl=en&sa=X&ved=0ahUKEwjox7_ykfnZAhUFLVAKHSA0DNMQ6AEIWDAK#v=onepage&q=%C3%9Cbel%20Yildmar&f=false)
2018/03/19
[ "https://economics.meta.stackexchange.com/questions/1866", "https://economics.meta.stackexchange.com", "https://economics.meta.stackexchange.com/users/1601/" ]
I got a response from the SE team member [animuson](https://economics.stackexchange.com/users/4303/animuson?tab=profile) it doesnt seem like its an issue. > > His books get brought up several times a year, but there is nothing inherently wrong with them. Our license does not forbid the use of the content in commercial works so long as the usual attribution requirements are followed, which he does in every book he publishes. > > > Regards, > animuson > > >
Here is the interpretation of the [CC license terms](https://stackoverflow.blog/2009/06/25/attribution-required/) taken by the SE network. In particular, > > If you republish this content, we require that you: > > > * Visually indicate that the content is from Stack Overflow or the Stack Exchange network in some way. It doesn’t have to be obnoxious; a discreet text blurb is fine. > * Hyperlink directly to the original question on the source site (e.g., <http://stackoverflow.com/questions/12345>) > * Show the author names for every question and answer > * Hyperlink each author name directly back to their user profile page on the source site (e.g., <http://stackoverflow.com/users/12345/username>) > > > Looking (through non-lawyer's eyes) at the legal text of the license, there seems to be some room for interpretation about whether all of these can really be required, depending on the medium in question. The "book" seems to comply only with points 1 and 3.
1,866
Just for your entertainment: There is a guy, George Duckett, who webscraped most SE sites and "published" the content into "books". Now he also has one for Economics, and if you have answered some questions you will likely find yourself within! [Link to the Econ book](https://books.google.hu/books?id=bF1RDwAAQBAJ&pg=PT1213&lpg=PT1213&dq=%C3%9Cbel+Yildmar&source=bl&ots=JyVmwvMp9x&sig=xdYS_h8G0eal3dDbZP1HyoL9Im4&hl=en&sa=X&ved=0ahUKEwjox7_ykfnZAhUFLVAKHSA0DNMQ6AEIWDAK#v=onepage&q=%C3%9Cbel%20Yildmar&f=false)
2018/03/19
[ "https://economics.meta.stackexchange.com/questions/1866", "https://economics.meta.stackexchange.com", "https://economics.meta.stackexchange.com/users/1601/" ]
I got a response from the SE team member [animuson](https://economics.stackexchange.com/users/4303/animuson?tab=profile) it doesnt seem like its an issue. > > His books get brought up several times a year, but there is nothing inherently wrong with them. Our license does not forbid the use of the content in commercial works so long as the usual attribution requirements are followed, which he does in every book he publishes. > > > Regards, > animuson > > >
**Update April 19, 2018** **[Read it from the publisher himself.](https://physics.meta.stackexchange.com/a/10602/193171)** --- The license used by SE is <https://creativecommons.org/licenses/by-sa/3.0/legalcode>. In this license we read: (in Definitions) <<*d. "**Distribute**" means to make available to the public the original and copies of the Work or Adaptation, as appropriate, **through sale or other transfer of ownership***>> And later on we read <<*3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, **royalty-free**, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:* ... *c. to **Distribute** and Publicly Perform the Work including as incorporated in Collections; and, d. to **Distribute** and Publicly Perform Adaptations.*>> So the CC-license used by SE **clearly allows for commercial exploitation of the SE content by anybody, and royalty-free.** To be exact we read, immediately after: *e. For the avoidance of doubt:* *i. Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License;* *ii. Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor waives the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; and,* *iii. Voluntary License Schemes. The Licensor waives the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this License.*>> **In plain words:** **"You, and we mean anybody, go on and try to make a handsome profit off our volunteer's contributions here. If they are not obliged by law to demand royalties, they have automatically waived their right to royalties."** I like the way SE encourages entrepreneurship.
15,835,653
I've found a terrific number of tutorials/code examples which provide you with the code to grab and echo the attachment ID of an image, but not a single one which works with anything else, such as Zip and Rar archives - which is precisely what I've working with. Would anyone know how to go about grabbing and echoing the ID of a file (in this case, a Zip archive) from within WordPress `attachment.php` page? Oddly enough, grabbing the ID of a Zip archive appears simple when attempted via `single.php`, but I'm really struggling to nail this from within `attachment.php`. Really can't understand why WordPress has a built-in `get_post_thumbnail_id();` for images, but nothing available for any other type of file.
2013/04/05
[ "https://Stackoverflow.com/questions/15835653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2075586/" ]
Refer to the example [*Show All attachments for the current post beside Thumb*](http://codex.wordpress.org/Function_Reference/get_post_thumbnail_id#Show_All_attachments_for_the_current_post_beside_Thumb) on (ironically, given your comments!) the [`get_post_thumbnail_id()` codex page](http://codex.wordpress.org/Function_Reference/get_post_thumbnail_id). Basically you set up a `get_posts()` query for *all* attachments. You'd then just need to filter your results on file type extension, or if you know it (and it's recorded correctly), the `WP_Post.post_mime_type` using [`get_post_mime_type()`](http://codex.wordpress.org/Function_Reference/get_post_mime_type). (The example filters out the featured image/thumb too... But your filter would take care of that anyhow). But if you can use the MIME type as a filter, you can set up the `get_posts()` args with a `'post_mime_types'` argument, to only return attachments of one (or more) specific MIME type(s). You'd probably want to take a peek at the attachments' underlying database entries to check how this is recorded so that you can properly match against it. I expect your .zip files are `application/zip`, but I'd double check before relying on that. So, something like: ``` <?php $args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID, 'post_mime_type' => 'application/zip' ); $attachments = get_posts( $args ); ?> ```
Thanks for responding, Sepster. I managed to find the embarrassingly simple answer by scouring through one of the TwentyTwelve theme's files; turns out the answer is as simple as echoing... ``` <?php the_ID(); ?> ``` ...inside the attachment.php file.
56,755,262
I am using sample csv to generate a network diagram. I need to name the lines that connects one component to other. In the sample Lines are generated by the following code: ``` # connect: {"from": "user", "to": "name", "invert": true, "label": "", \ # "style": "curved=1;endArrow=blockThin;endFill=1;fontSize=11;"} # connect: {"from": "refs", "to": "id", "style": "curved=1;fontSize=11;"} ``` The sample csv is: ```css ## ## Example CSV import. Use ## for comments and # for configuration. Paste CSV below. ## The following names are reserved and should not be used (or ignored): ## id, tooltip, placeholder(s), link and label (see below) ## # ## Node label with placeholders and HTML. ## Default is '%name_of_first_column%'. # # label: %name%<br>Hostname: <i style="color:gray;">%hostname%</i><br>IP: <i style="font-style: normal;color:gray;">%ip%</i><br>Zone: <i style="color:gray;">%zone%</i> # ## Node style (placeholders are replaced once). ## Default is the current style for nodes. # # style: label;image=%image%;whiteSpace=wrap;html=1;rounded=1;fillColor=%fill%;strokeColor=%stroke%; # ## Uses the given column name as the identity for cells (updates existing cells). ## Default is no identity (empty value or -). # # identity: - # ## Connections between rows ("from": source colum, "to": target column). ## Label, style and invert are optional. Defaults are '', current style and false. ## In addition to label, an optional fromlabel and tolabel can be used to name the column ## that contains the text for the label in the edges source or target (invert ignored). ## The label is concatenated in the form fromlabel + label + tolabel if all are defined. ## The target column may contain a comma-separated list of values. ## Multiple connect entries are allowed. # # connect: {"from": "user", "to": "name", "invert": true, "label": "", \ # "style": "curved=1;endArrow=blockThin;endFill=1;fontSize=11;"} # connect: {"from": "refs", "to": "id", "style": "curved=1;fontSize=11;"} # ## Node x-coordinate. Possible value is a column name. Default is empty. Layouts will ## override this value. # # left: # ## Node y-coordinate. Possible value is a column name. Default is empty. Layouts will ## override this value. # # top: # ## Node width. Possible value is a number (in px), auto or an @ sign followed by a column ## name that contains the value for the width. Default is auto. # # width: auto # ## Node height. Possible value is a number (in px), auto or an @ sign followed by a column ## name that contains the value for the height. Default is auto. # # height: auto # ## Padding for autosize. Default is 0. # # padding: -12 # ## Comma-separated list of ignored columns for metadata. (These can be ## used for connections and styles but will not be added as metadata.) # # ignore: id,image,fill,stroke # ## Column to be renamed to link attribute (used as link). # # link: url # ## Spacing between nodes. Default is 40. # # nodespacing: 40 # ## Spacing between parallel edges. Default is 40. # # edgespacing: 40 # ## Name of layout. Possible values are auto, none, verticaltree, horizontaltree, ## verticalflow, horizontalflow, organic, circle. Default is auto. # # layout: horizontalflow # ## ---- CSV below this line. First line are column names. ---- name,hostname,id,zone,ip,user,email,fill,stroke,refs,url,image A,Users1,a,zone0,10.1.1.1,,name@domain.com,#dae8fc,#6c8ebf,,https://users1.domain.com,https://cdn2.iconfinder.com/data/icons/office-icon-set-3/512/users.png B,Users2,b,zone0,10.1.1.2,,name@domain.com,#dae8fc,#6c8ebf,,https://users2.domain.com,https://cdn2.iconfinder.com/data/icons/office-icon-set-3/512/users.png C,Users3,c,zone2,10.1.1.3,,name@domain.com,#dae8fc,#6c8ebf,,https://users3.domain.com,https://cdn2.iconfinder.com/data/icons/office-icon-set-3/512/users.png D,Login1,d,zone1,10.1.1.4,A,name@domain.com,#b3b3b3,#000000,,https://login1.domain.com,https://cdn0.iconfinder.com/data/icons/icocentre-free-icons/147/f-server_128-512.png ``` I don't know what is the property name that will give a name to the lines automatically. I am expecting if there is a way to code "# connect: {}" json portion so that the lines can be named.
2019/06/25
[ "https://Stackoverflow.com/questions/56755262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3381341/" ]
You can use this snippet of [array\_walk](https://www.php.net/manual/en/function.array-walk.php), ``` array_walk($arr, function(&$val){ $val['project'] = implode(",", $val['project']); }); ``` [Demo](https://3v4l.org/LXn3L).
use [implode](https://php.net/implode) ``` $arr = array:12 [ 0 => array:2 [ "name" => "A1" "project" => array:1 [ 0 => "New Project" ] ] 1 => array:2 [ "name" => "A2" "project" => array:2 [ 0 => "New Project" 2 => "Project" ] ] foreach ($arr as &$value) { implode(', ', $value['project']); } ```
9,830,517
I have the following timer class : ``` class Timer { private: unsigned int curr,prev; float factor; float delta; public: Timer(float FrameLockFactor) { factor = FrameLockFactor; } ~Timer() { } void Update() { curr = SDL_GetTicks(); delta = (curr - prev) * (1000.f / factor); prev = curr; } float GetDelta() { return delta; } }; ``` And i use it like this : ``` //Create a timer and lock at 60fps Timer timer(60.0f); while() { float delta; float velocity = 4.0f; timer.Update(); delta = timer.GetDelta(); sprite.SetPosition( sprite.GetVector() + Vector2(0.0,velocity * delta) ); sprite.Draw(); } ``` But there is a big problem : My game runs way too slow for a program that is supposed to run at 60frames per second and the same test code runs smooth when not using frame indepented movement , so there must be something wrong with my code. Any help?
2012/03/22
[ "https://Stackoverflow.com/questions/9830517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1010005/" ]
If `delta` is supposed to be a count of frames, shouldn't it be calculated as ``` delta = (curr - prev) * (factor / 1000.f); ```
I don't really get what you are trying to do with your code. Especially the line `delta = (curr - prev) * (1000.f / factor);` does not make sense as far as I can see. If I understand this correctly you are trying to calculate how much time has passed since the last update and translate this into milliseconds per frame. What units are you using? I don't know what is returned by `SDL_GetTicks();`. Is this the number of processor or real clock ticks, which is returned? In case it is returning real clock ticks, the `(curr-prev)` part will most often be zero, since you have to do multiple updates per frame for this to work. If it is not returning real clock ticks, why are you multiplying by `1000f`. Where does this factor come from? With code like this, it is often very important to take care of round-off errors, so I am guessing that your problem lies somewhere in this area. Although without additional information I cannot tell what your actuall problem may be.
30,004,361
This is quite simple but I am still new to this. I have the following HTML: ``` <div class="bg"></div> <div class="jumbotron"></div> <div class="container" id="main-cont"> ....STUFF HERE.... </div> </div> ``` The image I'm using is 2400px high and I want the height to be 80% of the window height, so I need to set the height of the bg equal to the height of the jumbotron. Here is my css code, which will show what I am trying to accomplish with the JS. ``` .bg { position: fixed; background-size: cover; background: url('..//img/top-img.jpg') no-repeat center center; z-index: -1; width: 100%; height: 600px; top:0; left:0; } .jumbotron { height: 600px; color: white; background:transparent; } ``` Here is the JS. ``` <script> $(document).ready(function() { function setDivHeight() { windowHeight = $(window).innerHeight()*0.8; $('.jumbotron').css('height', windowHeight); $('.bg').css('height', windowHeight); }; }); </script> ``` The issues I am having are - 1. First of all, I don't think the JS is working. 2. If I was halfway scrolled down and refreshed the page, my css gets out of whack. The image goes behind the page contents and it looks ugly.
2015/05/02
[ "https://Stackoverflow.com/questions/30004361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3152131/" ]
If the `.jumbotron`'s parent is an element with full height, you could use calc: ``` height: calc(100% * 0.8); ``` Or just basic CSS: ``` height: 80%; ``` But [support is a bit touchy](http://caniuse.com/#search=calc). And again, you need to make sure the parent is has 100% height. --- JavaScript solution: ``` window.onload = function () { function resize () { var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); [].forEach.call(document.querySelectorAll('.jumbotron'), function (a) { a.style.height = h * 0.8 + 'px'; }); } window.onresize = resize; resize(); }; ``` [Fiddle](https://jsfiddle.net/blue1086/y9krr4hx/) ================================================= --- jQuery solution is a bit more simple: ``` $(window).resize(function () { $('.jumbotron').css('height', $(window).height() * 0.8); }); $(function(){ $(window).resize() }); ``` [Fiddle](https://jsfiddle.net/blue1086/y9krr4hx/1/) ===================================================
You can use the `vh` unit in CSS to accomplish what you want: ``` .bg, .jumbotron { height: 80vh; } ``` It is [supported in most browsers](http://caniuse.com/#feat=viewport-units), with the notable exception of Safari on iOS 7. See the link for a possible workaround - when using a CSS preprocessor you can easily automate that
51,109,709
After clicking the button the elements should move to their second positions. It only seems to work with the last element where I used `!important` which I don't want to use. Here is my code: ```js let ruch = document.querySelectorAll('.menu'); let myArray = Array.from(ruch); let btn = document.getElementById('btn'); btn.addEventListener('click', function () { myArray.forEach(function (item) { if (item == myArray[0]) { item.classList.add('run1'); } else if (item == myArray [4]) { item.classList.add('run2'); } else { item.classList.add('run'); } }); }); ``` ```css body { background-color: #302e2e; font-size:22px; } #btn{ position: absolute; left: 914px; top: 180px; } .wrapper{ position: relative; width:600px; margin: 0 auto; } .container{ position:absolute; top:250px; width:0px; } .menu{ padding:5px; border:1px solid #323232; width:100px; height:100px; background:#46f4a0; border-radius:20px; position: absolute; box-sizing: border-box; } .menu:nth-child(2){ left:105px; } .menu:nth-child(3){ left:210px; } .menu:nth-child(4){ left:315px; } .menu:nth-child(5){ left:420px; } .run{ opacity: 0; transition:3s ease-in-out; z-index: -1; top:110px; } .run1{ opacity: 0; transition:3s ease-in-out; z-index: -1; left:-110px; } .run2{ opacity: 0; transition:3s ease-in-out; z-index: -1; left:530px!important; } ``` ```html <button id="btn"> Kliknij </button> <div class="wrapper"> <div class="container "> <div class="menu ">About</div> <div class="menu ">My Projets</div> <div class="menu ">Some stuff</div> <div class="menu ">Werid shits</div> <div class="menu ">Contact</div> </div> </div> ``` Thanks for your help
2018/06/29
[ "https://Stackoverflow.com/questions/51109709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10012818/" ]
Like this? ([complementary CodePen](https://codepen.io/anon/pen/mKaazO)) ```js let menuItems = Array.from(document.querySelectorAll(".menu")); document.getElementById("btn").addEventListener("click", function() { menuItems[0].classList.add("run1"); menuItems[4].classList.add("run2"); menuItems.slice(1, 4).forEach(function(item) { item.classList.add("run"); }); }); ``` ```css body { background-color: #302e2e; font-size: 22px; } #btn { position: absolute; left: 914px; top: 180px; } .wrapper { position: relative; width: 600px; margin: 0 auto; } .container { position: absolute; top: 250px; width: 0px; } .menu { padding: 5px; border: 1px solid #323232; width: 100px; height: 100px; background: #46f4a0; border-radius: 20px; position: absolute; box-sizing: border-box; } .menu:nth-child(2) { left: 105px; } .menu:nth-child(3) { left: 210px; } .menu:nth-child(4) { left: 315px; } .menu:nth-child(5) { left: 420px; } .menu.run { opacity: 0; transition: 3s ease-in-out; transform: translateY(110px); } .menu.run1 { opacity: 0; transition: 3s ease-in-out; transform: translateX(-110px); } .menu.run2 { opacity: 0; transition: 3s ease-in-out; transform: translateX(110px); } ``` ```html <button id="btn">Kliknij</button> <div class="wrapper"> <div class="container"> <div class="menu">About</div> <div class="menu">My Projets</div> <div class="menu">Some stuff</div> <div class="menu">Werid shits</div> <div class="menu">Contact</div> </div> </div> ``` Please also look into your CSS again. You should avoid working with absolute positioning and pixel values only since it will look different on every device.
U need to move transition to '.menu' and it should look like that:`transition:3s transform ease-in-out;`. And in '.run', '.run1', '.run2' when left replace with: `transform: translateX(/*value*/px);`. And when top replace with: `transform: translateY(/*value*/px);`.
12,941,863
I have committed changes to Git and pushed to origin. Another developer was having trouble merging. They did something and did a push. I saw an update and did a pull and half my changes were reverted! What happened? I'm guessing they had merge conflicts and used their version of the file but even so I can't find any history of my work in Git? I'm using SourceTree and not quite comfortable with it yet. I've just installed Smart Git (more familiar with it) but not finding anything useful to discover what happened in either.
2012/10/17
[ "https://Stackoverflow.com/questions/12941863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/441016/" ]
In **SmartGit**, open the Log and use **Query|Load All Commits**. This should give you your commits temporarily back, so you can add a branch to make them accessible again. After that either Merge, Rebase or Cherry-Pick your changes to `master` (assuming it's `master` you and your team is working on).
If you are able to use the command-line, git log should show you all the commits. If you have already pulled locally, then you can use the reflog to unwind what has happened. <http://www.kernel.org/pub/software/scm/git/docs/git-reflog.html> You can then unwind if necessary and branch or cherry-pick to a new branch. Or you can revert the merge. <http://git-scm.com/2010/03/02/undoing-merges.html>
8,897,261
I need to save multiple options into a single field so that I didn’t have to create a column for each option. The options that can be selected will increase over time so using columns will probably not be the best way to go with this... One too many options can be selected at a time and save to the database. So I have come up with the following solution and was wondering if there was a better way to do this and also if anyone can see any issues with it. I have done testing and it seems to work fine for the variations I selected. Method: Assign all the options a unique prime number, let the user select the options he wants, multiply the selected option’s corresponding prime number and save the resultant value in the field. When checking if the option was selected: If the number saved is divisible by the prime number without a remained, that prime number’s corresponding option was selected by the user. Eg: * Monday 2, Tuesday 3, Wednesday 5, Thursday 7, Friday 11, Saturday 13, Sunday 17 Selection: Monday, Friday, Sunday 2 \* 11 \* 17 = 374 ``` **Monday** = 374/2=187, (Or 374 % 2 = 0) Tuesday = 374/3=124.6666666666667, Wednesday = 374/5=74.8, Thursday = 374/7=53.42857142857143, **Friday** = 374/11=34, Saturday = 374/13=28.76923076923077, **Sunday** = 374/17=22 ```
2012/01/17
[ "https://Stackoverflow.com/questions/8897261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127439/" ]
Use rows. This seems to be a standard many-to-many relationship. Create a table to hold the options, then another table to relate options to whatever the original table was. Further reading: <http://www.tomjewett.com/dbdesign/dbdesign.php?page=manymany.php>
Your approach seems particularly cryptic. If you *must* store multiple pieces of data in a single column, consider using XML. With an XML-typed field, you can store structured data in a relatively clean form, and use XQuery to at least have a chance to query and use it in a way that's compatible with other SQL queries.
8,897,261
I need to save multiple options into a single field so that I didn’t have to create a column for each option. The options that can be selected will increase over time so using columns will probably not be the best way to go with this... One too many options can be selected at a time and save to the database. So I have come up with the following solution and was wondering if there was a better way to do this and also if anyone can see any issues with it. I have done testing and it seems to work fine for the variations I selected. Method: Assign all the options a unique prime number, let the user select the options he wants, multiply the selected option’s corresponding prime number and save the resultant value in the field. When checking if the option was selected: If the number saved is divisible by the prime number without a remained, that prime number’s corresponding option was selected by the user. Eg: * Monday 2, Tuesday 3, Wednesday 5, Thursday 7, Friday 11, Saturday 13, Sunday 17 Selection: Monday, Friday, Sunday 2 \* 11 \* 17 = 374 ``` **Monday** = 374/2=187, (Or 374 % 2 = 0) Tuesday = 374/3=124.6666666666667, Wednesday = 374/5=74.8, Thursday = 374/7=53.42857142857143, **Friday** = 374/11=34, Saturday = 374/13=28.76923076923077, **Sunday** = 374/17=22 ```
2012/01/17
[ "https://Stackoverflow.com/questions/8897261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127439/" ]
I think you can use de bitwise permissions pattern. Basically you store each option as a power of 2. In this way you can have all the posible combinations in a single integer field. Just google Bitwise persmission to implement the solution
Your approach seems particularly cryptic. If you *must* store multiple pieces of data in a single column, consider using XML. With an XML-typed field, you can store structured data in a relatively clean form, and use XQuery to at least have a chance to query and use it in a way that's compatible with other SQL queries.
8,897,261
I need to save multiple options into a single field so that I didn’t have to create a column for each option. The options that can be selected will increase over time so using columns will probably not be the best way to go with this... One too many options can be selected at a time and save to the database. So I have come up with the following solution and was wondering if there was a better way to do this and also if anyone can see any issues with it. I have done testing and it seems to work fine for the variations I selected. Method: Assign all the options a unique prime number, let the user select the options he wants, multiply the selected option’s corresponding prime number and save the resultant value in the field. When checking if the option was selected: If the number saved is divisible by the prime number without a remained, that prime number’s corresponding option was selected by the user. Eg: * Monday 2, Tuesday 3, Wednesday 5, Thursday 7, Friday 11, Saturday 13, Sunday 17 Selection: Monday, Friday, Sunday 2 \* 11 \* 17 = 374 ``` **Monday** = 374/2=187, (Or 374 % 2 = 0) Tuesday = 374/3=124.6666666666667, Wednesday = 374/5=74.8, Thursday = 374/7=53.42857142857143, **Friday** = 374/11=34, Saturday = 374/13=28.76923076923077, **Sunday** = 374/17=22 ```
2012/01/17
[ "https://Stackoverflow.com/questions/8897261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127439/" ]
I think you can use de bitwise permissions pattern. Basically you store each option as a power of 2. In this way you can have all the posible combinations in a single integer field. Just google Bitwise persmission to implement the solution
Use rows. This seems to be a standard many-to-many relationship. Create a table to hold the options, then another table to relate options to whatever the original table was. Further reading: <http://www.tomjewett.com/dbdesign/dbdesign.php?page=manymany.php>
1,463,632
I am trying to use Test Driven Development to implement my signal processing library. But I have a little doubt: Assume I am trying to implement a sine method (I'm not): 1. Write the test (pseudo-code) ``` assertEqual(0, sine(0)) ``` 2. Write the first implementation ``` function sine(radians) return 0 ``` 3. Second test ``` assertEqual(1, sine(pi)) ``` At this point, should I: 1. implement a smart code that will work for pi and other values, or 2. implement the dumbest code that will work only for 0 and pi? If you choose the second option, when can I jump to the first option? I will have to do it eventually...
2009/09/23
[ "https://Stackoverflow.com/questions/1463632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48465/" ]
At this point, should I: 1. implement real code that will work outside the two simple tests? 2. implement more dumbest code that will work only for the two simple tests? Neither. I'm not sure where you got the "write just one test at a time" approach from, but it sure is a slow way to go. The point is to write clear tests and use that clear testing to design your program. So, write enough tests to actually validate a sine function. Two tests are clearly inadequate. In the case of a continuous function, you have to provide a table of known good values eventually. Why wait? However, testing continuous functions has some problems. You can't follow a dumb TDD procedure. You can't test *all* floating-point values between 0 and 2\*pi. You can't test a few random values. In the case of continuous functions, a "strict, unthinking TDD" doesn't work. The issue here is that you know your sine function implementation will be based on a bunch of symmetries. You have to test based on those symmetry rules you're using. Bugs hide in cracks and corners. Edge cases and corner cases are part of the implementation and if you unthinkingly follow TDD you can't test that. However, for continuous functions, you must test the edge and corner cases of the implementation. This doesn't mean TDD is broken or inadequate. It says that slavish devotion to a "test first" can't work without some thinking about what you real goal is.
Write tests that verify Identities. For the sin(x) example, think about double-angle formula and half-angle formula. Open a signal-processing textbook. Find the relevant chapters and implement every single one of those theorems/corollaries as test code applicable for your function. For most signal-processing functions there are identities that must be uphold for the inputs and the outputs. Write tests that verify those identities, regardless of what those inputs might be. Then think about the inputs. * Divide the implementation process into separate stages. Each stage should have a Goal. The tests for each stage would be to verify that Goal. (Note 1) 1. The goal of the first stage is to be "roughly correct". For the sin(x) example, this would be like a naive implementation using binary search and some mathematical identities. 2. The goal of the second stage is to be "accurate enough". You will try different ways of computing the same function and see which one gets better result. 3. The goal of the third stage is to be "efficient". (Note 1) Make it work, make it correct, make it fast, make it cheap. - attributed to Alan Kay
1,463,632
I am trying to use Test Driven Development to implement my signal processing library. But I have a little doubt: Assume I am trying to implement a sine method (I'm not): 1. Write the test (pseudo-code) ``` assertEqual(0, sine(0)) ``` 2. Write the first implementation ``` function sine(radians) return 0 ``` 3. Second test ``` assertEqual(1, sine(pi)) ``` At this point, should I: 1. implement a smart code that will work for pi and other values, or 2. implement the dumbest code that will work only for 0 and pi? If you choose the second option, when can I jump to the first option? I will have to do it eventually...
2009/09/23
[ "https://Stackoverflow.com/questions/1463632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48465/" ]
In kind of the strict baby-step TDD, you might implement the dumb method to get back to green, and then refactor the duplication inherent in the dumb code (testing for the input value is a kind of duplication between the test and the code) by producing a real algorithm. The hard part about getting a feel for TDD with such an algorithm is that your acceptance tests are really sitting right next to you (the table S. Lott suggests), so you kind of keep an eye on them the whole time. In more typical TDD, the unit is divorced enough from the whole that the acceptance tests can't just be plugged in right there, so you don't start thinking about testing for all scenarios, because all scenarios are not obvious. Typically, you might have a real algorithm after one or two cases. The important thing about TDD is that it is driving design, not the algorithm. Once you have enough cases to satisfy the design needs, the value in TDD drops significantly. Then the tests more convert into covering corner cases to ensure your algorithm is correct in all aspects you can think of. So, if you are confident in how to build the algorithm, go for it. The kinds of baby steps you are talking about are only appropriate when you are uncertain. By taking such baby steps you start to build out the boundaries of what your code has to cover, even though your implementation isn't actually real yet. But as I said, that is more for when you are uncertain about how to build the algorithm.
You should code up all your unit tests in one hit (in my opinion). While the idea of only creating tests specifically covering what has to be tested is correct, your particular specification calls for a functioning `sine()` function, *not* a `sine()` function that works for 0 and PI. Find a source you trust enough (a mathematician friend, tables at the back of a math book or another program that already has the sine function implemented). I opted for `bash/bc` because I'm too lazy to type it all in by hand :-). If it *were* a `sine()` function, I'd just run the following program and paste it into the test code. I'd also put a copy of this script in there as a comment as well so I can re-use it if something changes (such as the desired resolution if more than 20 degrees in this case, or the value of PI you want to use). ``` #!/bin/bash d=0 while [[ ${d} -le 400 ]] ; do r=$(echo "3.141592653589 * ${d} / 180" | bc -l) s=$(echo "s(${r})" | bc -l) echo "assertNear(${s},sine(${r})); // ${d} deg." d=$(expr ${d} + 20) done ``` This outputs: ``` assertNear(0,sine(0)); // 0 deg. assertNear(.34202014332558591077,sine(.34906585039877777777)); // 20 deg. assertNear(.64278760968640429167,sine(.69813170079755555555)); // 40 deg. assertNear(.86602540378430644035,sine(1.04719755119633333333)); // 60 deg. assertNear(.98480775301214683962,sine(1.39626340159511111111)); // 80 deg. assertNear(.98480775301228458404,sine(1.74532925199388888888)); // 100 deg. assertNear(.86602540378470305958,sine(2.09439510239266666666)); // 120 deg. assertNear(.64278760968701194759,sine(2.44346095279144444444)); // 140 deg. assertNear(.34202014332633131111,sine(2.79252680319022222222)); // 160 deg. assertNear(.00000000000079323846,sine(3.14159265358900000000)); // 180 deg. assertNear(-.34202014332484051044,sine(3.49065850398777777777)); // 200 deg. assertNear(-.64278760968579663575,sine(3.83972435438655555555)); // 220 deg. assertNear(-.86602540378390982112,sine(4.18879020478533333333)); // 240 deg. assertNear(-.98480775301200909521,sine(4.53785605518411111111)); // 260 deg. assertNear(-.98480775301242232845,sine(4.88692190558288888888)); // 280 deg. assertNear(-.86602540378509967881,sine(5.23598775598166666666)); // 300 deg. assertNear(-.64278760968761960351,sine(5.58505360638044444444)); // 320 deg. assertNear(-.34202014332707671144,sine(5.93411945677922222222)); // 340 deg. assertNear(-.00000000000158647692,sine(6.28318530717800000000)); // 360 deg. assertNear(.34202014332409511011,sine(6.63225115757677777777)); // 380 deg. assertNear(.64278760968518897983,sine(6.98131700797555555555)); // 400 deg. ``` Obviously you will need to map this answer to what your real function is meant to do. My point is that the test should fully validate the behavior of the code in this iteration. If this iteration was to produce a `sine()` function that only works for 0 and PI, then that's fine. But that would be a serious waste of an iteration in my opinion. It may be that your function is so complex that it *must* be done over several iterations. Then your approach two is correct and the tests should be updated in the *next* iteration where you add the extra functionality. Otherwise, find a way to add all the tests for this iteration quickly, then you won't have to worry about switching between real code and test code frequently.
1,463,632
I am trying to use Test Driven Development to implement my signal processing library. But I have a little doubt: Assume I am trying to implement a sine method (I'm not): 1. Write the test (pseudo-code) ``` assertEqual(0, sine(0)) ``` 2. Write the first implementation ``` function sine(radians) return 0 ``` 3. Second test ``` assertEqual(1, sine(pi)) ``` At this point, should I: 1. implement a smart code that will work for pi and other values, or 2. implement the dumbest code that will work only for 0 and pi? If you choose the second option, when can I jump to the first option? I will have to do it eventually...
2009/09/23
[ "https://Stackoverflow.com/questions/1463632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48465/" ]
Write tests that verify Identities. For the sin(x) example, think about double-angle formula and half-angle formula. Open a signal-processing textbook. Find the relevant chapters and implement every single one of those theorems/corollaries as test code applicable for your function. For most signal-processing functions there are identities that must be uphold for the inputs and the outputs. Write tests that verify those identities, regardless of what those inputs might be. Then think about the inputs. * Divide the implementation process into separate stages. Each stage should have a Goal. The tests for each stage would be to verify that Goal. (Note 1) 1. The goal of the first stage is to be "roughly correct". For the sin(x) example, this would be like a naive implementation using binary search and some mathematical identities. 2. The goal of the second stage is to be "accurate enough". You will try different ways of computing the same function and see which one gets better result. 3. The goal of the third stage is to be "efficient". (Note 1) Make it work, make it correct, make it fast, make it cheap. - attributed to Alan Kay
I don't know what language you are using, but when I am dealing with a numeric method, I typically write a simple test like yours first to make sure the outline is correct, and then I feed more values to cover cases where I suspect things might go wrong. In .NET, NUnit 2.5 has a nice feature for this, called `[TestCase]`, where you can feed multiple input values to the same test like this: ``` [TestCase(1,2,Result=3)] [TestCase(1,1,Result=2)] public int CheckAddition(int a, int b) { return a+b; } ```
1,463,632
I am trying to use Test Driven Development to implement my signal processing library. But I have a little doubt: Assume I am trying to implement a sine method (I'm not): 1. Write the test (pseudo-code) ``` assertEqual(0, sine(0)) ``` 2. Write the first implementation ``` function sine(radians) return 0 ``` 3. Second test ``` assertEqual(1, sine(pi)) ``` At this point, should I: 1. implement a smart code that will work for pi and other values, or 2. implement the dumbest code that will work only for 0 and pi? If you choose the second option, when can I jump to the first option? I will have to do it eventually...
2009/09/23
[ "https://Stackoverflow.com/questions/1463632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48465/" ]
At this point, should I: 1. implement real code that will work outside the two simple tests? 2. implement more dumbest code that will work only for the two simple tests? Neither. I'm not sure where you got the "write just one test at a time" approach from, but it sure is a slow way to go. The point is to write clear tests and use that clear testing to design your program. So, write enough tests to actually validate a sine function. Two tests are clearly inadequate. In the case of a continuous function, you have to provide a table of known good values eventually. Why wait? However, testing continuous functions has some problems. You can't follow a dumb TDD procedure. You can't test *all* floating-point values between 0 and 2\*pi. You can't test a few random values. In the case of continuous functions, a "strict, unthinking TDD" doesn't work. The issue here is that you know your sine function implementation will be based on a bunch of symmetries. You have to test based on those symmetry rules you're using. Bugs hide in cracks and corners. Edge cases and corner cases are part of the implementation and if you unthinkingly follow TDD you can't test that. However, for continuous functions, you must test the edge and corner cases of the implementation. This doesn't mean TDD is broken or inadequate. It says that slavish devotion to a "test first" can't work without some thinking about what you real goal is.
Short answer. * Write one test at a time. * Once it fails, Get back to green first. If that means doing the simplest thing that can work, do it. (Option 2) * Once you're in the green, you can look at the code and *choose* to cleanup (option1). Or you can say that the code still doesn't smell that much and write subsequent tests that put the spotlight on the smells. Another question you seem to have, is how many tests should you write. You need to test till fear (the function may not work) turns into boredom. So once you've tested for all the interesting input-output combinations, you're done.
1,463,632
I am trying to use Test Driven Development to implement my signal processing library. But I have a little doubt: Assume I am trying to implement a sine method (I'm not): 1. Write the test (pseudo-code) ``` assertEqual(0, sine(0)) ``` 2. Write the first implementation ``` function sine(radians) return 0 ``` 3. Second test ``` assertEqual(1, sine(pi)) ``` At this point, should I: 1. implement a smart code that will work for pi and other values, or 2. implement the dumbest code that will work only for 0 and pi? If you choose the second option, when can I jump to the first option? I will have to do it eventually...
2009/09/23
[ "https://Stackoverflow.com/questions/1463632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48465/" ]
At this point, should I: 1. implement real code that will work outside the two simple tests? 2. implement more dumbest code that will work only for the two simple tests? Neither. I'm not sure where you got the "write just one test at a time" approach from, but it sure is a slow way to go. The point is to write clear tests and use that clear testing to design your program. So, write enough tests to actually validate a sine function. Two tests are clearly inadequate. In the case of a continuous function, you have to provide a table of known good values eventually. Why wait? However, testing continuous functions has some problems. You can't follow a dumb TDD procedure. You can't test *all* floating-point values between 0 and 2\*pi. You can't test a few random values. In the case of continuous functions, a "strict, unthinking TDD" doesn't work. The issue here is that you know your sine function implementation will be based on a bunch of symmetries. You have to test based on those symmetry rules you're using. Bugs hide in cracks and corners. Edge cases and corner cases are part of the implementation and if you unthinkingly follow TDD you can't test that. However, for continuous functions, you must test the edge and corner cases of the implementation. This doesn't mean TDD is broken or inadequate. It says that slavish devotion to a "test first" can't work without some thinking about what you real goal is.
You should code up all your unit tests in one hit (in my opinion). While the idea of only creating tests specifically covering what has to be tested is correct, your particular specification calls for a functioning `sine()` function, *not* a `sine()` function that works for 0 and PI. Find a source you trust enough (a mathematician friend, tables at the back of a math book or another program that already has the sine function implemented). I opted for `bash/bc` because I'm too lazy to type it all in by hand :-). If it *were* a `sine()` function, I'd just run the following program and paste it into the test code. I'd also put a copy of this script in there as a comment as well so I can re-use it if something changes (such as the desired resolution if more than 20 degrees in this case, or the value of PI you want to use). ``` #!/bin/bash d=0 while [[ ${d} -le 400 ]] ; do r=$(echo "3.141592653589 * ${d} / 180" | bc -l) s=$(echo "s(${r})" | bc -l) echo "assertNear(${s},sine(${r})); // ${d} deg." d=$(expr ${d} + 20) done ``` This outputs: ``` assertNear(0,sine(0)); // 0 deg. assertNear(.34202014332558591077,sine(.34906585039877777777)); // 20 deg. assertNear(.64278760968640429167,sine(.69813170079755555555)); // 40 deg. assertNear(.86602540378430644035,sine(1.04719755119633333333)); // 60 deg. assertNear(.98480775301214683962,sine(1.39626340159511111111)); // 80 deg. assertNear(.98480775301228458404,sine(1.74532925199388888888)); // 100 deg. assertNear(.86602540378470305958,sine(2.09439510239266666666)); // 120 deg. assertNear(.64278760968701194759,sine(2.44346095279144444444)); // 140 deg. assertNear(.34202014332633131111,sine(2.79252680319022222222)); // 160 deg. assertNear(.00000000000079323846,sine(3.14159265358900000000)); // 180 deg. assertNear(-.34202014332484051044,sine(3.49065850398777777777)); // 200 deg. assertNear(-.64278760968579663575,sine(3.83972435438655555555)); // 220 deg. assertNear(-.86602540378390982112,sine(4.18879020478533333333)); // 240 deg. assertNear(-.98480775301200909521,sine(4.53785605518411111111)); // 260 deg. assertNear(-.98480775301242232845,sine(4.88692190558288888888)); // 280 deg. assertNear(-.86602540378509967881,sine(5.23598775598166666666)); // 300 deg. assertNear(-.64278760968761960351,sine(5.58505360638044444444)); // 320 deg. assertNear(-.34202014332707671144,sine(5.93411945677922222222)); // 340 deg. assertNear(-.00000000000158647692,sine(6.28318530717800000000)); // 360 deg. assertNear(.34202014332409511011,sine(6.63225115757677777777)); // 380 deg. assertNear(.64278760968518897983,sine(6.98131700797555555555)); // 400 deg. ``` Obviously you will need to map this answer to what your real function is meant to do. My point is that the test should fully validate the behavior of the code in this iteration. If this iteration was to produce a `sine()` function that only works for 0 and PI, then that's fine. But that would be a serious waste of an iteration in my opinion. It may be that your function is so complex that it *must* be done over several iterations. Then your approach two is correct and the tests should be updated in the *next* iteration where you add the extra functionality. Otherwise, find a way to add all the tests for this iteration quickly, then you won't have to worry about switching between real code and test code frequently.
1,463,632
I am trying to use Test Driven Development to implement my signal processing library. But I have a little doubt: Assume I am trying to implement a sine method (I'm not): 1. Write the test (pseudo-code) ``` assertEqual(0, sine(0)) ``` 2. Write the first implementation ``` function sine(radians) return 0 ``` 3. Second test ``` assertEqual(1, sine(pi)) ``` At this point, should I: 1. implement a smart code that will work for pi and other values, or 2. implement the dumbest code that will work only for 0 and pi? If you choose the second option, when can I jump to the first option? I will have to do it eventually...
2009/09/23
[ "https://Stackoverflow.com/questions/1463632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48465/" ]
I believe the step when you jump to the first option is when you see there are too many "ifs" in your code "just to pass the tests". That wouldn't be the case yet, just with 0 and pi. You'll feel the code is beginning to smell, and will be willing to refactor it asap. I'm not sure if that's what pure TDD says, but IMHO you do it in the refactor phase (test fail, test pass, refactor cycle). I mean, unless your failing tests ask for a different implementation.
Strictly following TDD, you can first implement the dumbest code that will work. In order to jump to the first option (to implement the real code), add more tests: ``` assertEqual(tan(x), sin(x)/cos(x)) ``` If you implement more than what is absolutely required by your tests, then your tests will not completely cover your implementation. For example, if you implemented the whole `sin()` function with just the two tests above, you could accidentally "break" it by returning a triangle function (that almost looks like a sine function) and your tests would not be able to detect the error. The other thing you will have to worry about for numeric functions is the notion of "equality" and having to deal with the inherent loss of precision in floating point calculations. That's what I *thought* your question was going to be about after reading just the title. :)
1,463,632
I am trying to use Test Driven Development to implement my signal processing library. But I have a little doubt: Assume I am trying to implement a sine method (I'm not): 1. Write the test (pseudo-code) ``` assertEqual(0, sine(0)) ``` 2. Write the first implementation ``` function sine(radians) return 0 ``` 3. Second test ``` assertEqual(1, sine(pi)) ``` At this point, should I: 1. implement a smart code that will work for pi and other values, or 2. implement the dumbest code that will work only for 0 and pi? If you choose the second option, when can I jump to the first option? I will have to do it eventually...
2009/09/23
[ "https://Stackoverflow.com/questions/1463632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48465/" ]
Write tests that verify Identities. For the sin(x) example, think about double-angle formula and half-angle formula. Open a signal-processing textbook. Find the relevant chapters and implement every single one of those theorems/corollaries as test code applicable for your function. For most signal-processing functions there are identities that must be uphold for the inputs and the outputs. Write tests that verify those identities, regardless of what those inputs might be. Then think about the inputs. * Divide the implementation process into separate stages. Each stage should have a Goal. The tests for each stage would be to verify that Goal. (Note 1) 1. The goal of the first stage is to be "roughly correct". For the sin(x) example, this would be like a naive implementation using binary search and some mathematical identities. 2. The goal of the second stage is to be "accurate enough". You will try different ways of computing the same function and see which one gets better result. 3. The goal of the third stage is to be "efficient". (Note 1) Make it work, make it correct, make it fast, make it cheap. - attributed to Alan Kay
Short answer. * Write one test at a time. * Once it fails, Get back to green first. If that means doing the simplest thing that can work, do it. (Option 2) * Once you're in the green, you can look at the code and *choose* to cleanup (option1). Or you can say that the code still doesn't smell that much and write subsequent tests that put the spotlight on the smells. Another question you seem to have, is how many tests should you write. You need to test till fear (the function may not work) turns into boredom. So once you've tested for all the interesting input-output combinations, you're done.
1,463,632
I am trying to use Test Driven Development to implement my signal processing library. But I have a little doubt: Assume I am trying to implement a sine method (I'm not): 1. Write the test (pseudo-code) ``` assertEqual(0, sine(0)) ``` 2. Write the first implementation ``` function sine(radians) return 0 ``` 3. Second test ``` assertEqual(1, sine(pi)) ``` At this point, should I: 1. implement a smart code that will work for pi and other values, or 2. implement the dumbest code that will work only for 0 and pi? If you choose the second option, when can I jump to the first option? I will have to do it eventually...
2009/09/23
[ "https://Stackoverflow.com/questions/1463632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48465/" ]
Note that (in NUnit) you can also do ``` Assert.That(2.1 + 1.2, Is.EqualTo(3.3).Within(0.0005); ``` when you're dealing with floating-point equality. One piece of advice I remember reading was to try to refactor out the magic numbers from your implementations.
I don't know what language you are using, but when I am dealing with a numeric method, I typically write a simple test like yours first to make sure the outline is correct, and then I feed more values to cover cases where I suspect things might go wrong. In .NET, NUnit 2.5 has a nice feature for this, called `[TestCase]`, where you can feed multiple input values to the same test like this: ``` [TestCase(1,2,Result=3)] [TestCase(1,1,Result=2)] public int CheckAddition(int a, int b) { return a+b; } ```
1,463,632
I am trying to use Test Driven Development to implement my signal processing library. But I have a little doubt: Assume I am trying to implement a sine method (I'm not): 1. Write the test (pseudo-code) ``` assertEqual(0, sine(0)) ``` 2. Write the first implementation ``` function sine(radians) return 0 ``` 3. Second test ``` assertEqual(1, sine(pi)) ``` At this point, should I: 1. implement a smart code that will work for pi and other values, or 2. implement the dumbest code that will work only for 0 and pi? If you choose the second option, when can I jump to the first option? I will have to do it eventually...
2009/09/23
[ "https://Stackoverflow.com/questions/1463632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48465/" ]
At this point, should I: 1. implement real code that will work outside the two simple tests? 2. implement more dumbest code that will work only for the two simple tests? Neither. I'm not sure where you got the "write just one test at a time" approach from, but it sure is a slow way to go. The point is to write clear tests and use that clear testing to design your program. So, write enough tests to actually validate a sine function. Two tests are clearly inadequate. In the case of a continuous function, you have to provide a table of known good values eventually. Why wait? However, testing continuous functions has some problems. You can't follow a dumb TDD procedure. You can't test *all* floating-point values between 0 and 2\*pi. You can't test a few random values. In the case of continuous functions, a "strict, unthinking TDD" doesn't work. The issue here is that you know your sine function implementation will be based on a bunch of symmetries. You have to test based on those symmetry rules you're using. Bugs hide in cracks and corners. Edge cases and corner cases are part of the implementation and if you unthinkingly follow TDD you can't test that. However, for continuous functions, you must test the edge and corner cases of the implementation. This doesn't mean TDD is broken or inadequate. It says that slavish devotion to a "test first" can't work without some thinking about what you real goal is.
In kind of the strict baby-step TDD, you might implement the dumb method to get back to green, and then refactor the duplication inherent in the dumb code (testing for the input value is a kind of duplication between the test and the code) by producing a real algorithm. The hard part about getting a feel for TDD with such an algorithm is that your acceptance tests are really sitting right next to you (the table S. Lott suggests), so you kind of keep an eye on them the whole time. In more typical TDD, the unit is divorced enough from the whole that the acceptance tests can't just be plugged in right there, so you don't start thinking about testing for all scenarios, because all scenarios are not obvious. Typically, you might have a real algorithm after one or two cases. The important thing about TDD is that it is driving design, not the algorithm. Once you have enough cases to satisfy the design needs, the value in TDD drops significantly. Then the tests more convert into covering corner cases to ensure your algorithm is correct in all aspects you can think of. So, if you are confident in how to build the algorithm, go for it. The kinds of baby steps you are talking about are only appropriate when you are uncertain. By taking such baby steps you start to build out the boundaries of what your code has to cover, even though your implementation isn't actually real yet. But as I said, that is more for when you are uncertain about how to build the algorithm.
1,463,632
I am trying to use Test Driven Development to implement my signal processing library. But I have a little doubt: Assume I am trying to implement a sine method (I'm not): 1. Write the test (pseudo-code) ``` assertEqual(0, sine(0)) ``` 2. Write the first implementation ``` function sine(radians) return 0 ``` 3. Second test ``` assertEqual(1, sine(pi)) ``` At this point, should I: 1. implement a smart code that will work for pi and other values, or 2. implement the dumbest code that will work only for 0 and pi? If you choose the second option, when can I jump to the first option? I will have to do it eventually...
2009/09/23
[ "https://Stackoverflow.com/questions/1463632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48465/" ]
At this point, should I: 1. implement real code that will work outside the two simple tests? 2. implement more dumbest code that will work only for the two simple tests? Neither. I'm not sure where you got the "write just one test at a time" approach from, but it sure is a slow way to go. The point is to write clear tests and use that clear testing to design your program. So, write enough tests to actually validate a sine function. Two tests are clearly inadequate. In the case of a continuous function, you have to provide a table of known good values eventually. Why wait? However, testing continuous functions has some problems. You can't follow a dumb TDD procedure. You can't test *all* floating-point values between 0 and 2\*pi. You can't test a few random values. In the case of continuous functions, a "strict, unthinking TDD" doesn't work. The issue here is that you know your sine function implementation will be based on a bunch of symmetries. You have to test based on those symmetry rules you're using. Bugs hide in cracks and corners. Edge cases and corner cases are part of the implementation and if you unthinkingly follow TDD you can't test that. However, for continuous functions, you must test the edge and corner cases of the implementation. This doesn't mean TDD is broken or inadequate. It says that slavish devotion to a "test first" can't work without some thinking about what you real goal is.
Note that (in NUnit) you can also do ``` Assert.That(2.1 + 1.2, Is.EqualTo(3.3).Within(0.0005); ``` when you're dealing with floating-point equality. One piece of advice I remember reading was to try to refactor out the magic numbers from your implementations.
4,059,683
I want to do something like SO does with DisplayName. When someone does not enter a DisplayName, I want to default this to 'User' + UserId. So the first user who signs up would get `User1` - since UserId will be 1, the second `User2` - since UserId will be 2, and so on. The easiest way I can think of doing this is using a trigger, but I don't like triggers. I could save the user, then update the user after the save (basically a trigger, but done in my code). Any other ideas on how I can handle this? Is there a way I can set the default value on the column in the database? I am using Asp.Net MVC 2, C# 4, EF4, and SQL Server 2008.
2010/10/30
[ "https://Stackoverflow.com/questions/4059683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144496/" ]
You can set the user name in the stored procedure. if a user name has been passed to stored procedure, simply save it. otherwise, get the primary key id of the last entered user and add 1 to it. format it to whatever you like (e.g. User + newID) and save this as the new user's user name.
You can have a computedColumn ``` [UserName] AS ('User' + CAST(UserID AS VARCHAR)) PERSISTED ```
4,059,683
I want to do something like SO does with DisplayName. When someone does not enter a DisplayName, I want to default this to 'User' + UserId. So the first user who signs up would get `User1` - since UserId will be 1, the second `User2` - since UserId will be 2, and so on. The easiest way I can think of doing this is using a trigger, but I don't like triggers. I could save the user, then update the user after the save (basically a trigger, but done in my code). Any other ideas on how I can handle this? Is there a way I can set the default value on the column in the database? I am using Asp.Net MVC 2, C# 4, EF4, and SQL Server 2008.
2010/10/30
[ "https://Stackoverflow.com/questions/4059683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144496/" ]
``` Select Coalesce(DisplayName, 'User' + Cast(UserID as varchar)) as UserName ```
You can set the user name in the stored procedure. if a user name has been passed to stored procedure, simply save it. otherwise, get the primary key id of the last entered user and add 1 to it. format it to whatever you like (e.g. User + newID) and save this as the new user's user name.
4,059,683
I want to do something like SO does with DisplayName. When someone does not enter a DisplayName, I want to default this to 'User' + UserId. So the first user who signs up would get `User1` - since UserId will be 1, the second `User2` - since UserId will be 2, and so on. The easiest way I can think of doing this is using a trigger, but I don't like triggers. I could save the user, then update the user after the save (basically a trigger, but done in my code). Any other ideas on how I can handle this? Is there a way I can set the default value on the column in the database? I am using Asp.Net MVC 2, C# 4, EF4, and SQL Server 2008.
2010/10/30
[ "https://Stackoverflow.com/questions/4059683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144496/" ]
You can set the user name in the stored procedure. if a user name has been passed to stored procedure, simply save it. otherwise, get the primary key id of the last entered user and add 1 to it. format it to whatever you like (e.g. User + newID) and save this as the new user's user name.
I would be inclined to generate it before saving to the database. No input = make one up. I also would not have user User1, User2, ... but user+random: user6238945, user9287561, user8934678, etc If you use 1, 2, 3, 4 etc then you are exposing an internal sequence. If someone gets "user4" then I know other users 1 to 3 exist, as well as number 5. This exposure was used many years by AOL or Compuserve (?) for phishing attacks.
4,059,683
I want to do something like SO does with DisplayName. When someone does not enter a DisplayName, I want to default this to 'User' + UserId. So the first user who signs up would get `User1` - since UserId will be 1, the second `User2` - since UserId will be 2, and so on. The easiest way I can think of doing this is using a trigger, but I don't like triggers. I could save the user, then update the user after the save (basically a trigger, but done in my code). Any other ideas on how I can handle this? Is there a way I can set the default value on the column in the database? I am using Asp.Net MVC 2, C# 4, EF4, and SQL Server 2008.
2010/10/30
[ "https://Stackoverflow.com/questions/4059683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144496/" ]
``` Select Coalesce(DisplayName, 'User' + Cast(UserID as varchar)) as UserName ```
You can have a computedColumn ``` [UserName] AS ('User' + CAST(UserID AS VARCHAR)) PERSISTED ```
4,059,683
I want to do something like SO does with DisplayName. When someone does not enter a DisplayName, I want to default this to 'User' + UserId. So the first user who signs up would get `User1` - since UserId will be 1, the second `User2` - since UserId will be 2, and so on. The easiest way I can think of doing this is using a trigger, but I don't like triggers. I could save the user, then update the user after the save (basically a trigger, but done in my code). Any other ideas on how I can handle this? Is there a way I can set the default value on the column in the database? I am using Asp.Net MVC 2, C# 4, EF4, and SQL Server 2008.
2010/10/30
[ "https://Stackoverflow.com/questions/4059683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144496/" ]
``` Select Coalesce(DisplayName, 'User' + Cast(UserID as varchar)) as UserName ```
I would be inclined to generate it before saving to the database. No input = make one up. I also would not have user User1, User2, ... but user+random: user6238945, user9287561, user8934678, etc If you use 1, 2, 3, 4 etc then you are exposing an internal sequence. If someone gets "user4" then I know other users 1 to 3 exist, as well as number 5. This exposure was used many years by AOL or Compuserve (?) for phishing attacks.
8,744,023
I am little confused about the MDM, wish that someone could help me here. I have studied the docs from the Apple website regarding the iOS MDM,but still I feel puzzled ,I have some questions. 1. Whether MDM server is communicating APNS every-time when it needs to execute command ? 2. Is it very complex to setup our own MDM server and how to setup our own MDM server ? Thank you in advance.
2012/01/05
[ "https://Stackoverflow.com/questions/8744023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1120610/" ]
1) the general idea is that you send one request via APNS and then respond with a command when the device 'phones home' to your MDM server. Once the device responds to your command, you can send another command back in response and so on until the device has executed all the commands at which point your server should respond with an empty HTTP response. 2) That entirely depends on what your definition of complex is! I have created 2 MDM 'servers' in the past year and it's not impossible but quite complex to detail.
MDM server communicates only when it needs to send a command to the device. Here is how it goes, 1. MDM server contacts APNS server with MDM payload. 2. APNS server triggers a wake up on device to check server for MDM command. 3. Mobile device contacts the MDM server for command to be executed. Implementing MDM is simple if you have a enterprise account. 1. Get your MDM certificate. <http://www.blueboxmoon.com/wordpress/?p=877> 2. Using IPCU create a profile and push it on mobile. 3. With this the device push magic will be passed to the checkin URL you specified in the config profile. 4. Then trigger the mdm payload using JAVAPNS with push magic and token. JavaPNS - <https://code.google.com/p/javapns/> 5. Create a simple page that will respond to device command. Refer Blackhat guide for full documentation. <https://media.blackhat.com/bh-us-11/Schuetz/BH_US_11_Schuetz_InsideAppleMDM_WP.pdf> or this <http://darthnull.org/media/papers/MDM_CommandReference.pdf> for commands reference.
3,495,216
How to output sql statement right before it's launched? To check all placed data inside prepared statement.
2010/08/16
[ "https://Stackoverflow.com/questions/3495216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/849669/" ]
Zend\_Db doesn't have a mechanism itself to output the sql statements that it generates. What you can do is modify the public method "query" in Zend/Db/Adapter/Abstract.php(line 445 in 1.10.6) to output the $sql local variable. The query method is called by both the update and insert methods.
There is actually a way to output the SQL it generates ``` $select = $db->select()->from('elements') ->where('id = ?', $this->_Id); $sql = $select->__toString(); echo $sql; ```
3,495,216
How to output sql statement right before it's launched? To check all placed data inside prepared statement.
2010/08/16
[ "https://Stackoverflow.com/questions/3495216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/849669/" ]
Zend\_Db doesn't have a mechanism itself to output the sql statements that it generates. What you can do is modify the public method "query" in Zend/Db/Adapter/Abstract.php(line 445 in 1.10.6) to output the $sql local variable. The query method is called by both the update and insert methods.
You can also use: echo (string) $select;
3,495,216
How to output sql statement right before it's launched? To check all placed data inside prepared statement.
2010/08/16
[ "https://Stackoverflow.com/questions/3495216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/849669/" ]
There is actually a way to output the SQL it generates ``` $select = $db->select()->from('elements') ->where('id = ?', $this->_Id); $sql = $select->__toString(); echo $sql; ```
You can also use: echo (string) $select;
67,746,066
I've devised an example of the usage of **Graphql** in **Spring Boot**. I got an error related with the definition of **Date** when I wrote a query in **Graphiql** Here is the error : `Can't serialize value : Expected a 'String' or 'java.time.temporal.TemporalAccessor' but was 'Timestamp'."` Here is my Doctor Entity which is shown below. ``` public class Doctor implements Serializable { .... private Date birthday; .... } ``` Here is my code snippet defined in **Graphiql** which is shown below. ``` { departments{ id name doctors{ id firstName lastName salary age birthday } hospital{ id name } } } ``` Here is my project file : [My Project Link](https://github.com/Rapter1990/springbootgraphql) How can I fix it?
2021/05/28
[ "https://Stackoverflow.com/questions/67746066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5719229/" ]
You probably want to do something like this, using flexbox as Pedro suggested. ```css /*******************************/ /********** About CSS **********/ /*******************************/ .about { position: relative; width: 100%; padding: 45px 0; } .about .about-img { flex: 1 1 0px; } .about .about-img img { position: relative; width: 100%; } .about .about-text p { font-size: 16px; } .about .about-text a.btn { position: relative; margin-top: 15px; padding: 12px 20px; font-size: 14px; font-weight: 600; letter-spacing: 1px; color: #F7CAC9; background: #343148; border-radius: 0; transition: .3s; } .about .about-text a.btn:hover { color: #343148; background: #F7CAC9; } /*******************************/ /******* Section Header ********/ /*******************************/ .hero-text { flex: 1 1 0px; } .section-header { position: relative; margin: 0 auto; margin-bottom: 45px; } .section-header p { display: inline-block; margin: 0 30px; margin-bottom: 5px; padding: 0 10px; position: relative; font-size: 16px; font-weight: 600; background: #ffffff; } .section-header p::after { /* les barres */ position: absolute; content: ""; height: 2px; top: 11px; right: -30px; left: -30px; background: #F7CAC9; z-index: -1; } .section-header h2 { margin: 0; position: relative; font-size: 40px; font-weight: 700; } /*******************************/ /********* Service CSS *********/ /*******************************/ .service { position: relative; width: 100%; padding: 45px 0 15px 0; } .hero-container { max-width: 900px; text-align: center; display: flex; } .container { max-width: 900px; text-align: center; } ``` ```html <!-- About Start --> <div class="about"> <div class="hero-container"> <div class="about-img"> <img src="https://zupimages.net/up/21/21/54ov.png" alt="Image"> </div> <div class="hero-text"> <div class="section-header"> <p>Learn About Us</p> <h2>Welcome to Yooga</h2> </div> <div class="about-text"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. Curabitur non nisl nec nisi scelerisque maximus. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> </div> <!-- About End --> <br /> <!-- Service Start --> <div class="service"> <div class="container"> <div class="section-header"> <p>What we do</p> <h2>Yoga For Health</h2> </div> <div class="about-text"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. Curabitur non nisl nec nisi scelerisque maximus. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> <!-- Service End --> ```
Can you check this: ```css /*******************************/ /********** About CSS **********/ /*******************************/ .about { display:flex; width: 100%; padding: 45px 0; flex-direction: row; } .about-img { width: 30%; } .about-image{ width: 100%; } .about-container{ width: 70%; padding-left: 30px; } .about .about-text p { font-size: 16px; } .about .about-text a.btn { position: relative; margin-top: 15px; padding: 12px 20px; font-size: 14px; font-weight: 600; letter-spacing: 1px; color: #F7CAC9; background: #343148; border-radius: 0; transition: .3s; } .about .about-text a.btn:hover { color: #343148; background: #F7CAC9; } /*******************************/ /******* Section Header ********/ /*******************************/ .section-header { position: relative; margin: 0 auto; margin-bottom: 45px; text-align:center; } .section-header p { display: inline-block; margin: 0 30px; margin-bottom: 5px; padding: 0 10px; position: relative; font-size: 16px; font-weight: 600; background: #ffffff; } .section-header p::after { /* les barres */ position: absolute; content: ""; height: 2px; top: 11px; right: -30px; left: -30px; background: #F7CAC9; z-index: -1; } .section-header h2 { margin: 0; position: relative; font-size: 40px; font-weight: 700; } /*******************************/ /********* Service CSS *********/ /*******************************/ .service { position: relative; width: 100%; padding: 45px 0 15px 0; } .container { text-align: center; } ``` ```html <!-- About Start --> <div class="about"> <div class="about-img"> <img class="about-image" src="https://zupimages.net/up/21/21/54ov.png" alt="Image"> </div> <div class="about-container"> <div class="section-header"> <p>Learn About Us</p> <h2>Welcome to Yooga</h2> </div> <div class="about-text"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. Curabitur non nisl nec nisi scelerisque maximus. </p> <a class="btn learn-more" href="">Learn More</a> </div> </div> </div> <!-- About End --> <br /> <!-- Service Start --> <div class="service"> <div class="container"> <div class="section-header"> <p>What we do</p> <h2>Yoga For Health</h2> </div> </div> </div> <!-- Service End --> ```
67,746,066
I've devised an example of the usage of **Graphql** in **Spring Boot**. I got an error related with the definition of **Date** when I wrote a query in **Graphiql** Here is the error : `Can't serialize value : Expected a 'String' or 'java.time.temporal.TemporalAccessor' but was 'Timestamp'."` Here is my Doctor Entity which is shown below. ``` public class Doctor implements Serializable { .... private Date birthday; .... } ``` Here is my code snippet defined in **Graphiql** which is shown below. ``` { departments{ id name doctors{ id firstName lastName salary age birthday } hospital{ id name } } } ``` Here is my project file : [My Project Link](https://github.com/Rapter1990/springbootgraphql) How can I fix it?
2021/05/28
[ "https://Stackoverflow.com/questions/67746066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5719229/" ]
You probably want to do something like this, using flexbox as Pedro suggested. ```css /*******************************/ /********** About CSS **********/ /*******************************/ .about { position: relative; width: 100%; padding: 45px 0; } .about .about-img { flex: 1 1 0px; } .about .about-img img { position: relative; width: 100%; } .about .about-text p { font-size: 16px; } .about .about-text a.btn { position: relative; margin-top: 15px; padding: 12px 20px; font-size: 14px; font-weight: 600; letter-spacing: 1px; color: #F7CAC9; background: #343148; border-radius: 0; transition: .3s; } .about .about-text a.btn:hover { color: #343148; background: #F7CAC9; } /*******************************/ /******* Section Header ********/ /*******************************/ .hero-text { flex: 1 1 0px; } .section-header { position: relative; margin: 0 auto; margin-bottom: 45px; } .section-header p { display: inline-block; margin: 0 30px; margin-bottom: 5px; padding: 0 10px; position: relative; font-size: 16px; font-weight: 600; background: #ffffff; } .section-header p::after { /* les barres */ position: absolute; content: ""; height: 2px; top: 11px; right: -30px; left: -30px; background: #F7CAC9; z-index: -1; } .section-header h2 { margin: 0; position: relative; font-size: 40px; font-weight: 700; } /*******************************/ /********* Service CSS *********/ /*******************************/ .service { position: relative; width: 100%; padding: 45px 0 15px 0; } .hero-container { max-width: 900px; text-align: center; display: flex; } .container { max-width: 900px; text-align: center; } ``` ```html <!-- About Start --> <div class="about"> <div class="hero-container"> <div class="about-img"> <img src="https://zupimages.net/up/21/21/54ov.png" alt="Image"> </div> <div class="hero-text"> <div class="section-header"> <p>Learn About Us</p> <h2>Welcome to Yooga</h2> </div> <div class="about-text"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. Curabitur non nisl nec nisi scelerisque maximus. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> </div> <!-- About End --> <br /> <!-- Service Start --> <div class="service"> <div class="container"> <div class="section-header"> <p>What we do</p> <h2>Yoga For Health</h2> </div> <div class="about-text"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. Curabitur non nisl nec nisi scelerisque maximus. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> <!-- Service End --> ```
``` <style> .about { position: relative; width: 100%; padding: 45px 0; } .about .about-img img { position: relative; width: 100%; } .about .about-text p { font-size: 16px; } .about .about-text a.btn { position: relative; margin-top: 15px; padding: 12px 20px; font-size: 14px; font-weight: 600; letter-spacing: 1px; color: #F7CAC9; background: #343148; border-radius: 0; transition: .3s; } .about .about-text a.btn:hover { color: #343148; background: #F7CAC9; } .about-text { text-align: left; } /*******************************/ /******* Section Header ********/ /*******************************/ .section-header { position: relative; margin: 0 auto; margin-bottom: 45px; text-align: left; } .section-header p { display: inline-block; margin: 0 30px; margin-bottom: 5px; padding: 0 10px; position: relative; font-size: 16px; font-weight: 600; background: #ffffff; } .section-header p::after { /* les barres */ position: absolute; content: ""; height: 2px; top: 11px; right: -30px; left: -30px; background: #F7CAC9; z-index: -1; } .section-header h2 { margin: 0; position: relative; font-size: 40px; font-weight: 700; } /*******************************/ /********* Service CSS *********/ /*******************************/ .service { position: relative; width: 100%; padding: 45px 0 15px 0; } .container { text-align: center; display: flex; } .about-img { flex: 0 0 42%; } </style> <!-- About Start --> <div class="about"> <div class="container"> <div class="about-img"> <img src="https://zupimages.net/up/21/21/54ov.png" alt="Image"> </div> <div> <div class="section-header"> <p>Learn About Us</p> <h2>Welcome to Yooga</h2> </div> <div class="about-text"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. Curabitur non nisl nec nisi scelerisque maximus. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> </div> <!-- About End --> <br /> <!-- Service Start --> <div class="service"> <div class="container"> <div class="section-header"> <p>What we do</p> <h2>Yoga For Health</h2> </div> </div> </div> <!-- Service End --> ```
67,746,066
I've devised an example of the usage of **Graphql** in **Spring Boot**. I got an error related with the definition of **Date** when I wrote a query in **Graphiql** Here is the error : `Can't serialize value : Expected a 'String' or 'java.time.temporal.TemporalAccessor' but was 'Timestamp'."` Here is my Doctor Entity which is shown below. ``` public class Doctor implements Serializable { .... private Date birthday; .... } ``` Here is my code snippet defined in **Graphiql** which is shown below. ``` { departments{ id name doctors{ id firstName lastName salary age birthday } hospital{ id name } } } ``` Here is my project file : [My Project Link](https://github.com/Rapter1990/springbootgraphql) How can I fix it?
2021/05/28
[ "https://Stackoverflow.com/questions/67746066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5719229/" ]
You can use *flexbox* to align things easily. > > Here is a beginner friendly guide to flexbox - [CSS Tricks - A Complete Guide to Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) > > > You can use this code to get the desired results NOTE: I have changed the markup a bit ```css h2 { font-size: 2.5rem; color: rgb(28, 19, 37); margin: 0; } p { color: rgb(134, 134, 134); margin: 1rem 0; line-height: 1.5; } button { outline: none; border: none; border-radius: 0.25rem; background: rgb(28, 19, 37); color: #F7CAC9; font-size: 1rem; letter-spacing: 0.5px; text-decoration: none; padding: 1rem 1.5rem; } .container { display: flex; font-family: sans-serif; max-width: 1000px; margin: 2rem auto; } .container img { height: 350px; margin: 1rem; } .section-header p { position: relative; } .section-header p::after, .section-header p::before { position: absolute; content: ""; height: 2px; width: 35px; background: #F7CAC9; z-index: -1; } .section-header p::after { top: 11px; margin: 0 10px; } .section-header p::before { top: 11px; margin-left: -45px; } .service .section-header { width: 100%; text-align: center; } ``` ```html <div class="about"> <div class="container"> <img src="https://zupimages.net/up/21/21/54ov.png" alt="Image"> <div class="content"> <div class="section-header"> <p>Learn About Us</p> <h2>Welcome to Yooga</h2> </div> <div class="about-text"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. Curabitur non nisl nec nisi scelerisque maximus. </p> <button>Learn More</button> </div> </div> </div> </div> <!-- About End --> <br /> <!-- Service Start --> <div class="service"> <div class="container"> <div class="section-header"> <p>What we do</p> <h2>Yoga For Health</h2> </div> </div> </div> ```
You probably want to do something like this, using flexbox as Pedro suggested. ```css /*******************************/ /********** About CSS **********/ /*******************************/ .about { position: relative; width: 100%; padding: 45px 0; } .about .about-img { flex: 1 1 0px; } .about .about-img img { position: relative; width: 100%; } .about .about-text p { font-size: 16px; } .about .about-text a.btn { position: relative; margin-top: 15px; padding: 12px 20px; font-size: 14px; font-weight: 600; letter-spacing: 1px; color: #F7CAC9; background: #343148; border-radius: 0; transition: .3s; } .about .about-text a.btn:hover { color: #343148; background: #F7CAC9; } /*******************************/ /******* Section Header ********/ /*******************************/ .hero-text { flex: 1 1 0px; } .section-header { position: relative; margin: 0 auto; margin-bottom: 45px; } .section-header p { display: inline-block; margin: 0 30px; margin-bottom: 5px; padding: 0 10px; position: relative; font-size: 16px; font-weight: 600; background: #ffffff; } .section-header p::after { /* les barres */ position: absolute; content: ""; height: 2px; top: 11px; right: -30px; left: -30px; background: #F7CAC9; z-index: -1; } .section-header h2 { margin: 0; position: relative; font-size: 40px; font-weight: 700; } /*******************************/ /********* Service CSS *********/ /*******************************/ .service { position: relative; width: 100%; padding: 45px 0 15px 0; } .hero-container { max-width: 900px; text-align: center; display: flex; } .container { max-width: 900px; text-align: center; } ``` ```html <!-- About Start --> <div class="about"> <div class="hero-container"> <div class="about-img"> <img src="https://zupimages.net/up/21/21/54ov.png" alt="Image"> </div> <div class="hero-text"> <div class="section-header"> <p>Learn About Us</p> <h2>Welcome to Yooga</h2> </div> <div class="about-text"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. Curabitur non nisl nec nisi scelerisque maximus. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> </div> <!-- About End --> <br /> <!-- Service Start --> <div class="service"> <div class="container"> <div class="section-header"> <p>What we do</p> <h2>Yoga For Health</h2> </div> <div class="about-text"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. Curabitur non nisl nec nisi scelerisque maximus. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> <!-- Service End --> ```
67,746,066
I've devised an example of the usage of **Graphql** in **Spring Boot**. I got an error related with the definition of **Date** when I wrote a query in **Graphiql** Here is the error : `Can't serialize value : Expected a 'String' or 'java.time.temporal.TemporalAccessor' but was 'Timestamp'."` Here is my Doctor Entity which is shown below. ``` public class Doctor implements Serializable { .... private Date birthday; .... } ``` Here is my code snippet defined in **Graphiql** which is shown below. ``` { departments{ id name doctors{ id firstName lastName salary age birthday } hospital{ id name } } } ``` Here is my project file : [My Project Link](https://github.com/Rapter1990/springbootgraphql) How can I fix it?
2021/05/28
[ "https://Stackoverflow.com/questions/67746066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5719229/" ]
You can use *flexbox* to align things easily. > > Here is a beginner friendly guide to flexbox - [CSS Tricks - A Complete Guide to Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) > > > You can use this code to get the desired results NOTE: I have changed the markup a bit ```css h2 { font-size: 2.5rem; color: rgb(28, 19, 37); margin: 0; } p { color: rgb(134, 134, 134); margin: 1rem 0; line-height: 1.5; } button { outline: none; border: none; border-radius: 0.25rem; background: rgb(28, 19, 37); color: #F7CAC9; font-size: 1rem; letter-spacing: 0.5px; text-decoration: none; padding: 1rem 1.5rem; } .container { display: flex; font-family: sans-serif; max-width: 1000px; margin: 2rem auto; } .container img { height: 350px; margin: 1rem; } .section-header p { position: relative; } .section-header p::after, .section-header p::before { position: absolute; content: ""; height: 2px; width: 35px; background: #F7CAC9; z-index: -1; } .section-header p::after { top: 11px; margin: 0 10px; } .section-header p::before { top: 11px; margin-left: -45px; } .service .section-header { width: 100%; text-align: center; } ``` ```html <div class="about"> <div class="container"> <img src="https://zupimages.net/up/21/21/54ov.png" alt="Image"> <div class="content"> <div class="section-header"> <p>Learn About Us</p> <h2>Welcome to Yooga</h2> </div> <div class="about-text"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. Curabitur non nisl nec nisi scelerisque maximus. </p> <button>Learn More</button> </div> </div> </div> </div> <!-- About End --> <br /> <!-- Service Start --> <div class="service"> <div class="container"> <div class="section-header"> <p>What we do</p> <h2>Yoga For Health</h2> </div> </div> </div> ```
Can you check this: ```css /*******************************/ /********** About CSS **********/ /*******************************/ .about { display:flex; width: 100%; padding: 45px 0; flex-direction: row; } .about-img { width: 30%; } .about-image{ width: 100%; } .about-container{ width: 70%; padding-left: 30px; } .about .about-text p { font-size: 16px; } .about .about-text a.btn { position: relative; margin-top: 15px; padding: 12px 20px; font-size: 14px; font-weight: 600; letter-spacing: 1px; color: #F7CAC9; background: #343148; border-radius: 0; transition: .3s; } .about .about-text a.btn:hover { color: #343148; background: #F7CAC9; } /*******************************/ /******* Section Header ********/ /*******************************/ .section-header { position: relative; margin: 0 auto; margin-bottom: 45px; text-align:center; } .section-header p { display: inline-block; margin: 0 30px; margin-bottom: 5px; padding: 0 10px; position: relative; font-size: 16px; font-weight: 600; background: #ffffff; } .section-header p::after { /* les barres */ position: absolute; content: ""; height: 2px; top: 11px; right: -30px; left: -30px; background: #F7CAC9; z-index: -1; } .section-header h2 { margin: 0; position: relative; font-size: 40px; font-weight: 700; } /*******************************/ /********* Service CSS *********/ /*******************************/ .service { position: relative; width: 100%; padding: 45px 0 15px 0; } .container { text-align: center; } ``` ```html <!-- About Start --> <div class="about"> <div class="about-img"> <img class="about-image" src="https://zupimages.net/up/21/21/54ov.png" alt="Image"> </div> <div class="about-container"> <div class="section-header"> <p>Learn About Us</p> <h2>Welcome to Yooga</h2> </div> <div class="about-text"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. Curabitur non nisl nec nisi scelerisque maximus. </p> <a class="btn learn-more" href="">Learn More</a> </div> </div> </div> <!-- About End --> <br /> <!-- Service Start --> <div class="service"> <div class="container"> <div class="section-header"> <p>What we do</p> <h2>Yoga For Health</h2> </div> </div> </div> <!-- Service End --> ```
67,746,066
I've devised an example of the usage of **Graphql** in **Spring Boot**. I got an error related with the definition of **Date** when I wrote a query in **Graphiql** Here is the error : `Can't serialize value : Expected a 'String' or 'java.time.temporal.TemporalAccessor' but was 'Timestamp'."` Here is my Doctor Entity which is shown below. ``` public class Doctor implements Serializable { .... private Date birthday; .... } ``` Here is my code snippet defined in **Graphiql** which is shown below. ``` { departments{ id name doctors{ id firstName lastName salary age birthday } hospital{ id name } } } ``` Here is my project file : [My Project Link](https://github.com/Rapter1990/springbootgraphql) How can I fix it?
2021/05/28
[ "https://Stackoverflow.com/questions/67746066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5719229/" ]
You can use *flexbox* to align things easily. > > Here is a beginner friendly guide to flexbox - [CSS Tricks - A Complete Guide to Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) > > > You can use this code to get the desired results NOTE: I have changed the markup a bit ```css h2 { font-size: 2.5rem; color: rgb(28, 19, 37); margin: 0; } p { color: rgb(134, 134, 134); margin: 1rem 0; line-height: 1.5; } button { outline: none; border: none; border-radius: 0.25rem; background: rgb(28, 19, 37); color: #F7CAC9; font-size: 1rem; letter-spacing: 0.5px; text-decoration: none; padding: 1rem 1.5rem; } .container { display: flex; font-family: sans-serif; max-width: 1000px; margin: 2rem auto; } .container img { height: 350px; margin: 1rem; } .section-header p { position: relative; } .section-header p::after, .section-header p::before { position: absolute; content: ""; height: 2px; width: 35px; background: #F7CAC9; z-index: -1; } .section-header p::after { top: 11px; margin: 0 10px; } .section-header p::before { top: 11px; margin-left: -45px; } .service .section-header { width: 100%; text-align: center; } ``` ```html <div class="about"> <div class="container"> <img src="https://zupimages.net/up/21/21/54ov.png" alt="Image"> <div class="content"> <div class="section-header"> <p>Learn About Us</p> <h2>Welcome to Yooga</h2> </div> <div class="about-text"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. Curabitur non nisl nec nisi scelerisque maximus. </p> <button>Learn More</button> </div> </div> </div> </div> <!-- About End --> <br /> <!-- Service Start --> <div class="service"> <div class="container"> <div class="section-header"> <p>What we do</p> <h2>Yoga For Health</h2> </div> </div> </div> ```
``` <style> .about { position: relative; width: 100%; padding: 45px 0; } .about .about-img img { position: relative; width: 100%; } .about .about-text p { font-size: 16px; } .about .about-text a.btn { position: relative; margin-top: 15px; padding: 12px 20px; font-size: 14px; font-weight: 600; letter-spacing: 1px; color: #F7CAC9; background: #343148; border-radius: 0; transition: .3s; } .about .about-text a.btn:hover { color: #343148; background: #F7CAC9; } .about-text { text-align: left; } /*******************************/ /******* Section Header ********/ /*******************************/ .section-header { position: relative; margin: 0 auto; margin-bottom: 45px; text-align: left; } .section-header p { display: inline-block; margin: 0 30px; margin-bottom: 5px; padding: 0 10px; position: relative; font-size: 16px; font-weight: 600; background: #ffffff; } .section-header p::after { /* les barres */ position: absolute; content: ""; height: 2px; top: 11px; right: -30px; left: -30px; background: #F7CAC9; z-index: -1; } .section-header h2 { margin: 0; position: relative; font-size: 40px; font-weight: 700; } /*******************************/ /********* Service CSS *********/ /*******************************/ .service { position: relative; width: 100%; padding: 45px 0 15px 0; } .container { text-align: center; display: flex; } .about-img { flex: 0 0 42%; } </style> <!-- About Start --> <div class="about"> <div class="container"> <div class="about-img"> <img src="https://zupimages.net/up/21/21/54ov.png" alt="Image"> </div> <div> <div class="section-header"> <p>Learn About Us</p> <h2>Welcome to Yooga</h2> </div> <div class="about-text"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. Curabitur non nisl nec nisi scelerisque maximus. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> </div> <!-- About End --> <br /> <!-- Service Start --> <div class="service"> <div class="container"> <div class="section-header"> <p>What we do</p> <h2>Yoga For Health</h2> </div> </div> </div> <!-- Service End --> ```
8,744,416
I searched a lot, but could not find the solution. I get the error: > > Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints. > > > I run `DataTable.GetErrors()` and see that some columns are set to `Not NULL` in SQL Compact Edition Database. And these columns are used in `LEFT OUTER JOIN` query so they are null when the query is run. (I can get the results when i run the query in Server Explorer in VS). The error occurs when trying to load the data in Datatable: ``` using (SqlCeCommand Cmd = new SqlCeCommand("Query HERE", "Connection HERE")) { C.Open(); using (SqlCeDataReader Rdr = Cmd.ExecuteReader()) { DataTable DT = new DataTable(); DT.Load(Rdr); return DT; } } ``` I tried so many solutions to overcome this however i was not able to solve it. I know about "EnforceConstraints" however as i do not use any dataset, i can not change that property.
2012/01/05
[ "https://Stackoverflow.com/questions/8744416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/894705/" ]
I managed to solve this by getting the schema of the table, iterating through the rows of the schema table (which are columns of the actual table) and creating a column with same properties as the schema column (only difference is setting new column's AllowDBNull to true and Unique and AutoIncrement to false) and finally adding the new column to a fresh datatable which will later be filled with data of our actual table (by the help of a DataReader to get only data and not the schema). Here is the code: ``` using (SqlCeConnection C = new SqlCeConnection(DBStr)) using (Cmd) { //using SqlCeCommand Cmd.Connection = C; C.Open(); using (SqlCeDataReader Rdr = Cmd.ExecuteReader()) { //Create datatable to hold schema and data seperately //Get schema of our actual table DataTable DTSchema = Rdr.GetSchemaTable(); DataTable DT = new DataTable(); if (DTSchema != null) if (DTSchema.Rows.Count > 0) for (int i = 0; i < DTSchema.Rows.Count; i++) { //Create new column for each row in schema table //Set properties that are causing errors and add it to our datatable //Rows in schema table are filled with information of columns in our actual table DataColumn Col = new DataColumn(DTSchema.Rows[i]["ColumnName"].ToString(), (Type)DTSchema.Rows[i]["DataType"]); Col.AllowDBNull = true; Col.Unique = false; Col.AutoIncrement = false; DT.Columns.Add(Col); } while (Rdr.Read()) { //Read data and fill it to our datatable DataRow Row = DT.NewRow(); for (int i = 0; i < DT.Columns.Count; i++) { Row[i] = Rdr[i]; } DT.Rows.Add(Row); } //This is our datatable filled with data return DT; } } ```
In case it catches anyone else; in my SQLite database I had NULL entries stored as strings (`"NULL"`), simply fixing the data worked. This is a SQLite specific issue as you can mix datatypes in columns!
5,052,814
I have JPA mapping to HSQLDB and persistence.xml reads as below: ``` <persistence-unit name="HMC"> <jta-data-source>java:hmc</jta-data-source> <class>org.hmc.jpa.models.BloodGroup</class> <class>org.hmc.jpa.models.ContactInfo</class> <properties> <property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup"/> <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" /> </properties> </persistence-unit> ``` But whenever application is deployed, it JBoss throws RuntimeException saying: `Specification violation [EJB3 JPA 6.2.1.2] - You have not defined a non-jta-data-source for a RESOURCE_LOCAL enabled persistence context named: ABC` I also have datasource defined in JBoss. Is there anything that I am missing in the configuration? Regards, Satya
2011/02/19
[ "https://Stackoverflow.com/questions/5052814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/469320/" ]
1. if the transaction type of the persistence unit is JTA, the jta-datasource element is used to declare the JNDI name of the JTA data source that will be used to obtain connections. This is the common case. 2. if the transaction type of the persistence unit is resource-local, the non-jta-data-source should be used to declare the JNDI name of a non-JTA data source.
I got it working by removing `transaction-type="RESOURCE_LOCAL"` and changing `java:hmc` to `java:/hmc`. But now my application has another problem whenever I try to persist. It throws : `java.lang.IllegalStateException: A JTA EntityManager cannot use getTransaction()` Can anybody tell me how to get a connection and start transaction in JTA mode? Regards, Satya
5,052,814
I have JPA mapping to HSQLDB and persistence.xml reads as below: ``` <persistence-unit name="HMC"> <jta-data-source>java:hmc</jta-data-source> <class>org.hmc.jpa.models.BloodGroup</class> <class>org.hmc.jpa.models.ContactInfo</class> <properties> <property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup"/> <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" /> </properties> </persistence-unit> ``` But whenever application is deployed, it JBoss throws RuntimeException saying: `Specification violation [EJB3 JPA 6.2.1.2] - You have not defined a non-jta-data-source for a RESOURCE_LOCAL enabled persistence context named: ABC` I also have datasource defined in JBoss. Is there anything that I am missing in the configuration? Regards, Satya
2011/02/19
[ "https://Stackoverflow.com/questions/5052814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/469320/" ]
hat is happening is that JBoss automatically scans and validates files named persistence.xml, since you are using spring to manage your beans, I guess you are not using EJB3. What needs to be understood is if you want JBoss to control JTA transactions for you and if you want to use JBoss Transaction Manager, or if you just want to do JPA transactions, without JTA transaction control. If you want to just use the JPA transactions and skip JBoss TransactionManagener, you can just rename your persistence.xml file to spring-persistence.xml (or whatever you like), and in spring-context.xml file you can change your entityManagerFactory to this: ``` <!-- JPA primary EntityManagerFactory --> <bean id="entityManagerFactory" lazy-init="true" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" p:persistenceUnitName="ExamplePU" p:persistenceXmlLocation="classpath:/META-INF/spring-persistence.xml" p:jpaVendorAdapter-ref="jpaVendorAdapter" p:jpaDialect-ref="jpaDialect" p:dataSource-ref="dataSource"/> ``` What happens is that by renaming the file JBoss won't validate it, since you are working outside of the EJB spec and not using any EJB beans, JBoss shouldn't be scanning this file anyways. And since you renamed it, you need to tell spring where it is and under what name.
I got it working by removing `transaction-type="RESOURCE_LOCAL"` and changing `java:hmc` to `java:/hmc`. But now my application has another problem whenever I try to persist. It throws : `java.lang.IllegalStateException: A JTA EntityManager cannot use getTransaction()` Can anybody tell me how to get a connection and start transaction in JTA mode? Regards, Satya
32,170,865
Why are the variable q2,q3 not being initialized, yet q1 is? This is how the outcome should be similar to: > > WELCOME TO MITCHELL'S TINY ADVENTURE! > > > You are in a creepy house! Would you like to go "upstairs" or into > the "kitchen"? > > > > > > > kitchen > > > > > > > > > There is a long countertop with dirty dishes everywhere. Off to one > side there is, as you'd expect, a refrigerator. You may open the > "refrigerator" or look in a "cabinet". > > > > > > > refrigerator > > > > > > > > > Inside the refrigerator you see food and stuff. It looks pretty > nasty. Would you like to eat some of the food? ("yes" or "no") > > > > > > > no > > > > > > > > > ``` import java.util.Scanner; public class App1 { public static void main(String[] Args) { Scanner keyboard = new Scanner(System.in); String q1; String q2; String q3; String a = "upstairs"; String b = "kitchen"; String c = "refrigerator"; String d = "cabinet"; String e = "yes"; String f = "no"; String g = "hallway"; String h = "bedroom"; String i = "bathroom"; System.out.println("Welcome To Mitchell's Tiny Adventure!"); System.out.println(); System.out.println("You are in a creepy house, would you like to go upstairs or into the kitchen?"); System.out.print(">"); q1 = keyboard.nextLine(); System.out.println(); if (q1.equals(a)) { System.out.println("Upstairs you see a hallway. At the end of the hallway is the master"); System.out.println("\"bedroom\". There is also a \"bathroom\" off the hallway. Where would you like"); System.out.println("to go?"); System.out.print(">"); q2 = keyboard.nextLine(); System.out.println(); } else if (q1.equals(b)) { System.out.println("There is a long countertop with dirty dishes everywhere. Off to one"); System.out.println("side there is, as you'd expect, a refrigerator. You may open the \"refrigerator\""); System.out.println("or look in a \"cabinet\"."); System.out.print(">"); q2 = keyboard.nextLine(); System.out.println(); } if (q2.equals(c)) { System.out.println("Inside the refrigerator you see food and stuff. It looks pretty nasty."); System.out.println("Would you like to eat some of the food? (\"yes\" or \"no\")"); System.out.print(">"); q3 = keyboard.nextLine(); System.out.println(); } else if (q2.equals(d)) { System.out.println("Inside the cabinet is the boogie man, Are you scare? \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); }if (q2.equals(g)){ System.out.println("You fall in the hallway can you make it? \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); }else if (q2.equals(h)){ System.out.println("You run into the bedroom were there are monsters live are you afraid \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); }else if(q2.equals(i)){ System.out.println("You run into the bathroom do you have to use it \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); } } } ```
2015/08/23
[ "https://Stackoverflow.com/questions/32170865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5195457/" ]
Every variable needs to be initialized, before it is accessed the very first time. This can happen automatically for constants and fields, but it needs to be done manually for local variables. So the developers has to decide which value should be the first value for a variable. Mostly it is either `null` (for object types) or `0`/`false` (for primitive types). So, now about your question: > > Why are the variable q2,q3 not being initialized, yet q1 is? > > > About `q1`: the first time you try to read the reference "in" that variable is here: ``` if (q1.equals(a)) { ``` but before that, you're having this assignment: ``` q1 = keyboard.nextLine(); ``` Here you initialize the variable `q1` with the returned reference of the `keyboard.nextLine()` method call. Now about `q2`: (The problem with `q2` and `q3` are the same, so I just focus on `q2`). You have this assignment in both the `if` and the `else if` block: ``` q2 = keyboard.nextLine(); ``` So you try to assign it to another user input if `q1` equals *"upstairs"* or *"kitchen"*. But what will `q2` be, if `q1` is neither of them? Maybe it is *"garden"* or *"downstairs"*, then `q2` will remain uninitialized and the compiler can detect that, hence the error. You must think about what to do if `q1` is neither of them. You could ask the user again, until you get a valid answer. Or you can exit the program, if such situation is not allowed. It is up to you. You could also initialize `q2` and `q3` with a certain default value to avoid that error and to avoid unexpected exceptions like a `NullPointerException`. It can be done like this: ``` String q2 = ""; String q3 = ""; ```
You must initialize local variables before you use them. Try ``` String q1 = ""; String q2 = ""; String q3 = ""; ```
32,170,865
Why are the variable q2,q3 not being initialized, yet q1 is? This is how the outcome should be similar to: > > WELCOME TO MITCHELL'S TINY ADVENTURE! > > > You are in a creepy house! Would you like to go "upstairs" or into > the "kitchen"? > > > > > > > kitchen > > > > > > > > > There is a long countertop with dirty dishes everywhere. Off to one > side there is, as you'd expect, a refrigerator. You may open the > "refrigerator" or look in a "cabinet". > > > > > > > refrigerator > > > > > > > > > Inside the refrigerator you see food and stuff. It looks pretty > nasty. Would you like to eat some of the food? ("yes" or "no") > > > > > > > no > > > > > > > > > ``` import java.util.Scanner; public class App1 { public static void main(String[] Args) { Scanner keyboard = new Scanner(System.in); String q1; String q2; String q3; String a = "upstairs"; String b = "kitchen"; String c = "refrigerator"; String d = "cabinet"; String e = "yes"; String f = "no"; String g = "hallway"; String h = "bedroom"; String i = "bathroom"; System.out.println("Welcome To Mitchell's Tiny Adventure!"); System.out.println(); System.out.println("You are in a creepy house, would you like to go upstairs or into the kitchen?"); System.out.print(">"); q1 = keyboard.nextLine(); System.out.println(); if (q1.equals(a)) { System.out.println("Upstairs you see a hallway. At the end of the hallway is the master"); System.out.println("\"bedroom\". There is also a \"bathroom\" off the hallway. Where would you like"); System.out.println("to go?"); System.out.print(">"); q2 = keyboard.nextLine(); System.out.println(); } else if (q1.equals(b)) { System.out.println("There is a long countertop with dirty dishes everywhere. Off to one"); System.out.println("side there is, as you'd expect, a refrigerator. You may open the \"refrigerator\""); System.out.println("or look in a \"cabinet\"."); System.out.print(">"); q2 = keyboard.nextLine(); System.out.println(); } if (q2.equals(c)) { System.out.println("Inside the refrigerator you see food and stuff. It looks pretty nasty."); System.out.println("Would you like to eat some of the food? (\"yes\" or \"no\")"); System.out.print(">"); q3 = keyboard.nextLine(); System.out.println(); } else if (q2.equals(d)) { System.out.println("Inside the cabinet is the boogie man, Are you scare? \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); }if (q2.equals(g)){ System.out.println("You fall in the hallway can you make it? \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); }else if (q2.equals(h)){ System.out.println("You run into the bedroom were there are monsters live are you afraid \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); }else if(q2.equals(i)){ System.out.println("You run into the bathroom do you have to use it \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); } } } ```
2015/08/23
[ "https://Stackoverflow.com/questions/32170865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5195457/" ]
In the first section, if all your tests for `q1` were false, `q2` would remain uninitialized, but you reference `q2` in the 2nd section; similarly for `q3`. If a code path exists that allows a local variable to be referenced without first being initialized, this compile error will occur. Note that the compiler does not examine the *logic* aspects of the code, so for example this will fail to compile: ``` String a = "foo"; String s; if (a.equals("foo")) { s = "bar"; } else if (!a.equals("foo")) { s = "baz"; } System.out.println(s); // error ``` Even though we can see that *logically* `s` must be initialized, the compiler sees only boolean methods, which may result in `s` not being assigned.
You must initialize local variables before you use them. Try ``` String q1 = ""; String q2 = ""; String q3 = ""; ```
32,170,865
Why are the variable q2,q3 not being initialized, yet q1 is? This is how the outcome should be similar to: > > WELCOME TO MITCHELL'S TINY ADVENTURE! > > > You are in a creepy house! Would you like to go "upstairs" or into > the "kitchen"? > > > > > > > kitchen > > > > > > > > > There is a long countertop with dirty dishes everywhere. Off to one > side there is, as you'd expect, a refrigerator. You may open the > "refrigerator" or look in a "cabinet". > > > > > > > refrigerator > > > > > > > > > Inside the refrigerator you see food and stuff. It looks pretty > nasty. Would you like to eat some of the food? ("yes" or "no") > > > > > > > no > > > > > > > > > ``` import java.util.Scanner; public class App1 { public static void main(String[] Args) { Scanner keyboard = new Scanner(System.in); String q1; String q2; String q3; String a = "upstairs"; String b = "kitchen"; String c = "refrigerator"; String d = "cabinet"; String e = "yes"; String f = "no"; String g = "hallway"; String h = "bedroom"; String i = "bathroom"; System.out.println("Welcome To Mitchell's Tiny Adventure!"); System.out.println(); System.out.println("You are in a creepy house, would you like to go upstairs or into the kitchen?"); System.out.print(">"); q1 = keyboard.nextLine(); System.out.println(); if (q1.equals(a)) { System.out.println("Upstairs you see a hallway. At the end of the hallway is the master"); System.out.println("\"bedroom\". There is also a \"bathroom\" off the hallway. Where would you like"); System.out.println("to go?"); System.out.print(">"); q2 = keyboard.nextLine(); System.out.println(); } else if (q1.equals(b)) { System.out.println("There is a long countertop with dirty dishes everywhere. Off to one"); System.out.println("side there is, as you'd expect, a refrigerator. You may open the \"refrigerator\""); System.out.println("or look in a \"cabinet\"."); System.out.print(">"); q2 = keyboard.nextLine(); System.out.println(); } if (q2.equals(c)) { System.out.println("Inside the refrigerator you see food and stuff. It looks pretty nasty."); System.out.println("Would you like to eat some of the food? (\"yes\" or \"no\")"); System.out.print(">"); q3 = keyboard.nextLine(); System.out.println(); } else if (q2.equals(d)) { System.out.println("Inside the cabinet is the boogie man, Are you scare? \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); }if (q2.equals(g)){ System.out.println("You fall in the hallway can you make it? \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); }else if (q2.equals(h)){ System.out.println("You run into the bedroom were there are monsters live are you afraid \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); }else if(q2.equals(i)){ System.out.println("You run into the bathroom do you have to use it \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); } } } ```
2015/08/23
[ "https://Stackoverflow.com/questions/32170865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5195457/" ]
Every variable needs to be initialized, before it is accessed the very first time. This can happen automatically for constants and fields, but it needs to be done manually for local variables. So the developers has to decide which value should be the first value for a variable. Mostly it is either `null` (for object types) or `0`/`false` (for primitive types). So, now about your question: > > Why are the variable q2,q3 not being initialized, yet q1 is? > > > About `q1`: the first time you try to read the reference "in" that variable is here: ``` if (q1.equals(a)) { ``` but before that, you're having this assignment: ``` q1 = keyboard.nextLine(); ``` Here you initialize the variable `q1` with the returned reference of the `keyboard.nextLine()` method call. Now about `q2`: (The problem with `q2` and `q3` are the same, so I just focus on `q2`). You have this assignment in both the `if` and the `else if` block: ``` q2 = keyboard.nextLine(); ``` So you try to assign it to another user input if `q1` equals *"upstairs"* or *"kitchen"*. But what will `q2` be, if `q1` is neither of them? Maybe it is *"garden"* or *"downstairs"*, then `q2` will remain uninitialized and the compiler can detect that, hence the error. You must think about what to do if `q1` is neither of them. You could ask the user again, until you get a valid answer. Or you can exit the program, if such situation is not allowed. It is up to you. You could also initialize `q2` and `q3` with a certain default value to avoid that error and to avoid unexpected exceptions like a `NullPointerException`. It can be done like this: ``` String q2 = ""; String q3 = ""; ```
well in line 42 : `if (q2.equals(c)) {` and in line 53 : `} else if (q2.equals(d)) {` you attempt to call the `equals()` method in an uninitialized variable (`String q2`) , try to initialize them first or check them for null values , it depends on how you want to handle each case
32,170,865
Why are the variable q2,q3 not being initialized, yet q1 is? This is how the outcome should be similar to: > > WELCOME TO MITCHELL'S TINY ADVENTURE! > > > You are in a creepy house! Would you like to go "upstairs" or into > the "kitchen"? > > > > > > > kitchen > > > > > > > > > There is a long countertop with dirty dishes everywhere. Off to one > side there is, as you'd expect, a refrigerator. You may open the > "refrigerator" or look in a "cabinet". > > > > > > > refrigerator > > > > > > > > > Inside the refrigerator you see food and stuff. It looks pretty > nasty. Would you like to eat some of the food? ("yes" or "no") > > > > > > > no > > > > > > > > > ``` import java.util.Scanner; public class App1 { public static void main(String[] Args) { Scanner keyboard = new Scanner(System.in); String q1; String q2; String q3; String a = "upstairs"; String b = "kitchen"; String c = "refrigerator"; String d = "cabinet"; String e = "yes"; String f = "no"; String g = "hallway"; String h = "bedroom"; String i = "bathroom"; System.out.println("Welcome To Mitchell's Tiny Adventure!"); System.out.println(); System.out.println("You are in a creepy house, would you like to go upstairs or into the kitchen?"); System.out.print(">"); q1 = keyboard.nextLine(); System.out.println(); if (q1.equals(a)) { System.out.println("Upstairs you see a hallway. At the end of the hallway is the master"); System.out.println("\"bedroom\". There is also a \"bathroom\" off the hallway. Where would you like"); System.out.println("to go?"); System.out.print(">"); q2 = keyboard.nextLine(); System.out.println(); } else if (q1.equals(b)) { System.out.println("There is a long countertop with dirty dishes everywhere. Off to one"); System.out.println("side there is, as you'd expect, a refrigerator. You may open the \"refrigerator\""); System.out.println("or look in a \"cabinet\"."); System.out.print(">"); q2 = keyboard.nextLine(); System.out.println(); } if (q2.equals(c)) { System.out.println("Inside the refrigerator you see food and stuff. It looks pretty nasty."); System.out.println("Would you like to eat some of the food? (\"yes\" or \"no\")"); System.out.print(">"); q3 = keyboard.nextLine(); System.out.println(); } else if (q2.equals(d)) { System.out.println("Inside the cabinet is the boogie man, Are you scare? \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); }if (q2.equals(g)){ System.out.println("You fall in the hallway can you make it? \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); }else if (q2.equals(h)){ System.out.println("You run into the bedroom were there are monsters live are you afraid \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); }else if(q2.equals(i)){ System.out.println("You run into the bathroom do you have to use it \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); } } } ```
2015/08/23
[ "https://Stackoverflow.com/questions/32170865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5195457/" ]
In the first section, if all your tests for `q1` were false, `q2` would remain uninitialized, but you reference `q2` in the 2nd section; similarly for `q3`. If a code path exists that allows a local variable to be referenced without first being initialized, this compile error will occur. Note that the compiler does not examine the *logic* aspects of the code, so for example this will fail to compile: ``` String a = "foo"; String s; if (a.equals("foo")) { s = "bar"; } else if (!a.equals("foo")) { s = "baz"; } System.out.println(s); // error ``` Even though we can see that *logically* `s` must be initialized, the compiler sees only boolean methods, which may result in `s` not being assigned.
well in line 42 : `if (q2.equals(c)) {` and in line 53 : `} else if (q2.equals(d)) {` you attempt to call the `equals()` method in an uninitialized variable (`String q2`) , try to initialize them first or check them for null values , it depends on how you want to handle each case
32,170,865
Why are the variable q2,q3 not being initialized, yet q1 is? This is how the outcome should be similar to: > > WELCOME TO MITCHELL'S TINY ADVENTURE! > > > You are in a creepy house! Would you like to go "upstairs" or into > the "kitchen"? > > > > > > > kitchen > > > > > > > > > There is a long countertop with dirty dishes everywhere. Off to one > side there is, as you'd expect, a refrigerator. You may open the > "refrigerator" or look in a "cabinet". > > > > > > > refrigerator > > > > > > > > > Inside the refrigerator you see food and stuff. It looks pretty > nasty. Would you like to eat some of the food? ("yes" or "no") > > > > > > > no > > > > > > > > > ``` import java.util.Scanner; public class App1 { public static void main(String[] Args) { Scanner keyboard = new Scanner(System.in); String q1; String q2; String q3; String a = "upstairs"; String b = "kitchen"; String c = "refrigerator"; String d = "cabinet"; String e = "yes"; String f = "no"; String g = "hallway"; String h = "bedroom"; String i = "bathroom"; System.out.println("Welcome To Mitchell's Tiny Adventure!"); System.out.println(); System.out.println("You are in a creepy house, would you like to go upstairs or into the kitchen?"); System.out.print(">"); q1 = keyboard.nextLine(); System.out.println(); if (q1.equals(a)) { System.out.println("Upstairs you see a hallway. At the end of the hallway is the master"); System.out.println("\"bedroom\". There is also a \"bathroom\" off the hallway. Where would you like"); System.out.println("to go?"); System.out.print(">"); q2 = keyboard.nextLine(); System.out.println(); } else if (q1.equals(b)) { System.out.println("There is a long countertop with dirty dishes everywhere. Off to one"); System.out.println("side there is, as you'd expect, a refrigerator. You may open the \"refrigerator\""); System.out.println("or look in a \"cabinet\"."); System.out.print(">"); q2 = keyboard.nextLine(); System.out.println(); } if (q2.equals(c)) { System.out.println("Inside the refrigerator you see food and stuff. It looks pretty nasty."); System.out.println("Would you like to eat some of the food? (\"yes\" or \"no\")"); System.out.print(">"); q3 = keyboard.nextLine(); System.out.println(); } else if (q2.equals(d)) { System.out.println("Inside the cabinet is the boogie man, Are you scare? \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); }if (q2.equals(g)){ System.out.println("You fall in the hallway can you make it? \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); }else if (q2.equals(h)){ System.out.println("You run into the bedroom were there are monsters live are you afraid \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); }else if(q2.equals(i)){ System.out.println("You run into the bathroom do you have to use it \"yes or no\""); q3 = keyboard.nextLine(); System.out.println(); } } } ```
2015/08/23
[ "https://Stackoverflow.com/questions/32170865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5195457/" ]
Every variable needs to be initialized, before it is accessed the very first time. This can happen automatically for constants and fields, but it needs to be done manually for local variables. So the developers has to decide which value should be the first value for a variable. Mostly it is either `null` (for object types) or `0`/`false` (for primitive types). So, now about your question: > > Why are the variable q2,q3 not being initialized, yet q1 is? > > > About `q1`: the first time you try to read the reference "in" that variable is here: ``` if (q1.equals(a)) { ``` but before that, you're having this assignment: ``` q1 = keyboard.nextLine(); ``` Here you initialize the variable `q1` with the returned reference of the `keyboard.nextLine()` method call. Now about `q2`: (The problem with `q2` and `q3` are the same, so I just focus on `q2`). You have this assignment in both the `if` and the `else if` block: ``` q2 = keyboard.nextLine(); ``` So you try to assign it to another user input if `q1` equals *"upstairs"* or *"kitchen"*. But what will `q2` be, if `q1` is neither of them? Maybe it is *"garden"* or *"downstairs"*, then `q2` will remain uninitialized and the compiler can detect that, hence the error. You must think about what to do if `q1` is neither of them. You could ask the user again, until you get a valid answer. Or you can exit the program, if such situation is not allowed. It is up to you. You could also initialize `q2` and `q3` with a certain default value to avoid that error and to avoid unexpected exceptions like a `NullPointerException`. It can be done like this: ``` String q2 = ""; String q3 = ""; ```
In the first section, if all your tests for `q1` were false, `q2` would remain uninitialized, but you reference `q2` in the 2nd section; similarly for `q3`. If a code path exists that allows a local variable to be referenced without first being initialized, this compile error will occur. Note that the compiler does not examine the *logic* aspects of the code, so for example this will fail to compile: ``` String a = "foo"; String s; if (a.equals("foo")) { s = "bar"; } else if (!a.equals("foo")) { s = "baz"; } System.out.println(s); // error ``` Even though we can see that *logically* `s` must be initialized, the compiler sees only boolean methods, which may result in `s` not being assigned.
40,991,477
I've written this code in appDelegate ``` import UserNotifications var registerId = String() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.registerForPushNotifications(application) return true } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { let tokenChars = UnsafePointer<CChar>(deviceToken.bytes) var tokenString = "" for i in 0..<deviceToken.length { tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]]) } registerId = tokenString } func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { if notificationSettings.types != .None { application.registerForRemoteNotifications() } } func registerForPushNotifications(application: UIApplication) { if #available(iOS 10.0, *){ UNUserNotificationCenter.currentNotificationCenter().delegate = self UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert], completionHandler: {(granted, error) in if (granted) { application.registerForRemoteNotifications() } else{ registerId = "111111" //Do stuff if unsuccessful... } }) } else{ let notificationSettings = UIUserNotificationSettings( forTypes: [.Badge, .Sound, .Alert], categories: nil) application.registerUserNotificationSettings(notificationSettings) } } } ``` With this code I'm able to get the device token in ios version < 10 , but for ios 10 and higher the didRegisterForRemoteNotificationsWithDeviceToken is not getting called. Any help appreciated
2016/12/06
[ "https://Stackoverflow.com/questions/40991477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6540692/" ]
Apart from all these you have to enable your push notifications from capabilities. Click on your project target you will see the screen and on capabilities enable push notifications. [![enter image description here](https://i.stack.imgur.com/WLVrK.png)](https://i.stack.imgur.com/WLVrK.png)
Use this for ios 10 - ``` func registerForPushNotifications(_ application: UIApplication) { let notificationSettings = UIUserNotificationSettings( types: [.badge, .sound, .alert], categories: nil) application.registerUserNotificationSettings(notificationSettings) } func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) { if notificationSettings.types != UIUserNotificationType() { application.registerForRemoteNotifications() } } func application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) { var token: String = "" for i in 0..<deviceToken.count { token += String(format: "%02.2hhx", deviceToken[i] as CVarArg) } UserDefaults.standard.setValue(token, forKey: "kDeviceToken") UserDefaults.standard.synchronize() } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {} ``` PS:- Create proper certificate and bundle id also .Follow this tutorial - <https://www.raywenderlich.com/123862/push-notifications-tutorial> Use //Register for push Notifications ``` registerForPushNotifications(application) ``` in **didFinishLaunchingWithOptions** method
40,991,477
I've written this code in appDelegate ``` import UserNotifications var registerId = String() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.registerForPushNotifications(application) return true } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { let tokenChars = UnsafePointer<CChar>(deviceToken.bytes) var tokenString = "" for i in 0..<deviceToken.length { tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]]) } registerId = tokenString } func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { if notificationSettings.types != .None { application.registerForRemoteNotifications() } } func registerForPushNotifications(application: UIApplication) { if #available(iOS 10.0, *){ UNUserNotificationCenter.currentNotificationCenter().delegate = self UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert], completionHandler: {(granted, error) in if (granted) { application.registerForRemoteNotifications() } else{ registerId = "111111" //Do stuff if unsuccessful... } }) } else{ let notificationSettings = UIUserNotificationSettings( forTypes: [.Badge, .Sound, .Alert], categories: nil) application.registerUserNotificationSettings(notificationSettings) } } } ``` With this code I'm able to get the device token in ios version < 10 , but for ios 10 and higher the didRegisterForRemoteNotificationsWithDeviceToken is not getting called. Any help appreciated
2016/12/06
[ "https://Stackoverflow.com/questions/40991477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6540692/" ]
One last thing, add framework: ``` import UserNotifications class AppDelegate: /*Some other protocols I am extending...*/, UNUserNotificationCenterDelegate { func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { ... registerForPushNotifications(application) ... } func registerForPushNotifications(application: UIApplication) { if #available(iOS 10.0, *){ UNUserNotificationCenter.current().delegate = self UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert], completionHandler: {(granted, error) in if (granted) { UIApplication.shared.registerForRemoteNotifications() } else{ //Do stuff if unsuccessful... } }) } else { //If user is not on iOS 10 use the old methods we've been using let notificationSettings = UIUserNotificationSettings( types: [.badge, .sound, .alert], categories: nil) application.registerUserNotificationSettings(notificationSettings) } } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { } @available(iOS 10.0, *) func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) { //Handle the notification } @available(iOS 10.0, *) func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) { //Handle the notification } } ```
Apart from all these you have to enable your push notifications from capabilities. Click on your project target you will see the screen and on capabilities enable push notifications. [![enter image description here](https://i.stack.imgur.com/WLVrK.png)](https://i.stack.imgur.com/WLVrK.png)
40,991,477
I've written this code in appDelegate ``` import UserNotifications var registerId = String() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.registerForPushNotifications(application) return true } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { let tokenChars = UnsafePointer<CChar>(deviceToken.bytes) var tokenString = "" for i in 0..<deviceToken.length { tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]]) } registerId = tokenString } func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { if notificationSettings.types != .None { application.registerForRemoteNotifications() } } func registerForPushNotifications(application: UIApplication) { if #available(iOS 10.0, *){ UNUserNotificationCenter.currentNotificationCenter().delegate = self UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert], completionHandler: {(granted, error) in if (granted) { application.registerForRemoteNotifications() } else{ registerId = "111111" //Do stuff if unsuccessful... } }) } else{ let notificationSettings = UIUserNotificationSettings( forTypes: [.Badge, .Sound, .Alert], categories: nil) application.registerUserNotificationSettings(notificationSettings) } } } ``` With this code I'm able to get the device token in ios version < 10 , but for ios 10 and higher the didRegisterForRemoteNotificationsWithDeviceToken is not getting called. Any help appreciated
2016/12/06
[ "https://Stackoverflow.com/questions/40991477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6540692/" ]
One last thing, add framework: ``` import UserNotifications class AppDelegate: /*Some other protocols I am extending...*/, UNUserNotificationCenterDelegate { func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { ... registerForPushNotifications(application) ... } func registerForPushNotifications(application: UIApplication) { if #available(iOS 10.0, *){ UNUserNotificationCenter.current().delegate = self UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert], completionHandler: {(granted, error) in if (granted) { UIApplication.shared.registerForRemoteNotifications() } else{ //Do stuff if unsuccessful... } }) } else { //If user is not on iOS 10 use the old methods we've been using let notificationSettings = UIUserNotificationSettings( types: [.badge, .sound, .alert], categories: nil) application.registerUserNotificationSettings(notificationSettings) } } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { } @available(iOS 10.0, *) func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) { //Handle the notification } @available(iOS 10.0, *) func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) { //Handle the notification } } ```
Use this for ios 10 - ``` func registerForPushNotifications(_ application: UIApplication) { let notificationSettings = UIUserNotificationSettings( types: [.badge, .sound, .alert], categories: nil) application.registerUserNotificationSettings(notificationSettings) } func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) { if notificationSettings.types != UIUserNotificationType() { application.registerForRemoteNotifications() } } func application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) { var token: String = "" for i in 0..<deviceToken.count { token += String(format: "%02.2hhx", deviceToken[i] as CVarArg) } UserDefaults.standard.setValue(token, forKey: "kDeviceToken") UserDefaults.standard.synchronize() } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {} ``` PS:- Create proper certificate and bundle id also .Follow this tutorial - <https://www.raywenderlich.com/123862/push-notifications-tutorial> Use //Register for push Notifications ``` registerForPushNotifications(application) ``` in **didFinishLaunchingWithOptions** method
51,491,119
I am fairly new to python and need help taking a json file and incorporating it into the **init** in a class to be used through out, but I am getting the error below and don't understand why. I have a build a few classes before and this seems to look the same. `AttributeError: 'dict' object has no attribute 'zipcode'` I have a separate json file called `config.json` that I have changed some information in (i.e. location and api key), but other than that, this is what I am working with. `config.json:` ``` { "unit_system":"metric", "location_information":{ "country_code":"US", "country_name":"United States", "city":"New York City", "state":"New York", "postal":10001 }, "api_keys":{ "weather_api_key":"97a484e1039b7a0779b59f2e57e597a3" } } ``` `weather.py` ``` class weather: """weather retrieving app""" def __init__(self, data): """initialize attributes for weather app""" self.unit_system = data['unit_system'] #unit system self.country_code = data['location_information']['country_code'] self.zipcode = data['location_information']['postal'] #location information self.api_key = data['api_keys']['weather_api_key'] #api key informaation def get_update(self): threading.Timer(5.0, w.get_update).start() #runs get_update every 5 seconds #get weather information weather_url = 'http://api.openweathermap.org/data/2.5/weather?zip=' \ + str(self.zipcode) + ',' \ + self.country_code + '&appid=' \ + self.api_key weather_request = requests.get(weather_url) weather_data = weather_request.json() temp_k = float(weather_data['main']['temp']) #determine unit system conversions if self.unit_system == 'english': temp = (temp_k - 273.15) * 1.8 + 32 elif self.unit_system == 'metric': temp = temp_k - 273.15 print(temp) #return(temp) import threading import requests import json with open('config.json') as config_file: config = json.load(config_file) w = weather(config) w.get_update() ```
2018/07/24
[ "https://Stackoverflow.com/questions/51491119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10125794/" ]
You need to use javascript to get screen's information.
It is not possible using CSS, however you can control the page design using media queries. Or, you can get the screen height by using `screen.height` and width by using `screen.width`. [**They are JS properties**] Here is a basic JS code of doing this: ```js console.log("Width: "+screen.width+": Height: "+screen.height); ```
51,491,119
I am fairly new to python and need help taking a json file and incorporating it into the **init** in a class to be used through out, but I am getting the error below and don't understand why. I have a build a few classes before and this seems to look the same. `AttributeError: 'dict' object has no attribute 'zipcode'` I have a separate json file called `config.json` that I have changed some information in (i.e. location and api key), but other than that, this is what I am working with. `config.json:` ``` { "unit_system":"metric", "location_information":{ "country_code":"US", "country_name":"United States", "city":"New York City", "state":"New York", "postal":10001 }, "api_keys":{ "weather_api_key":"97a484e1039b7a0779b59f2e57e597a3" } } ``` `weather.py` ``` class weather: """weather retrieving app""" def __init__(self, data): """initialize attributes for weather app""" self.unit_system = data['unit_system'] #unit system self.country_code = data['location_information']['country_code'] self.zipcode = data['location_information']['postal'] #location information self.api_key = data['api_keys']['weather_api_key'] #api key informaation def get_update(self): threading.Timer(5.0, w.get_update).start() #runs get_update every 5 seconds #get weather information weather_url = 'http://api.openweathermap.org/data/2.5/weather?zip=' \ + str(self.zipcode) + ',' \ + self.country_code + '&appid=' \ + self.api_key weather_request = requests.get(weather_url) weather_data = weather_request.json() temp_k = float(weather_data['main']['temp']) #determine unit system conversions if self.unit_system == 'english': temp = (temp_k - 273.15) * 1.8 + 32 elif self.unit_system == 'metric': temp = temp_k - 273.15 print(temp) #return(temp) import threading import requests import json with open('config.json') as config_file: config = json.load(config_file) w = weather(config) w.get_update() ```
2018/07/24
[ "https://Stackoverflow.com/questions/51491119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10125794/" ]
In this case I suggest you to use **vh** (hundreds of viewport height): If you set `height: 100vh;` it would take 100% height of each screen. [Code Example](https://jsfiddle.net/besartm/avhx65t8/15/)
You need to use javascript to get screen's information.
51,491,119
I am fairly new to python and need help taking a json file and incorporating it into the **init** in a class to be used through out, but I am getting the error below and don't understand why. I have a build a few classes before and this seems to look the same. `AttributeError: 'dict' object has no attribute 'zipcode'` I have a separate json file called `config.json` that I have changed some information in (i.e. location and api key), but other than that, this is what I am working with. `config.json:` ``` { "unit_system":"metric", "location_information":{ "country_code":"US", "country_name":"United States", "city":"New York City", "state":"New York", "postal":10001 }, "api_keys":{ "weather_api_key":"97a484e1039b7a0779b59f2e57e597a3" } } ``` `weather.py` ``` class weather: """weather retrieving app""" def __init__(self, data): """initialize attributes for weather app""" self.unit_system = data['unit_system'] #unit system self.country_code = data['location_information']['country_code'] self.zipcode = data['location_information']['postal'] #location information self.api_key = data['api_keys']['weather_api_key'] #api key informaation def get_update(self): threading.Timer(5.0, w.get_update).start() #runs get_update every 5 seconds #get weather information weather_url = 'http://api.openweathermap.org/data/2.5/weather?zip=' \ + str(self.zipcode) + ',' \ + self.country_code + '&appid=' \ + self.api_key weather_request = requests.get(weather_url) weather_data = weather_request.json() temp_k = float(weather_data['main']['temp']) #determine unit system conversions if self.unit_system == 'english': temp = (temp_k - 273.15) * 1.8 + 32 elif self.unit_system == 'metric': temp = temp_k - 273.15 print(temp) #return(temp) import threading import requests import json with open('config.json') as config_file: config = json.load(config_file) w = weather(config) w.get_update() ```
2018/07/24
[ "https://Stackoverflow.com/questions/51491119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10125794/" ]
You can't "get" the viewport height as such, in the way that you can with JS to store it in a variable, but you can use it in `calc()` to change the height of elements. For example, `height: calc( 100vh - 50px );` which would equate to "the window height less 50px".
You need to use javascript to get screen's information.
51,491,119
I am fairly new to python and need help taking a json file and incorporating it into the **init** in a class to be used through out, but I am getting the error below and don't understand why. I have a build a few classes before and this seems to look the same. `AttributeError: 'dict' object has no attribute 'zipcode'` I have a separate json file called `config.json` that I have changed some information in (i.e. location and api key), but other than that, this is what I am working with. `config.json:` ``` { "unit_system":"metric", "location_information":{ "country_code":"US", "country_name":"United States", "city":"New York City", "state":"New York", "postal":10001 }, "api_keys":{ "weather_api_key":"97a484e1039b7a0779b59f2e57e597a3" } } ``` `weather.py` ``` class weather: """weather retrieving app""" def __init__(self, data): """initialize attributes for weather app""" self.unit_system = data['unit_system'] #unit system self.country_code = data['location_information']['country_code'] self.zipcode = data['location_information']['postal'] #location information self.api_key = data['api_keys']['weather_api_key'] #api key informaation def get_update(self): threading.Timer(5.0, w.get_update).start() #runs get_update every 5 seconds #get weather information weather_url = 'http://api.openweathermap.org/data/2.5/weather?zip=' \ + str(self.zipcode) + ',' \ + self.country_code + '&appid=' \ + self.api_key weather_request = requests.get(weather_url) weather_data = weather_request.json() temp_k = float(weather_data['main']['temp']) #determine unit system conversions if self.unit_system == 'english': temp = (temp_k - 273.15) * 1.8 + 32 elif self.unit_system == 'metric': temp = temp_k - 273.15 print(temp) #return(temp) import threading import requests import json with open('config.json') as config_file: config = json.load(config_file) w = weather(config) w.get_update() ```
2018/07/24
[ "https://Stackoverflow.com/questions/51491119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10125794/" ]
In this case I suggest you to use **vh** (hundreds of viewport height): If you set `height: 100vh;` it would take 100% height of each screen. [Code Example](https://jsfiddle.net/besartm/avhx65t8/15/)
It is not possible using CSS, however you can control the page design using media queries. Or, you can get the screen height by using `screen.height` and width by using `screen.width`. [**They are JS properties**] Here is a basic JS code of doing this: ```js console.log("Width: "+screen.width+": Height: "+screen.height); ```
51,491,119
I am fairly new to python and need help taking a json file and incorporating it into the **init** in a class to be used through out, but I am getting the error below and don't understand why. I have a build a few classes before and this seems to look the same. `AttributeError: 'dict' object has no attribute 'zipcode'` I have a separate json file called `config.json` that I have changed some information in (i.e. location and api key), but other than that, this is what I am working with. `config.json:` ``` { "unit_system":"metric", "location_information":{ "country_code":"US", "country_name":"United States", "city":"New York City", "state":"New York", "postal":10001 }, "api_keys":{ "weather_api_key":"97a484e1039b7a0779b59f2e57e597a3" } } ``` `weather.py` ``` class weather: """weather retrieving app""" def __init__(self, data): """initialize attributes for weather app""" self.unit_system = data['unit_system'] #unit system self.country_code = data['location_information']['country_code'] self.zipcode = data['location_information']['postal'] #location information self.api_key = data['api_keys']['weather_api_key'] #api key informaation def get_update(self): threading.Timer(5.0, w.get_update).start() #runs get_update every 5 seconds #get weather information weather_url = 'http://api.openweathermap.org/data/2.5/weather?zip=' \ + str(self.zipcode) + ',' \ + self.country_code + '&appid=' \ + self.api_key weather_request = requests.get(weather_url) weather_data = weather_request.json() temp_k = float(weather_data['main']['temp']) #determine unit system conversions if self.unit_system == 'english': temp = (temp_k - 273.15) * 1.8 + 32 elif self.unit_system == 'metric': temp = temp_k - 273.15 print(temp) #return(temp) import threading import requests import json with open('config.json') as config_file: config = json.load(config_file) w = weather(config) w.get_update() ```
2018/07/24
[ "https://Stackoverflow.com/questions/51491119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10125794/" ]
You can't "get" the viewport height as such, in the way that you can with JS to store it in a variable, but you can use it in `calc()` to change the height of elements. For example, `height: calc( 100vh - 50px );` which would equate to "the window height less 50px".
It is not possible using CSS, however you can control the page design using media queries. Or, you can get the screen height by using `screen.height` and width by using `screen.width`. [**They are JS properties**] Here is a basic JS code of doing this: ```js console.log("Width: "+screen.width+": Height: "+screen.height); ```
51,491,119
I am fairly new to python and need help taking a json file and incorporating it into the **init** in a class to be used through out, but I am getting the error below and don't understand why. I have a build a few classes before and this seems to look the same. `AttributeError: 'dict' object has no attribute 'zipcode'` I have a separate json file called `config.json` that I have changed some information in (i.e. location and api key), but other than that, this is what I am working with. `config.json:` ``` { "unit_system":"metric", "location_information":{ "country_code":"US", "country_name":"United States", "city":"New York City", "state":"New York", "postal":10001 }, "api_keys":{ "weather_api_key":"97a484e1039b7a0779b59f2e57e597a3" } } ``` `weather.py` ``` class weather: """weather retrieving app""" def __init__(self, data): """initialize attributes for weather app""" self.unit_system = data['unit_system'] #unit system self.country_code = data['location_information']['country_code'] self.zipcode = data['location_information']['postal'] #location information self.api_key = data['api_keys']['weather_api_key'] #api key informaation def get_update(self): threading.Timer(5.0, w.get_update).start() #runs get_update every 5 seconds #get weather information weather_url = 'http://api.openweathermap.org/data/2.5/weather?zip=' \ + str(self.zipcode) + ',' \ + self.country_code + '&appid=' \ + self.api_key weather_request = requests.get(weather_url) weather_data = weather_request.json() temp_k = float(weather_data['main']['temp']) #determine unit system conversions if self.unit_system == 'english': temp = (temp_k - 273.15) * 1.8 + 32 elif self.unit_system == 'metric': temp = temp_k - 273.15 print(temp) #return(temp) import threading import requests import json with open('config.json') as config_file: config = json.load(config_file) w = weather(config) w.get_update() ```
2018/07/24
[ "https://Stackoverflow.com/questions/51491119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10125794/" ]
You can't "get" the viewport height as such, in the way that you can with JS to store it in a variable, but you can use it in `calc()` to change the height of elements. For example, `height: calc( 100vh - 50px );` which would equate to "the window height less 50px".
In this case I suggest you to use **vh** (hundreds of viewport height): If you set `height: 100vh;` it would take 100% height of each screen. [Code Example](https://jsfiddle.net/besartm/avhx65t8/15/)
221
Латинка використовується для більшості слов’янських мов, і з цим немає проблем. Відмінність абетки створює додатковий бар’єр поміж нами і західними країнами. Відразу сам собі заперечу наступним: 1. [Сербохорватська мова](https://en.wikipedia.org/wiki/Serbo-Croatian) має і латинку, і кирилицю, але і бар’єри нікуди не поділися. 2. Українська кирилиця має всі необхідні літери для передавання звуків, що ними користуються в українській мові, а в латинці доведеться ставити над ними всілякі позначки, як це є у Франції й Німеччині, наприклад. Заперечення до 2: в Чехії це є, і вони не збираються переходити назад на кирилицю.
2017/02/11
[ "https://ukrainian.stackexchange.com/questions/221", "https://ukrainian.stackexchange.com", "https://ukrainian.stackexchange.com/users/240/" ]
Запитання, як на мою думку, занадто широке, але для тих, кому цікаво з якими складнощами вже стикалися при спробах застосувати латинику в українській мові, думаю, будуть корисні наступні відомості: В вікіпедії є стаття про [українську латинику](https://uk.wikipedia.org/wiki/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B0_%D0%BB%D0%B0%D1%82%D0%B8%D0%BD%D0%BA%D0%B0). В XIX сторіччі було дві великі спроби латинізувати українську абетку, які призвели до так званої [азбучної війни](https://uk.wikipedia.org/wiki/%D0%90%D0%B7%D0%B1%D1%83%D1%87%D0%BD%D0%B0_%D0%B2%D1%96%D0%B9%D0%BD%D0%B0). Обидві спроби мали місце серед української громади австро-угорської імперії. Перша спроба - [abecadło](https://uk.wikipedia.org/wiki/%D0%90%D0%B1%D0%B5%D1%86%D0%B0%D0%B4%D0%BB%D0%BE) при передачі звуків української мови використовує латинику схожу на польську абетку. Яка також іноді називається abecadło, але більш поширена нава [Alfabet](https://pl.wikipedia.org/wiki/Alfabet) Друга спроба - варіант, який запропонував [Josyf Jireček](https://uk.wikipedia.org/wiki/%D0%99%D0%BE%D1%81%D0%B8%D1%84_%D0%87%D1%80%D0%B5%D1%87%D0%B5%D0%BA). Ця спроба більше схожа на спробу запозичення тогочасного [чеського алфавіту](https://cs.wikipedia.org/wiki/%C4%8Cesk%C3%BD_pravopis) Азбучна війна закінчилася переходом на переважно кирилічну [драгоманівку](https://uk.wikipedia.org/wiki/%D0%94%D1%80%D0%B0%D0%B3%D0%BE%D0%BC%D0%B0%D0%BD%D1%96%D0%B2%D0%BA%D0%B0), в якій, на відміну від сучасної української кирилиці, немає літери `щ`, і звук передається сполученням `шч` (*шчо* є ближчим до принципу 'як чуємо так і пишемо'), й передається як `j`, йотовані голосні передаються як `j + голосна`, пом'якшення приголосних перед голосним як `ь + голосна`. Також були і пізніші спроби перевести українську на латинику за українських радянських часів "до самогубства [Скрипника](https://uk.wikipedia.org/wiki/%D0%A1%D0%BA%D1%80%D0%B8%D0%BF%D0%BD%D0%B8%D0%BA_%D0%9C%D0%B8%D0%BA%D0%BE%D0%BB%D0%B0_%D0%9E%D0%BB%D0%B5%D0%BA%D1%81%D1%96%D0%B9%D0%BE%D0%B2%D0%B8%D1%87)": > > 1927 р. під час Всеукраїнської правописної конференції в Харкові мовознавці Майк Йогансен, Борис Ткаченко та Михайло Наконечний запропонували прийняти латинку як частину правопису. Внаслідок голосування переважив один голос проти. > > > Крім радикального переходу на латинку, існувала ідея впровадження кількох латинських літер — ѕ (замість дз), z (замість дж) та j (замість й, зокрема в є, ї, ю, я). Цю ідею виніс Євген Тимченко, її було частково підтримано і Харківська конференція затвердила введення s та z до української абетки. Проте після того, як ЦК КП(б)У на чолі з Л. Кагановичем засудив впровадження нових літер, конференція анулювала своє рішення > > > Також, лінгвіст [Юрій Шевельов](https://uk.wikipedia.org/wiki/%D0%A8%D0%B5%D0%B2%D0%B5%D0%BB%D1%8C%D0%BE%D0%B2_%D0%AE%D1%80%D1%96%D0%B9_%D0%92%D0%BE%D0%BB%D0%BE%D0%B4%D0%B8%D0%BC%D0%B8%D1%80%D0%BE%D0%B2%D0%B8%D1%87) використовував латинику для передачі сучасної української мови у своїх працях, принаймні написаних англійською та, здається, німецькою мовами. Але при перекладі українською з англійської його "[Історичної фонології української мови](https://books.google.pl/books/about/%D0%86%D1%81%D1%82%D0%BE%D1%80%D0%B8%D1%87%D0%BD%D0%B0_%D1%84%D0%BE%D0%BD%D0%BE%D0%BB%D0%BE%D0%B3%D1%96%D1%8F_%D1%83.html?id=a33ERmARrc8C&redir_esc=y)" перекладачі [Сергій Вакуленко](http://www.hi-phi.org.ua/index.php/chleny-tovarystva/6-vakulenko-serhii) та [Андрій Даниленко](https://uk.wikipedia.org/wiki/%D0%94%D0%B0%D0%BD%D0%B8%D0%BB%D0%B5%D0%BD%D0%BA%D0%BE_%D0%90%D0%BD%D0%B4%D1%80%D1%96%D0%B9_%D0%86%D0%B2%D0%B0%D0%BD%D0%BE%D0%B2%D0%B8%D1%87) використали кирилицю не тільки для передачі ідей українською мовою, а також і приклади, які в оригінальному тексті кодифіковані латиникою. Також варто не забувати про сучасний і [досить незграбний офіційний варіант](https://uk.wikipedia.org/wiki/%D0%9B%D0%B0%D1%82%D0%B8%D0%BD%D1%96%D0%B7%D0%B0%D1%86%D1%96%D1%8F_%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) латинізації української мови, прийнятий міністерством закордонних справ кабінету [Азарова](https://uk.wikipedia.org/wiki/%D0%90%D0%B7%D0%B0%D1%80%D0%BE%D0%B2_%D0%9C%D0%B8%D0%BA%D0%BE%D0%BB%D0%B0_%D0%AF%D0%BD%D0%BE%D0%B2%D0%B8%D1%87).
В Україні питання переходу на латиницю на державному рівні поки що не підіймалось. Не дивлячись на те, що очевидного і простого рішення не існує, ми все таки можемо спробувати проаналізувати це питання з різних сторін. **З політичної точки зору** В першу чергу, перехід на латиницю, може сприйматись, в першу чергу, як *політичне* рішення відходу від колоніальної та агресивної політики Російської Федерації щодо колишніх співдружніх республік. Це розуміють і в самій Росії, статті на кшалт ["Гудбай, Russkiy mir"](https://www.novayagazeta.ru/articles/2016/02/22/67521-gudbay-russkiy-mir) без проблем можна знайти після того як влада Казахстану офіційно повідомила про бажання перейти на латиницю до 2025 року: [![enter image description here](https://i.stack.imgur.com/GRRQB.jpg)](https://i.stack.imgur.com/GRRQB.jpg) Щодо самого Казахстану, то після офіційного повідомлення в країні закономірно [виникли](http://russian.eurasianet.org/node/59994) дискусії: > > Лінгвісти розійшлись в думках з приводу того, що краще - латиниця або > кирилиця - передає специфіку звукового ладу казахської мови, і яку > форму латиниці слід прийняти (тюркські держави, що використовують > латиницю, такі як Туреччина, Узбекистан, Азербайджан і Туркменістан, > користуються різними її варіаціями). Існує навіть рух, що виступає за > відмову від кирилиці на користь рунічного письма, на якому казахська > мову існувала в давнину. У 1929 році в радянському Казахстані > казахська мова перевели з арабської в'язі на латиницю, потім в 1940 > році була введена кирилиця як загальний алфавіт для всіх республік. > > > Українцям може бути цікавою статистика володіння казахської та російськими мовами в Казахстані, оскільки аргументація, що в країні живе велика кількість виключно російськомовних громадян, є вагомою і для України: > > Надійні статистичні дані про лінгвістичну ситуацію [в Казахстані] знайти непросто, > проте згідно з останнім переписом населення від 2009 року лише дві > третини громадян республіки повідомили про пристойний знанні ними > казахської мови, тоді як 94 відсотки населення заявили, що розуміють > російську мову. Астана поставила за мету забезпечити до 2025 року > володіння казахською мовою 95 відсотками громадян, зберігши > знання російської на рівні 90 відсотків. > > > Цікавою є [інформація](https://ru.wikipedia.org/wiki/%D0%9A%D0%B0%D0%B7%D0%B0%D1%85%D1%81%D0%BA%D0%B0%D1%8F_%D0%BF%D0%B8%D1%81%D1%8C%D0%BC%D0%B5%D0%BD%D0%BD%D0%BE%D1%81%D1%82%D1%8C), що латинським алфавітом (на базі турецького алфавіту) неофіційно користується казахська діаспора в Турції. Також казахська діаспора використовує сурогатні латиниці в Німеччині, США і інших західних країнах. Ще одним прикладом може бути Білорусь, де за період незалежності кількість людей, що розмовляють білоруською мовою, значно [зменшилась](https://vkurier.by/47398): > > 21 лютого відзначають Міжнародний день рідної мови. Для Білорусі це > досить «болюче» свято, адже на рідній для країни мові розмовляють > одиниці. Тому стверджувати, що в синьоокою дві державні мови, на жаль, > не доводиться: реальність показує зворотне. > > > Таким чином, з політичної точки щору перехід на латиницю є виправданим. **З лінгвістичної точки зору** Не дивлячись на те, що вивчення іноземних мов у нас досить розповсюджене як в школах, так і в вищих навчальних закладах, статистика володіння розмовною мовою та регулярного відвідування іноземних країн в Україні на низькому рівні. З іншої сторони, спроби створення українських аналогів stack overflow, google, facebook та інших популярних зарубіжних ресурсів потерпіли повне фіаско (на відміну від Росії, де популярними якраз є клони популярних сервісів). З цього можна зробити обережний висновок, що для певної кількості українців відсутність української чи російської локалізації не є проблемою з точки зору використання тих чи інших сервісів чи послуг. З точки зору періодики, книг, навчальних матеріалів, то тут ситуація більш складна, оскільки в більшості випадків цей простір заповнений російськомовним продуктом, а якісних енциклопедій, фундаментальних праць українською надзвичайно мало. Перехід на латиницю, а, як наслідок, збільшення кількості людей, що розуміють іноземні мови, може частково вирішити проблему доступу до знань та матеріалів, що є переважно англійською мовою. **З практичної точки зору** Одночасний перехід навряд чи буде можливим, тому компромісним варіатом є існування обох алфавітів та поступовий перехід протягом 10-15 років. На мій погляд, важливим є той факт, який статус у відносинах, насамперед, з Європою буде займати Україна. Якщо євроінтеграційні процеси будуть реальними і будуть реально підтримуватись всіма сторонами, то процес переходу матиме сенс, в іншому випадку залишиться велика кількість людей, що захоче залишити кирилицю в якості запасного варіанту на випадок, якщо євроінтеграційні процеси не будуть фундаментальними та всебічними.
221
Латинка використовується для більшості слов’янських мов, і з цим немає проблем. Відмінність абетки створює додатковий бар’єр поміж нами і західними країнами. Відразу сам собі заперечу наступним: 1. [Сербохорватська мова](https://en.wikipedia.org/wiki/Serbo-Croatian) має і латинку, і кирилицю, але і бар’єри нікуди не поділися. 2. Українська кирилиця має всі необхідні літери для передавання звуків, що ними користуються в українській мові, а в латинці доведеться ставити над ними всілякі позначки, як це є у Франції й Німеччині, наприклад. Заперечення до 2: в Чехії це є, і вони не збираються переходити назад на кирилицю.
2017/02/11
[ "https://ukrainian.stackexchange.com/questions/221", "https://ukrainian.stackexchange.com", "https://ukrainian.stackexchange.com/users/240/" ]
В Україні питання переходу на латиницю на державному рівні поки що не підіймалось. Не дивлячись на те, що очевидного і простого рішення не існує, ми все таки можемо спробувати проаналізувати це питання з різних сторін. **З політичної точки зору** В першу чергу, перехід на латиницю, може сприйматись, в першу чергу, як *політичне* рішення відходу від колоніальної та агресивної політики Російської Федерації щодо колишніх співдружніх республік. Це розуміють і в самій Росії, статті на кшалт ["Гудбай, Russkiy mir"](https://www.novayagazeta.ru/articles/2016/02/22/67521-gudbay-russkiy-mir) без проблем можна знайти після того як влада Казахстану офіційно повідомила про бажання перейти на латиницю до 2025 року: [![enter image description here](https://i.stack.imgur.com/GRRQB.jpg)](https://i.stack.imgur.com/GRRQB.jpg) Щодо самого Казахстану, то після офіційного повідомлення в країні закономірно [виникли](http://russian.eurasianet.org/node/59994) дискусії: > > Лінгвісти розійшлись в думках з приводу того, що краще - латиниця або > кирилиця - передає специфіку звукового ладу казахської мови, і яку > форму латиниці слід прийняти (тюркські держави, що використовують > латиницю, такі як Туреччина, Узбекистан, Азербайджан і Туркменістан, > користуються різними її варіаціями). Існує навіть рух, що виступає за > відмову від кирилиці на користь рунічного письма, на якому казахська > мову існувала в давнину. У 1929 році в радянському Казахстані > казахська мова перевели з арабської в'язі на латиницю, потім в 1940 > році була введена кирилиця як загальний алфавіт для всіх республік. > > > Українцям може бути цікавою статистика володіння казахської та російськими мовами в Казахстані, оскільки аргументація, що в країні живе велика кількість виключно російськомовних громадян, є вагомою і для України: > > Надійні статистичні дані про лінгвістичну ситуацію [в Казахстані] знайти непросто, > проте згідно з останнім переписом населення від 2009 року лише дві > третини громадян республіки повідомили про пристойний знанні ними > казахської мови, тоді як 94 відсотки населення заявили, що розуміють > російську мову. Астана поставила за мету забезпечити до 2025 року > володіння казахською мовою 95 відсотками громадян, зберігши > знання російської на рівні 90 відсотків. > > > Цікавою є [інформація](https://ru.wikipedia.org/wiki/%D0%9A%D0%B0%D0%B7%D0%B0%D1%85%D1%81%D0%BA%D0%B0%D1%8F_%D0%BF%D0%B8%D1%81%D1%8C%D0%BC%D0%B5%D0%BD%D0%BD%D0%BE%D1%81%D1%82%D1%8C), що латинським алфавітом (на базі турецького алфавіту) неофіційно користується казахська діаспора в Турції. Також казахська діаспора використовує сурогатні латиниці в Німеччині, США і інших західних країнах. Ще одним прикладом може бути Білорусь, де за період незалежності кількість людей, що розмовляють білоруською мовою, значно [зменшилась](https://vkurier.by/47398): > > 21 лютого відзначають Міжнародний день рідної мови. Для Білорусі це > досить «болюче» свято, адже на рідній для країни мові розмовляють > одиниці. Тому стверджувати, що в синьоокою дві державні мови, на жаль, > не доводиться: реальність показує зворотне. > > > Таким чином, з політичної точки щору перехід на латиницю є виправданим. **З лінгвістичної точки зору** Не дивлячись на те, що вивчення іноземних мов у нас досить розповсюджене як в школах, так і в вищих навчальних закладах, статистика володіння розмовною мовою та регулярного відвідування іноземних країн в Україні на низькому рівні. З іншої сторони, спроби створення українських аналогів stack overflow, google, facebook та інших популярних зарубіжних ресурсів потерпіли повне фіаско (на відміну від Росії, де популярними якраз є клони популярних сервісів). З цього можна зробити обережний висновок, що для певної кількості українців відсутність української чи російської локалізації не є проблемою з точки зору використання тих чи інших сервісів чи послуг. З точки зору періодики, книг, навчальних матеріалів, то тут ситуація більш складна, оскільки в більшості випадків цей простір заповнений російськомовним продуктом, а якісних енциклопедій, фундаментальних праць українською надзвичайно мало. Перехід на латиницю, а, як наслідок, збільшення кількості людей, що розуміють іноземні мови, може частково вирішити проблему доступу до знань та матеріалів, що є переважно англійською мовою. **З практичної точки зору** Одночасний перехід навряд чи буде можливим, тому компромісним варіатом є існування обох алфавітів та поступовий перехід протягом 10-15 років. На мій погляд, важливим є той факт, який статус у відносинах, насамперед, з Європою буде займати Україна. Якщо євроінтеграційні процеси будуть реальними і будуть реально підтримуватись всіма сторонами, то процес переходу матиме сенс, в іншому випадку залишиться велика кількість людей, що захоче залишити кирилицю в якості запасного варіанту на випадок, якщо євроінтеграційні процеси не будуть фундаментальними та всебічними.
Можна, наприклад, брати давні відомости, а саме: доволї непогана технічна з 75 сторінками [книга](//diasporiana.org.ua/wp-content/uploads/books/11976/file.pdf) 1933 року „[Йосиф Їречек](//uk.wikipedia.org/wiki/%D0%99%D0%BE%D1%81%D0%B8%D1%84_%D0%87%D1%80%D0%B5%D1%87%D0%B5%D0%BA) і українська мова (до [азбучної заверюхи 1859 р.](//uk.wikipedia.org/wiki/%D0%90%D0%B7%D0%B1%D1%83%D1%87%D0%BD%D0%B0_%D0%B2%D1%96%D0%B9%D0%BD%D0%B0#%D0%94%D1%80%D1%83%D0%B3%D0%B8%D0%B9_%D1%81%D0%BF%D0%B0%D0%BB%D0%B0%D1%85))“ [Василя Сїмовича](//uk.wikipedia.org/wiki/%D0%A1%D1%96%D0%BC%D0%BE%D0%B2%D0%B8%D1%87_%D0%92%D0%B0%D1%81%D0%B8%D0%BB%D1%8C_%D0%86%D0%B2%D0%B0%D0%BD%D0%BE%D0%B2%D0%B8%D1%87). Там про мовні і політичні питаня, про сам вплив на мову тошчо. Також проблеми писемностей: як латинкової, так і кириличної. Також вартий уваги [займавий факт і збіг](https://www.istpravda.com.ua/articles/2021/04/7/159284/): > > … таємний указ імператора Всеросійського Олександра ІІ від 20 жовтня 1859 року про заборону друкування азбук чи інших творів українською мовою з використанням польської абетки. > > > У фонді Подільського духовної консисторії Державного архіву Хмельницької області потрапила на очі справа "О запрещении печатания азбук русского языка с применением польского алфавита" (Ф-315, оп. 1, спр. 1484). > > > Збіг в тому, же рік той самий, коли Їречек передставив свою латинку. Також можна зауважити, же за 4 роки, а са́ме 1863 року, буде сумнозвісний [Валуєвський циркуляр](https://uk.wikipedia.org/wiki/%D0%92%D0%B0%D0%BB%D1%83%D1%94%D0%B2%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D1%86%D0%B8%D1%80%D0%BA%D1%83%D0%BB%D1%8F%D1%80). --- Моя основна думка про перевагу. Українцї ототожнюватимуть себе з латинковим сьвітом, а не з кириличним. Тобто, по-мойому, доречним також варто розглянути питаня трудностїв, коли українська залишається на кирилицї. Один з показових прикладів [сучасности](//theverge.com/2018/5/22/17380630/) про родину кирилицї — Бoлґарія: > > … Twitter announced it would become more aggressive in pursuing trolls on its service, a move which seems to have had some unforeseen consequences, judging by the present upheaval in the Bulgarian Twitter community. An increasingly large and unhappy number of people have had their Twitter accounts suspended and messages filtered out of conversations, apparently for the offense of merely tweeting in Cyrillic. … > > > > > --- > > > … Twitter оголосив, що він стане агресивнішим у переслідувані тролів; цей крок, здається, мав непередбачувані наслідки, судячи з нинішніх потрясінь у болгарській твітер-спільноті. Все більша кількість людей мають заблоковані облікові записи, а їхні повідомленя вилучаються з обговорень — напевно, всього лиш через те, що вони переписувалися кирилицею… > Дуже приблизний переклад > > > Очевидно, шчо таке буває не лиш тут: більшість проґрам спершу нацїлені на латинку, а лиш потім на инші писемности (виняток — власна писемніть, але однаково першою разом чи другою є латинка). ---
221
Латинка використовується для більшості слов’янських мов, і з цим немає проблем. Відмінність абетки створює додатковий бар’єр поміж нами і західними країнами. Відразу сам собі заперечу наступним: 1. [Сербохорватська мова](https://en.wikipedia.org/wiki/Serbo-Croatian) має і латинку, і кирилицю, але і бар’єри нікуди не поділися. 2. Українська кирилиця має всі необхідні літери для передавання звуків, що ними користуються в українській мові, а в латинці доведеться ставити над ними всілякі позначки, як це є у Франції й Німеччині, наприклад. Заперечення до 2: в Чехії це є, і вони не збираються переходити назад на кирилицю.
2017/02/11
[ "https://ukrainian.stackexchange.com/questions/221", "https://ukrainian.stackexchange.com", "https://ukrainian.stackexchange.com/users/240/" ]
Запитання, як на мою думку, занадто широке, але для тих, кому цікаво з якими складнощами вже стикалися при спробах застосувати латинику в українській мові, думаю, будуть корисні наступні відомості: В вікіпедії є стаття про [українську латинику](https://uk.wikipedia.org/wiki/%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B0_%D0%BB%D0%B0%D1%82%D0%B8%D0%BD%D0%BA%D0%B0). В XIX сторіччі було дві великі спроби латинізувати українську абетку, які призвели до так званої [азбучної війни](https://uk.wikipedia.org/wiki/%D0%90%D0%B7%D0%B1%D1%83%D1%87%D0%BD%D0%B0_%D0%B2%D1%96%D0%B9%D0%BD%D0%B0). Обидві спроби мали місце серед української громади австро-угорської імперії. Перша спроба - [abecadło](https://uk.wikipedia.org/wiki/%D0%90%D0%B1%D0%B5%D1%86%D0%B0%D0%B4%D0%BB%D0%BE) при передачі звуків української мови використовує латинику схожу на польську абетку. Яка також іноді називається abecadło, але більш поширена нава [Alfabet](https://pl.wikipedia.org/wiki/Alfabet) Друга спроба - варіант, який запропонував [Josyf Jireček](https://uk.wikipedia.org/wiki/%D0%99%D0%BE%D1%81%D0%B8%D1%84_%D0%87%D1%80%D0%B5%D1%87%D0%B5%D0%BA). Ця спроба більше схожа на спробу запозичення тогочасного [чеського алфавіту](https://cs.wikipedia.org/wiki/%C4%8Cesk%C3%BD_pravopis) Азбучна війна закінчилася переходом на переважно кирилічну [драгоманівку](https://uk.wikipedia.org/wiki/%D0%94%D1%80%D0%B0%D0%B3%D0%BE%D0%BC%D0%B0%D0%BD%D1%96%D0%B2%D0%BA%D0%B0), в якій, на відміну від сучасної української кирилиці, немає літери `щ`, і звук передається сполученням `шч` (*шчо* є ближчим до принципу 'як чуємо так і пишемо'), й передається як `j`, йотовані голосні передаються як `j + голосна`, пом'якшення приголосних перед голосним як `ь + голосна`. Також були і пізніші спроби перевести українську на латинику за українських радянських часів "до самогубства [Скрипника](https://uk.wikipedia.org/wiki/%D0%A1%D0%BA%D1%80%D0%B8%D0%BF%D0%BD%D0%B8%D0%BA_%D0%9C%D0%B8%D0%BA%D0%BE%D0%BB%D0%B0_%D0%9E%D0%BB%D0%B5%D0%BA%D1%81%D1%96%D0%B9%D0%BE%D0%B2%D0%B8%D1%87)": > > 1927 р. під час Всеукраїнської правописної конференції в Харкові мовознавці Майк Йогансен, Борис Ткаченко та Михайло Наконечний запропонували прийняти латинку як частину правопису. Внаслідок голосування переважив один голос проти. > > > Крім радикального переходу на латинку, існувала ідея впровадження кількох латинських літер — ѕ (замість дз), z (замість дж) та j (замість й, зокрема в є, ї, ю, я). Цю ідею виніс Євген Тимченко, її було частково підтримано і Харківська конференція затвердила введення s та z до української абетки. Проте після того, як ЦК КП(б)У на чолі з Л. Кагановичем засудив впровадження нових літер, конференція анулювала своє рішення > > > Також, лінгвіст [Юрій Шевельов](https://uk.wikipedia.org/wiki/%D0%A8%D0%B5%D0%B2%D0%B5%D0%BB%D1%8C%D0%BE%D0%B2_%D0%AE%D1%80%D1%96%D0%B9_%D0%92%D0%BE%D0%BB%D0%BE%D0%B4%D0%B8%D0%BC%D0%B8%D1%80%D0%BE%D0%B2%D0%B8%D1%87) використовував латинику для передачі сучасної української мови у своїх працях, принаймні написаних англійською та, здається, німецькою мовами. Але при перекладі українською з англійської його "[Історичної фонології української мови](https://books.google.pl/books/about/%D0%86%D1%81%D1%82%D0%BE%D1%80%D0%B8%D1%87%D0%BD%D0%B0_%D1%84%D0%BE%D0%BD%D0%BE%D0%BB%D0%BE%D0%B3%D1%96%D1%8F_%D1%83.html?id=a33ERmARrc8C&redir_esc=y)" перекладачі [Сергій Вакуленко](http://www.hi-phi.org.ua/index.php/chleny-tovarystva/6-vakulenko-serhii) та [Андрій Даниленко](https://uk.wikipedia.org/wiki/%D0%94%D0%B0%D0%BD%D0%B8%D0%BB%D0%B5%D0%BD%D0%BA%D0%BE_%D0%90%D0%BD%D0%B4%D1%80%D1%96%D0%B9_%D0%86%D0%B2%D0%B0%D0%BD%D0%BE%D0%B2%D0%B8%D1%87) використали кирилицю не тільки для передачі ідей українською мовою, а також і приклади, які в оригінальному тексті кодифіковані латиникою. Також варто не забувати про сучасний і [досить незграбний офіційний варіант](https://uk.wikipedia.org/wiki/%D0%9B%D0%B0%D1%82%D0%B8%D0%BD%D1%96%D0%B7%D0%B0%D1%86%D1%96%D1%8F_%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) латинізації української мови, прийнятий міністерством закордонних справ кабінету [Азарова](https://uk.wikipedia.org/wiki/%D0%90%D0%B7%D0%B0%D1%80%D0%BE%D0%B2_%D0%9C%D0%B8%D0%BA%D0%BE%D0%BB%D0%B0_%D0%AF%D0%BD%D0%BE%D0%B2%D0%B8%D1%87).
Можна, наприклад, брати давні відомости, а саме: доволї непогана технічна з 75 сторінками [книга](//diasporiana.org.ua/wp-content/uploads/books/11976/file.pdf) 1933 року „[Йосиф Їречек](//uk.wikipedia.org/wiki/%D0%99%D0%BE%D1%81%D0%B8%D1%84_%D0%87%D1%80%D0%B5%D1%87%D0%B5%D0%BA) і українська мова (до [азбучної заверюхи 1859 р.](//uk.wikipedia.org/wiki/%D0%90%D0%B7%D0%B1%D1%83%D1%87%D0%BD%D0%B0_%D0%B2%D1%96%D0%B9%D0%BD%D0%B0#%D0%94%D1%80%D1%83%D0%B3%D0%B8%D0%B9_%D1%81%D0%BF%D0%B0%D0%BB%D0%B0%D1%85))“ [Василя Сїмовича](//uk.wikipedia.org/wiki/%D0%A1%D1%96%D0%BC%D0%BE%D0%B2%D0%B8%D1%87_%D0%92%D0%B0%D1%81%D0%B8%D0%BB%D1%8C_%D0%86%D0%B2%D0%B0%D0%BD%D0%BE%D0%B2%D0%B8%D1%87). Там про мовні і політичні питаня, про сам вплив на мову тошчо. Також проблеми писемностей: як латинкової, так і кириличної. Також вартий уваги [займавий факт і збіг](https://www.istpravda.com.ua/articles/2021/04/7/159284/): > > … таємний указ імператора Всеросійського Олександра ІІ від 20 жовтня 1859 року про заборону друкування азбук чи інших творів українською мовою з використанням польської абетки. > > > У фонді Подільського духовної консисторії Державного архіву Хмельницької області потрапила на очі справа "О запрещении печатания азбук русского языка с применением польского алфавита" (Ф-315, оп. 1, спр. 1484). > > > Збіг в тому, же рік той самий, коли Їречек передставив свою латинку. Також можна зауважити, же за 4 роки, а са́ме 1863 року, буде сумнозвісний [Валуєвський циркуляр](https://uk.wikipedia.org/wiki/%D0%92%D0%B0%D0%BB%D1%83%D1%94%D0%B2%D1%81%D1%8C%D0%BA%D0%B8%D0%B9_%D1%86%D0%B8%D1%80%D0%BA%D1%83%D0%BB%D1%8F%D1%80). --- Моя основна думка про перевагу. Українцї ототожнюватимуть себе з латинковим сьвітом, а не з кириличним. Тобто, по-мойому, доречним також варто розглянути питаня трудностїв, коли українська залишається на кирилицї. Один з показових прикладів [сучасности](//theverge.com/2018/5/22/17380630/) про родину кирилицї — Бoлґарія: > > … Twitter announced it would become more aggressive in pursuing trolls on its service, a move which seems to have had some unforeseen consequences, judging by the present upheaval in the Bulgarian Twitter community. An increasingly large and unhappy number of people have had their Twitter accounts suspended and messages filtered out of conversations, apparently for the offense of merely tweeting in Cyrillic. … > > > > > --- > > > … Twitter оголосив, що він стане агресивнішим у переслідувані тролів; цей крок, здається, мав непередбачувані наслідки, судячи з нинішніх потрясінь у болгарській твітер-спільноті. Все більша кількість людей мають заблоковані облікові записи, а їхні повідомленя вилучаються з обговорень — напевно, всього лиш через те, що вони переписувалися кирилицею… > Дуже приблизний переклад > > > Очевидно, шчо таке буває не лиш тут: більшість проґрам спершу нацїлені на латинку, а лиш потім на инші писемности (виняток — власна писемніть, але однаково першою разом чи другою є латинка). ---
38,693,236
I'm trying to build a counter in python with the property of closure. The code in the following works: ``` def generate_counter(): CNT = [0] def add_one(): CNT[0] = CNT[0] + 1 return CNT[0] return add_one ``` However when I change the list CNT to a var, it did not work: ``` def generate_counter1(): x = 0 def add_one(): x = x + 1 return x return add_one ``` when I print the closure property of an instance, I found the `__closure__` of the second case is none: ``` >>> ct1 = generate_counter() >>> ct2 = generate_counter1() >>> print(ct1.__closure__[0]) <cell at 0xb723765c: list object at 0xb724370c> >>> print(ct2.__closure__) None ``` Just wondering why the index in outer function has to be a list? --- Thanks for the answers! Found the docs which clearly explained this problem <https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value>
2016/08/01
[ "https://Stackoverflow.com/questions/38693236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3295434/" ]
Python determines the scope of a name by looking at name binding behaviour; assignment is one such behaviour (function parameters, importing, the target in `for target ...` or `while .. as target` are other examples). A name you bind to in a function is considered *local*. See the [*Naming and Binding* section](https://docs.python.org/3/reference/executionmodel.html#naming-and-binding) of the reference documentation. So the name `x` in your second example is a *local* variable, because you assigned directly to it: ``` x = x + 1 ``` In fact, because you never gave that `x` a local value, you'll get an exception when you try to use that function; the local name is *unbound* when you try to read it: ``` >>> generate_counter1()() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 4, in add_one UnboundLocalError: local variable 'x' referenced before assignment ``` In your first example no such binding takes place; you are instead altering the *contents* of `CNT`, what that name references is not altered. If you are using Python 3, you can override the decision to make a name local, by using a [`nonlocal` statement](https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement): ``` def generate_counter2(): x = 0 def add_one(): nonlocal x x = x + 1 return x return add_one ``` By making `x` non-local, Python finds it in the parent context and creates a closure for it again. ``` >>> def generate_counter2(): ... x = 0 ... def add_one(): ... nonlocal x ... x = x + 1 ... return x ... return add_one ... >>> generate_counter2().__closure__ (<cell at 0x1078c62e8: int object at 0x1072c8070>,) ``` `nonlocal` is new in Python 3; in Python 2 you are limited to tricks like using a mutable list object to evade the binding rule. Another trick would be to assign the counter to an attribute of the nested function; again, this avoids binding a name in the current scope: ``` def generate_counter3(): def add_one(): add_one.x += 1 return add_one.x add_one.x = 0 return add_one ```
It doesn't *have* to be a list, it just has to be an mutable object which you *mutate*, not reassign. From the [docs](https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python): > > If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global. > > > Thus, in your second example, `x` is considered local (to the inner function), and, after your first assignment, you're shadowing the outer 'x'. On the other hand, in the first example (since you don't assign a value to `CNT`) it operates on the `CNT` defined in the outer function.
33,198,127
I am working with codeigniter / SQL. Where I want to insert unicode string with 'N' Prefix the insert. How can I achieve it in regular insert. **Regular Code:** ``` $data = array( 'title' => 'My title' , 'name' => 'My Name' , 'data' => 'My data' ); $this->db->insert('mytable', $data); ``` **INSERT Trying to Achieve:** ``` INSERT INTO mytable (title, name, data) VALUES ('My title','My Name',N'My data'); ``` Is there any way to achive the above insert instead of manually writing the Query.?
2015/10/18
[ "https://Stackoverflow.com/questions/33198127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2090453/" ]
This is the simplest way to do it. ``` $data = array( 'title' => 'My title' , 'name' => 'My Name' , 'data' => 'N'.'My data' ); $this->db->insert('mytable', $data); ``` Or, if the prefix needs to more dynamic do this ``` $pre = foo(bar); $data = array( 'title' => 'My title' , 'name' => 'My Name' , 'data' => $pre.'My data' ); $this->db->insert('mytable', $data); ```
Thanks Eggy and Leandro for their suggestion. I use CI 3.1.9 and here is my solution: ``` public function escape($str) { ... elseif (is_string($str) OR (is_object($str) && method_exists($str, '__toString'))) { if ($this->dbdriver == 'sqlsrv') { return "N'".$this->escape_str($str)."'"; } return "'".$this->escape_str($str)."'"; } ... } ```
33,198,127
I am working with codeigniter / SQL. Where I want to insert unicode string with 'N' Prefix the insert. How can I achieve it in regular insert. **Regular Code:** ``` $data = array( 'title' => 'My title' , 'name' => 'My Name' , 'data' => 'My data' ); $this->db->insert('mytable', $data); ``` **INSERT Trying to Achieve:** ``` INSERT INTO mytable (title, name, data) VALUES ('My title','My Name',N'My data'); ``` Is there any way to achive the above insert instead of manually writing the Query.?
2015/10/18
[ "https://Stackoverflow.com/questions/33198127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2090453/" ]
I was having problems with Unicode using Codeignter 3, driver sqlsrv and I managed to get it working modifying the System/database/DB\_Driver.php. Probably there is a better solution out there, it's not beautiful but it's working, just modify the functions \_insert and \_update. ``` protected function _insert($table, $keys, $values) { foreach($values as $key => $value) { if(substr($value,0,1) == "'") { $values[$key] = "N". $value; } } return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')'; } protected function _update($table, $values) { foreach($values as $key => $value) { if(substr($value,0,1) == "'") { $values[$key] = "N". $value; } } foreach ($values as $key => $val) { $valstr[] = $key.' = '.$val; } return 'UPDATE '.$table.' SET '.implode(', ', $valstr) .$this->_compile_wh('qb_where') .$this->_compile_order_by() .($this->qb_limit ? ' LIMIT '.$this->qb_limit : ''); } ```
Thanks Eggy and Leandro for their suggestion. I use CI 3.1.9 and here is my solution: ``` public function escape($str) { ... elseif (is_string($str) OR (is_object($str) && method_exists($str, '__toString'))) { if ($this->dbdriver == 'sqlsrv') { return "N'".$this->escape_str($str)."'"; } return "'".$this->escape_str($str)."'"; } ... } ```
114,052
I am receiving the expcetion `CGI::Session::CookieStore::TamperedWithCookie` after changing the `config.action_controller.session.secret` setting on an app (as part of preparation to full deployment. Am I right in assuming that changing the secret while testers have cookies set is the cause of this, and what other cause could there be (both due to secuirty attacks, and coding issues)
2008/09/22
[ "https://Stackoverflow.com/questions/114052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ]
The cause of your exception is most certainly changing the secret while testers have cookies set. The cookie is cryptographically signed using the secret to protect against users tampering with their cookie. For example, they might try to change their stored user id in order to elevate their privileges. You could ask the testers to clear their cookies. Or, you could catch the exception and remove the cookie for your application. Some sites prefer to use [ActiveRecordSession](http://api.rubyonrails.org/classes/ActionController/Base.html) store for more control over their sessions so they drop all sessions when required but at a cost of performance.
Yes, testers should clear their cookies. Any time the cookie cannot be decrypted with the specified secret you'll get that error.
114,052
I am receiving the expcetion `CGI::Session::CookieStore::TamperedWithCookie` after changing the `config.action_controller.session.secret` setting on an app (as part of preparation to full deployment. Am I right in assuming that changing the secret while testers have cookies set is the cause of this, and what other cause could there be (both due to secuirty attacks, and coding issues)
2008/09/22
[ "https://Stackoverflow.com/questions/114052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ]
Yes, testers should clear their cookies. Any time the cookie cannot be decrypted with the specified secret you'll get that error.
I found a [plugin on Github](http://github.com/mhartl/catch_cookie_exception) that will trap the error and write it to the log without exposing the error to the user. I was plagued by this problem on a Rails 2.1 instance and it did the trick.
114,052
I am receiving the expcetion `CGI::Session::CookieStore::TamperedWithCookie` after changing the `config.action_controller.session.secret` setting on an app (as part of preparation to full deployment. Am I right in assuming that changing the secret while testers have cookies set is the cause of this, and what other cause could there be (both due to secuirty attacks, and coding issues)
2008/09/22
[ "https://Stackoverflow.com/questions/114052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ]
The cause of your exception is most certainly changing the secret while testers have cookies set. The cookie is cryptographically signed using the secret to protect against users tampering with their cookie. For example, they might try to change their stored user id in order to elevate their privileges. You could ask the testers to clear their cookies. Or, you could catch the exception and remove the cookie for your application. Some sites prefer to use [ActiveRecordSession](http://api.rubyonrails.org/classes/ActionController/Base.html) store for more control over their sessions so they drop all sessions when required but at a cost of performance.
I found a [plugin on Github](http://github.com/mhartl/catch_cookie_exception) that will trap the error and write it to the log without exposing the error to the user. I was plagued by this problem on a Rails 2.1 instance and it did the trick.
41,529
From [OpenVMS](http://en.wikipedia.org/wiki/OpenVMS) [DCL Dictionary](http://h71000.www7.hp.com/doc/83final/9996/9996pro_179.html): > > The Ctrl/T function displays a single line of statistical information > about the current process. When you press Ctrl/T during an interactive > terminal session, it momentarily interrupts the current command, > command procedure, or image to display statistics. The statistical > information includes the node and user names, the current time, the > current process, CPU usage, number of page faults, level of I/O > activity, and memory usage. For example: > > > ``` BOSTON::SMITH 16:21:04 EDT CPU=00:00:03.33 PF=778 IO=296 MEM=277 ``` What is Linux for OpenVMS DCL Ctrl/T?
2012/06/24
[ "https://unix.stackexchange.com/questions/41529", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/3999/" ]
I sincerely doubt there's an exact analog. The nature of a Linux process (and consequently of running a command) is so different than the nature of a VMS process and how it runs a command that nothing like this can really exist. As I understand VMS, when you run a command like `TYPE SOMEFILE.TXT`, DCL reads the TYPE.EXE into the memory of the *same process* that DCL runs in, fixes up all the relocations that TYPE.EXE needs, and then jumps to the first instruction of TYPE.EXE. When TYPE.EXE has done its work, the OS returns control to the DCL code that still resides in the same process as TYPE.EXE. That heavyweight process, which includes DCL, a table of lexicals, and a well-known jump table of addresses of various things, allows Ctrl-T to work. That key sequence is just a special form of keyboard interrupt, and the DCL code in any given process can do the work you describe. A linux process doesn't always have a shell (DCL analog) in it. A linux process may not even have keyboard interrupt handler code registered with the kernel, which would mean that any keyboard interrupt (Ctrl-C or Ctrl-) gets the kernel to cause the process to exit.
On Linux, dd supports SIGUSR1 for status: <http://man7.org/linux/man-pages/man1/dd.1.html> > > > ``` > Sending a USR1 signal to a running 'dd' process makes it print I/O > statistics to standard error and then resume copying. > > ``` > > On BSD, dd support SIGINFO for status: <https://www.freebsd.org/cgi/man.cgi?query=dd&sektion=1> > > If dd receives a SIGINFO (see the status argument for stty(1)) signal, > the current input and output block counts will be written to the standard > error output in the same format as the standard completion message. If > dd receives a SIGINT signal, the current input and output block counts > will be written to the standard error output in the same format as the > standard completion message and dd will exit. > > > BTW: The VMS BACKUP program has a nice output for Control-T.
41,529
From [OpenVMS](http://en.wikipedia.org/wiki/OpenVMS) [DCL Dictionary](http://h71000.www7.hp.com/doc/83final/9996/9996pro_179.html): > > The Ctrl/T function displays a single line of statistical information > about the current process. When you press Ctrl/T during an interactive > terminal session, it momentarily interrupts the current command, > command procedure, or image to display statistics. The statistical > information includes the node and user names, the current time, the > current process, CPU usage, number of page faults, level of I/O > activity, and memory usage. For example: > > > ``` BOSTON::SMITH 16:21:04 EDT CPU=00:00:03.33 PF=778 IO=296 MEM=277 ``` What is Linux for OpenVMS DCL Ctrl/T?
2012/06/24
[ "https://unix.stackexchange.com/questions/41529", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/3999/" ]
BSD UNIX family support SIGINFO signal [1] and VSTATUS control character [2], normally bound to Ctrl/T. The output looks like this: ``` load: 0.12 cmd: cat 13579 [ttyraw] 0.00u 0.00s 0% 880k ``` [1] signal(7) [2] stty(1)
On Linux, dd supports SIGUSR1 for status: <http://man7.org/linux/man-pages/man1/dd.1.html> > > > ``` > Sending a USR1 signal to a running 'dd' process makes it print I/O > statistics to standard error and then resume copying. > > ``` > > On BSD, dd support SIGINFO for status: <https://www.freebsd.org/cgi/man.cgi?query=dd&sektion=1> > > If dd receives a SIGINFO (see the status argument for stty(1)) signal, > the current input and output block counts will be written to the standard > error output in the same format as the standard completion message. If > dd receives a SIGINT signal, the current input and output block counts > will be written to the standard error output in the same format as the > standard completion message and dd will exit. > > > BTW: The VMS BACKUP program has a nice output for Control-T.
74,265,769
Here is my Task ``` private async Task UploadFiles(InputFileChangeEventArgs inputFileChangeEventArgs) { _CarregaFoto = true; var fileFormat = "image/png"; var MAXALLOWEDSIZE = 60000000; var imageFile = await inputFileChangeEventArgs.File.RequestImageFileAsync(fileFormat, 6000, 6000); var buffer = new byte[imageFile.Size]; await imageFile.OpenReadStream(MAXALLOWEDSIZE).ReadAsync(buffer); AnexoDenunciaModel _novaFoto = new AnexoDenunciaModel(); _novaFoto.imagem = buffer; _novaFoto.id_ocorre = id; _novaFoto.nome = imageFile.Name; _novaFoto.Denunciante = true; await _db.InsertAnexoDenuncia(_novaFoto); _CarregaFoto = false; await LeTabelas2(); } ``` I've tried to change var fileFormat to pdf or discart this part but with no success, the task only accept png, jpg, etc. files. How can i accept other types like pdf, txt files?
2022/10/31
[ "https://Stackoverflow.com/questions/74265769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20122702/" ]
Hey @JSpadawan best practice is to use filter like- ``` const [data,setData] = useState() useEffect(()=>{ const apiData = fetch(APILINK).then((res)=>res.json()).catch(err) if(apiData.length>0){ setData(apiData) } },[]) ``` This will set the data of api.. now use filter like- ``` const [searchValue, setSearchValue]= useState() const filterData = data && data.filter((data)=>data.includes(searchValue)) ``` After this you can use filterdata any where you want. If you still facing issue just lemme know, i will help you more. Thanks
You can set the movies with the useEffect, but I would recommend having a secondary useEffect that would be for the seach bar. You should try to avoid making tons of API calls as the more you make, the more it will slow down the application. So have one useEffect that will set the data, and a second one that you can filter out the ones that match the search bar. If the searchValue is updated every key stroke then searching for a movie with a long title would create tons of API calls. You could put the fetch call in an async/await function so you get the data, then set it, then you can filter with a different effect. ``` useEffect(() => { const getData = async () => { await fetch( `https://api.themoviedb.org/3/search/movie?api_keylanguage=en-US&query=${searchValue}&` ) .then((res) => res.json()) .then((data) => { setMovies(data.results); }); } getData(); }, []); // empty array will run once on component load, or add a dependency of when you want it to re-call the api ``` Then a second useEffect for filtering ``` useEffect(() => { let searchTextFilter = movies.filter(i => { return (!searchValue || (searchValue && i.Title.toLowerCase().includes(searchFilter?.toLowerCase() ))) }); }, [searchValue]) ```
4,086
I would like to turn this 32GB USB 2.0 flash drive into a 32 GB partition with Ubuntu installed on it which I can boot and read/write persist as any normal hard drive install would be expected to do. The trick is that I don't want to have to install Ubuntu to create this thing. Can I create it from a live boot of a CD? If so, I'll take the challenge to the next level by saying I'd like to avoid that as well. There has to be a way to create it from Windows to USB right? (I have ISO of 10.4)
2010/09/13
[ "https://askubuntu.com/questions/4086", "https://askubuntu.com", "https://askubuntu.com/users/2230/" ]
[UNetbootin](http://unetbootin.sourceforge.net/) is what you want. Runs on Windows and Linux and creates bootable flash drives from ISO images, 10.04 included. However, the default setup does *not* use persistent space, so changes made will be lost on shutdown. An appropriate way to work around this is to follow [these instructions](http://unetbootin.sourceforge.net/diskimg/readme.txt). I believe you may be able to add `persistent` to the boot options alone, but I haven't tested this and the other method is what seems to work for most.
+1 to PenDriveLinux. They've been working on this for a while, they have half a dozen solutions. I've personally used one or two from a windows install (within a Ubuntu-hosted Virtual machine!) and works great.
4,086
I would like to turn this 32GB USB 2.0 flash drive into a 32 GB partition with Ubuntu installed on it which I can boot and read/write persist as any normal hard drive install would be expected to do. The trick is that I don't want to have to install Ubuntu to create this thing. Can I create it from a live boot of a CD? If so, I'll take the challenge to the next level by saying I'd like to avoid that as well. There has to be a way to create it from Windows to USB right? (I have ISO of 10.4)
2010/09/13
[ "https://askubuntu.com/questions/4086", "https://askubuntu.com", "https://askubuntu.com/users/2230/" ]
[UNetbootin](http://unetbootin.sourceforge.net/) is what you want. Runs on Windows and Linux and creates bootable flash drives from ISO images, 10.04 included. However, the default setup does *not* use persistent space, so changes made will be lost on shutdown. An appropriate way to work around this is to follow [these instructions](http://unetbootin.sourceforge.net/diskimg/readme.txt). I believe you may be able to add `persistent` to the boot options alone, but I haven't tested this and the other method is what seems to work for most.
Following creates persistence partitions of any size: Boot Live CD. Plug in flash drive. Start Partition Editor Create 1GB+ FAT32 partition, (on the left side of the bar). (larger size is optional) Create a 4GB+ ext2 partition to the right of this, labeled it "casper-rw". (ext3 and ext4 also work). Create another ext2 partition in the remaining space and label it "home-rw". (optional, creates a separate home partition) Close Partition Editor. Un-mount and re-mount flash drive. Start "Create a live usb startup disk", (usb-creator). Select "Discard on shutdown". Press "Make Startup Disk. When usb-creator finishes, run "gksu nautilus" Select disk / syslinux / text.cfg and add "persistent" as shown below: append noprompt cdrom-detect/try-usb=true persistent file=/cdrom/preseed/ubuntu.seed boot=casper initrd=/casper/initrd.gz quiet splash -- Shutdown, remove CD, reboot. You might like to make the first, (Fat32), partition larger as it is the only one a Windows machine can see.
4,086
I would like to turn this 32GB USB 2.0 flash drive into a 32 GB partition with Ubuntu installed on it which I can boot and read/write persist as any normal hard drive install would be expected to do. The trick is that I don't want to have to install Ubuntu to create this thing. Can I create it from a live boot of a CD? If so, I'll take the challenge to the next level by saying I'd like to avoid that as well. There has to be a way to create it from Windows to USB right? (I have ISO of 10.4)
2010/09/13
[ "https://askubuntu.com/questions/4086", "https://askubuntu.com", "https://askubuntu.com/users/2230/" ]
+1 to PenDriveLinux. They've been working on this for a while, they have half a dozen solutions. I've personally used one or two from a windows install (within a Ubuntu-hosted Virtual machine!) and works great.
Following creates persistence partitions of any size: Boot Live CD. Plug in flash drive. Start Partition Editor Create 1GB+ FAT32 partition, (on the left side of the bar). (larger size is optional) Create a 4GB+ ext2 partition to the right of this, labeled it "casper-rw". (ext3 and ext4 also work). Create another ext2 partition in the remaining space and label it "home-rw". (optional, creates a separate home partition) Close Partition Editor. Un-mount and re-mount flash drive. Start "Create a live usb startup disk", (usb-creator). Select "Discard on shutdown". Press "Make Startup Disk. When usb-creator finishes, run "gksu nautilus" Select disk / syslinux / text.cfg and add "persistent" as shown below: append noprompt cdrom-detect/try-usb=true persistent file=/cdrom/preseed/ubuntu.seed boot=casper initrd=/casper/initrd.gz quiet splash -- Shutdown, remove CD, reboot. You might like to make the first, (Fat32), partition larger as it is the only one a Windows machine can see.
37,515,315
Trying to check if double variable obtained from textfield has a value or not let value:Double? = Double(valueTextfield.text!) if(value.isEmpty()) X if(value. == nil) X if(value == 0) X How do I do this
2016/05/29
[ "https://Stackoverflow.com/questions/37515315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3773060/" ]
You can use Double's init method and pass in the UITextField's text like this: ``` guard let text = valueTextfield.text, value = Double(text) else { // Here you can handle the case where the text is not a vaid Double string. return } // Here, value will be a valid Double type here if the textField contains a valid Double string. ```
Try this: ``` if let doubleFromText = Double(textField.text!) { //use doubleFromText } else { //could not make double } ``` For this, make sure `textField.text` is not `nil`. It's okay if it is "". It will go into the else part of the statement
23,170,918
If I use the same settings across my project, can I instantiate a single static copy of my `JsonSerializerSettings` and use that throughout? For example : ``` private static readonly JsonSerializerSettings settings = new JsonSerializerSettings { Formatting = Formatting.Indented, TypeNameHandling = TypeNameHandling.None, DateFormatHandling = DateFormatHandling.IsoDateFormat, TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple }; public static string ToJSONString(this Object source) { return JsonConvert.SerializeObject(source, settings); } ``` So, am i thread *dangerous*?
2014/04/19
[ "https://Stackoverflow.com/questions/23170918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215068/" ]
The following conversation happened on twitter, @JamesNK being the author of JSON.net: <https://twitter.com/jonathan_oliver/status/332227095616966656> > > From: Jonathan Oliver ‏@jonathan\_oliver To: @JamesNK > > > Are the static JsonConvert.DeserializeObject methods thread safe? Getting some strange errors using 5.0.4 and 5.0.5. > > > Response: > > James Newton-King ♔ ‏@JamesNK 8 May 2013 @jonathan\_oliver > > > Yes. Create an issue on GitHub if they’re not > > > Response: > > Jonathan Oliver ‏@jonathan\_oliver 9 May 2013 > > > @JamesNK It turns out a ContractResolver attached to a static JsonSerializerSettings object I used with JsonConvert wasn't thread safe. > > > I do not see that a bug was ever filed, but this does hint that the design of them is supposed to be thread safe, but there maybe implementation specific ways to ruin that or it might not be as a whole.
Since you say you don't mutate `JsonSerializerSettings` there is no need to worry about thread safety. Thread race can happen only when modifying the shared data in another thread but that is not the case here. I suggest you to read [this article](http://www.albahari.com/threading/), in the end you should have a good understanding of threads, thread safety etc. Also Thread safety is a more general term, you need to be more precise what you meant by that. Refer [What is this thing you call "thread safe"?](http://blogs.msdn.com/b/ericlippert/archive/2009/10/19/what-is-this-thing-you-call-thread-safe.aspx) for more info.
199,834
I want to understand the architecture of web apps that use subdomains. I don't think that I'm phrasing this well, so let me explain. Many web apps, like tumblr or shopify create a user's site on a subdomain. Say for example my tumblr account was `johndoe` then you could find my tumblr blog at `johndoe.tumblr.com`. Can someone explain how this is implemented?
2013/05/29
[ "https://softwareengineering.stackexchange.com/questions/199834", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/92485/" ]
Basically you could either set new CNAME record to your DNS server for each user (if you have such ability by your Hosting/DNS server provider) or use the [Wildcard DNS record](http://en.wikipedia.org/wiki/Wildcard_DNS_record) method and then use some rewrite rules to process the requests. You can read more about it on [this older post in stackoverflow](https://stackoverflow.com/questions/183928/how-to-let-php-to-create-subdomain-automatically-for-each-user).
If you could't edit your DNS record, you can also insert a subdomain which will be pointing to `*.yourdomain.com` and it willl receive any subdomains, that way you will can check on your system if that subdomain inserted by the user is a valid domain, check on a whitelist array, os simply checking on the database if the user exists on the system.
59,421,691
I want to make a function that recives a data in a type of dictionary, and then appends that data to JSON file. This is how JSON file to looks like [{},{},{}] and after appending I want it to be [{},{},{},{}]. Function below is what I tried, if I use 'w', it overwrites, and if I use 'a', file after appending looks like this [{},{},{}{}] which isn't JSON anymore. How to achieve this? ``` def save_to_file(user_data): f = open('users.json', 'a') json.dump(user_data, f, indent=2) f.close() ```
2019/12/20
[ "https://Stackoverflow.com/questions/59421691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12275765/" ]
This is one approach. **Ex:** ``` def save_to_file(user_data): with open('users.json') as jfile: data = json.loads(jfile) #Read content data.append(user_data) #Append with open('users.json', 'w') as jfile: json.dump(data, jfile, indent=2) #Write back ```
Check the following code: It works: ``` import json user_data = {"a":123} def save_to_file(user_data): f = open("tweet.json", 'a') json.dump(user_data, f) f.close() save_to_file(user_data) ```
59,421,691
I want to make a function that recives a data in a type of dictionary, and then appends that data to JSON file. This is how JSON file to looks like [{},{},{}] and after appending I want it to be [{},{},{},{}]. Function below is what I tried, if I use 'w', it overwrites, and if I use 'a', file after appending looks like this [{},{},{}{}] which isn't JSON anymore. How to achieve this? ``` def save_to_file(user_data): f = open('users.json', 'a') json.dump(user_data, f, indent=2) f.close() ```
2019/12/20
[ "https://Stackoverflow.com/questions/59421691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12275765/" ]
This is one approach. **Ex:** ``` def save_to_file(user_data): with open('users.json') as jfile: data = json.loads(jfile) #Read content data.append(user_data) #Append with open('users.json', 'w') as jfile: json.dump(data, jfile, indent=2) #Write back ```
Rather than writing your own logic perhaps use TinyDB. It uses JSON to save data and makes it rather easy to append/delete data even from multiple sources: <https://tinydb.readthedocs.io/en/latest/index.html>
123,098
I'm writing an essay about Don DiLillo's novel *White Noise*, and would like to explore Murray Jay Siskand's fascination with death. The particular word I'm looking for means "death-centric", to fit in the topic sentence "Furthermore, the consumerist society that envelops Siskind results in his `<word goes here>` viewpoint of his surroundings." Failing that, is there a way to rework this sentence as to allow for an elegant focus on his death-centric viewpoint?
2013/08/19
[ "https://english.stackexchange.com/questions/123098", "https://english.stackexchange.com", "https://english.stackexchange.com/users/25083/" ]
I have not read the book but to provide a bit of breadth to the discussion (and avoid pornography) I suggest "fatalistic." From dictionary.com: > > Fatalistic: noun > 1. the acceptance of all things and events as inevitable; submission to fate: Her fatalism helped her to face death with stoic calm. 2. Philosophy . the doctrine that all events are subject to fate or inevitable predetermination. > > > Thus: > > Furthermore, the consumerist society that envelops Siskind results in [a] *fatalistic* viewpoint of his surroundings. > > > This provides a bit of elegance to your sentence while also providing the hint that the character's viewpoint is a bit darker.
you can say [***eschatological***](http://dictionary.reference.com/browse/eschatology?s=t) viewpoint. The context will make the meaning abundantly clear.
123,098
I'm writing an essay about Don DiLillo's novel *White Noise*, and would like to explore Murray Jay Siskand's fascination with death. The particular word I'm looking for means "death-centric", to fit in the topic sentence "Furthermore, the consumerist society that envelops Siskind results in his `<word goes here>` viewpoint of his surroundings." Failing that, is there a way to rework this sentence as to allow for an elegant focus on his death-centric viewpoint?
2013/08/19
[ "https://english.stackexchange.com/questions/123098", "https://english.stackexchange.com", "https://english.stackexchange.com/users/25083/" ]
The word **morbid** might work > > Characterized by or appealing to an abnormal and unhealthy interest in disturbing and unpleasant subjects, esp. death and disease. ([The Oxford Pocket Dictionary of Current English](http://www.encyclopedia.com/topic/morbid.aspx)) > > > Or **macabre** > > having death as a subject : comprising or including a personalized representation of death ([Merriam-Webster Online](http://www.merriam-webster.com/dictionary/macabre)) > > > Although the dictionary definitions might suggest that macabre is a better fit, I would be more likely to use morbid in the example sentence. Macabre often implies some connection to the more horrific aspects of death, while morbid suggests an unhealthy/depressed world view. It's hard to truly judge the best fit without knowing more context!
I have not read the book but to provide a bit of breadth to the discussion (and avoid pornography) I suggest "fatalistic." From dictionary.com: > > Fatalistic: noun > 1. the acceptance of all things and events as inevitable; submission to fate: Her fatalism helped her to face death with stoic calm. 2. Philosophy . the doctrine that all events are subject to fate or inevitable predetermination. > > > Thus: > > Furthermore, the consumerist society that envelops Siskind results in [a] *fatalistic* viewpoint of his surroundings. > > > This provides a bit of elegance to your sentence while also providing the hint that the character's viewpoint is a bit darker.
123,098
I'm writing an essay about Don DiLillo's novel *White Noise*, and would like to explore Murray Jay Siskand's fascination with death. The particular word I'm looking for means "death-centric", to fit in the topic sentence "Furthermore, the consumerist society that envelops Siskind results in his `<word goes here>` viewpoint of his surroundings." Failing that, is there a way to rework this sentence as to allow for an elegant focus on his death-centric viewpoint?
2013/08/19
[ "https://english.stackexchange.com/questions/123098", "https://english.stackexchange.com", "https://english.stackexchange.com/users/25083/" ]
The combining form *thanat-* (or *thanato-*), meaning *death*, with the combining form *-centric*, gives you *thanatocentric* -- literally, *centered on death*.
The term you're looking for is > > **Morbid Obsession** > > > You will find this term has deep usage, [including in professional literature](http://www.wsps.info/index.php?option=com_content&view=article&id=75). In the case of your fill-in-the-blank, you would say *"morbidly obsessive"*
123,098
I'm writing an essay about Don DiLillo's novel *White Noise*, and would like to explore Murray Jay Siskand's fascination with death. The particular word I'm looking for means "death-centric", to fit in the topic sentence "Furthermore, the consumerist society that envelops Siskind results in his `<word goes here>` viewpoint of his surroundings." Failing that, is there a way to rework this sentence as to allow for an elegant focus on his death-centric viewpoint?
2013/08/19
[ "https://english.stackexchange.com/questions/123098", "https://english.stackexchange.com", "https://english.stackexchange.com/users/25083/" ]
The word **morbid** might work > > Characterized by or appealing to an abnormal and unhealthy interest in disturbing and unpleasant subjects, esp. death and disease. ([The Oxford Pocket Dictionary of Current English](http://www.encyclopedia.com/topic/morbid.aspx)) > > > Or **macabre** > > having death as a subject : comprising or including a personalized representation of death ([Merriam-Webster Online](http://www.merriam-webster.com/dictionary/macabre)) > > > Although the dictionary definitions might suggest that macabre is a better fit, I would be more likely to use morbid in the example sentence. Macabre often implies some connection to the more horrific aspects of death, while morbid suggests an unhealthy/depressed world view. It's hard to truly judge the best fit without knowing more context!
The combining form *thanat-* (or *thanato-*), meaning *death*, with the combining form *-centric*, gives you *thanatocentric* -- literally, *centered on death*.
123,098
I'm writing an essay about Don DiLillo's novel *White Noise*, and would like to explore Murray Jay Siskand's fascination with death. The particular word I'm looking for means "death-centric", to fit in the topic sentence "Furthermore, the consumerist society that envelops Siskind results in his `<word goes here>` viewpoint of his surroundings." Failing that, is there a way to rework this sentence as to allow for an elegant focus on his death-centric viewpoint?
2013/08/19
[ "https://english.stackexchange.com/questions/123098", "https://english.stackexchange.com", "https://english.stackexchange.com/users/25083/" ]
The term you're looking for is > > **Morbid Obsession** > > > You will find this term has deep usage, [including in professional literature](http://www.wsps.info/index.php?option=com_content&view=article&id=75). In the case of your fill-in-the-blank, you would say *"morbidly obsessive"*
Necroxxx is exemplified by the following words: [Necrophilia](http://en.wikipedia.org/wiki/Necrophilia), also called thanatophilia or necrolagnia, is the sexual attraction to corpses. It is classified as a paraphilia by the Diagnostic and Statistical Manual of the American Psychiatric Association. The word is derived from the Greek words: νεκρός (nekros; "dead") and φιλία (philia; "love"). The dictionaries have a more complete definition: [nec·ro·phil·i·a](http://www.thefreedictionary.com/necrophilic) (nkr-fl-) also nec·rophi·lism (n-krf-lzm, n-) > > n. > > 1. Obsessive fascination with death and corpses. > > 2. Erotic attraction to or sexual contact with corpses. > > > Hence, necrophilic and necrophiliac. The word is seek is probably [necromania](http://dictionary.reference.com/browse/necromania) > > Medical Dictionary > > necromania: nec·ro·ma·ni·a (něk'rə-mā'nē-ə, -mān'yə) > > n. An abnormal tendency to dwell with longing on death. > > > Hence necromaniac, a person who indulges in necromania. *Apparently, Necromania is also the name of a porn movie.* If you are willing to coin a new word, it could be **necro-centric**. If you don't mind being sarcastic, then coin the word **necroholic**, addicted to the subject of the dead. Other necro words are: necromancy, necrology, necrological, necrologistics, necrophoresis. > > Furthermore, the consumerist society that envelops Siskind results in his necrophiliac/necromaniac/necro-centric viewpoint of his surroundings. > > > If I were you, I would use necro-centric.
123,098
I'm writing an essay about Don DiLillo's novel *White Noise*, and would like to explore Murray Jay Siskand's fascination with death. The particular word I'm looking for means "death-centric", to fit in the topic sentence "Furthermore, the consumerist society that envelops Siskind results in his `<word goes here>` viewpoint of his surroundings." Failing that, is there a way to rework this sentence as to allow for an elegant focus on his death-centric viewpoint?
2013/08/19
[ "https://english.stackexchange.com/questions/123098", "https://english.stackexchange.com", "https://english.stackexchange.com/users/25083/" ]
The term you're looking for is > > **Morbid Obsession** > > > You will find this term has deep usage, [including in professional literature](http://www.wsps.info/index.php?option=com_content&view=article&id=75). In the case of your fill-in-the-blank, you would say *"morbidly obsessive"*
I have not read the book but to provide a bit of breadth to the discussion (and avoid pornography) I suggest "fatalistic." From dictionary.com: > > Fatalistic: noun > 1. the acceptance of all things and events as inevitable; submission to fate: Her fatalism helped her to face death with stoic calm. 2. Philosophy . the doctrine that all events are subject to fate or inevitable predetermination. > > > Thus: > > Furthermore, the consumerist society that envelops Siskind results in [a] *fatalistic* viewpoint of his surroundings. > > > This provides a bit of elegance to your sentence while also providing the hint that the character's viewpoint is a bit darker.
123,098
I'm writing an essay about Don DiLillo's novel *White Noise*, and would like to explore Murray Jay Siskand's fascination with death. The particular word I'm looking for means "death-centric", to fit in the topic sentence "Furthermore, the consumerist society that envelops Siskind results in his `<word goes here>` viewpoint of his surroundings." Failing that, is there a way to rework this sentence as to allow for an elegant focus on his death-centric viewpoint?
2013/08/19
[ "https://english.stackexchange.com/questions/123098", "https://english.stackexchange.com", "https://english.stackexchange.com/users/25083/" ]
The term you're looking for is > > **Morbid Obsession** > > > You will find this term has deep usage, [including in professional literature](http://www.wsps.info/index.php?option=com_content&view=article&id=75). In the case of your fill-in-the-blank, you would say *"morbidly obsessive"*
I would suggest ***thanatotic*** as an appropriate contextual adjective if you want to specifically refer to the concept of death as opposed to a general *fatalistic* worldview. der. from Thanatos <http://dictionary.reference.com/browse/Thanatos> in a manner similar to *eros* By analogy you might also use ***mortal***, although common use of this term in other contexts might make it seem rather awkward in this sense. ***thanatomania*** This word [exists](http://en.wiktionary.org/wiki/thanatomania) and unlike the related *necromania*, does not have sexual connotations. No need for neologisms I guess.
123,098
I'm writing an essay about Don DiLillo's novel *White Noise*, and would like to explore Murray Jay Siskand's fascination with death. The particular word I'm looking for means "death-centric", to fit in the topic sentence "Furthermore, the consumerist society that envelops Siskind results in his `<word goes here>` viewpoint of his surroundings." Failing that, is there a way to rework this sentence as to allow for an elegant focus on his death-centric viewpoint?
2013/08/19
[ "https://english.stackexchange.com/questions/123098", "https://english.stackexchange.com", "https://english.stackexchange.com/users/25083/" ]
Necroxxx is exemplified by the following words: [Necrophilia](http://en.wikipedia.org/wiki/Necrophilia), also called thanatophilia or necrolagnia, is the sexual attraction to corpses. It is classified as a paraphilia by the Diagnostic and Statistical Manual of the American Psychiatric Association. The word is derived from the Greek words: νεκρός (nekros; "dead") and φιλία (philia; "love"). The dictionaries have a more complete definition: [nec·ro·phil·i·a](http://www.thefreedictionary.com/necrophilic) (nkr-fl-) also nec·rophi·lism (n-krf-lzm, n-) > > n. > > 1. Obsessive fascination with death and corpses. > > 2. Erotic attraction to or sexual contact with corpses. > > > Hence, necrophilic and necrophiliac. The word is seek is probably [necromania](http://dictionary.reference.com/browse/necromania) > > Medical Dictionary > > necromania: nec·ro·ma·ni·a (něk'rə-mā'nē-ə, -mān'yə) > > n. An abnormal tendency to dwell with longing on death. > > > Hence necromaniac, a person who indulges in necromania. *Apparently, Necromania is also the name of a porn movie.* If you are willing to coin a new word, it could be **necro-centric**. If you don't mind being sarcastic, then coin the word **necroholic**, addicted to the subject of the dead. Other necro words are: necromancy, necrology, necrological, necrologistics, necrophoresis. > > Furthermore, the consumerist society that envelops Siskind results in his necrophiliac/necromaniac/necro-centric viewpoint of his surroundings. > > > If I were you, I would use necro-centric.
I would suggest ***thanatotic*** as an appropriate contextual adjective if you want to specifically refer to the concept of death as opposed to a general *fatalistic* worldview. der. from Thanatos <http://dictionary.reference.com/browse/Thanatos> in a manner similar to *eros* By analogy you might also use ***mortal***, although common use of this term in other contexts might make it seem rather awkward in this sense. ***thanatomania*** This word [exists](http://en.wiktionary.org/wiki/thanatomania) and unlike the related *necromania*, does not have sexual connotations. No need for neologisms I guess.
123,098
I'm writing an essay about Don DiLillo's novel *White Noise*, and would like to explore Murray Jay Siskand's fascination with death. The particular word I'm looking for means "death-centric", to fit in the topic sentence "Furthermore, the consumerist society that envelops Siskind results in his `<word goes here>` viewpoint of his surroundings." Failing that, is there a way to rework this sentence as to allow for an elegant focus on his death-centric viewpoint?
2013/08/19
[ "https://english.stackexchange.com/questions/123098", "https://english.stackexchange.com", "https://english.stackexchange.com/users/25083/" ]
The combining form *thanat-* (or *thanato-*), meaning *death*, with the combining form *-centric*, gives you *thanatocentric* -- literally, *centered on death*.
I have not read the book but to provide a bit of breadth to the discussion (and avoid pornography) I suggest "fatalistic." From dictionary.com: > > Fatalistic: noun > 1. the acceptance of all things and events as inevitable; submission to fate: Her fatalism helped her to face death with stoic calm. 2. Philosophy . the doctrine that all events are subject to fate or inevitable predetermination. > > > Thus: > > Furthermore, the consumerist society that envelops Siskind results in [a] *fatalistic* viewpoint of his surroundings. > > > This provides a bit of elegance to your sentence while also providing the hint that the character's viewpoint is a bit darker.
123,098
I'm writing an essay about Don DiLillo's novel *White Noise*, and would like to explore Murray Jay Siskand's fascination with death. The particular word I'm looking for means "death-centric", to fit in the topic sentence "Furthermore, the consumerist society that envelops Siskind results in his `<word goes here>` viewpoint of his surroundings." Failing that, is there a way to rework this sentence as to allow for an elegant focus on his death-centric viewpoint?
2013/08/19
[ "https://english.stackexchange.com/questions/123098", "https://english.stackexchange.com", "https://english.stackexchange.com/users/25083/" ]
The word **morbid** might work > > Characterized by or appealing to an abnormal and unhealthy interest in disturbing and unpleasant subjects, esp. death and disease. ([The Oxford Pocket Dictionary of Current English](http://www.encyclopedia.com/topic/morbid.aspx)) > > > Or **macabre** > > having death as a subject : comprising or including a personalized representation of death ([Merriam-Webster Online](http://www.merriam-webster.com/dictionary/macabre)) > > > Although the dictionary definitions might suggest that macabre is a better fit, I would be more likely to use morbid in the example sentence. Macabre often implies some connection to the more horrific aspects of death, while morbid suggests an unhealthy/depressed world view. It's hard to truly judge the best fit without knowing more context!
you can say [***eschatological***](http://dictionary.reference.com/browse/eschatology?s=t) viewpoint. The context will make the meaning abundantly clear.