qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
223,880 | *Huge omega thanks to @wasif for emailing me this challenge idea in its basic form*
Everyone knows that questions on StackExchange require tags - labels that allow posts to be grouped together by category. However, most of the time, I barely know which tags exist, because there's just *so many* of them.
Henceforth, today's task is to tell me every single tag that exists on the Code Golf and Coding Challenges Stack Exchange.
The Challenge
-------------
Write a program or function that prints/returns a list of all available tags on <https://codegolf.stackexchange.com>
As tags can be created/deleted at any time, simply hard-coding a list of tags is not a valid solution - the list must be correct at run-time regardless of when the program/function is executed.
The tags avaliable can be seen [here](https://codegolf.stackexchange.com/tags)
Rules
-----
* As this is an [internet](/questions/tagged/internet "show questions tagged 'internet'") challenge, internet connections are allowed. However, web requests can only be made to codegolf.stackexchange.com and api.stackexchange.com domains.
* Output can be given in any convenient and reasonable format.
* The tags can be in any order, so long as all current tags are returned.
* The exact name of the tags must be used (e.g. `code-golf` is valid, `code GOLF` is not valid.)
* And as usual, standard loopholes apply, shortest code wins
Example Program
---------------
```python
import urllib.request
import regex
pobj = regex.compile('rel="tag">(.*)</a>')
page_number = 2
req = urllib.request.urlopen(f"https://codegolf.stackexchange.com/tags?page=1&tab=name")
data = req.read().decode('utf-8')
tags = []
while data.count("tag") != 43:
tags += pobj.findall(data)
req = urllib.request.urlopen(f"https://codegolf.stackexchange.com/tags?page={page_number}&tab=name")
data = req.read().decode('utf-8')
page_number += 1
print(tags)
``` | 2021/04/20 | [
"https://codegolf.stackexchange.com/questions/223880",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/78850/"
] | [05AB1E](https://github.com/Adriandmen/05AB1E), ~~60~~ ~~57~~ 56 bytes
======================================================================
```
[N>’¸¸.‚‹º.ŒŒ/›´?€¼=ƒËŠˆ&€®=ÿ’.wD2è'eQ#“e":"“¡¦ε'"¡н]\)
```
Outputs as a list of pages, where each page is a list of tags.
```
[N>’...’.wD2è'eQ#“e":"“¡¦ε'"¡н]\) # trimmed program
[ # # while...
è # character in...
.wD # data of response from URL...
# (implicit) "http://" concatenated with...
’...’ # "api.stackexchange.com/tags?site=codegolf&page=ÿ"...
# (implicit) with ÿ replaced by...
N # current index in loop...
> # plus 1...
è # at index...
2 # literal...
# # is not...
Q # equal to...
'e # literal...
.w # push data of response from URL...
# (implicit) "http://" concatenated with...
’...’ # "api.stackexchange.com/tags?site=codegolf&page=ÿ"...
# (implicit) with ÿ replaced by...
N # current index in loop...
> # plus 1...
¡ # split by...
“e":"“ # literal...
¦ # excluding the first...
ε # with each element replaced by...
н # first element of...
# (implicit) current element in map...
¡ # split by...
'" # literal
] # exit map
] # exit infinite loop
\ # delete top element of stack
) # push stack
# implicit output
``` | [Bash](https://www.gnu.org/software/bash/) + wget + jq, 86
==========================================================
Assumes there are no more than 99 pages of results (currently 10 pages).
```bash
wget -qO- api.stackexchange.com/tags?site=codegolf\&page={1..99}|zcat|jq .items[].name
```
Testing this blew through my daily API requests limit pretty quick. |
223,880 | *Huge omega thanks to @wasif for emailing me this challenge idea in its basic form*
Everyone knows that questions on StackExchange require tags - labels that allow posts to be grouped together by category. However, most of the time, I barely know which tags exist, because there's just *so many* of them.
Henceforth, today's task is to tell me every single tag that exists on the Code Golf and Coding Challenges Stack Exchange.
The Challenge
-------------
Write a program or function that prints/returns a list of all available tags on <https://codegolf.stackexchange.com>
As tags can be created/deleted at any time, simply hard-coding a list of tags is not a valid solution - the list must be correct at run-time regardless of when the program/function is executed.
The tags avaliable can be seen [here](https://codegolf.stackexchange.com/tags)
Rules
-----
* As this is an [internet](/questions/tagged/internet "show questions tagged 'internet'") challenge, internet connections are allowed. However, web requests can only be made to codegolf.stackexchange.com and api.stackexchange.com domains.
* Output can be given in any convenient and reasonable format.
* The tags can be in any order, so long as all current tags are returned.
* The exact name of the tags must be used (e.g. `code-golf` is valid, `code GOLF` is not valid.)
* And as usual, standard loopholes apply, shortest code wins
Example Program
---------------
```python
import urllib.request
import regex
pobj = regex.compile('rel="tag">(.*)</a>')
page_number = 2
req = urllib.request.urlopen(f"https://codegolf.stackexchange.com/tags?page=1&tab=name")
data = req.read().decode('utf-8')
tags = []
while data.count("tag") != 43:
tags += pobj.findall(data)
req = urllib.request.urlopen(f"https://codegolf.stackexchange.com/tags?page={page_number}&tab=name")
data = req.read().decode('utf-8')
page_number += 1
print(tags)
``` | 2021/04/20 | [
"https://codegolf.stackexchange.com/questions/223880",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/78850/"
] | JavaScript (Firefox chrome), 135 bytes
======================================
```javascript
f=async(i=1)=>(await((await fetch('http://codegolf.stackexchange.com/tags?page='+i)).text())).match(/[\w-]+(?=)/g).map(alert)|f(i+1)
```
1. ~~Open [Browser Console of Firefox](https://developer.mozilla.org/en-US/docs/Tools/Browser_Console);~~ You may however open console on this page instead;
2. Paste codes there;
3. Invoke it by running `f()`;
4. Click to close many many `alert`'s
---
Source codes for tags page contains line
```html
<a href="/questions/tagged/code-golf" class="post-tag" title="show questions tagged 'code-golf'" rel="tag">code-golf</a>
```
We match the text `code-golf` between `'` by `/[\w-]+(?=)/g`.
The recursion terminate when ith page contains no tags. While the match result is null, and `.map` on `null` cause an error. | [Bash](https://www.gnu.org/software/bash/) + wget + jq, 86
==========================================================
Assumes there are no more than 99 pages of results (currently 10 pages).
```bash
wget -qO- api.stackexchange.com/tags?site=codegolf\&page={1..99}|zcat|jq .items[].name
```
Testing this blew through my daily API requests limit pretty quick. |
223,880 | *Huge omega thanks to @wasif for emailing me this challenge idea in its basic form*
Everyone knows that questions on StackExchange require tags - labels that allow posts to be grouped together by category. However, most of the time, I barely know which tags exist, because there's just *so many* of them.
Henceforth, today's task is to tell me every single tag that exists on the Code Golf and Coding Challenges Stack Exchange.
The Challenge
-------------
Write a program or function that prints/returns a list of all available tags on <https://codegolf.stackexchange.com>
As tags can be created/deleted at any time, simply hard-coding a list of tags is not a valid solution - the list must be correct at run-time regardless of when the program/function is executed.
The tags avaliable can be seen [here](https://codegolf.stackexchange.com/tags)
Rules
-----
* As this is an [internet](/questions/tagged/internet "show questions tagged 'internet'") challenge, internet connections are allowed. However, web requests can only be made to codegolf.stackexchange.com and api.stackexchange.com domains.
* Output can be given in any convenient and reasonable format.
* The tags can be in any order, so long as all current tags are returned.
* The exact name of the tags must be used (e.g. `code-golf` is valid, `code GOLF` is not valid.)
* And as usual, standard loopholes apply, shortest code wins
Example Program
---------------
```python
import urllib.request
import regex
pobj = regex.compile('rel="tag">(.*)</a>')
page_number = 2
req = urllib.request.urlopen(f"https://codegolf.stackexchange.com/tags?page=1&tab=name")
data = req.read().decode('utf-8')
tags = []
while data.count("tag") != 43:
tags += pobj.findall(data)
req = urllib.request.urlopen(f"https://codegolf.stackexchange.com/tags?page={page_number}&tab=name")
data = req.read().decode('utf-8')
page_number += 1
print(tags)
``` | 2021/04/20 | [
"https://codegolf.stackexchange.com/questions/223880",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/78850/"
] | [Jyxal 0.2.0](https://github.com/Vyxal/Jyxal/tree/0.2.0), 44 bytes
==================================================================
```
0{›:`ȯø.⟩β•∵.•⅛/ɾƈ?λ→=%&λẋ=¬⋎»₅`%¨UøJht(ntt,
```
[Jyxal-is-not-hosted-anywhere-so-read-the-readme-to-see-how-to-try-this](https://github.com/Vyxal/Jyxal/blob/master/README.md)
Fixed thanks to @emanresu A
Absolutely crushes 05AB1E. On my machine, it goes through the first 25 pages before getting a 403 and printing `4` forever. Unfortunately, Vyxal cannot decompress zipped responses so I kinda had to use Jyxal in place. This is heavily dependent on the ordering of the values in the JSON response.
```
0{›:`ȯø.⟩β•∵.•⅛/ɾƈ?λ→=%&λẋ=¬⋎»₅`%¨UøJht(ntt, # I don't need the 2 closing parens at the end.
0 # Push 0 (Jyxal does not have implicit input yet)
{ # Loop forever
› # And increment the number
% # Replace all "%" in the string...
`ȯø.⟩β•∵.•⅛/ɾƈ?λ→=%&λẋ=¬⋎»₅` # "api.stackexchange.com/tags?page=%&site=codegolf"
: # With the current loop index
¨U # Make a GET request to that URL...
øJ # And decode the JSON response
h # Get the first key-value pair...
t # And the second item; that is, the "items" array
(n # For each item in that array...
t # Get the last key-value pair and then...
t # Get the value
, # Print that value
``` | [Bash](https://www.gnu.org/software/bash/) + wget + jq, 86
==========================================================
Assumes there are no more than 99 pages of results (currently 10 pages).
```bash
wget -qO- api.stackexchange.com/tags?site=codegolf\&page={1..99}|zcat|jq .items[].name
```
Testing this blew through my daily API requests limit pretty quick. |
13,099 | Thank you for all the help [on my other question](https://salesforce.stackexchange.com/questions/13039/help-with-triggers-classes-for-case-creation-based-on-field-change-in-customer). I was so happy to see a community that doesn't have trolls.
So the good news is that the code compiles with no errors.
The bad news is that I have no code coverage and the trigger will not fire. I have moved the code over to my sandbox so I don't spill anything in production.
As stated in my previous question, this is my first Apex Project and the first time I have done any serious coding in (I'm embarassed to say) nearly 20 years.
Here is the updated code:
```
@isTest(SeeAllData=true)
public with sharing class FirmwareClass{
public void createCases(List<Customer_Asset__c> assets){
List<Case> casesToCreate = new List<Case>();
for(Customer_Asset__c acc:assets){
if (acc.Firmware_Update_Available__c == TRUE){
Case caseToAdd = new Case();
caseToAdd.AccountId = acc.Account__c;
caseToAdd.Subject = 'Software Upgrade Available';
casesToCreate.add(caseToAdd);
}
}
if (casesToCreate.size() > 0)
insert casesToCreate;
}
}
```
And the Trigger:
```
trigger FirmwareTrigger on Customer_Asset__c (after update) {
System.debug('@@@ trgInsertNote');
FirmwareClass helper = new FirmwareClass();
helper.createCases(Trigger.new);
}
```
The logic seems to work, I just can't get the trigger to fire. There are no validation rules in place to stop it. The only thing that seems to be stopping it from working is code coverage. | 2013/06/21 | [
"https://salesforce.stackexchange.com/questions/13099",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/3089/"
] | I came across similar situation and ended up with that it is a WAD. This error will be shown when we do not enter data in correct format. eg if in email we enter "abc" instead if we enter "abc@hjds.com" then we don't get error. Client side validation is the only workaround here.
Thanks | Do you have a user "profile" set up for sites users that includes access to your custom object? If not, you won't be able to access those objects from sites and will get an error message of the kind you're seeing.
Are these custom "objects" perhaps instead custom "fields" on say Opportunity or Accounts? If so, that could be the problem. If you're trying to access any fields (standard or custom) on Accounts, Opportunities, Events or Leads (and a few others), unless you have full partner licenses, you'll need to mirror them through a Custom Object that contains those fields and then sync them back to the primary object using triggers or batchable classes. |
13,099 | Thank you for all the help [on my other question](https://salesforce.stackexchange.com/questions/13039/help-with-triggers-classes-for-case-creation-based-on-field-change-in-customer). I was so happy to see a community that doesn't have trolls.
So the good news is that the code compiles with no errors.
The bad news is that I have no code coverage and the trigger will not fire. I have moved the code over to my sandbox so I don't spill anything in production.
As stated in my previous question, this is my first Apex Project and the first time I have done any serious coding in (I'm embarassed to say) nearly 20 years.
Here is the updated code:
```
@isTest(SeeAllData=true)
public with sharing class FirmwareClass{
public void createCases(List<Customer_Asset__c> assets){
List<Case> casesToCreate = new List<Case>();
for(Customer_Asset__c acc:assets){
if (acc.Firmware_Update_Available__c == TRUE){
Case caseToAdd = new Case();
caseToAdd.AccountId = acc.Account__c;
caseToAdd.Subject = 'Software Upgrade Available';
casesToCreate.add(caseToAdd);
}
}
if (casesToCreate.size() > 0)
insert casesToCreate;
}
}
```
And the Trigger:
```
trigger FirmwareTrigger on Customer_Asset__c (after update) {
System.debug('@@@ trgInsertNote');
FirmwareClass helper = new FirmwareClass();
helper.createCases(Trigger.new);
}
```
The logic seems to work, I just can't get the trigger to fire. There are no validation rules in place to stop it. The only thing that seems to be stopping it from working is code coverage. | 2013/06/21 | [
"https://salesforce.stackexchange.com/questions/13099",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/3089/"
] | I came across similar situation and ended up with that it is a WAD. This error will be shown when we do not enter data in correct format. eg if in email we enter "abc" instead if we enter "abc@hjds.com" then we don't get error. Client side validation is the only workaround here.
Thanks | Please check your field level security and also if you are setting form field values with jquery or javascript than don't make them hidden.
Hope this will help you. |
13,099 | Thank you for all the help [on my other question](https://salesforce.stackexchange.com/questions/13039/help-with-triggers-classes-for-case-creation-based-on-field-change-in-customer). I was so happy to see a community that doesn't have trolls.
So the good news is that the code compiles with no errors.
The bad news is that I have no code coverage and the trigger will not fire. I have moved the code over to my sandbox so I don't spill anything in production.
As stated in my previous question, this is my first Apex Project and the first time I have done any serious coding in (I'm embarassed to say) nearly 20 years.
Here is the updated code:
```
@isTest(SeeAllData=true)
public with sharing class FirmwareClass{
public void createCases(List<Customer_Asset__c> assets){
List<Case> casesToCreate = new List<Case>();
for(Customer_Asset__c acc:assets){
if (acc.Firmware_Update_Available__c == TRUE){
Case caseToAdd = new Case();
caseToAdd.AccountId = acc.Account__c;
caseToAdd.Subject = 'Software Upgrade Available';
casesToCreate.add(caseToAdd);
}
}
if (casesToCreate.size() > 0)
insert casesToCreate;
}
}
```
And the Trigger:
```
trigger FirmwareTrigger on Customer_Asset__c (after update) {
System.debug('@@@ trgInsertNote');
FirmwareClass helper = new FirmwareClass();
helper.createCases(Trigger.new);
}
```
The logic seems to work, I just can't get the trigger to fire. There are no validation rules in place to stop it. The only thing that seems to be stopping it from working is code coverage. | 2013/06/21 | [
"https://salesforce.stackexchange.com/questions/13099",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/3089/"
] | I came across similar situation and ended up with that it is a WAD. This error will be shown when we do not enter data in correct format. eg if in email we enter "abc" instead if we enter "abc@hjds.com" then we don't get error. Client side validation is the only workaround here.
Thanks | Do check the Data Type against the input field.
If your data type is number and your submitting a text then
"We're unable to retrieve your data due to an error." messages is shown.
The value should match against the data type of an object and validation
for the same can be done on client side.
May be this should help |
13,099 | Thank you for all the help [on my other question](https://salesforce.stackexchange.com/questions/13039/help-with-triggers-classes-for-case-creation-based-on-field-change-in-customer). I was so happy to see a community that doesn't have trolls.
So the good news is that the code compiles with no errors.
The bad news is that I have no code coverage and the trigger will not fire. I have moved the code over to my sandbox so I don't spill anything in production.
As stated in my previous question, this is my first Apex Project and the first time I have done any serious coding in (I'm embarassed to say) nearly 20 years.
Here is the updated code:
```
@isTest(SeeAllData=true)
public with sharing class FirmwareClass{
public void createCases(List<Customer_Asset__c> assets){
List<Case> casesToCreate = new List<Case>();
for(Customer_Asset__c acc:assets){
if (acc.Firmware_Update_Available__c == TRUE){
Case caseToAdd = new Case();
caseToAdd.AccountId = acc.Account__c;
caseToAdd.Subject = 'Software Upgrade Available';
casesToCreate.add(caseToAdd);
}
}
if (casesToCreate.size() > 0)
insert casesToCreate;
}
}
```
And the Trigger:
```
trigger FirmwareTrigger on Customer_Asset__c (after update) {
System.debug('@@@ trgInsertNote');
FirmwareClass helper = new FirmwareClass();
helper.createCases(Trigger.new);
}
```
The logic seems to work, I just can't get the trigger to fire. There are no validation rules in place to stop it. The only thing that seems to be stopping it from working is code coverage. | 2013/06/21 | [
"https://salesforce.stackexchange.com/questions/13099",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/3089/"
] | I came across similar situation and ended up with that it is a WAD. This error will be shown when we do not enter data in correct format. eg if in email we enter "abc" instead if we enter "abc@hjds.com" then we don't get error. Client side validation is the only workaround here.
Thanks | There are a few different possibilities that I can think of:
1. It could be that the Site's Guest User does not have the correct permissions on the Object (CRUD) or Object's fields (Field Level Security). Note that this is NOT the Site Contributor or Site Publisher user that you use to construct the Site. You can see the permissions by navigating to the Site Configuration page and clicking on the Guest User Profile. Clicking on the Guest User Profile will take you to a normal profile edit screen where you can check CRUD and FLS. Obviously you need Create and Read to use a form.

2. The data connection needs to be repaired. See [this page in the docs](http://help.salesforce.com/apex/HTViewHelpDoc?id=siteforce_data_repair.htm&language=en_US). It can happen if:
2.1 Field has been renamed since the form was created.
2.2 Field has been deleted since the form was created.
2.3 Field has been made not visible since the form was created.
2.4 A new required field has been added to the object since the form was created.
2.5 Permissions have changed since the form was created.
3. Something else. You set up a debug log for the Site User. In the Lookup dialog type the name (or beginning of the name) of the Site Guest User. It should be in the form or Site Name Site Guest User, e.g., for a site named Test Site, it would be Test Site Site Guest User. You can also get the user's name from the profile page, by clicking the View Users button. Here's an example of the debug log Lookup:
 |
64,085,248 | I have the following doubt
First code:
```
x= 'ab'
y = 'cd'
z = 'ef'
for i,j in x,y :
print (i,j)
>>> Output : a b
c d
```
>
> Variable 'i' is : a c , and variable 'j' is : b d
>
>
>
Second code:
```
x= 'ab'
y = 'cd'
z = 'ef'
for i,j in x,y,z:
print (i,j)
>>> Output : a b
c d
e f
```
>
> Variable 'i' is : a c e, and variable 'j' : b d f
>
>
>
. . and so on.
Now look this:
```
x= 'ab'
y = 'cd'
z = 'ef'
for i,j in x :
print (i,j)
>>> Output : error not enough values to unpack
```
Why I can't get : a b , where :
>
> Variable 'i' is : a, and variable 'j' : b
>
>
>
Im very confused. | 2020/09/27 | [
"https://Stackoverflow.com/questions/64085248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6091910/"
] | The problem is that "in x" iterates through the string, *as a string*. The first iteration returns `a`; the second returns `b`. Each single character is "not enough values to unpack". Simply
```
i, j = x
```
works as you want. Note that, in the other loops, you iterated through a *tuple* of strings; this is not the same as iterating through a single string. | You can try something like this:
```py
x = 'ab'
y = 'cd'
z = 'ef'
i, j = x
print(i, j)
``` |
64,085,248 | I have the following doubt
First code:
```
x= 'ab'
y = 'cd'
z = 'ef'
for i,j in x,y :
print (i,j)
>>> Output : a b
c d
```
>
> Variable 'i' is : a c , and variable 'j' is : b d
>
>
>
Second code:
```
x= 'ab'
y = 'cd'
z = 'ef'
for i,j in x,y,z:
print (i,j)
>>> Output : a b
c d
e f
```
>
> Variable 'i' is : a c e, and variable 'j' : b d f
>
>
>
. . and so on.
Now look this:
```
x= 'ab'
y = 'cd'
z = 'ef'
for i,j in x :
print (i,j)
>>> Output : error not enough values to unpack
```
Why I can't get : a b , where :
>
> Variable 'i' is : a, and variable 'j' : b
>
>
>
Im very confused. | 2020/09/27 | [
"https://Stackoverflow.com/questions/64085248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6091910/"
] | In the first piece of code, you iterate on the tuple of strings `(x, y)` (you didn't write the parentheses, but the comma makes the tuple, not the parentheses).
So it boils down to:
```
for two_letters_string in (x, y):
...
```
You do a second thing here: instead of `two_letters_string`, you used a tuple `(i, j)` as variable. So, Python will unpack the two letters string, and the first letter ends up in `i`, the second in `j`.
The same happens in the second piece of code. You just have one more loop and iterate on one more string.
The last piece of code is very different: you don't iterate on a tuple of strings, but on a string made of 2 characters. Iterating on a string iterates on its characters, so it will yield `'a'` on the first loop and `'b'` on the second. But you try to unpack these one-character strings into two variables `i` and `j`, which is not possible.
Note that this works:
```
x = 'ab'
for i, j in x, : # Note the comma after x!
print (i, j)
# a b
```
as the comma after `x` creates a tuple of one item. You are in the same situation as in the first two cases, but with only one loop here. | You can try something like this:
```py
x = 'ab'
y = 'cd'
z = 'ef'
i, j = x
print(i, j)
``` |
64,085,248 | I have the following doubt
First code:
```
x= 'ab'
y = 'cd'
z = 'ef'
for i,j in x,y :
print (i,j)
>>> Output : a b
c d
```
>
> Variable 'i' is : a c , and variable 'j' is : b d
>
>
>
Second code:
```
x= 'ab'
y = 'cd'
z = 'ef'
for i,j in x,y,z:
print (i,j)
>>> Output : a b
c d
e f
```
>
> Variable 'i' is : a c e, and variable 'j' : b d f
>
>
>
. . and so on.
Now look this:
```
x= 'ab'
y = 'cd'
z = 'ef'
for i,j in x :
print (i,j)
>>> Output : error not enough values to unpack
```
Why I can't get : a b , where :
>
> Variable 'i' is : a, and variable 'j' : b
>
>
>
Im very confused. | 2020/09/27 | [
"https://Stackoverflow.com/questions/64085248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6091910/"
] | The problem is that "in x" iterates through the string, *as a string*. The first iteration returns `a`; the second returns `b`. Each single character is "not enough values to unpack". Simply
```
i, j = x
```
works as you want. Note that, in the other loops, you iterated through a *tuple* of strings; this is not the same as iterating through a single string. | that's happening because you are given on the loop 2 items i, j
try this now:
```
x= 'ab'
y = 'cd'
z = 'ef'
for i in x :
print (i)
``` |
64,085,248 | I have the following doubt
First code:
```
x= 'ab'
y = 'cd'
z = 'ef'
for i,j in x,y :
print (i,j)
>>> Output : a b
c d
```
>
> Variable 'i' is : a c , and variable 'j' is : b d
>
>
>
Second code:
```
x= 'ab'
y = 'cd'
z = 'ef'
for i,j in x,y,z:
print (i,j)
>>> Output : a b
c d
e f
```
>
> Variable 'i' is : a c e, and variable 'j' : b d f
>
>
>
. . and so on.
Now look this:
```
x= 'ab'
y = 'cd'
z = 'ef'
for i,j in x :
print (i,j)
>>> Output : error not enough values to unpack
```
Why I can't get : a b , where :
>
> Variable 'i' is : a, and variable 'j' : b
>
>
>
Im very confused. | 2020/09/27 | [
"https://Stackoverflow.com/questions/64085248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6091910/"
] | In the first piece of code, you iterate on the tuple of strings `(x, y)` (you didn't write the parentheses, but the comma makes the tuple, not the parentheses).
So it boils down to:
```
for two_letters_string in (x, y):
...
```
You do a second thing here: instead of `two_letters_string`, you used a tuple `(i, j)` as variable. So, Python will unpack the two letters string, and the first letter ends up in `i`, the second in `j`.
The same happens in the second piece of code. You just have one more loop and iterate on one more string.
The last piece of code is very different: you don't iterate on a tuple of strings, but on a string made of 2 characters. Iterating on a string iterates on its characters, so it will yield `'a'` on the first loop and `'b'` on the second. But you try to unpack these one-character strings into two variables `i` and `j`, which is not possible.
Note that this works:
```
x = 'ab'
for i, j in x, : # Note the comma after x!
print (i, j)
# a b
```
as the comma after `x` creates a tuple of one item. You are in the same situation as in the first two cases, but with only one loop here. | that's happening because you are given on the loop 2 items i, j
try this now:
```
x= 'ab'
y = 'cd'
z = 'ef'
for i in x :
print (i)
``` |
355,124 | I have a Mac running OS X 10.5 that has a Windows XP boot camp partition that will no longer boots and is throwing me input/output errors when I attempt to view the Bootcamp partition in Terminal. My first priority is backing up everything off this partition.
What are some methods I can use to copy over the files to an external disk? I'm looking for something that will hop over the io errors and grab as much as possible.
Basically, I can boot into the Mac OS X without problem and the Bootcamp partition appears. However, browsing the Bootcamp partition in Finder or viewing the files in Terminal is slow and problematic (io errors). Any advice on getting those files out as quickly as possible is appreciated. | 2011/11/08 | [
"https://superuser.com/questions/355124",
"https://superuser.com",
"https://superuser.com/users/104577/"
] | A possible link to live video has been reported over the last couple of days. It is possible that you have no firewall set on your router.
Enter this in search - it has an uninstaller at this location:
```
C:\users\Your_User_Name\appdata\local\akamai\
```
I do not know if you should let it pass. That would depend on what you would need it for, if at all.
[This site](http://www.akamai.com/html/misc/akamai_client/netsession_interface_faq.html) claims to be the source. All information was from [this site](http://truxtertech.com/news/) and it has much more detail. It does not sound like it is a highly dangerous type, but you can never be too careful. | It is reported to be harmless, but no one remembers ever authorizing the software to install. I myself uninstalled it and everything has been running fine since.
I have been told that other people are using this software, bundled with some new virus, it's yet another exploit using someone's harmless software. |
355,124 | I have a Mac running OS X 10.5 that has a Windows XP boot camp partition that will no longer boots and is throwing me input/output errors when I attempt to view the Bootcamp partition in Terminal. My first priority is backing up everything off this partition.
What are some methods I can use to copy over the files to an external disk? I'm looking for something that will hop over the io errors and grab as much as possible.
Basically, I can boot into the Mac OS X without problem and the Bootcamp partition appears. However, browsing the Bootcamp partition in Finder or viewing the files in Terminal is slow and problematic (io errors). Any advice on getting those files out as quickly as possible is appreciated. | 2011/11/08 | [
"https://superuser.com/questions/355124",
"https://superuser.com",
"https://superuser.com/users/104577/"
] | A possible link to live video has been reported over the last couple of days. It is possible that you have no firewall set on your router.
Enter this in search - it has an uninstaller at this location:
```
C:\users\Your_User_Name\appdata\local\akamai\
```
I do not know if you should let it pass. That would depend on what you would need it for, if at all.
[This site](http://www.akamai.com/html/misc/akamai_client/netsession_interface_faq.html) claims to be the source. All information was from [this site](http://truxtertech.com/news/) and it has much more detail. It does not sound like it is a highly dangerous type, but you can never be too careful. | Scott Hanselman has a write up of this that can be found [here](http://www.hanselman.com/blog/CSIMyComputerWhatIsNetsessionwinexeFromAkamaiAndHowDidItGetOnMySystem.aspx). He explains how he found it and what he's found out about it.
Summary seems to be that it is signed by Akamai (CDN company) and probably bundled as part of Flash. What it does we don't know! It's official website is [here](http://www.akamai.com/client). |
994,414 | Call a triple-x number an integer $k$ such that $k=x(x+1)(x+2)$ where $x \in Z$. How many triple-x numbers are there between 0 and 100,000?
I thought by doing $8!$ and $9!$ would work to see how many combinations there would be. I am not sure how to solve this problem. Can someone show me how to solve this? | 2014/10/28 | [
"https://math.stackexchange.com/questions/994414",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/187869/"
] | First, let's note that for $x=-3$ or lower the product will be negative and thus, there aren't any values lower than this. $x=-2,-1,0$ all give the same value of 0. Note that $46\*47\*48=103776$ while $45\*46\*47=97290$ which would give 45 as the highest bound and 0 is the lowest, thus producing 46 numbers assuming that the ends are inclusive. | Well, there's one with $x = 0$, one with $x = 1$, and keep going until you get something bigger than $100,000$. Equivalently, you're solving the inequality $x(x+1)(x+2) < 100,000$, which can be done in various ways (though there's no really *clean* way of doing it). |
5,449,470 | How do I structure my data such that say, there is one question that associates with 5 choices, and each choice has a vote associated with it? if you think of it like a tree, the question is the root which has 5 leaves,the choices, and each choice has only one leaf, votes.
```
var myJSONObject = {"bindings": [
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
{"ircEvent": "PRIVMSG", "method":
```
the reason why I want to do this is that i want to have a tree-wise structure after I stringify my javascript. the piece of code above is from JSON.org, I guess I want the structure like that "bindings" has 3 ircEvents(leaves), I just dont know how to build this from backward(from javascript) Thank you | 2011/03/27 | [
"https://Stackoverflow.com/questions/5449470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/624392/"
] | **See update below**
If you have a JavaScript object already, use `JSON.stringify` on it to get the equivalent JSON string. There's an implementation of `JSON.stringify` in json2.js by Douglas Crockford (originator of JSON) [on his github page](https://github.com/douglascrockford/JSON-js/). An increasing number of browsers have it built in now that it's been standardized, but many (many) do not, so for now we still do have to use a utility script (Crockford's or another one).
Fundamentally, it's quite easy to generate JSON from an object graph (that was one of the points of JSON, to be something easily produced and consumed).
JSON is a subset of JavaScript Object Literal notation. So this JavaScript (not JSON) object:
```
{"bindings": [
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"}
]
}
```
looks *exactly* like that in JSON. If you were going to put it inside a file you would read into memory or from a server or whatever, that's what you'd put. If you were going to embed a string containing JSON inside JavaScript code (perhaps an odd thing to do, but), you'd just wrap that in quotes:
```
var aJSONString = '{"bindings": [' +
'{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},' +
'{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"}' +
']' +
'}';
```
If you JavaScript literal had been written without quotes around the key names, or using single quotes, you'd have to change that because JSON requires specifically that key names and all strings be in double quotes. So this JavaScript object literal:
```
{foo: 'bar'}
```
becomes
```
{"foo": "bar"}
```
in JSON.
---
**Update**: Re your comment below: Sorry, I misunderstood the question.
Building tree structures in JavaScript is dead easy. JavaScript objects are fundamentally fairly freeform collections of key/value pairs (e.g., "maps" or "dictionaries"). So:
```
// Start with a blank object
var obj = {};
// Add a leaf to it
obj.foo = {};
// Add a leaf under the leaf, with the value 42
obj.foo.subfoo = 42;
// Add a new leave to the root; this one's an array with 1, 2, and 3 in it
obj.bar = [1, 2, 3];
alert(JSON.stringify(obj));
// '{"foo: {"subfoo": 42}, "bar": [1, 2, 3]}'
```
You can write that as a literal, of course, but I think you know that:
```
var obj = {
foo: {
subfoo: 42
},
bar: [1, 2, 3]
};
```
What you may not know is that the things on the right-hand side in a literal can be variables; their value will be used, just like with an assignment. So this gives me exactly the same `obj` as the above:
```
var fortytwo = 42;
var obj = {
foo: {
subfoo: fortytwo
},
bar: [1, 2, 3]
};
``` | Simplest way to convert JSON text to JS object use "eval()".
```
var obj = eval('(' + myJSONtext + ')');
```
However eval() has security issues as we can compile and execute any javascript code within it. Therefore "parse" is recomended to convert JSON text to JS object.
```
var obj = JSON.parse(myJSONtext);
```
To convert JS object to JSON Text use stringify.
```
var myJSONText = JSON.stringify(obj);
```
See here for more details. <http://json.org/js.html> |
119,813 | I would love to make something like this for personal use/as a printable, however, I lack the know-how to space the numbers and to neatly create the circles.
My goal:
Create a pdf file with several circles. One for the months, one for the days (numbers) and names of days. Plus ideally another circle to create an overlay effect (to single out the days & month)
<https://www.presentandcorrect.com/products/perpetual-wall-calendar>
<https://www.etsy.com/uk/listing/519833417/perpetual-calendar-wooden-perpetual>
<https://www.pinterest.co.uk/pin/20829217012627477/>
Problems I run into:
* Type on a path tool makes the circle disappear (I use a circle with no fill, just the stroke, I assume I need to use two circles to create one - one to place the text on, and one to have as the background colour, or could leave plain white)
* The numbers/text are not spaced properly. There surely must be a trick for this! But I'm not sure what I'm looking for/what it is called to space everything evenly.
* The text floats above the circle/outside of it. Stroke issues, but not sure how to fix it.
Any advice is much appreciated!!
Thanks | 2019/01/31 | [
"https://graphicdesign.stackexchange.com/questions/119813",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/132644/"
] | I'm not sure about whats your goal but to create a design similar to the examples you provided is quite simple.
1. Create a circle with the Ellipse tool (with the size you want to print) and create two more identical circles. Scale one of these circles down to 75% and the other down to 50%. You should create something like this:
[](https://i.stack.imgur.com/f2fga.png)
[](https://i.stack.imgur.com/0btHN.png)
2. Then select the middle circle and use the Scissors tool to open the path. Then use the Text tool to write the numbers / letters on the top of your new path. Adjust the space and size of your font.
[](https://i.stack.imgur.com/enLIX.png)
[](https://i.stack.imgur.com/F59wI.png)
3. Adjust the size of your donut by resizing and centering each circle
[](https://i.stack.imgur.com/uTbHz.png) | Obviously you cannot place texts and numbers consistently. This is one way to place them for a reading hole at three o'clock like in your first example:
[](https://i.stack.imgur.com/I5agS.jpg)
1. Write one day name. Be sure it's aligned to middle of the line in type settings. Left or right will fail. Draw about a rotating disk wide rectangle around it and place the name properly thinking the disk. I did it only approximately.
2. Make a rotated copy with Object > Transform > Rotate > Copy The rotation angle must be 360 degrees divided by 7 in this case
3. Make 5 more copies by pressing Ctrl+D. Group the results temporarily. You will need it as a group when you align the cirles later.
4. Draw three circles: The midpoint, the middle line of the texts and the outline of the disk
5. Ungroup the weekday name pack, delete the rectangles
6. Change the names, you may be forced to insert a space for better alignment or in other way to adjust the placement in type controlling panels. I added only a couple of spaces. The needed adjustments depend on used font. Constant width letters surely need nothing.
For better control you can inset 2 extra circles to show the width of the day reading hole.
[](https://i.stack.imgur.com/lbK24.jpg)
Radical changes in type character panel can make the text unpleasing, so try to select a font which doesn't need wide adjustments. This is one:
[](https://i.stack.imgur.com/C14zy.jpg) |
119,813 | I would love to make something like this for personal use/as a printable, however, I lack the know-how to space the numbers and to neatly create the circles.
My goal:
Create a pdf file with several circles. One for the months, one for the days (numbers) and names of days. Plus ideally another circle to create an overlay effect (to single out the days & month)
<https://www.presentandcorrect.com/products/perpetual-wall-calendar>
<https://www.etsy.com/uk/listing/519833417/perpetual-calendar-wooden-perpetual>
<https://www.pinterest.co.uk/pin/20829217012627477/>
Problems I run into:
* Type on a path tool makes the circle disappear (I use a circle with no fill, just the stroke, I assume I need to use two circles to create one - one to place the text on, and one to have as the background colour, or could leave plain white)
* The numbers/text are not spaced properly. There surely must be a trick for this! But I'm not sure what I'm looking for/what it is called to space everything evenly.
* The text floats above the circle/outside of it. Stroke issues, but not sure how to fix it.
Any advice is much appreciated!!
Thanks | 2019/01/31 | [
"https://graphicdesign.stackexchange.com/questions/119813",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/132644/"
] | I'm not sure about whats your goal but to create a design similar to the examples you provided is quite simple.
1. Create a circle with the Ellipse tool (with the size you want to print) and create two more identical circles. Scale one of these circles down to 75% and the other down to 50%. You should create something like this:
[](https://i.stack.imgur.com/f2fga.png)
[](https://i.stack.imgur.com/0btHN.png)
2. Then select the middle circle and use the Scissors tool to open the path. Then use the Text tool to write the numbers / letters on the top of your new path. Adjust the space and size of your font.
[](https://i.stack.imgur.com/enLIX.png)
[](https://i.stack.imgur.com/F59wI.png)
3. Adjust the size of your donut by resizing and centering each circle
[](https://i.stack.imgur.com/uTbHz.png) | Solutions for the problems you run into.
* Type on a path makes the path invisible. Yes you may need to create two more concentric circles in donut shape to get that background.
* Try the below approach to space the text evenly.
Follow the below steps to get the result you wanted in the first link you've given.
**Step 1:**
With the ellipse tool, make a perfect circle, and change it to a pie by changing the angle. In this case, I've taken 360°/7. (360° for the full circle degree and 7 for seven days of the week.)
[](https://i.stack.imgur.com/sMEtD.jpg)
**Step 2:**
With the Scissors tool (C), change the pie into an arc by trimming at either end of the arc. Turn on Dynamic Guides to help select the right point with ease.
[](https://i.stack.imgur.com/RjJYj.jpg)
**Step 3:**
With the Text tool (T) selected, click at one end of the arc, to make a text to path. Type in MON for the first day of the week. And Center Align the text.
[](https://i.stack.imgur.com/ECc7j.jpg)
**Step 4:**
With the Rotation tool (R) selected, Alt + Click at the end of the pie to make it as the Arc's rotation center.
[](https://i.stack.imgur.com/zaDq4.jpg)
**Step 5:**
Now rotate the Arc to 51.43° (360°/7) and copy it 6 times. That makes a total of 7 texts in Arcs in a complete circle.
[](https://i.stack.imgur.com/ecIva.jpg)[](https://i.stack.imgur.com/c22hh.jpg)
**Step 6:**
Edit the text to Weekdays.
[](https://i.stack.imgur.com/RVg3a.jpg)
* The text's baseline aligns with the path. You may try shifting the text's baseline in the Character panel.
[](https://i.stack.imgur.com/WtYC6.jpg) |
54,415,854 | I'm fetching the chart dynamically ..
This is `chart` of current month which ranges from 1-31
[](https://i.stack.imgur.com/98trd.png)
I want to have a `range filter` for example:
`2012/01/1 to 2014/01/1`
How can I do this `labels` will be too many?
Lets say I decide on doing it `yearly` but what if the user want to see from this `year` `jan` to `nov` i should make it monthly then how I can know? if its monthly or yearly or what is the best way to do this? | 2019/01/29 | [
"https://Stackoverflow.com/questions/54415854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6725765/"
] | As explained by the logs, the `install.sh` script is trying to locate a profile, which it could not found. (remember that the script provided in user-data is run as root, so $HOME is `/root`.
The solution is to either ensure the profile file will exist before installation, either to manually change the path after the installation, as suggested in the log message.
**Solution 1** (untested)
```
#!/bin/bash
touch ~/.bashrc # this ensure the bashrc file is created
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bash
source ~/.bashrc
nvm install 7
```
**Solution 2** (tested)
```
#!/bin/bash
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bash
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
nvm install 7
```
(when run from user-data, $HOME is /)
I tested the above in an interactive session on Amazon Linux.
```
$ ssh ec2-user@ec2-18-202-174-164.eu-west-1.compute.amazonaws.com
Warning: Permanently added 'ec2-18-202-174-164.eu-west-1.compute.amazonaws.com,18.202.174.164' (ECDSA) to the list of known hosts.
__| __|_ )
_| ( / Amazon Linux 2 AMI
___|\___|___|
https://aws.amazon.com/amazon-linux-2/
3 package(s) needed for security, out of 3 available
Run "sudo yum update" to apply all updates.
[ec2-user@ip-172-31-30-44 ~]$ sudo bash
[root@ip-172-31-30-44 ec2-user]# curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bash
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 10250 100 10250 0 0 10250 0 0:00:01 --:--:-- 0:00:01 54521
=> Downloading nvm as script to '/root/.nvm'
=> Appending source string to /root/.bashrc
=> Close and reopen your terminal to start using nvm or run the following to use it now:
export NVM_DIR="/root/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
[root@ip-172-31-30-44 ec2-user]#
[root@ip-172-31-30-44 ec2-user]# export NVM_DIR="$HOME/.nvm"
[root@ip-172-31-30-44 ec2-user]# [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
[root@ip-172-31-30-44 ec2-user]# nvm install 7
######################################################################## 100.0%
Computing checksum with sha256sum
Checksums matched!
Now using node v7.10.1 (npm v4.2.0)
Creating default alias: default -> 7 (-> v7.10.1)
[root@ip-172-31-30-44 ec2-user]# node --version
v7.10.1
```
Note that the above will install `nvm`, `node` and `npm` for the root user. It will not add the correct ENV VAR in `ec2-user`'s environment. To do so, login as `ec2-user` then either type
```
export NVM_DIR="/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
```
or add this to `ec2-user`'s `.bashrc`
The proof it works (login as `ec2-user` :
```
[ec2-user@ip-172-31-20-26 ~]$ export NVM_DIR="/.nvm"
[ec2-user@ip-172-31-20-26 ~]$ [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ec2-user@ip-172-31-20-26 ~]$ node --version && npm --version
v7.10.1
4.2.0
```
You can automate that in your `user-data` script :
```
cat <<EOF >> /home/ec2-user/.bashrc
export NVM_DIR="/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
EOF
``` | If we are using amazon linux, try to install the `nvm` version 16
```
#!/bin/bash
sudo su
cd ~
amazon-linux-extras install nginx1 -y
systemctl enable nginx
systemctl start nginx
touch ~/.bashrc
cat > /tmp/startup.sh << EOF
echo "Setting up NodeJS Environment"
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.39.0/install.sh | bash
echo 'export NVM_DIR="/home/ec2-user/.nvm"' >> /home/ec2-user/.bashrc
echo 'export NVM_DIR="/home/ec2-user/.nvm"' >> /home/ec2-user/.bash_profile
echo '[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm' >> /home/ec2-user/.bashrc
. /home/ec2-user/.nvm/nvm.sh
. /home/ec2-user/.bash_profile
. /home/ec2-user/.bashrc
# Install NVM, NPM, Node.JS & Grunt
nvm install 16
nvm ls
EOF
chown ec2-user:ec2-user /tmp/startup.sh && chmod a+x /tmp/startup.sh
sleep 1; su - ec2-user -c "/tmp/startup.sh"
``` |
54,415,854 | I'm fetching the chart dynamically ..
This is `chart` of current month which ranges from 1-31
[](https://i.stack.imgur.com/98trd.png)
I want to have a `range filter` for example:
`2012/01/1 to 2014/01/1`
How can I do this `labels` will be too many?
Lets say I decide on doing it `yearly` but what if the user want to see from this `year` `jan` to `nov` i should make it monthly then how I can know? if its monthly or yearly or what is the best way to do this? | 2019/01/29 | [
"https://Stackoverflow.com/questions/54415854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6725765/"
] | As explained by the logs, the `install.sh` script is trying to locate a profile, which it could not found. (remember that the script provided in user-data is run as root, so $HOME is `/root`.
The solution is to either ensure the profile file will exist before installation, either to manually change the path after the installation, as suggested in the log message.
**Solution 1** (untested)
```
#!/bin/bash
touch ~/.bashrc # this ensure the bashrc file is created
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bash
source ~/.bashrc
nvm install 7
```
**Solution 2** (tested)
```
#!/bin/bash
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bash
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
nvm install 7
```
(when run from user-data, $HOME is /)
I tested the above in an interactive session on Amazon Linux.
```
$ ssh ec2-user@ec2-18-202-174-164.eu-west-1.compute.amazonaws.com
Warning: Permanently added 'ec2-18-202-174-164.eu-west-1.compute.amazonaws.com,18.202.174.164' (ECDSA) to the list of known hosts.
__| __|_ )
_| ( / Amazon Linux 2 AMI
___|\___|___|
https://aws.amazon.com/amazon-linux-2/
3 package(s) needed for security, out of 3 available
Run "sudo yum update" to apply all updates.
[ec2-user@ip-172-31-30-44 ~]$ sudo bash
[root@ip-172-31-30-44 ec2-user]# curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bash
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 10250 100 10250 0 0 10250 0 0:00:01 --:--:-- 0:00:01 54521
=> Downloading nvm as script to '/root/.nvm'
=> Appending source string to /root/.bashrc
=> Close and reopen your terminal to start using nvm or run the following to use it now:
export NVM_DIR="/root/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
[root@ip-172-31-30-44 ec2-user]#
[root@ip-172-31-30-44 ec2-user]# export NVM_DIR="$HOME/.nvm"
[root@ip-172-31-30-44 ec2-user]# [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
[root@ip-172-31-30-44 ec2-user]# nvm install 7
######################################################################## 100.0%
Computing checksum with sha256sum
Checksums matched!
Now using node v7.10.1 (npm v4.2.0)
Creating default alias: default -> 7 (-> v7.10.1)
[root@ip-172-31-30-44 ec2-user]# node --version
v7.10.1
```
Note that the above will install `nvm`, `node` and `npm` for the root user. It will not add the correct ENV VAR in `ec2-user`'s environment. To do so, login as `ec2-user` then either type
```
export NVM_DIR="/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
```
or add this to `ec2-user`'s `.bashrc`
The proof it works (login as `ec2-user` :
```
[ec2-user@ip-172-31-20-26 ~]$ export NVM_DIR="/.nvm"
[ec2-user@ip-172-31-20-26 ~]$ [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ec2-user@ip-172-31-20-26 ~]$ node --version && npm --version
v7.10.1
4.2.0
```
You can automate that in your `user-data` script :
```
cat <<EOF >> /home/ec2-user/.bashrc
export NVM_DIR="/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
EOF
``` | After spending several hours on an exercise, this worked for me.
```bash
#!/bin/bash
touch ~/.bashrc
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
source ~/.bashrc
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
nvm install --lts
``` |
54,415,854 | I'm fetching the chart dynamically ..
This is `chart` of current month which ranges from 1-31
[](https://i.stack.imgur.com/98trd.png)
I want to have a `range filter` for example:
`2012/01/1 to 2014/01/1`
How can I do this `labels` will be too many?
Lets say I decide on doing it `yearly` but what if the user want to see from this `year` `jan` to `nov` i should make it monthly then how I can know? if its monthly or yearly or what is the best way to do this? | 2019/01/29 | [
"https://Stackoverflow.com/questions/54415854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6725765/"
] | If we are using amazon linux, try to install the `nvm` version 16
```
#!/bin/bash
sudo su
cd ~
amazon-linux-extras install nginx1 -y
systemctl enable nginx
systemctl start nginx
touch ~/.bashrc
cat > /tmp/startup.sh << EOF
echo "Setting up NodeJS Environment"
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.39.0/install.sh | bash
echo 'export NVM_DIR="/home/ec2-user/.nvm"' >> /home/ec2-user/.bashrc
echo 'export NVM_DIR="/home/ec2-user/.nvm"' >> /home/ec2-user/.bash_profile
echo '[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm' >> /home/ec2-user/.bashrc
. /home/ec2-user/.nvm/nvm.sh
. /home/ec2-user/.bash_profile
. /home/ec2-user/.bashrc
# Install NVM, NPM, Node.JS & Grunt
nvm install 16
nvm ls
EOF
chown ec2-user:ec2-user /tmp/startup.sh && chmod a+x /tmp/startup.sh
sleep 1; su - ec2-user -c "/tmp/startup.sh"
``` | After spending several hours on an exercise, this worked for me.
```bash
#!/bin/bash
touch ~/.bashrc
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
source ~/.bashrc
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
nvm install --lts
``` |
36,299,342 | I have a simple form with only 1 input field. For each input a new object is created.This is my method for adding new objects. I am looking for Angular way to add IDs to these objects, what would you suggest?
```
$scope.addToDoItem = function(){
var toDoItems = $scope.toDoItems;
var newToDoItem = {
"id" : // id should be generated here
"content" : $scope.toDoItem,
"createdAt" : Date.now()
}
toDoItems.push(newToDoItem);
ls.set("toDoData", toDoItems);
$scope.toDoItem = "";
};
```
The view:
```
<form>
<input type="text" ng-model="toDoItem">
<input type="submit" ng-click="addToDoItem()">
</form>
``` | 2016/03/30 | [
"https://Stackoverflow.com/questions/36299342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5426743/"
] | I don't think there is "angular way" of doing it.
However, currently you are using the milliseconds for `createdAt` value, so you can use the same value for Id as well. If you don't have application where new value can be added more frequently you will have your unique value:
```
var currentDate = Date.now();
var newToDoItem = {
"id" : currentDate
"content" : $scope.toDoItem,
"createdAt" : currentDate
}
```
The downside is that the ID values will be large and they will not come in order. If you want values to be 1, 2, 3, etc, then you can create variable for maximum ID in your controller and use it to increase the value:
```
var maxId = 0;
//if you need to restore maxId you can use
//var maxId = $scope.toDoItems.reduce(function(max,cur){return Math.max(max,cur.id); },0);
$scope.addToDoItem = function(){
var toDoItems = $scope.toDoItems;
maxId++;
var newToDoItem = {
"id" : maxId,
"content" : $scope.toDoItem,
"createdAt" : Date.now()
}
toDoItems.push(newToDoItem);
ls.set("toDoData", toDoItems);
$scope.toDoItem = "";
};
``` | if you want a random hash you could also do this
```
$scope.addToDoItem = function() {
var toDoItems = $scope.toDoItems;
var newToDoItem = {
"id": function randString() {
var x = 32; // hashlength
var s = "";
while (s.length < x && x > 0) {
var r = Math.random();
s += (r < 0.1 ? Math.floor(r * 100) : String.fromCharCode(Math.floor(r * 26) + (r > 0.5 ? 97 : 65)));
}
return s;
},
"content": $scope.toDoItem,
"createdAt": Date.now()
}
toDoItems.push(newToDoItem);
ls.set("toDoData", toDoItems);
$scope.toDoItem = "";
};
``` |
34,066,626 | Working on a project for my web design class and can't figure out where all this white space is coming from. Everything needs to touch each other yet I think I have extra padding somewhere but I just can't seem to pinpoint it. Here is all my code. Also, I'd like to know how to get rid of the bullets in my `<ul>` on the left. I've tried `list-style-type:none` but that doesn't seem to do anything.
```
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>SylviaGunter WEB-210 Project 6</title>
<meta name="viewport" content="width=device-width">
<link href='https://fonts.googleapis.com/css?family=Peralta' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Gochi+Hand|Peralta' rel='stylesheet' type='text/css'>
<link rel="stylesheet"
href=01%20-%20Large%20CSS.css>
<link rel="stylesheet" type="text/css" href="02 - Medium CSS">
<link rel="stylesheet" type="text/css" href="03 - Small CSS">
<link rel="stylesheet" type="text/css" href="04 - Print CSS">
<link rel="stylesheet" type="text/css" href="05 - IE">
</head>
<body>
<div class="wrapper">
<body>
<div class="banner">
<h1>Best TV Ever</h1>
<div class="topnav">
<ul>
<li><a href="#">50s</a></li>
<li><a href="#">60s</a></li>
<li><a href="#">70s</a></li>
<li><a href="#">80s</a></li>
<li><a href="#">90s</a></li>
</ul>
</div>
</div>
</body>
[insert menu toggle here]
[insert menu checkbox here]
<aside class="sidebar1">
Best Prime Time Shows
<ul>
<li><a href="#">Alice</a></li>
<li><a href="#">All In The Family</a></li>
<li><a href="#">Barney Miller</a></li>
<li><a href="#">Beverly Hillbillies</a></li>
<li><a href="#">Bewitched</a></li>
<li><a href="#">The Bob Newhart Show</a></li>
<li><a href="#">The Brady Bunch</a></li>
<li><a href="#">Gilligan's Island</a></li>
<li><a href="#">Good Times</a></li>
<li><a href="#">The Love Boat</a></li>
<li><a href="#">Mary Tyler Moore</a></li>
<li><a href="#">M*A*S*H</a></li>
<li><a href="#">Maude</a></li>
<li><a href="#">One Day At A Time</a></li>
<li><a href="#">Petticoat Junction</a></li>
<li><a href="#">Soap</a></li>
<li><a href="#">Taxi</a></li>
<li><a href="#">What's Happening</a></li>
<li><a href="#">Welcome Back Kotter</a></li>
<li><a href="#">WKRP In Cincinatti</a></li>
</ul>
</aside>
<article class="main">
<h2>The Genius of Krofft</h2>
<h3>H.R. Pufnstuff</h3>
<p> <img src="hrpufnstuff.jpg" alt="hrpufnstuff" height="150" width="200">H.R. Pufnstuf centered on a shipwrecked boy named Jimmy. He and his friend, a talking flute named Freddy, take a ride on a mysterious boat, which promised adventures across the sea, to Living Island. The Mayor of Living Island was a friendly and helpful dragon named H.R. Pufnstuf. The boat was actually owned and controlled by a wicked witch named Wilhelmina W. Witchiepoo who rode on a broomstick-like vehicle called the Vroom Broom. She used the boat to lure Jimmy and Freddy to her castle on Living Island, where she was going to take Jimmy prisoner and steal Freddy. But Pufnstuf found out about her plot and was able to rescue Jimmy when he leaped out of the enchanted boat with Freddy and swam ashore.</p>
<h3>Lidsville</h3>
<p><img src="lidsville.jpg" alt="lidsville" height="150" width="200">
The show involved a teenage boy named Mark who fell into the hat of Merlo the Magician and arrived in Lidsville, a land of living hats. The hats on the show are depicted as having the same characteristics as the humans who would normally wear them.</p>
<h3>The Bugaloos</h3>
<p><img src="bugaloos.jpg" alt="bugaloos" height="150" width="200">The Bugaloos featured a musical group composed of four British-accented teenagers, who lived in fictional Tranquility Forest. They wore insect-themed outfits with antennae and wings which allowed them to fly. They were constantly beset by the evil machinations of Benita Bizarre, played by comedienne Martha Raye.</p>
<h3>Land of the Lost</h3>
<p><img src="landlost.jpg" alt="landlost" height="150" width="200">Land of the Lost details the adventures of the Marshall family (father Rick and his teenage children Will and Holly) who are trapped in an alternate universe inhabited by dinosaurs, a primate-type people called Pakuni, and aggressive humanoid/lizard creatures called Sleestak.</p>
<h3>Sigmund the Sea Monster</h3>
<p><img src="sigmund.jpg" alt="sigmund" height="150" width="200">The show centered on two brothers, Johnny and Scott Stuart, who discover Sigmund, a friendly young sea monster who had been thrown out by his comically dysfunctional undersea family for refusing to frighten people. The boys hide Sigmund in their clubhouse.</p>
</article>
<aside class="sidebar2">
Best Superhero Shows
<ul>
<li><a href="#">Batman (1966)</a></li>
<li><a href="#">The Bionic Woman (1976)</a></li>
<li><a href="#">Electra Woman and Dyna Girl (1976)</a></li>
<li><a href="#">The Greatest American Hero (1981)</a></li>
<li><a href="#">The Incredible Hulk (1977)</a></li>
<li><a href="#">Isis (1975)</a></li>
<li><a href="#">Shazam! (1974)</a></li>
<li><a href="#">The Six Million Dollar Man (1974)</a></li>
<li><a href="#">Wonder Woman (1976)</a></li>
</ul>
</aside>
<div id="footer">
Stop watching TV and write some code!
</div>
</body>
</html>
```
```
body{
}
.banner h1{
background-color: black;
background-image: url(logo.png);
background-repeat: no-repeat;
font-family: Peralta;
color: white;
height: 100px;
padding-top: 25px;
padding-left: 150px;}
h2{
font-family: Peralta;
text-align: center;
height: 25px;
background-color: white;
padding-top: 0;
height: 50px;
}
p{
border-bottom: 1px solid black;
padding-bottom: 3em;
display: block;
overflow: hidden;
height:130px;
}
img{
float: left;
margin-right: 1em;
width: 150px;
height: 100px;
padding-left: 10px;
border-radius: 20px;}
.topnav ul li {
display: inline-block;
float: right;
position: relative;
top: -120px;
}
.topnav ul li a:link{
text-decoration: none;
color: black;
background-color: white;
border-radius: 50%;
margin: 10px;
width: 100px;
font-size: 20px}
*{
-moz-box-sizing:border-box;
box-sizing: border-box;
}
.sidebar1{
float: left;
width: 265px;
padding: 0 20px 0 20px;
background: url(sidebar1background.jpg);
background-repeat: repeat-y;
height: 1000px;
}
.main{
float: left;
width: 60%;
padding: 0 20px 0 20px;
background-color: #d4ff80;
height: 1000px;
}
.sidebar2{
float: right;
width: 265px;
padding-right: 30px;
padding: 0 10px 0 20px;
background: url(sidebar2background.jpg)right top;
background-repeat: repeat-y;
height: 1000px;
list-style-type: none;
}
.sidebar1 a:link{
background-color: #c1c1a4;
border-radius: 20px;
border:1px solid white;
display: block;
background-size: 15px;
text-decoration: none;
width: 200px;
padding: 5px 5px 5px 35px;
margin-bottom: 10px;
color: darkgreen;
padding-right: 20px;
}
#footer{
clear: both;
height: 50px;
padding-top: 15px;
background-color: black;
color: white;
text-align: center;
}
``` | 2015/12/03 | [
"https://Stackoverflow.com/questions/34066626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5346865/"
] | You need a `group by`:
```
SELECT tickets.*, COUNT(sales.ID) AS tcount
FROM tickets LEFT JOIN
sales
ON tickets.ID = sales.ticket_ID
GROUP BY tickets.ID;
``` | Either switch the table orders or do a `RIGHT JOIN` instead. ie:
```
SELECT tickets.*,
COUNT(sales.ID) AS tcount
FROM sales LEFT JOIN tickets ON tickets.ID = sales.ticket_ID
```
or
```
SELECT tickets.*,
COUNT(sales.ID) AS tcount
FROM tickets RIGHT JOIN sales ON tickets.ID = sales.ticket_ID
``` |
33,383 | In the trinity the belief is that the Father is God, the Son is God, and the holy ghost is God.
The Father is a Person, and Son is a Person, and the holy Ghost is a Person.
And they all always existed, no beginning to any of the Persons.
Co-equal, co-substantial, co-eternal.
Now is the understanding that they have independent Will?
[Luke 22:42 | Bible Hub](http://biblehub.com/luke/22-42.htm)
>
> Father, if you are willing, take this cup from me; yet not my will,
> but yours be done
>
>
>
If they have different Will's, how can they still yet be All-Powerful?
Have they ever had different Will's?
Example when Jesus was in such distress and was calling out 'Why have your forsaken me' it would seem obvious his Will was to be saved?
What I am trying to get at is, if indeed they have different Will's, one of the Person's will want to overcome the other.
Interested to hear what theologians have said regarding this matter as it seems to be logically you can't get around this issue.
If you say that they don't have independant Will, then they are not All-Powerful.
**Example:**
Jesus wants A, Father wants B. Jesus wants to do what the Father pleases (B), and the Father wants to do what Jesus pleases (A). So do they choose A or B? And whenever either of them submits to anothers Will that would make them not having the attribute of All-Powerful.
It becomes more complicated when you bring in the 3rd Person.
Jesus wants A, the Father wants B and the holy ghost wants C. Now they all have to agree before doing something, and have to agree who will be submitted their will and forgoing their attribute of All-Powerful. | 2014/10/01 | [
"https://christianity.stackexchange.com/questions/33383",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/14745/"
] | Edit: removed old answer
I think this link will help explain what you are asking: [Was Jesus Limited While On Earth?](http://gracethrufaith.com/ask-a-bible-teacher/was-jesus-limited-while-on-earth/)
For future reference if that site or page disappears from the internet it is quoted below:
>
> ### Was Jesus Limited While On Earth?
>
>
> Wednesday, January 29th, 2014 tags:The Holy Spirit,Theology
>
>
> **Q.** I have a question about Our Lord when He was on earth. I have heard it said that His knowledge or power was limited on earth according to God the Father’s discretion. That is why Jesus frequently prayed to the Father or the scriptures say, “Not even the Son of Man knows” about a particular thing. Do you agree with this?
>
>
> **A.** I believe when Jesus agreed to become a man, He voluntarily set aside His Godly powers and limited Himself to the powers available to mankind. This is why He attributed His ability to perform miracles to the Holy Spirit (Matt. 12:28), was in daily prayer with the Father, claimed not to know certain things (Matt. 24:36), and promised us we could do even greater things than he had done (John 14:12).
>
>
> There are at least 3 reasons why we know this is true. First, God can’t be tempted (James 1:13), but Jesus was tempted in every way and yet was without sin. (Hebr. 4:15) Second, according to the Law of Redemption He had to become a man to redeem what Adam had lost (Lev. 25:25) and save us, and third He had to become a man so He could be put to death. It’s impossible to kill God.
>
>
>
>
>
>
> | In your question you appear to be overlooking two very important things.
1. Jesus was not only God, but he was also human.
2. Humans feel physical pain, even though Spirits do not.
In the Scriptures that you cite it must be remembered that Jesus was in an inordinate state. That is to say that the Deity Jesus was aware of the oncoming pain:
>
> Matthew 17:22 and 23 And while they abode in Galilee, Jesus said unto them, The Son of man shall be betrayed into the hands of men: 23 And they shall kill him, and the third day he shall be raised again. And they were exceeding sorry.
>
>
>
and as a man he would know just how painful that was going to be.
The plea to the father would have to come from the human part of Jesus, and it is not surprising that the man Jesus' will was not to go through all that torture and pain.
>
> Luke 22:41 through 44 And he was withdrawn from them about a stone's cast, and kneeled down, and prayed, 42 Saying, Father, if thou be willing, remove this cup from me: nevertheless not my will, but thine, be done. 43 And there appeared an angel unto him from heaven, strengthening him. 44 And being in an agony he prayed more earnestly: ***and his sweat was as it were great drops of blood falling down to the ground.***
>
>
>
This is a physical human phenomenon, and Medical Doctors have witnessed blood emitting from pores of people under extreme anxiety. Jesus would have had to fit into that category; having the foreknowledge of his torture and death on the cross.
As far as:
>
> Matthew 27:46 And about the ninth hour Jesus cried with a loud voice, saying, Eli, Eli, lama sabachthani? that is to say, My God, my God, why hast thou forsaken me?
>
>
>
God cannot look upon sin, and when Jesus became sinful by assuming our sins, he was forsaken by God. and it is imperative that we understand that God was forsaking the man Jesus on the cross, and that means all three of the Trinity were abandoning his physical man.
I know that there are going to be many comments concerning how Jesus could abandon himself, but that is not the case. The eternal son which was present at creation abandoned the physical body it had been inhabiting while on earth. consider:
>
> John 1:1 In the beginning was the Word, and the Word was with God, and the Word was God.
>
>
>
Hope this helps. |
33,383 | In the trinity the belief is that the Father is God, the Son is God, and the holy ghost is God.
The Father is a Person, and Son is a Person, and the holy Ghost is a Person.
And they all always existed, no beginning to any of the Persons.
Co-equal, co-substantial, co-eternal.
Now is the understanding that they have independent Will?
[Luke 22:42 | Bible Hub](http://biblehub.com/luke/22-42.htm)
>
> Father, if you are willing, take this cup from me; yet not my will,
> but yours be done
>
>
>
If they have different Will's, how can they still yet be All-Powerful?
Have they ever had different Will's?
Example when Jesus was in such distress and was calling out 'Why have your forsaken me' it would seem obvious his Will was to be saved?
What I am trying to get at is, if indeed they have different Will's, one of the Person's will want to overcome the other.
Interested to hear what theologians have said regarding this matter as it seems to be logically you can't get around this issue.
If you say that they don't have independant Will, then they are not All-Powerful.
**Example:**
Jesus wants A, Father wants B. Jesus wants to do what the Father pleases (B), and the Father wants to do what Jesus pleases (A). So do they choose A or B? And whenever either of them submits to anothers Will that would make them not having the attribute of All-Powerful.
It becomes more complicated when you bring in the 3rd Person.
Jesus wants A, the Father wants B and the holy ghost wants C. Now they all have to agree before doing something, and have to agree who will be submitted their will and forgoing their attribute of All-Powerful. | 2014/10/01 | [
"https://christianity.stackexchange.com/questions/33383",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/14745/"
] | The question, as it stands, really isn't soluable.
**Reason #1: The Crucifixion raises other Trinitarian questions**
First and foremost, the Trinity itself is hard enough to understand. [There is no good analogy](https://christianity.stackexchange.com/a/13655/1039) and any attempt to make one will necessarily [fail by over emphasizing oneness or threeness](https://www.youtube.com/watch?v=KQLfgaUoQCw).
Worse, the Crucifixion and death of Christ means that either Jesus was in some fashion separated from the Father were separated on the cross, or else there is the problem of [Patripassianism](http://en.wikipedia.org/wiki/Patripassianism) - meaning that the Father somehow dies too.
One solution [kenosis](http://www.theopedia.com/Kenosis) modifies the hypostatic union to explain how Jesus can be fully God and yet somehow not able to do everything God did, but it is just one solution.
**Reason #2: The Trinity logically requires that the Wills cannot be separated**
In 2007, William P. Young write a book called [The Shack](http://en.wikipedia.org/wiki/The_Shack) which was rather popular in the Contemporary Christian market for a bit. The story itself imagined a Mack, a man whose daughter was killed, spending a weekend in which he got to meet Jesus face to face. Along the way, develops the characters of "Papa" an African-American female personification of God the Father, Jesus, and Sarayu, the Holy Spirit. His general idea was to understand the Trinity as the God whose very essence modeled true love-in-relationship that mankind was supposed to be.
From that vantage point, he was able to illustrate the Trinity and its coordinate implications for separate wills that I, as an evangelical, found useful.
To begin with, Young acknowledges that man has only a finite capacity to comprehend a finite God. He has "Papa" say:
>
> "The problem is that many folks try to grasp some sense of who I am by taking the best version of themselves, projecting that to the nth degree, factoring in all the goodness they can perceive, which often isn’t much, and then call that God. And while it may seem like a noble effort, the truth is that it falls pitifully short of who I really am. I’m not merely the best version of you that you can think of. I am far more than that, above and beyond all that you can ask or think.”
>
>
> “Never mind that,” she continued. “What’s important is this: If I were simply One God and only One Person, then you would find yourself in this Creation without something wonderful, without something essential even. And I would be utterly other than I am.”
>
>
> “And we would be without . . . ?” Mack didn’t even know how to finish the question.
>
>
> “Love and relationship. All love and relationship is possible for you only because it already exists within Me, within God myself. Love is not the limitation; love is the flying. I am love.”
>
>
>
Mack and "Papa" explicitly mention the Trinity, and Mack's inability to understand, and then get to the question you have: Namely, what happens if "Papa" and "Jesus" and "Sarayu" are in disagreement. Sarayu picks up the conversation, saying:
>
> “Mackenzie, we have no concept of final authority among us, only unity. We are in a circle of relationship, not a chain of command or ‘great chain of being’ as your ancestors termed it. What you’re seeing here is relationship without any overlay of power. We don’t need power over the other because we are always looking out for the best. Hierarchy would make no sense among us. Actually, this is your problem, not ours.”
>
>
> “Really? How so?”
>
>
> “Humans are so lost and damaged that to you it is almost incomprehensible that people could work or live together without someone being in charge.”
>
>
> “It’s one reason why experiencing true relationship is so difficult for you,” Jesus added. “Once you have a hierarchy you need rules to protect and administer it, and then you need law and the enforcement of the rules, and you end up with some kind of chain of command or a system of order that destroys relationship rather than promotes it. You rarely see or experience relationship apart from power. Hierarchy imposes laws and rules and you end up missing the wonder of relationship that we intended for you.”
>
>
> Sarayu continued, “When you chose independence over relationship, you became a danger to each other. Others became objects to be manipulated or managed for your own happiness. Authority, as you usually think of it, is merely the excuse the strong use to make others conform to what they want.”
>
>
>
...
>
> “We carefully respect your choices, so we work within your systems even while we seek to free you from them,” Papa continued. “Creation has been taken down a very different path than we desired. In your world the value of the individual is constantly weighed against the survival of the system, whether political, economic, social, or religious—any system actually. First one person, and then a few, and finally even many are easily sacrificed for the good and ongoing existence of that system. In one form or another this lies behind every struggle for power, every prejudice, every war, and every abuse of relationship. The ‘will to power and independence’ has become so ubiquitous that it is now considered normal.”
>
>
> “It is the human paradigm,” added Papa, having returned with more food. “It is like water to fish, so prevalent that it goes unseen and unquestioned. It is the matrix; a diabolical scheme in which you are hopelessly trapped even while completely unaware of its existence.”
>
>
> Jesus picked up the conversation. “As the crowning glory of Creation, you were made in our image, unencumbered by structure and free to simply ‘be’ in relationship with me and one another. If you had truly learned to regard each other’s concerns as significant as your own, there would be no need for hierarchy.”
>
>
> Mack sat back in his chair, staggered by the implications of what he was hearing. “So are you telling me that whenever we humans protect ourselves with power . . .”
>
>
> “You are yielding to the matrix, not to us,” finished Jesus.
>
>
> “And now,” Sarayu interjected, “we have come full circle, back to one of my initial statements: You humans are so lost and damaged that to you it is almost incomprehensible that relationship could exist apart from hierarchy. So you think that God must relate inside a hierarchy like you do. But we do not.”
>
>
>
In short, Young is suggesting that the question is most properly answered "[Mu](http://en.wikipedia.org/wiki/Mu_(negative))", meaning the question has a certain level of sense, but that a direct answer is ultimately non-sensical because the question holds an inherent problem within it.
Here, it is most fair to represent Young as saying that the Trinity is in relationship but not in hierarchy. The question of a separate "will" is sensical, but ultimately not answerable, because the relationship is so tight. (A situation that in statistics would be called [Multicollinearity](http://en.wikipedia.org/wiki/Multicollinearity)).
Put yet another way, there is no way to separate the wills, but that does not abrogate their theoretical existence. God's perfection in relationship means that wills cannot be in contradiction to one another, but this does not mean that they are the same.
Or, if the 8th Century Theologian [Boethius](http://en.wikipedia.org/wiki/Boethius) in [De Trinitae](http://pvspade.com/Logic/docs/BoethiusDeTrin.pdf) can better say:
>
> Thus ‘different’ is said in respect to either genus, species or number. But it is variety among accidents that produces difference in respect to number. For three men differ nei- ther in genus nor species, but in their accidents; for even if we mentally separate all acci- dents from them, there is still a different <168.60> location for each and all of them, which we can in no way imagine to be one: for two bodies will not occupy one location; and location is an accident. Therefore these three men are many in respect to number, since they become many by their accidents.
>
>
>
**Reason #3: Second Council of Constantinople (553 AD) is hard to understand**
Really, [this](http://www.fordham.edu/halsall/basis/const2.txt) is your full answer. It will go into the nature of the hypostatic union, the homoousion, and the definition of persons, wills and essences. This will literally take semesters of study to be comprehensible, but is your official "Christian" answer.
Ultimately, the creeds are trying to avoid errors such [Modalistic Monarchism](http://en.wikipedia.org/wiki/Monarchianism) and still make it comprehensible. Good luck. | In your question you appear to be overlooking two very important things.
1. Jesus was not only God, but he was also human.
2. Humans feel physical pain, even though Spirits do not.
In the Scriptures that you cite it must be remembered that Jesus was in an inordinate state. That is to say that the Deity Jesus was aware of the oncoming pain:
>
> Matthew 17:22 and 23 And while they abode in Galilee, Jesus said unto them, The Son of man shall be betrayed into the hands of men: 23 And they shall kill him, and the third day he shall be raised again. And they were exceeding sorry.
>
>
>
and as a man he would know just how painful that was going to be.
The plea to the father would have to come from the human part of Jesus, and it is not surprising that the man Jesus' will was not to go through all that torture and pain.
>
> Luke 22:41 through 44 And he was withdrawn from them about a stone's cast, and kneeled down, and prayed, 42 Saying, Father, if thou be willing, remove this cup from me: nevertheless not my will, but thine, be done. 43 And there appeared an angel unto him from heaven, strengthening him. 44 And being in an agony he prayed more earnestly: ***and his sweat was as it were great drops of blood falling down to the ground.***
>
>
>
This is a physical human phenomenon, and Medical Doctors have witnessed blood emitting from pores of people under extreme anxiety. Jesus would have had to fit into that category; having the foreknowledge of his torture and death on the cross.
As far as:
>
> Matthew 27:46 And about the ninth hour Jesus cried with a loud voice, saying, Eli, Eli, lama sabachthani? that is to say, My God, my God, why hast thou forsaken me?
>
>
>
God cannot look upon sin, and when Jesus became sinful by assuming our sins, he was forsaken by God. and it is imperative that we understand that God was forsaking the man Jesus on the cross, and that means all three of the Trinity were abandoning his physical man.
I know that there are going to be many comments concerning how Jesus could abandon himself, but that is not the case. The eternal son which was present at creation abandoned the physical body it had been inhabiting while on earth. consider:
>
> John 1:1 In the beginning was the Word, and the Word was with God, and the Word was God.
>
>
>
Hope this helps. |
33,383 | In the trinity the belief is that the Father is God, the Son is God, and the holy ghost is God.
The Father is a Person, and Son is a Person, and the holy Ghost is a Person.
And they all always existed, no beginning to any of the Persons.
Co-equal, co-substantial, co-eternal.
Now is the understanding that they have independent Will?
[Luke 22:42 | Bible Hub](http://biblehub.com/luke/22-42.htm)
>
> Father, if you are willing, take this cup from me; yet not my will,
> but yours be done
>
>
>
If they have different Will's, how can they still yet be All-Powerful?
Have they ever had different Will's?
Example when Jesus was in such distress and was calling out 'Why have your forsaken me' it would seem obvious his Will was to be saved?
What I am trying to get at is, if indeed they have different Will's, one of the Person's will want to overcome the other.
Interested to hear what theologians have said regarding this matter as it seems to be logically you can't get around this issue.
If you say that they don't have independant Will, then they are not All-Powerful.
**Example:**
Jesus wants A, Father wants B. Jesus wants to do what the Father pleases (B), and the Father wants to do what Jesus pleases (A). So do they choose A or B? And whenever either of them submits to anothers Will that would make them not having the attribute of All-Powerful.
It becomes more complicated when you bring in the 3rd Person.
Jesus wants A, the Father wants B and the holy ghost wants C. Now they all have to agree before doing something, and have to agree who will be submitted their will and forgoing their attribute of All-Powerful. | 2014/10/01 | [
"https://christianity.stackexchange.com/questions/33383",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/14745/"
] | **Catholic teaching and understanding** is that Christ has two wills, divine (of which, there is only one1) and human - without the human, to my understanding, he couldn't have redeemed in the manner he redeemed [cf. [Heb 5:8](https://www.biblegateway.com/passage/?search=Hebrews%205%3A8&version=RSVCE) & [Phil 2:7-9](https://www.biblegateway.com/passage/?search=Philippians%202%3A7-9&version=RSVCE)].
1. **In the Godhead the essence, will, and action are but one.** - cf. The divine unity in [The Blessed Trinity | New Advent](http://www.newadvent.org/cathen/15047a.htm).
From the catechism of the Catholic Church,
>
> **Christ's human will** [CCC **475**](http://www.vatican.va/archive/ccc_css/archive/catechism/p122a3p1.htm#475) Similarly, at the sixth ecumenical council, Constantinople III in 681, the Church confessed
> that Christ possesses two wills and two natural operations, divine and
> human. They are not opposed to each other, but cooperate in such a way
> that the Word made flesh willed humanly in obedience to his Father all
> that he had decided divinely with the Father and the Holy Spirit for
> our salvation.2 Christ's human will "does not resist or
> oppose but rather submits to his divine and almighty
> will."3
>
>
>
2. cf. Council of Constantinople III (681): DS 556-559.
3. Council of Constantinople III: DS 556.
Please see also *On the human soul of Christ* in [The Incarnation | New Advent](http://www.newadvent.org/cathen/07706b.htm#III1b).
---
As for `“My God, my God, why hast thou forsaken me?”`, the best explanation I have read is that Jesus said these words aloud, and continued to pray Psalm 22 silently. It ends in vindication and victory.
>
> [Matt 27:46 (RSVCE)](https://www.biblegateway.com/passage/?search=Matthew%2027%3A46&version=RSVCE) 46 And about the ninth hour Jesus cried with a
> loud voice, “*Eli, Eli, la′ma sabach-tha′ni*?” that is, “My God, my
> God, why hast thou forsaken me?”[a]
>
>
> Footnotes:
>
> a. Jesus applies [Psalm 22](https://www.biblegateway.com/passage/?version=RSVCE&search=Psalm%2022) (Vulgate 21) to
> himself.
>
>
> | In your question you appear to be overlooking two very important things.
1. Jesus was not only God, but he was also human.
2. Humans feel physical pain, even though Spirits do not.
In the Scriptures that you cite it must be remembered that Jesus was in an inordinate state. That is to say that the Deity Jesus was aware of the oncoming pain:
>
> Matthew 17:22 and 23 And while they abode in Galilee, Jesus said unto them, The Son of man shall be betrayed into the hands of men: 23 And they shall kill him, and the third day he shall be raised again. And they were exceeding sorry.
>
>
>
and as a man he would know just how painful that was going to be.
The plea to the father would have to come from the human part of Jesus, and it is not surprising that the man Jesus' will was not to go through all that torture and pain.
>
> Luke 22:41 through 44 And he was withdrawn from them about a stone's cast, and kneeled down, and prayed, 42 Saying, Father, if thou be willing, remove this cup from me: nevertheless not my will, but thine, be done. 43 And there appeared an angel unto him from heaven, strengthening him. 44 And being in an agony he prayed more earnestly: ***and his sweat was as it were great drops of blood falling down to the ground.***
>
>
>
This is a physical human phenomenon, and Medical Doctors have witnessed blood emitting from pores of people under extreme anxiety. Jesus would have had to fit into that category; having the foreknowledge of his torture and death on the cross.
As far as:
>
> Matthew 27:46 And about the ninth hour Jesus cried with a loud voice, saying, Eli, Eli, lama sabachthani? that is to say, My God, my God, why hast thou forsaken me?
>
>
>
God cannot look upon sin, and when Jesus became sinful by assuming our sins, he was forsaken by God. and it is imperative that we understand that God was forsaking the man Jesus on the cross, and that means all three of the Trinity were abandoning his physical man.
I know that there are going to be many comments concerning how Jesus could abandon himself, but that is not the case. The eternal son which was present at creation abandoned the physical body it had been inhabiting while on earth. consider:
>
> John 1:1 In the beginning was the Word, and the Word was with God, and the Word was God.
>
>
>
Hope this helps. |
73,489,249 | I need to show a popup every time when i open the app after 20 sec.
**code:** with this code i can show popup only when i open the app first time after 20 sec.. but **i need to show the same when i close the app and open again**.. how to do that? please guide me.
```
var timer = Timer()
override func viewDidLoad() {
timer = Timer.scheduledTimer(timeInterval: 20.0, target: self, selector: #selector(displayAlert), userInfo: nil, repeats: false)
}
@objc func displayAlert()
{
print("after 20 sec")
showPopup()
}
``` | 2022/08/25 | [
"https://Stackoverflow.com/questions/73489249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19758374/"
] | First of all, you have to locate your `select` element in the script. To do this, you need to provide it with a specific `id`.
```
<select id="test_selector">
<option>test1</option>
<option>test2</option>
</select>
```
Then you can use this `id` to access that *selector* in the JS. In order to get the updated value, chain it with the `change` event listener. Its callback receives the `event` parameter which contains the info you need.
```
document.getElementById('test_selector').addEventListener('change', event => {
console.log(event.target.value);
});
``` | Try this
```
select.addEventListener('select',(e)=>{
console.log(e.target.value);
})
``` |
73,489,249 | I need to show a popup every time when i open the app after 20 sec.
**code:** with this code i can show popup only when i open the app first time after 20 sec.. but **i need to show the same when i close the app and open again**.. how to do that? please guide me.
```
var timer = Timer()
override func viewDidLoad() {
timer = Timer.scheduledTimer(timeInterval: 20.0, target: self, selector: #selector(displayAlert), userInfo: nil, repeats: false)
}
@objc func displayAlert()
{
print("after 20 sec")
showPopup()
}
``` | 2022/08/25 | [
"https://Stackoverflow.com/questions/73489249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19758374/"
] | First of all, you have to locate your `select` element in the script. To do this, you need to provide it with a specific `id`.
```
<select id="test_selector">
<option>test1</option>
<option>test2</option>
</select>
```
Then you can use this `id` to access that *selector* in the JS. In order to get the updated value, chain it with the `change` event listener. Its callback receives the `event` parameter which contains the info you need.
```
document.getElementById('test_selector').addEventListener('change', event => {
console.log(event.target.value);
});
``` | Another option is to do it on jquery if you feel more comfy with it
Give your select an id
```
<select id="id_selector">
<option>test1</option>
<option>test2</option>
</select>
```
Use a jquery .change function to get the value of the selected option
```
$('#id_selector').change(function(){
console.log($('#id_selector').val());
//or console.log($(this).val()); to make the code shorter
});
``` |
73,489,249 | I need to show a popup every time when i open the app after 20 sec.
**code:** with this code i can show popup only when i open the app first time after 20 sec.. but **i need to show the same when i close the app and open again**.. how to do that? please guide me.
```
var timer = Timer()
override func viewDidLoad() {
timer = Timer.scheduledTimer(timeInterval: 20.0, target: self, selector: #selector(displayAlert), userInfo: nil, repeats: false)
}
@objc func displayAlert()
{
print("after 20 sec")
showPopup()
}
``` | 2022/08/25 | [
"https://Stackoverflow.com/questions/73489249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19758374/"
] | Another option is to do it on jquery if you feel more comfy with it
Give your select an id
```
<select id="id_selector">
<option>test1</option>
<option>test2</option>
</select>
```
Use a jquery .change function to get the value of the selected option
```
$('#id_selector').change(function(){
console.log($('#id_selector').val());
//or console.log($(this).val()); to make the code shorter
});
``` | Try this
```
select.addEventListener('select',(e)=>{
console.log(e.target.value);
})
``` |
822,846 | I have a class I'm unit testing that requires fairly extensive database setup before the individual test methods can run. This setup takes a long time: for reasons hopefully not relevant to the question at hand, I need to populate the DB programatically instead of from an SQL dump.
The issue I have is with the tear-down. How can I easily rollback all the changes made in the db setup phase?
I'm currently using Hibernate + Spring Transactional Testing support, such that my individual test methods are wrapped in transactions.
One solution would be to do the db setup within each test method, such that the db setup would be rolled back automatically. However, the test methods would take forever to run since each method would need to re-prep the database.
Any other ideas? Basically, I'm looking for a way to run my db setup, run my individual tests (each wrapped in a transaction which gets rolled-back after execution), and then roll-back the initial db setup. Any ideas on making this working in a Hibernate / Spring / Junit fashion? Is there a Hibernate "drop all tables" equivalent command? | 2009/05/05 | [
"https://Stackoverflow.com/questions/822846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84818/"
] | Are you stuck with a specific database vendor? If not, you could use an in-memory database, such as [HSQLDB](http://hsqldb.org/). When you are done with the tests you just throw away the state. This is only appropriate if the tables can be empty at the start of the test suite (before your programmatic setup, that is).
You still need to create tables, but if everything is neatly mapped using Hibernate you can use the hbm2ddl to generate your tables. All you have to do is add the following to your *test* session factory definition:
```
<session-factory>
...
<property name="hibernate.hbm2ddl.auto">create</property>
...
</session-factory>
```
If this solution seems applicable I can elaborate on it. | You may want to look at @AfterClass annotation, for Junit 4. This annotation will run when the tests are done.
<http://cwiki.apache.org/DIRxDEV/junit4-primer.html> |
822,846 | I have a class I'm unit testing that requires fairly extensive database setup before the individual test methods can run. This setup takes a long time: for reasons hopefully not relevant to the question at hand, I need to populate the DB programatically instead of from an SQL dump.
The issue I have is with the tear-down. How can I easily rollback all the changes made in the db setup phase?
I'm currently using Hibernate + Spring Transactional Testing support, such that my individual test methods are wrapped in transactions.
One solution would be to do the db setup within each test method, such that the db setup would be rolled back automatically. However, the test methods would take forever to run since each method would need to re-prep the database.
Any other ideas? Basically, I'm looking for a way to run my db setup, run my individual tests (each wrapped in a transaction which gets rolled-back after execution), and then roll-back the initial db setup. Any ideas on making this working in a Hibernate / Spring / Junit fashion? Is there a Hibernate "drop all tables" equivalent command? | 2009/05/05 | [
"https://Stackoverflow.com/questions/822846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84818/"
] | Are you stuck with a specific database vendor? If not, you could use an in-memory database, such as [HSQLDB](http://hsqldb.org/). When you are done with the tests you just throw away the state. This is only appropriate if the tables can be empty at the start of the test suite (before your programmatic setup, that is).
You still need to create tables, but if everything is neatly mapped using Hibernate you can use the hbm2ddl to generate your tables. All you have to do is add the following to your *test* session factory definition:
```
<session-factory>
...
<property name="hibernate.hbm2ddl.auto">create</property>
...
</session-factory>
```
If this solution seems applicable I can elaborate on it. | DNUnit should help you in this regard.
You can create separate data sets for each individual test case if you wish. |
822,846 | I have a class I'm unit testing that requires fairly extensive database setup before the individual test methods can run. This setup takes a long time: for reasons hopefully not relevant to the question at hand, I need to populate the DB programatically instead of from an SQL dump.
The issue I have is with the tear-down. How can I easily rollback all the changes made in the db setup phase?
I'm currently using Hibernate + Spring Transactional Testing support, such that my individual test methods are wrapped in transactions.
One solution would be to do the db setup within each test method, such that the db setup would be rolled back automatically. However, the test methods would take forever to run since each method would need to re-prep the database.
Any other ideas? Basically, I'm looking for a way to run my db setup, run my individual tests (each wrapped in a transaction which gets rolled-back after execution), and then roll-back the initial db setup. Any ideas on making this working in a Hibernate / Spring / Junit fashion? Is there a Hibernate "drop all tables" equivalent command? | 2009/05/05 | [
"https://Stackoverflow.com/questions/822846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84818/"
] | Are you stuck with a specific database vendor? If not, you could use an in-memory database, such as [HSQLDB](http://hsqldb.org/). When you are done with the tests you just throw away the state. This is only appropriate if the tables can be empty at the start of the test suite (before your programmatic setup, that is).
You still need to create tables, but if everything is neatly mapped using Hibernate you can use the hbm2ddl to generate your tables. All you have to do is add the following to your *test* session factory definition:
```
<session-factory>
...
<property name="hibernate.hbm2ddl.auto">create</property>
...
</session-factory>
```
If this solution seems applicable I can elaborate on it. | DBUnit will help a lot with this. You could theoretically turn off autocommits on JDBC, but it will get hairy. The most obvious solution is to use DBUnit to set your data to a known state before you run the tests. IF for some reason you need your data back after the tests are run, you could look at @AfterClass on a suite that runs all of your tests, but it is generally considered a better practice to set up your tests and then run them, so that if the test fails, it is not just because it didn't have a prestine environment due to a failure to clean up an different test. You ensure that each test sets up its environment directly. |
822,846 | I have a class I'm unit testing that requires fairly extensive database setup before the individual test methods can run. This setup takes a long time: for reasons hopefully not relevant to the question at hand, I need to populate the DB programatically instead of from an SQL dump.
The issue I have is with the tear-down. How can I easily rollback all the changes made in the db setup phase?
I'm currently using Hibernate + Spring Transactional Testing support, such that my individual test methods are wrapped in transactions.
One solution would be to do the db setup within each test method, such that the db setup would be rolled back automatically. However, the test methods would take forever to run since each method would need to re-prep the database.
Any other ideas? Basically, I'm looking for a way to run my db setup, run my individual tests (each wrapped in a transaction which gets rolled-back after execution), and then roll-back the initial db setup. Any ideas on making this working in a Hibernate / Spring / Junit fashion? Is there a Hibernate "drop all tables" equivalent command? | 2009/05/05 | [
"https://Stackoverflow.com/questions/822846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84818/"
] | Are you stuck with a specific database vendor? If not, you could use an in-memory database, such as [HSQLDB](http://hsqldb.org/). When you are done with the tests you just throw away the state. This is only appropriate if the tables can be empty at the start of the test suite (before your programmatic setup, that is).
You still need to create tables, but if everything is neatly mapped using Hibernate you can use the hbm2ddl to generate your tables. All you have to do is add the following to your *test* session factory definition:
```
<session-factory>
...
<property name="hibernate.hbm2ddl.auto">create</property>
...
</session-factory>
```
If this solution seems applicable I can elaborate on it. | One solution that you may want to consider is to use a "manual" rollback or compensating transaction in db tear down. I suppose (and if it's not then it should be a trivial add-on to your Hibernate entities) all your entities have datetime create attribute indicating when they were INSERTed into the table. Your db setup method should record time before everything else. Then you have rather simple procedure for db tear down to delete all entities that were created after time recored in db setup.
Of course, this won't work for updates in db setup... But if you have limited number of updates then consider saving pristine image for this type of data and restore it during db tear down. |
822,846 | I have a class I'm unit testing that requires fairly extensive database setup before the individual test methods can run. This setup takes a long time: for reasons hopefully not relevant to the question at hand, I need to populate the DB programatically instead of from an SQL dump.
The issue I have is with the tear-down. How can I easily rollback all the changes made in the db setup phase?
I'm currently using Hibernate + Spring Transactional Testing support, such that my individual test methods are wrapped in transactions.
One solution would be to do the db setup within each test method, such that the db setup would be rolled back automatically. However, the test methods would take forever to run since each method would need to re-prep the database.
Any other ideas? Basically, I'm looking for a way to run my db setup, run my individual tests (each wrapped in a transaction which gets rolled-back after execution), and then roll-back the initial db setup. Any ideas on making this working in a Hibernate / Spring / Junit fashion? Is there a Hibernate "drop all tables" equivalent command? | 2009/05/05 | [
"https://Stackoverflow.com/questions/822846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84818/"
] | Are you stuck with a specific database vendor? If not, you could use an in-memory database, such as [HSQLDB](http://hsqldb.org/). When you are done with the tests you just throw away the state. This is only appropriate if the tables can be empty at the start of the test suite (before your programmatic setup, that is).
You still need to create tables, but if everything is neatly mapped using Hibernate you can use the hbm2ddl to generate your tables. All you have to do is add the following to your *test* session factory definition:
```
<session-factory>
...
<property name="hibernate.hbm2ddl.auto">create</property>
...
</session-factory>
```
If this solution seems applicable I can elaborate on it. | If you're working with relatively small database, and with a DBMS that can do backups/exports of it relatively fast (like MS SQL Server), you can consider creating a database backup before the tests, and then restore it when all testing is complete. This enables you to set-up a development/testing database and use it as a starting state for all your tests.
I did it with native JDBC, executing ''backup database'' and ''restore database'' T-SQL in-between tests, and it worked reasonably well.
However, this approach is dependent on having the DBMS server on your local machine (for reasonable speed), you having sufficient privileges (which than should not be a problem), and the total size of database not exceeding a few tens on MB - at least in my experience. |
822,846 | I have a class I'm unit testing that requires fairly extensive database setup before the individual test methods can run. This setup takes a long time: for reasons hopefully not relevant to the question at hand, I need to populate the DB programatically instead of from an SQL dump.
The issue I have is with the tear-down. How can I easily rollback all the changes made in the db setup phase?
I'm currently using Hibernate + Spring Transactional Testing support, such that my individual test methods are wrapped in transactions.
One solution would be to do the db setup within each test method, such that the db setup would be rolled back automatically. However, the test methods would take forever to run since each method would need to re-prep the database.
Any other ideas? Basically, I'm looking for a way to run my db setup, run my individual tests (each wrapped in a transaction which gets rolled-back after execution), and then roll-back the initial db setup. Any ideas on making this working in a Hibernate / Spring / Junit fashion? Is there a Hibernate "drop all tables" equivalent command? | 2009/05/05 | [
"https://Stackoverflow.com/questions/822846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84818/"
] | Are you stuck with a specific database vendor? If not, you could use an in-memory database, such as [HSQLDB](http://hsqldb.org/). When you are done with the tests you just throw away the state. This is only appropriate if the tables can be empty at the start of the test suite (before your programmatic setup, that is).
You still need to create tables, but if everything is neatly mapped using Hibernate you can use the hbm2ddl to generate your tables. All you have to do is add the following to your *test* session factory definition:
```
<session-factory>
...
<property name="hibernate.hbm2ddl.auto">create</property>
...
</session-factory>
```
If this solution seems applicable I can elaborate on it. | Is there a reason that you have to have a connection to the database to run your unit tests? It sounds like it might be easier to refactor your class so that you can mock the interaction with the database. You can mock classes (with some exceptions) as well as interfaces with EasyMock (www.easymock.org).
If your class relies on a complex pre-existing state in a connected database, it would probably be easier to write faster executing tests using mocks. We don't know what the size of your project is or how often your tests are run, but execution time might be something to think about, especially in a large project. |
822,846 | I have a class I'm unit testing that requires fairly extensive database setup before the individual test methods can run. This setup takes a long time: for reasons hopefully not relevant to the question at hand, I need to populate the DB programatically instead of from an SQL dump.
The issue I have is with the tear-down. How can I easily rollback all the changes made in the db setup phase?
I'm currently using Hibernate + Spring Transactional Testing support, such that my individual test methods are wrapped in transactions.
One solution would be to do the db setup within each test method, such that the db setup would be rolled back automatically. However, the test methods would take forever to run since each method would need to re-prep the database.
Any other ideas? Basically, I'm looking for a way to run my db setup, run my individual tests (each wrapped in a transaction which gets rolled-back after execution), and then roll-back the initial db setup. Any ideas on making this working in a Hibernate / Spring / Junit fashion? Is there a Hibernate "drop all tables" equivalent command? | 2009/05/05 | [
"https://Stackoverflow.com/questions/822846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84818/"
] | Are you stuck with a specific database vendor? If not, you could use an in-memory database, such as [HSQLDB](http://hsqldb.org/). When you are done with the tests you just throw away the state. This is only appropriate if the tables can be empty at the start of the test suite (before your programmatic setup, that is).
You still need to create tables, but if everything is neatly mapped using Hibernate you can use the hbm2ddl to generate your tables. All you have to do is add the following to your *test* session factory definition:
```
<session-factory>
...
<property name="hibernate.hbm2ddl.auto">create</property>
...
</session-factory>
```
If this solution seems applicable I can elaborate on it. | Hibernate has a neat little feature that is heavily under-documented and unknown. You can execute an SQL script during the SessionFactory creation right after the database schema generation to import data in a fresh database. You just need to add a file named import.sql in your classpath root and set either create or create-drop as your hibernate.hbm2ddl.auto property.
<http://in.relation.to/Bloggers/RotterdamJBugAndHibernatesImportsql> |
71,992,622 | I have two lists, one contains the working days, the other one contains the fees corresponding to the working days:
```
wd = [1, 4, 5, 6]
fees = [1.44, 1.17, 1.21, 1.26]
```
I need a third list with all workdays, filling up fees in the workdays that do not have fees with fees from the previous day:
```
result = [1.44, 1.44, 1.44, 1.17, 1.21, 1.26]
correspDay = [1, 2, 3, 4, 5, 6]
```
How can I code this? | 2022/04/24 | [
"https://Stackoverflow.com/questions/71992622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18930272/"
] | I'd start by building a dictionary to be able to look up fees by day:
```
>>> wd = [1,4,5,6]
>>> fees = [1.44, 1.17, 1.21, 1.26]
>>> fee_dict = dict(zip(wd, fees))
```
Then build `correspDay` with a simple `range`:
```
>>> correspDay = list(range(1, 7))
```
and build `result` by iterating over `correspDay`, using `fee_dict` to look up the fees and using the last entry when `fee_dict` comes up empty:
```
>>> result = []
>>> for i in correspDay:
... result.append(fee_dict.get(i) or result[-1])
...
>>> result
[1.44, 1.44, 1.44, 1.17, 1.21, 1.26]
``` | I would put the values in a dictionary, then loop through the days of the week (1-7) checking if we already have a value for that day. If you do have a value for that day store it incase the next day doesn't have a value. If there isn't a value create an item in the dictionary with a key for that day and a value of the last fee.
At the end I have sorted the list but there is no real reason to do this other than to make the output easier to read
```
fees_dict = {1: 1.44, 4: 1.17, 5: 1.21, 6: 1.26}
last_fee = 0
for i in range(1, 8):
if i in fees_dict:
last_fee = fees_dict[i]
else:
fees_dict[i] = last_fee
sorted_fees_dict = dict(sorted(fees_dict.items()))
print(sorted_fees_dict)
``` |
71,992,622 | I have two lists, one contains the working days, the other one contains the fees corresponding to the working days:
```
wd = [1, 4, 5, 6]
fees = [1.44, 1.17, 1.21, 1.26]
```
I need a third list with all workdays, filling up fees in the workdays that do not have fees with fees from the previous day:
```
result = [1.44, 1.44, 1.44, 1.17, 1.21, 1.26]
correspDay = [1, 2, 3, 4, 5, 6]
```
How can I code this? | 2022/04/24 | [
"https://Stackoverflow.com/questions/71992622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18930272/"
] | I'd start by building a dictionary to be able to look up fees by day:
```
>>> wd = [1,4,5,6]
>>> fees = [1.44, 1.17, 1.21, 1.26]
>>> fee_dict = dict(zip(wd, fees))
```
Then build `correspDay` with a simple `range`:
```
>>> correspDay = list(range(1, 7))
```
and build `result` by iterating over `correspDay`, using `fee_dict` to look up the fees and using the last entry when `fee_dict` comes up empty:
```
>>> result = []
>>> for i in correspDay:
... result.append(fee_dict.get(i) or result[-1])
...
>>> result
[1.44, 1.44, 1.44, 1.17, 1.21, 1.26]
``` | `feeMap` maps `days` to `fee` that has to be paid `prev` is used to store the previous value(fee).
```
#!/usr/bin/env python3.10
wd = [1,4,5,6]
fees = [1.44, 1.17, 1.21, 1.26]
corresDay = list(range(1, 6))
feeMap = dict()
index = 0
for index, day in enumerate(wd):
feeMap[day] = fees[index]
prev = None
for day in range(1, 6):
if day not in feeMap.keys():
feeMap[day] = prev
else:
prev = feeMap[day]
feeMap = sorted(feeMap.items())
print(feeMap)
```
output:
=======
```
$ ./working_days.py
[(1, 1.44), (2, 1.44), (3, 1.44), (4, 1.17), (5, 1.21), (6, 1.26)]
``` |
71,992,622 | I have two lists, one contains the working days, the other one contains the fees corresponding to the working days:
```
wd = [1, 4, 5, 6]
fees = [1.44, 1.17, 1.21, 1.26]
```
I need a third list with all workdays, filling up fees in the workdays that do not have fees with fees from the previous day:
```
result = [1.44, 1.44, 1.44, 1.17, 1.21, 1.26]
correspDay = [1, 2, 3, 4, 5, 6]
```
How can I code this? | 2022/04/24 | [
"https://Stackoverflow.com/questions/71992622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18930272/"
] | I'd start by building a dictionary to be able to look up fees by day:
```
>>> wd = [1,4,5,6]
>>> fees = [1.44, 1.17, 1.21, 1.26]
>>> fee_dict = dict(zip(wd, fees))
```
Then build `correspDay` with a simple `range`:
```
>>> correspDay = list(range(1, 7))
```
and build `result` by iterating over `correspDay`, using `fee_dict` to look up the fees and using the last entry when `fee_dict` comes up empty:
```
>>> result = []
>>> for i in correspDay:
... result.append(fee_dict.get(i) or result[-1])
...
>>> result
[1.44, 1.44, 1.44, 1.17, 1.21, 1.26]
``` | I didn't do anything I saw the good people above and I try to make it more clear for you.
```
wd = [1,4,5,6]
fees = [1.44, 1.17, 1.21, 1.26]
fee_dict = dict(zip(wd, fees))
correspDay = list(range(1,8))
result = []
for i in correspDay:
result.append(fee_dict.get(i) or result[-1])
```
I just add this line to make the output in dictionary
```
result = dict(zip(correspDay, result))
```
output:
```
{1: 1.44, 2: 1.44, 3: 1.44, 4: 1.17, 5: 1.21, 6: 1.26, 7: 1.26}
``` |
71,992,622 | I have two lists, one contains the working days, the other one contains the fees corresponding to the working days:
```
wd = [1, 4, 5, 6]
fees = [1.44, 1.17, 1.21, 1.26]
```
I need a third list with all workdays, filling up fees in the workdays that do not have fees with fees from the previous day:
```
result = [1.44, 1.44, 1.44, 1.17, 1.21, 1.26]
correspDay = [1, 2, 3, 4, 5, 6]
```
How can I code this? | 2022/04/24 | [
"https://Stackoverflow.com/questions/71992622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18930272/"
] | I would put the values in a dictionary, then loop through the days of the week (1-7) checking if we already have a value for that day. If you do have a value for that day store it incase the next day doesn't have a value. If there isn't a value create an item in the dictionary with a key for that day and a value of the last fee.
At the end I have sorted the list but there is no real reason to do this other than to make the output easier to read
```
fees_dict = {1: 1.44, 4: 1.17, 5: 1.21, 6: 1.26}
last_fee = 0
for i in range(1, 8):
if i in fees_dict:
last_fee = fees_dict[i]
else:
fees_dict[i] = last_fee
sorted_fees_dict = dict(sorted(fees_dict.items()))
print(sorted_fees_dict)
``` | `feeMap` maps `days` to `fee` that has to be paid `prev` is used to store the previous value(fee).
```
#!/usr/bin/env python3.10
wd = [1,4,5,6]
fees = [1.44, 1.17, 1.21, 1.26]
corresDay = list(range(1, 6))
feeMap = dict()
index = 0
for index, day in enumerate(wd):
feeMap[day] = fees[index]
prev = None
for day in range(1, 6):
if day not in feeMap.keys():
feeMap[day] = prev
else:
prev = feeMap[day]
feeMap = sorted(feeMap.items())
print(feeMap)
```
output:
=======
```
$ ./working_days.py
[(1, 1.44), (2, 1.44), (3, 1.44), (4, 1.17), (5, 1.21), (6, 1.26)]
``` |
71,992,622 | I have two lists, one contains the working days, the other one contains the fees corresponding to the working days:
```
wd = [1, 4, 5, 6]
fees = [1.44, 1.17, 1.21, 1.26]
```
I need a third list with all workdays, filling up fees in the workdays that do not have fees with fees from the previous day:
```
result = [1.44, 1.44, 1.44, 1.17, 1.21, 1.26]
correspDay = [1, 2, 3, 4, 5, 6]
```
How can I code this? | 2022/04/24 | [
"https://Stackoverflow.com/questions/71992622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18930272/"
] | I would put the values in a dictionary, then loop through the days of the week (1-7) checking if we already have a value for that day. If you do have a value for that day store it incase the next day doesn't have a value. If there isn't a value create an item in the dictionary with a key for that day and a value of the last fee.
At the end I have sorted the list but there is no real reason to do this other than to make the output easier to read
```
fees_dict = {1: 1.44, 4: 1.17, 5: 1.21, 6: 1.26}
last_fee = 0
for i in range(1, 8):
if i in fees_dict:
last_fee = fees_dict[i]
else:
fees_dict[i] = last_fee
sorted_fees_dict = dict(sorted(fees_dict.items()))
print(sorted_fees_dict)
``` | I didn't do anything I saw the good people above and I try to make it more clear for you.
```
wd = [1,4,5,6]
fees = [1.44, 1.17, 1.21, 1.26]
fee_dict = dict(zip(wd, fees))
correspDay = list(range(1,8))
result = []
for i in correspDay:
result.append(fee_dict.get(i) or result[-1])
```
I just add this line to make the output in dictionary
```
result = dict(zip(correspDay, result))
```
output:
```
{1: 1.44, 2: 1.44, 3: 1.44, 4: 1.17, 5: 1.21, 6: 1.26, 7: 1.26}
``` |
349,129 | Two ePub books that I've bought won't open in Books.app in macOS Mojave 10.14. The books have social DRM (personal information added to the content of the book), and I don't think this should be a problem for Books.app. If I rename the epub extension to zip, then I can unzip the file using the `unzip` command. Using the Finder doesn't work somehow. Other books open normally.
Looking at the contents, I see that it uses XHTML inside an OEBPS folder, while other books use HTML in an OPS folder.
What is the reason that Books.app doesn't open these ePub files? I can read them OK with Calibre. | 2019/01/20 | [
"https://apple.stackexchange.com/questions/349129",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/35070/"
] | If your ebook indeed is unencrypted, you can try to open the ePub with the free Sigil.app (an ePub creator/editor) and write another copy to disk.
Sigil is able to repair a lot of structural problems. You can get a precompiled dmg as well as the full source code [here](https://github.com/Sigil-Ebook/Sigil/releases/tag/0.9.10).
I agree the "social DRM" should not pose any obstacle for using these eBooks with Books.app. But I suspect the "patching personal data into the eBooks" is done by an automated process, which simply went awry in your case. Maybe you even have some special characters in your identifying information (quotes, accents, ampersand, general unicode characters). | It's hard to know whether the "social DRM" or some other aspect of the epubs you mention is causing the problem with Books app. The best course is to let the publisher know so they can investigate if they wish and in the meantime use Calibre or another epub reader to read the books. |
35,036,918 | This is the regex I'm using
```
.match(/\[(.*)\]\s*([^\s]+)\s*([^\s]+)\s*(.*)/)
```
and it fails to capture the timestamp properly when there is another close square bracket
```
[2016-01-22 22:14:58,098] WARN service.catalog.MediaController - foo1 foo foo foo foo foo
[2016-01-22 22:14:58,235] WARN service.catalog.MediaController - foo2 foo foo foo foo foo]; sdfd sf sd
[2016-01-22 22:14:58,240] INFO service.catalog.RestAPIController - foo3 foo foo foo] foo foo
[2016-01-22 22:14:58,259] INFO service.catalog.DynamicRoutingController - foo4 foo foo foo foo foo
[2016-01-22 22:14:58,457] ERROR service.catalog.BaseController - foo5 foo foo foo foo foo
``` | 2016/01/27 | [
"https://Stackoverflow.com/questions/35036918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989155/"
] | Try to make your regex more restrictive by matching the pattern more closely.
So for example, for the timestamp in the beginning use something like this:
```
\[\d{4}-\d\d-\d\d \d\d:\d\d:\d\d,\d\d\d\]
```
This way you will make sure there are no false positive matches | Your timestamp seems to have a straight forward layout, why not capture that explicitly:
```
var regex = /\[\d{2,4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}(?:,|.)\d+\]/;
'[2016-01-22 22:14:58,235] WARN service.catalog.MediaController - foo2 foo foo foo foo foo]; sdfd sf sd'.match(regex) // -> ["[2016-01-22 22:14:58,235]"]
```
I've included for the year to have 2 instead of 4 digits and your milliseconds being separated by , or . |
35,036,918 | This is the regex I'm using
```
.match(/\[(.*)\]\s*([^\s]+)\s*([^\s]+)\s*(.*)/)
```
and it fails to capture the timestamp properly when there is another close square bracket
```
[2016-01-22 22:14:58,098] WARN service.catalog.MediaController - foo1 foo foo foo foo foo
[2016-01-22 22:14:58,235] WARN service.catalog.MediaController - foo2 foo foo foo foo foo]; sdfd sf sd
[2016-01-22 22:14:58,240] INFO service.catalog.RestAPIController - foo3 foo foo foo] foo foo
[2016-01-22 22:14:58,259] INFO service.catalog.DynamicRoutingController - foo4 foo foo foo foo foo
[2016-01-22 22:14:58,457] ERROR service.catalog.BaseController - foo5 foo foo foo foo foo
``` | 2016/01/27 | [
"https://Stackoverflow.com/questions/35036918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989155/"
] | Try this:
```
^\[(.*?)\]
```
[Demo - RegEx101](https://regex101.com/r/oZ2cQ6/1) | Try to make your regex more restrictive by matching the pattern more closely.
So for example, for the timestamp in the beginning use something like this:
```
\[\d{4}-\d\d-\d\d \d\d:\d\d:\d\d,\d\d\d\]
```
This way you will make sure there are no false positive matches |
35,036,918 | This is the regex I'm using
```
.match(/\[(.*)\]\s*([^\s]+)\s*([^\s]+)\s*(.*)/)
```
and it fails to capture the timestamp properly when there is another close square bracket
```
[2016-01-22 22:14:58,098] WARN service.catalog.MediaController - foo1 foo foo foo foo foo
[2016-01-22 22:14:58,235] WARN service.catalog.MediaController - foo2 foo foo foo foo foo]; sdfd sf sd
[2016-01-22 22:14:58,240] INFO service.catalog.RestAPIController - foo3 foo foo foo] foo foo
[2016-01-22 22:14:58,259] INFO service.catalog.DynamicRoutingController - foo4 foo foo foo foo foo
[2016-01-22 22:14:58,457] ERROR service.catalog.BaseController - foo5 foo foo foo foo foo
``` | 2016/01/27 | [
"https://Stackoverflow.com/questions/35036918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989155/"
] | Try to make your regex more restrictive by matching the pattern more closely.
So for example, for the timestamp in the beginning use something like this:
```
\[\d{4}-\d\d-\d\d \d\d:\d\d:\d\d,\d\d\d\]
```
This way you will make sure there are no false positive matches | It is not really clear what you want to achive. My idea is `\d{1,4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}:\d{1,2},\d{1,3}`. If you want do capture the brackets either, add `\[` and `\]` to the expression. |
35,036,918 | This is the regex I'm using
```
.match(/\[(.*)\]\s*([^\s]+)\s*([^\s]+)\s*(.*)/)
```
and it fails to capture the timestamp properly when there is another close square bracket
```
[2016-01-22 22:14:58,098] WARN service.catalog.MediaController - foo1 foo foo foo foo foo
[2016-01-22 22:14:58,235] WARN service.catalog.MediaController - foo2 foo foo foo foo foo]; sdfd sf sd
[2016-01-22 22:14:58,240] INFO service.catalog.RestAPIController - foo3 foo foo foo] foo foo
[2016-01-22 22:14:58,259] INFO service.catalog.DynamicRoutingController - foo4 foo foo foo foo foo
[2016-01-22 22:14:58,457] ERROR service.catalog.BaseController - foo5 foo foo foo foo foo
``` | 2016/01/27 | [
"https://Stackoverflow.com/questions/35036918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989155/"
] | Try to make your regex more restrictive by matching the pattern more closely.
So for example, for the timestamp in the beginning use something like this:
```
\[\d{4}-\d\d-\d\d \d\d:\d\d:\d\d,\d\d\d\]
```
This way you will make sure there are no false positive matches | This regex should work for you:
```
/\[[\d-\s:,]+]/gm
```
[demo](https://regex101.com/r/bA0bU7/1)
PD: Your option is not bad idea, is the most specific that can be, and that´s good: [(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d,\d\d\d)] |
35,036,918 | This is the regex I'm using
```
.match(/\[(.*)\]\s*([^\s]+)\s*([^\s]+)\s*(.*)/)
```
and it fails to capture the timestamp properly when there is another close square bracket
```
[2016-01-22 22:14:58,098] WARN service.catalog.MediaController - foo1 foo foo foo foo foo
[2016-01-22 22:14:58,235] WARN service.catalog.MediaController - foo2 foo foo foo foo foo]; sdfd sf sd
[2016-01-22 22:14:58,240] INFO service.catalog.RestAPIController - foo3 foo foo foo] foo foo
[2016-01-22 22:14:58,259] INFO service.catalog.DynamicRoutingController - foo4 foo foo foo foo foo
[2016-01-22 22:14:58,457] ERROR service.catalog.BaseController - foo5 foo foo foo foo foo
``` | 2016/01/27 | [
"https://Stackoverflow.com/questions/35036918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989155/"
] | Try this:
```
^\[(.*?)\]
```
[Demo - RegEx101](https://regex101.com/r/oZ2cQ6/1) | Your timestamp seems to have a straight forward layout, why not capture that explicitly:
```
var regex = /\[\d{2,4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}(?:,|.)\d+\]/;
'[2016-01-22 22:14:58,235] WARN service.catalog.MediaController - foo2 foo foo foo foo foo]; sdfd sf sd'.match(regex) // -> ["[2016-01-22 22:14:58,235]"]
```
I've included for the year to have 2 instead of 4 digits and your milliseconds being separated by , or . |
35,036,918 | This is the regex I'm using
```
.match(/\[(.*)\]\s*([^\s]+)\s*([^\s]+)\s*(.*)/)
```
and it fails to capture the timestamp properly when there is another close square bracket
```
[2016-01-22 22:14:58,098] WARN service.catalog.MediaController - foo1 foo foo foo foo foo
[2016-01-22 22:14:58,235] WARN service.catalog.MediaController - foo2 foo foo foo foo foo]; sdfd sf sd
[2016-01-22 22:14:58,240] INFO service.catalog.RestAPIController - foo3 foo foo foo] foo foo
[2016-01-22 22:14:58,259] INFO service.catalog.DynamicRoutingController - foo4 foo foo foo foo foo
[2016-01-22 22:14:58,457] ERROR service.catalog.BaseController - foo5 foo foo foo foo foo
``` | 2016/01/27 | [
"https://Stackoverflow.com/questions/35036918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989155/"
] | Try this:
```
^\[(.*?)\]
```
[Demo - RegEx101](https://regex101.com/r/oZ2cQ6/1) | It is not really clear what you want to achive. My idea is `\d{1,4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}:\d{1,2},\d{1,3}`. If you want do capture the brackets either, add `\[` and `\]` to the expression. |
35,036,918 | This is the regex I'm using
```
.match(/\[(.*)\]\s*([^\s]+)\s*([^\s]+)\s*(.*)/)
```
and it fails to capture the timestamp properly when there is another close square bracket
```
[2016-01-22 22:14:58,098] WARN service.catalog.MediaController - foo1 foo foo foo foo foo
[2016-01-22 22:14:58,235] WARN service.catalog.MediaController - foo2 foo foo foo foo foo]; sdfd sf sd
[2016-01-22 22:14:58,240] INFO service.catalog.RestAPIController - foo3 foo foo foo] foo foo
[2016-01-22 22:14:58,259] INFO service.catalog.DynamicRoutingController - foo4 foo foo foo foo foo
[2016-01-22 22:14:58,457] ERROR service.catalog.BaseController - foo5 foo foo foo foo foo
``` | 2016/01/27 | [
"https://Stackoverflow.com/questions/35036918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989155/"
] | Try this:
```
^\[(.*?)\]
```
[Demo - RegEx101](https://regex101.com/r/oZ2cQ6/1) | This regex should work for you:
```
/\[[\d-\s:,]+]/gm
```
[demo](https://regex101.com/r/bA0bU7/1)
PD: Your option is not bad idea, is the most specific that can be, and that´s good: [(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d,\d\d\d)] |
2,872,555 | Summary of environment.
* Asp.net web application (source stored in svn)
* SQL Server database. (Database schema (tables/sprocs) stored in svn)
* db version is synced with web application assembly version. (stored in table 'CurrentVersion')
* CI hudson server that checks out web app from repo and runs custom msbuild file to publish/package app.
My msbuild script updates the assembly version of the web app (Major.Minor.Revision.Build) on each build. The 'Revision' is set to the currently checked out svn revision and the 'Build' to the hudson build number (incremented on each automated build).
This way i can match the app to a specific trunk revision also get other build stats from the hudson build number.
I'd like to automate the collecting of migration scripts (updated sprocs etc) to add to the zip package.
I guess by comparing the svn revision of the db that has yet to be deployed to, to the revision being deployed, i can find what db files have changed in the trunk since the last deployment to that database/environment.
This could easily be achieved by manually calling the `svn diff -r REVNO:REVNO` command to list changed .sql files. These files could then manually have to be added to the package.
It would be great if this could be automated.
Firstly i'd imagine I'll have to write a custom task to check the version of the db that has yet to be deployed to. After that I'm quite unsure.
Does anyone have any suggestion on how this would be achieved through an msbuild task either existing or custom?
Finally I'll have to autogen a script to add to the package that updates the database version table so as to be in sync with the application. | 2010/05/20 | [
"https://Stackoverflow.com/questions/2872555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/345963/"
] | Have a look at SQL database projects. In VS 2010 they have been enhanced quite a bit and have built in deployment capabilities that can sync your DEV database to other environments.
Here are a few good links about DB projects in vs 2010:
<http://msmvps.com/blogs/deborahk/archive/2010/05/02/vs-2010-database-project-building-and-deployment.aspx>
<http://weblogs.asp.net/gunnarpeipman/archive/2009/07/29/visual-studio-2010-database-projects.aspx> | Try SQL Examiner:
<http://www.sqlaccessories.com/Howto/Version_Control.aspx>
You can automate script collecting with SQL Examiner command-line tool. |
2,872,555 | Summary of environment.
* Asp.net web application (source stored in svn)
* SQL Server database. (Database schema (tables/sprocs) stored in svn)
* db version is synced with web application assembly version. (stored in table 'CurrentVersion')
* CI hudson server that checks out web app from repo and runs custom msbuild file to publish/package app.
My msbuild script updates the assembly version of the web app (Major.Minor.Revision.Build) on each build. The 'Revision' is set to the currently checked out svn revision and the 'Build' to the hudson build number (incremented on each automated build).
This way i can match the app to a specific trunk revision also get other build stats from the hudson build number.
I'd like to automate the collecting of migration scripts (updated sprocs etc) to add to the zip package.
I guess by comparing the svn revision of the db that has yet to be deployed to, to the revision being deployed, i can find what db files have changed in the trunk since the last deployment to that database/environment.
This could easily be achieved by manually calling the `svn diff -r REVNO:REVNO` command to list changed .sql files. These files could then manually have to be added to the package.
It would be great if this could be automated.
Firstly i'd imagine I'll have to write a custom task to check the version of the db that has yet to be deployed to. After that I'm quite unsure.
Does anyone have any suggestion on how this would be achieved through an msbuild task either existing or custom?
Finally I'll have to autogen a script to add to the package that updates the database version table so as to be in sync with the application. | 2010/05/20 | [
"https://Stackoverflow.com/questions/2872555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/345963/"
] | Have a look at SQL database projects. In VS 2010 they have been enhanced quite a bit and have built in deployment capabilities that can sync your DEV database to other environments.
Here are a few good links about DB projects in vs 2010:
<http://msmvps.com/blogs/deborahk/archive/2010/05/02/vs-2010-database-project-building-and-deployment.aspx>
<http://weblogs.asp.net/gunnarpeipman/archive/2009/07/29/visual-studio-2010-database-projects.aspx> | The solutions available today that target a .NET/SQL Server stack are:
* [DBUp](https://dbup.github.io/) (open source)
* [ReadyRoll](http://www.red-gate.com/products/sql-development/readyroll/) (deeper Visual Studio integration,
auto-generation of scripts)
The latter product is one that we're actively developing here at Redgate. |
2,872,555 | Summary of environment.
* Asp.net web application (source stored in svn)
* SQL Server database. (Database schema (tables/sprocs) stored in svn)
* db version is synced with web application assembly version. (stored in table 'CurrentVersion')
* CI hudson server that checks out web app from repo and runs custom msbuild file to publish/package app.
My msbuild script updates the assembly version of the web app (Major.Minor.Revision.Build) on each build. The 'Revision' is set to the currently checked out svn revision and the 'Build' to the hudson build number (incremented on each automated build).
This way i can match the app to a specific trunk revision also get other build stats from the hudson build number.
I'd like to automate the collecting of migration scripts (updated sprocs etc) to add to the zip package.
I guess by comparing the svn revision of the db that has yet to be deployed to, to the revision being deployed, i can find what db files have changed in the trunk since the last deployment to that database/environment.
This could easily be achieved by manually calling the `svn diff -r REVNO:REVNO` command to list changed .sql files. These files could then manually have to be added to the package.
It would be great if this could be automated.
Firstly i'd imagine I'll have to write a custom task to check the version of the db that has yet to be deployed to. After that I'm quite unsure.
Does anyone have any suggestion on how this would be achieved through an msbuild task either existing or custom?
Finally I'll have to autogen a script to add to the package that updates the database version table so as to be in sync with the application. | 2010/05/20 | [
"https://Stackoverflow.com/questions/2872555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/345963/"
] | Integrating SQL changes into an automated build/deploy process is HARD. I know, because I've tried to to it a couple times with limited success. What you're trying to do is roughly on the right track, but I would argue that it's actually a bit too complicated. In your proposal, you suggest collecting the specific SQL scripts that need to be applied to your DB at build/package time. Instead, you should package *all* your delta scripts (for the entire history of your database) with your project, and calculate the deltas that actually need to be applied when you *deploy* -- that way, your deployable package can be deployed to environments with databases of differing versions. There are two implementation pieces you need to achieve this:
1) You need to package your deltas into your deployable package. Note that you should package *deltas* -- not static files that create the schema in its current state. These delta scripts should be in source control. It's okay to keep the static schema in source control as well, but you will have to keep it in sync with the deltas. You can actually use a tool like Red Gate's SQLCompare or the VS Database version to generate (most) deltas from the static schema. To get the deltas into your deployable package, and given that you're using svn -- you may want to look into svn:externals as a way to "soft link" the delta scripts into your web project. Your build script can then simply copy them into your deployable package.
2) You need a system that can read the list of delta files, compare them to an existing database, determine which deltas need to be applied to that database, and then apply the deltas (and update the bookkeeping information, like the database version). There is an open-source project (sponsored by ThoughtWorks) called [dbdeploy](http://dbdeploy.com/) that accomplishes this. I've had some success with that tool personally.
Good luck -- this is a tough nut to crack (correctly). | Try SQL Examiner:
<http://www.sqlaccessories.com/Howto/Version_Control.aspx>
You can automate script collecting with SQL Examiner command-line tool. |
2,872,555 | Summary of environment.
* Asp.net web application (source stored in svn)
* SQL Server database. (Database schema (tables/sprocs) stored in svn)
* db version is synced with web application assembly version. (stored in table 'CurrentVersion')
* CI hudson server that checks out web app from repo and runs custom msbuild file to publish/package app.
My msbuild script updates the assembly version of the web app (Major.Minor.Revision.Build) on each build. The 'Revision' is set to the currently checked out svn revision and the 'Build' to the hudson build number (incremented on each automated build).
This way i can match the app to a specific trunk revision also get other build stats from the hudson build number.
I'd like to automate the collecting of migration scripts (updated sprocs etc) to add to the zip package.
I guess by comparing the svn revision of the db that has yet to be deployed to, to the revision being deployed, i can find what db files have changed in the trunk since the last deployment to that database/environment.
This could easily be achieved by manually calling the `svn diff -r REVNO:REVNO` command to list changed .sql files. These files could then manually have to be added to the package.
It would be great if this could be automated.
Firstly i'd imagine I'll have to write a custom task to check the version of the db that has yet to be deployed to. After that I'm quite unsure.
Does anyone have any suggestion on how this would be achieved through an msbuild task either existing or custom?
Finally I'll have to autogen a script to add to the package that updates the database version table so as to be in sync with the application. | 2010/05/20 | [
"https://Stackoverflow.com/questions/2872555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/345963/"
] | Integrating SQL changes into an automated build/deploy process is HARD. I know, because I've tried to to it a couple times with limited success. What you're trying to do is roughly on the right track, but I would argue that it's actually a bit too complicated. In your proposal, you suggest collecting the specific SQL scripts that need to be applied to your DB at build/package time. Instead, you should package *all* your delta scripts (for the entire history of your database) with your project, and calculate the deltas that actually need to be applied when you *deploy* -- that way, your deployable package can be deployed to environments with databases of differing versions. There are two implementation pieces you need to achieve this:
1) You need to package your deltas into your deployable package. Note that you should package *deltas* -- not static files that create the schema in its current state. These delta scripts should be in source control. It's okay to keep the static schema in source control as well, but you will have to keep it in sync with the deltas. You can actually use a tool like Red Gate's SQLCompare or the VS Database version to generate (most) deltas from the static schema. To get the deltas into your deployable package, and given that you're using svn -- you may want to look into svn:externals as a way to "soft link" the delta scripts into your web project. Your build script can then simply copy them into your deployable package.
2) You need a system that can read the list of delta files, compare them to an existing database, determine which deltas need to be applied to that database, and then apply the deltas (and update the bookkeeping information, like the database version). There is an open-source project (sponsored by ThoughtWorks) called [dbdeploy](http://dbdeploy.com/) that accomplishes this. I've had some success with that tool personally.
Good luck -- this is a tough nut to crack (correctly). | The solutions available today that target a .NET/SQL Server stack are:
* [DBUp](https://dbup.github.io/) (open source)
* [ReadyRoll](http://www.red-gate.com/products/sql-development/readyroll/) (deeper Visual Studio integration,
auto-generation of scripts)
The latter product is one that we're actively developing here at Redgate. |
5,238,773 | How can I get my toggle button to not only change names from view to hide but to also display a table that I have in a div tag?
I currently have the following for my script:
```
<script type = "text/javascript">
function buttonToggle(where,pval,nval)
{
where.value = (where.value == pval) ? nval : pval;
}
</script>
```
and this is the code for the button:
```
<input type="button" name="button1" id="nextbt" value="View " onclick="buttonToggle(this,'View ','Hide ')">
``` | 2011/03/08 | [
"https://Stackoverflow.com/questions/5238773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650553/"
] | Something like:
```
function buttonToggle(where,pval,nval) {
var display = where.value === nval ? 'none' : 'block'; // or 'table'
document.getElementById('yourTableId').style.display = display;
where.value = (where.value == pval) ? nval : pval;
}
```
---
Or better:
```
function buttonToggle(source, target, show_val, hide_val) {
var display = source.value === hide_val ? 'none' : 'block'; // or 'table'
target.style.display = display;
source.value = (source.value == show_val) ? hide_val : show_val;
}
```
and instead of adding your click handler inline, use JavaScript:
```
document.getElementById('nextbt').onclick = (function() {
var table = document.getElementById('yourTableId');
return function() {
buttonToggle(this, table, 'View', 'Hide');
};
}());
``` | You will want to change the div's `style.visible` to `visible` or `hidden`, and/or set the `style.display` to `block` or `none`.
See: <http://w3schools.com/css/css_display_visibility.asp> |
5,238,773 | How can I get my toggle button to not only change names from view to hide but to also display a table that I have in a div tag?
I currently have the following for my script:
```
<script type = "text/javascript">
function buttonToggle(where,pval,nval)
{
where.value = (where.value == pval) ? nval : pval;
}
</script>
```
and this is the code for the button:
```
<input type="button" name="button1" id="nextbt" value="View " onclick="buttonToggle(this,'View ','Hide ')">
``` | 2011/03/08 | [
"https://Stackoverflow.com/questions/5238773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650553/"
] | use jQuery. see demo <http://jsfiddle.net/nBJXq/2/> | You will want to change the div's `style.visible` to `visible` or `hidden`, and/or set the `style.display` to `block` or `none`.
See: <http://w3schools.com/css/css_display_visibility.asp> |
5,238,773 | How can I get my toggle button to not only change names from view to hide but to also display a table that I have in a div tag?
I currently have the following for my script:
```
<script type = "text/javascript">
function buttonToggle(where,pval,nval)
{
where.value = (where.value == pval) ? nval : pval;
}
</script>
```
and this is the code for the button:
```
<input type="button" name="button1" id="nextbt" value="View " onclick="buttonToggle(this,'View ','Hide ')">
``` | 2011/03/08 | [
"https://Stackoverflow.com/questions/5238773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650553/"
] | Well if you can use jQuery it would be very easy:
```
$('#nextbt').click(function() {
if ($(this).attr('value') == 'show') {
$(this).attr('value', 'hide');
$('#myotherdiv').slideDown();
} else {
$(this).attr('value', 'show');
$('#myotherdiv').slideUp();
}
// or if you don't care about changing the button text, simply:
$('#myotherdiv').slideToggle();
});
```
More here: <http://api.jquery.com/slideToggle/> | You will want to change the div's `style.visible` to `visible` or `hidden`, and/or set the `style.display` to `block` or `none`.
See: <http://w3schools.com/css/css_display_visibility.asp> |
5,238,773 | How can I get my toggle button to not only change names from view to hide but to also display a table that I have in a div tag?
I currently have the following for my script:
```
<script type = "text/javascript">
function buttonToggle(where,pval,nval)
{
where.value = (where.value == pval) ? nval : pval;
}
</script>
```
and this is the code for the button:
```
<input type="button" name="button1" id="nextbt" value="View " onclick="buttonToggle(this,'View ','Hide ')">
``` | 2011/03/08 | [
"https://Stackoverflow.com/questions/5238773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650553/"
] | Let's say you add the `id` of the table you want to show/hide as the `rel` attribute of the button:
```
<input type="button" name="button1" id="nextbt"
rel="myTable" value="View "
onclick="buttonToggle(this,'View ','Hide ')">
<table id="myTable">
<tr>
<td>myTable</td>
</tr>
</table>
```
Then you could add the following to your `buttonToggle` function:
```
function buttonToggle(where, pval, nval) {
var table = document.getElementById(where.attributes.rel.value);
where.value = (where.value == pval) ? nval : pval;
table.style.display = (table.style.display == 'block') ? 'none' : 'block';
}
```
[See example.](http://jsfiddle.net/qMEzn/2/) | You will want to change the div's `style.visible` to `visible` or `hidden`, and/or set the `style.display` to `block` or `none`.
See: <http://w3schools.com/css/css_display_visibility.asp> |
5,238,773 | How can I get my toggle button to not only change names from view to hide but to also display a table that I have in a div tag?
I currently have the following for my script:
```
<script type = "text/javascript">
function buttonToggle(where,pval,nval)
{
where.value = (where.value == pval) ? nval : pval;
}
</script>
```
and this is the code for the button:
```
<input type="button" name="button1" id="nextbt" value="View " onclick="buttonToggle(this,'View ','Hide ')">
``` | 2011/03/08 | [
"https://Stackoverflow.com/questions/5238773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650553/"
] | Well if you can use jQuery it would be very easy:
```
$('#nextbt').click(function() {
if ($(this).attr('value') == 'show') {
$(this).attr('value', 'hide');
$('#myotherdiv').slideDown();
} else {
$(this).attr('value', 'show');
$('#myotherdiv').slideUp();
}
// or if you don't care about changing the button text, simply:
$('#myotherdiv').slideToggle();
});
```
More here: <http://api.jquery.com/slideToggle/> | Something like:
```
function buttonToggle(where,pval,nval) {
var display = where.value === nval ? 'none' : 'block'; // or 'table'
document.getElementById('yourTableId').style.display = display;
where.value = (where.value == pval) ? nval : pval;
}
```
---
Or better:
```
function buttonToggle(source, target, show_val, hide_val) {
var display = source.value === hide_val ? 'none' : 'block'; // or 'table'
target.style.display = display;
source.value = (source.value == show_val) ? hide_val : show_val;
}
```
and instead of adding your click handler inline, use JavaScript:
```
document.getElementById('nextbt').onclick = (function() {
var table = document.getElementById('yourTableId');
return function() {
buttonToggle(this, table, 'View', 'Hide');
};
}());
``` |
5,238,773 | How can I get my toggle button to not only change names from view to hide but to also display a table that I have in a div tag?
I currently have the following for my script:
```
<script type = "text/javascript">
function buttonToggle(where,pval,nval)
{
where.value = (where.value == pval) ? nval : pval;
}
</script>
```
and this is the code for the button:
```
<input type="button" name="button1" id="nextbt" value="View " onclick="buttonToggle(this,'View ','Hide ')">
``` | 2011/03/08 | [
"https://Stackoverflow.com/questions/5238773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650553/"
] | Well if you can use jQuery it would be very easy:
```
$('#nextbt').click(function() {
if ($(this).attr('value') == 'show') {
$(this).attr('value', 'hide');
$('#myotherdiv').slideDown();
} else {
$(this).attr('value', 'show');
$('#myotherdiv').slideUp();
}
// or if you don't care about changing the button text, simply:
$('#myotherdiv').slideToggle();
});
```
More here: <http://api.jquery.com/slideToggle/> | use jQuery. see demo <http://jsfiddle.net/nBJXq/2/> |
5,238,773 | How can I get my toggle button to not only change names from view to hide but to also display a table that I have in a div tag?
I currently have the following for my script:
```
<script type = "text/javascript">
function buttonToggle(where,pval,nval)
{
where.value = (where.value == pval) ? nval : pval;
}
</script>
```
and this is the code for the button:
```
<input type="button" name="button1" id="nextbt" value="View " onclick="buttonToggle(this,'View ','Hide ')">
``` | 2011/03/08 | [
"https://Stackoverflow.com/questions/5238773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650553/"
] | Well if you can use jQuery it would be very easy:
```
$('#nextbt').click(function() {
if ($(this).attr('value') == 'show') {
$(this).attr('value', 'hide');
$('#myotherdiv').slideDown();
} else {
$(this).attr('value', 'show');
$('#myotherdiv').slideUp();
}
// or if you don't care about changing the button text, simply:
$('#myotherdiv').slideToggle();
});
```
More here: <http://api.jquery.com/slideToggle/> | Let's say you add the `id` of the table you want to show/hide as the `rel` attribute of the button:
```
<input type="button" name="button1" id="nextbt"
rel="myTable" value="View "
onclick="buttonToggle(this,'View ','Hide ')">
<table id="myTable">
<tr>
<td>myTable</td>
</tr>
</table>
```
Then you could add the following to your `buttonToggle` function:
```
function buttonToggle(where, pval, nval) {
var table = document.getElementById(where.attributes.rel.value);
where.value = (where.value == pval) ? nval : pval;
table.style.display = (table.style.display == 'block') ? 'none' : 'block';
}
```
[See example.](http://jsfiddle.net/qMEzn/2/) |
53,093,998 | I'm trying to convert the sine of an angle from radians to degrees and I keep getting inaccurate numbers. My code looks like this:
```
public class PhysicsSolverAttempt2 {
public static void main(String[] args) {
double[] numbers = {60, 30, 0};
double launchAngle = Double.parseDouble(numbers[0]);
double iV = Double.parseDouble(numbers[1]);
System.out.println(launchAngle);
double iVV = iV * Math.toDegrees(Math.sin(launchAngle));
System.out.println(Math.toDegrees(Math.sin(launchAngle)));
}
}
```
When I use Math.sin(launchAngle), it gives me a perfect output in radians. However, when I convert the radians to degrees using the Math.toDegrees() function at the end, it gives me -17.464362139918286, though performing the same calculation with a calculator yields the number 0.86602540378. Am I using Math.toDegrees() incorrectly, or do I need to perform extra steps to get an accurate result? | 2018/11/01 | [
"https://Stackoverflow.com/questions/53093998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9647271/"
] | Seems that your `region` data was double-encoded. In javascript, you'll want to decode that, e.g.
```
const response = {
"result": "ok",
"data": [
{
"idx": 1,
"region": "[\"USA \", \"Mexico \", \"Canada \"]",
"regDate": "2018-10-31T07:53:12.000Z"
}
]
};
const regions = JSON.parse(response.data[0].region);
```
For time formatting, you could use the built-in Javascript `Date` type, such as..
```
const regDate = new Date(response.data[0].regDate);
const regDatestr =
regDate.getUTCFullYear() + '-' +
regDate.getUTCMonth() + '-' +
regDate.getDate() + ' ' +
regDate.getUTCHours() + ':' +
regDate.getUTCMinutes()
;
```
If you need more functionality than the built-in, I would recommend [date-fns](https://date-fns.org/). | You'd save the results of your JSON query to a variable `data`. Then you'd do this:
```
var countries = "";
for (var i = 0; i < data[0].region.length; i++) {
countries += data[0].region[i];
}
var time = data[0].regDate.split("000Z");
``` |
48,265,971 | I am newish to Java and trying to building a small rocket program.
I have 3 distinct methods that change the size and colour of the rockets exhaust jet on the graphical display when invoked which work great individually.
```
public void pulse1()
{
jet.setDiameter(6);
jet.setColour(OUColour.RED);
jet.setXPos(58);
}
public void pulse2()
{
jet.setDiameter(12);
jet.setColour(OUColour.ORANGE);
jet.setXPos(55);
}
public void pulse3()
{
jet.setDiameter(24);
jet.setColour(OUColour.RED);
jet.setXPos(48);
}
```
However, what I am trying to do is code another method `ignition()` that uses some sort of loop to invoke each of the three pulse methods in that chronological order a maximum of 5 times with a 500 millisecond delay between each call. (the idea being to simulate on the graphical display the firing up of the rockets engines)
Thus far I have tried the following without success.
```
public void ignition()
{
pulse1();
delay(500); // uses the inbuilt delay method
pulse2();
delay(500);
pulse3();
}
``` | 2018/01/15 | [
"https://Stackoverflow.com/questions/48265971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7052518/"
] | When this error occurs, it generally means that hibernate is having problem mapping foreign keys on a right number of columns.
In above case, the `subject` entity in `StudentSubject` class was not getting mapped to two columns, that is the `name` and `teacher_email`(which is the primary key of `Teacher` table).
To fix such errors, add `@JoinColumns` as below
```
class StudentSubject {
@Id
@ManyToOne
@JoinColumns({
@JoinColumn(referencedColumnName = "name"),
@JoinColumn(referencedColumnName = "teacher_email") })
private Subject subject;
}
```
The `referencedColumnName` refers to the name of the column in the foreign table. | try to set OneToMany in this way:
```
@OneToMany(
cascade = CascadeType.ALL,
orphanRemoval = true)
private List<StudentSubject> students = new ArrayList<>();
``` |
48,265,971 | I am newish to Java and trying to building a small rocket program.
I have 3 distinct methods that change the size and colour of the rockets exhaust jet on the graphical display when invoked which work great individually.
```
public void pulse1()
{
jet.setDiameter(6);
jet.setColour(OUColour.RED);
jet.setXPos(58);
}
public void pulse2()
{
jet.setDiameter(12);
jet.setColour(OUColour.ORANGE);
jet.setXPos(55);
}
public void pulse3()
{
jet.setDiameter(24);
jet.setColour(OUColour.RED);
jet.setXPos(48);
}
```
However, what I am trying to do is code another method `ignition()` that uses some sort of loop to invoke each of the three pulse methods in that chronological order a maximum of 5 times with a 500 millisecond delay between each call. (the idea being to simulate on the graphical display the firing up of the rockets engines)
Thus far I have tried the following without success.
```
public void ignition()
{
pulse1();
delay(500); // uses the inbuilt delay method
pulse2();
delay(500);
pulse3();
}
``` | 2018/01/15 | [
"https://Stackoverflow.com/questions/48265971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7052518/"
] | When this error occurs, it generally means that hibernate is having problem mapping foreign keys on a right number of columns.
In above case, the `subject` entity in `StudentSubject` class was not getting mapped to two columns, that is the `name` and `teacher_email`(which is the primary key of `Teacher` table).
To fix such errors, add `@JoinColumns` as below
```
class StudentSubject {
@Id
@ManyToOne
@JoinColumns({
@JoinColumn(referencedColumnName = "name"),
@JoinColumn(referencedColumnName = "teacher_email") })
private Subject subject;
}
```
The `referencedColumnName` refers to the name of the column in the foreign table. | It is definitely too late but I will answer so maybe it helps some other people. I had similar issue to yours, my error was slightly different though:
```
Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: collection foreign key mapping has wrong number of columns: com.bla.bla.yourPackage..className.errorField type: long
```
In my case the error was clear enough but still took me a while to figure out. If I apply it to your case then you had a wrong 1:M mapping in this place:
```
@OneToMany(mappedBy = "student")
private List<StudentSubject> students;
```
mappedBy should be mapped by one of the fields (columns) in the **StudentSubject** class. Refer to this for better understanding:
<https://l-lin.github.io/2018-11-14_jpa_onetomany_composite_pk/>
So, if you change "mappedBy" to something like this, it should work:
```
//@OneToMany(mappedBy = "student.name")
@OneToMany(mappedBy = "student.teacher")
private List<StudentSubject> students;
``` |
137,537 | ```
left_click = mouse_check_button_pressed (mb_left)
battleMode = true
if (left_click) battleMode = false
if battleMode = false then {
if (key_right) then {
x= x+5
sprite_index= spr_walking
image_speed = 0.5
}
}
```
`battleMode` becomes `true` again once left click is not being held. I tried changing `mouse_check_button_pressed` to `mouse_check_button_released` and `mouse_check_button`, but `battleMode` becomes `true` again when `left_click` has done its job. | 2017/02/18 | [
"https://gamedev.stackexchange.com/questions/137537",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/97889/"
] | 1. To set the text you have to use
```
BitmapFontCache.setText(text, x, y);
```
2. In the render method you just do
```
BitmapFontCache.draw(batch);
```
3. You only have to update the score position once in the render method. | Thanks for `Klemmensen` I ended up doing
```
game.font.setColor(Color.WHITE);
game.font.draw(game.batch, "Score: " +score, x, y);
``` |
32,670,720 | I need to find the minimum value in int array, but the answer it gives me is really odd and from that I cannot even judge where the error is, I would really appreciate help. Here is the code I have written:
```
#include <stdio.h>
#include <iostream>
#include <cmath>
#include <iomanip>
#include <conio.h>
#include <random>
#include <cstdlib>
#include <ctime>
using namespace std;
int minVert(int minimum, int i) {
int j, array[20];
for (j = 0; j < 19; j++) {
if (array[i] < minimum ) {
minimum = array[i];
}
}
return minimum;
}
int main(int k, int minimum) {
int array[20];
srand(time(NULL));
for (int i = 0; i < 20; i++) {
k = rand() % 1000 + 2;
array[i] = k;
}
cout << "Tiek generets masivs..." << endl << "..." << endl << "..." << endl << "..." << endl << endl;
cout << "Masiva elementi ir: " << endl;
for (int j = 0; j <20; j++) {
cout << array[j] << endl;
}
cout << endl << "Masiva mazaka vertiba ir: " << endl << minimum << endl << endl;
cout << "Nospiediet jebkuru taustinu, lai izietu no programmas" << endl;
_getch();
return 0;
}
``` | 2015/09/19 | [
"https://Stackoverflow.com/questions/32670720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5001188/"
] | >
>
> ```
> int main(int k, int minimum){
>
> ```
>
>
This is illegal. The only valid signature for `main()` is
```
int main(int argc, char* argv[]) {
// ...
}
```
or leave out any parameters at all
```
int main() {
// ...
}
```
In the first case `argc` contains the number of command line arguments passed, and `argv` is an array of `char*` pointers, that contain the arguments.
Note that `argv[0]` contains the name of the executed program itself. | Initialize your minimum variable as `minimum = array[0]` so your code will become like follow
```
int minVert(int minimum, int i){
int j, array[20];
minimum = array[0];
for (j = 0; j < 19; j++) {
if (array[i] < minimum ) {
minimum = array[i];
}
}
return minimum;
}
```
And if you want to write a function to find the minimum from an array the best practice is to write a code which will take reference of the array and return the minimum value |
32,670,720 | I need to find the minimum value in int array, but the answer it gives me is really odd and from that I cannot even judge where the error is, I would really appreciate help. Here is the code I have written:
```
#include <stdio.h>
#include <iostream>
#include <cmath>
#include <iomanip>
#include <conio.h>
#include <random>
#include <cstdlib>
#include <ctime>
using namespace std;
int minVert(int minimum, int i) {
int j, array[20];
for (j = 0; j < 19; j++) {
if (array[i] < minimum ) {
minimum = array[i];
}
}
return minimum;
}
int main(int k, int minimum) {
int array[20];
srand(time(NULL));
for (int i = 0; i < 20; i++) {
k = rand() % 1000 + 2;
array[i] = k;
}
cout << "Tiek generets masivs..." << endl << "..." << endl << "..." << endl << "..." << endl << endl;
cout << "Masiva elementi ir: " << endl;
for (int j = 0; j <20; j++) {
cout << array[j] << endl;
}
cout << endl << "Masiva mazaka vertiba ir: " << endl << minimum << endl << endl;
cout << "Nospiediet jebkuru taustinu, lai izietu no programmas" << endl;
_getch();
return 0;
}
``` | 2015/09/19 | [
"https://Stackoverflow.com/questions/32670720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5001188/"
] | I think your trying to populate the array with random numbers and then find the minimum.
First remove those parameters from the main function if your not going to use them. You haven't really called the function you wrote in the main. so either write that inside the main or call that function.
i would suggest this :
```
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
srand(time(NULL));
int array[5];
int minimum;
for(int i = 0; i < 20; i++)
{
array[i] = rand() % 100 + 2;
}
for(int i = 0; i < 20; i++)
{
cout << array[i] << endl;
}
minimum = array[0];
for(int i = 0; i < 20; i++)
{
if(array[i] < minimum)
{
minimum = array[i];
}
}
cout << "minumum is : " << minimum;
}
``` | Initialize your minimum variable as `minimum = array[0]` so your code will become like follow
```
int minVert(int minimum, int i){
int j, array[20];
minimum = array[0];
for (j = 0; j < 19; j++) {
if (array[i] < minimum ) {
minimum = array[i];
}
}
return minimum;
}
```
And if you want to write a function to find the minimum from an array the best practice is to write a code which will take reference of the array and return the minimum value |
32,670,720 | I need to find the minimum value in int array, but the answer it gives me is really odd and from that I cannot even judge where the error is, I would really appreciate help. Here is the code I have written:
```
#include <stdio.h>
#include <iostream>
#include <cmath>
#include <iomanip>
#include <conio.h>
#include <random>
#include <cstdlib>
#include <ctime>
using namespace std;
int minVert(int minimum, int i) {
int j, array[20];
for (j = 0; j < 19; j++) {
if (array[i] < minimum ) {
minimum = array[i];
}
}
return minimum;
}
int main(int k, int minimum) {
int array[20];
srand(time(NULL));
for (int i = 0; i < 20; i++) {
k = rand() % 1000 + 2;
array[i] = k;
}
cout << "Tiek generets masivs..." << endl << "..." << endl << "..." << endl << "..." << endl << endl;
cout << "Masiva elementi ir: " << endl;
for (int j = 0; j <20; j++) {
cout << array[j] << endl;
}
cout << endl << "Masiva mazaka vertiba ir: " << endl << minimum << endl << endl;
cout << "Nospiediet jebkuru taustinu, lai izietu no programmas" << endl;
_getch();
return 0;
}
``` | 2015/09/19 | [
"https://Stackoverflow.com/questions/32670720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5001188/"
] | I think your trying to populate the array with random numbers and then find the minimum.
First remove those parameters from the main function if your not going to use them. You haven't really called the function you wrote in the main. so either write that inside the main or call that function.
i would suggest this :
```
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
srand(time(NULL));
int array[5];
int minimum;
for(int i = 0; i < 20; i++)
{
array[i] = rand() % 100 + 2;
}
for(int i = 0; i < 20; i++)
{
cout << array[i] << endl;
}
minimum = array[0];
for(int i = 0; i < 20; i++)
{
if(array[i] < minimum)
{
minimum = array[i];
}
}
cout << "minumum is : " << minimum;
}
``` | >
>
> ```
> int main(int k, int minimum){
>
> ```
>
>
This is illegal. The only valid signature for `main()` is
```
int main(int argc, char* argv[]) {
// ...
}
```
or leave out any parameters at all
```
int main() {
// ...
}
```
In the first case `argc` contains the number of command line arguments passed, and `argv` is an array of `char*` pointers, that contain the arguments.
Note that `argv[0]` contains the name of the executed program itself. |
92,959 | I am the creator of a growing open source project. Currently, I'm becoming frusterated trying to figure out the best way to manage documentation. Here are the options I have considered:
* HTML Website
* A Github Wiki
* Markdown Files Hosted On Github
* Placing All Docs in Github README.md
The documentation is already written in Markdown, I just can't figure out how I want to make it available. I'm really drawn towards Git since I can branch and tag the documentation just like I can branch and tag the source.
I could use a Markdown library to translate the Markdown to HTML and display it on a styled website. I would need to upload changes to the website anytime there was a change, and it would be difficult to manage all of the different "tags" of the documentation.
Github Wikis (as far as I know) do not change according to the branch you are on. So, I could only have the "master" version of the documentation in Github Wiki form at any given time.
Putting it all in the Github README is kinda neat. I get branching and tagging, but it's a little tiring to use and doesn't lend itself well to easy navigation.
Am I missing some awesome solution? What other options do I have? | 2011/07/14 | [
"https://softwareengineering.stackexchange.com/questions/92959",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/4881/"
] | One thing I would say is the documentation MUST be in the source code files (using whatever markup you want) and then docs generated automatically from these.
At least on your site, you can generate formatted downloads of the docs as part of the source package so the user doesn't need a specific doc tool
The chance of somebody else fixing/adding a function and then editing/adding a bit of markup documentation immediately adjacent in the same file may be low BUT the chance of them finding a completely different file in a different document repository to do the same are slightly less than zero.
You can always have a tutorial.h that contains big blocks of text if your want - but treat it as part of the source | Markdown Files Hosted with the source works extremely well.
The RST-based [docutils](http://docutils.sourceforge.net/) tools, for example, can create HTML or LaTex (and PDFs) from one set of documents.
This -- in effect -- combines your option 1 and option 3. |
92,959 | I am the creator of a growing open source project. Currently, I'm becoming frusterated trying to figure out the best way to manage documentation. Here are the options I have considered:
* HTML Website
* A Github Wiki
* Markdown Files Hosted On Github
* Placing All Docs in Github README.md
The documentation is already written in Markdown, I just can't figure out how I want to make it available. I'm really drawn towards Git since I can branch and tag the documentation just like I can branch and tag the source.
I could use a Markdown library to translate the Markdown to HTML and display it on a styled website. I would need to upload changes to the website anytime there was a change, and it would be difficult to manage all of the different "tags" of the documentation.
Github Wikis (as far as I know) do not change according to the branch you are on. So, I could only have the "master" version of the documentation in Github Wiki form at any given time.
Putting it all in the Github README is kinda neat. I get branching and tagging, but it's a little tiring to use and doesn't lend itself well to easy navigation.
Am I missing some awesome solution? What other options do I have? | 2011/07/14 | [
"https://softwareengineering.stackexchange.com/questions/92959",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/4881/"
] | One thing I would say is the documentation MUST be in the source code files (using whatever markup you want) and then docs generated automatically from these.
At least on your site, you can generate formatted downloads of the docs as part of the source package so the user doesn't need a specific doc tool
The chance of somebody else fixing/adding a function and then editing/adding a bit of markup documentation immediately adjacent in the same file may be low BUT the chance of them finding a completely different file in a different document repository to do the same are slightly less than zero.
You can always have a tutorial.h that contains big blocks of text if your want - but treat it as part of the source | If your project is a library, nothing beats javadoc-style documentation to document the API syntax from comments within the code itself.
As for the documentation on tutorials, usage examples, etc. I highly recommend using a wiki format. Other projects I've seen have separate pages for different branches. When you start a new branch you just copy over the things that haven't changed to a new page and update from there.
My reason for recommending a wiki is anecdotal, but from personal experience. I have contributed documentation updates to open source projects on several occasions, but they have all been on wikis. If I'm trying to figure something out and the documentation is misleading or unhelpful, after I figure it out I will update the wiki while I'm in the docs and it's fresh in my mind. If not out of a sense of giving back, at the least because I know I'm likely to need to look it up again myself in a year or two.
If there isn't a wiki, the barrier to entry is just too high to bother, between figuring out how the documentation is generated, where it's stored, getting the latest from source control, how to make edits, making the actual edits, and navigating the mailing lists to get a patch accepted.
If you want tight control over your documentation, by all means use whatever is most comfortable for you, because you'll mostly be the only one updating it. If you want to encourage community participation, use a wiki. |
92,959 | I am the creator of a growing open source project. Currently, I'm becoming frusterated trying to figure out the best way to manage documentation. Here are the options I have considered:
* HTML Website
* A Github Wiki
* Markdown Files Hosted On Github
* Placing All Docs in Github README.md
The documentation is already written in Markdown, I just can't figure out how I want to make it available. I'm really drawn towards Git since I can branch and tag the documentation just like I can branch and tag the source.
I could use a Markdown library to translate the Markdown to HTML and display it on a styled website. I would need to upload changes to the website anytime there was a change, and it would be difficult to manage all of the different "tags" of the documentation.
Github Wikis (as far as I know) do not change according to the branch you are on. So, I could only have the "master" version of the documentation in Github Wiki form at any given time.
Putting it all in the Github README is kinda neat. I get branching and tagging, but it's a little tiring to use and doesn't lend itself well to easy navigation.
Am I missing some awesome solution? What other options do I have? | 2011/07/14 | [
"https://softwareengineering.stackexchange.com/questions/92959",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/4881/"
] | One thing I would say is the documentation MUST be in the source code files (using whatever markup you want) and then docs generated automatically from these.
At least on your site, you can generate formatted downloads of the docs as part of the source package so the user doesn't need a specific doc tool
The chance of somebody else fixing/adding a function and then editing/adding a bit of markup documentation immediately adjacent in the same file may be low BUT the chance of them finding a completely different file in a different document repository to do the same are slightly less than zero.
You can always have a tutorial.h that contains big blocks of text if your want - but treat it as part of the source | If you don't mind converting the docs from Markdown to reStructuredText, consider [Sphinx](http://sphinx.pocoo.org)
. It's just as easy as markdown, but it's a lot more powerful. |
92,959 | I am the creator of a growing open source project. Currently, I'm becoming frusterated trying to figure out the best way to manage documentation. Here are the options I have considered:
* HTML Website
* A Github Wiki
* Markdown Files Hosted On Github
* Placing All Docs in Github README.md
The documentation is already written in Markdown, I just can't figure out how I want to make it available. I'm really drawn towards Git since I can branch and tag the documentation just like I can branch and tag the source.
I could use a Markdown library to translate the Markdown to HTML and display it on a styled website. I would need to upload changes to the website anytime there was a change, and it would be difficult to manage all of the different "tags" of the documentation.
Github Wikis (as far as I know) do not change according to the branch you are on. So, I could only have the "master" version of the documentation in Github Wiki form at any given time.
Putting it all in the Github README is kinda neat. I get branching and tagging, but it's a little tiring to use and doesn't lend itself well to easy navigation.
Am I missing some awesome solution? What other options do I have? | 2011/07/14 | [
"https://softwareengineering.stackexchange.com/questions/92959",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/4881/"
] | If your project is a library, nothing beats javadoc-style documentation to document the API syntax from comments within the code itself.
As for the documentation on tutorials, usage examples, etc. I highly recommend using a wiki format. Other projects I've seen have separate pages for different branches. When you start a new branch you just copy over the things that haven't changed to a new page and update from there.
My reason for recommending a wiki is anecdotal, but from personal experience. I have contributed documentation updates to open source projects on several occasions, but they have all been on wikis. If I'm trying to figure something out and the documentation is misleading or unhelpful, after I figure it out I will update the wiki while I'm in the docs and it's fresh in my mind. If not out of a sense of giving back, at the least because I know I'm likely to need to look it up again myself in a year or two.
If there isn't a wiki, the barrier to entry is just too high to bother, between figuring out how the documentation is generated, where it's stored, getting the latest from source control, how to make edits, making the actual edits, and navigating the mailing lists to get a patch accepted.
If you want tight control over your documentation, by all means use whatever is most comfortable for you, because you'll mostly be the only one updating it. If you want to encourage community participation, use a wiki. | Markdown Files Hosted with the source works extremely well.
The RST-based [docutils](http://docutils.sourceforge.net/) tools, for example, can create HTML or LaTex (and PDFs) from one set of documents.
This -- in effect -- combines your option 1 and option 3. |
92,959 | I am the creator of a growing open source project. Currently, I'm becoming frusterated trying to figure out the best way to manage documentation. Here are the options I have considered:
* HTML Website
* A Github Wiki
* Markdown Files Hosted On Github
* Placing All Docs in Github README.md
The documentation is already written in Markdown, I just can't figure out how I want to make it available. I'm really drawn towards Git since I can branch and tag the documentation just like I can branch and tag the source.
I could use a Markdown library to translate the Markdown to HTML and display it on a styled website. I would need to upload changes to the website anytime there was a change, and it would be difficult to manage all of the different "tags" of the documentation.
Github Wikis (as far as I know) do not change according to the branch you are on. So, I could only have the "master" version of the documentation in Github Wiki form at any given time.
Putting it all in the Github README is kinda neat. I get branching and tagging, but it's a little tiring to use and doesn't lend itself well to easy navigation.
Am I missing some awesome solution? What other options do I have? | 2011/07/14 | [
"https://softwareengineering.stackexchange.com/questions/92959",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/4881/"
] | Markdown Files Hosted with the source works extremely well.
The RST-based [docutils](http://docutils.sourceforge.net/) tools, for example, can create HTML or LaTex (and PDFs) from one set of documents.
This -- in effect -- combines your option 1 and option 3. | If you don't mind converting the docs from Markdown to reStructuredText, consider [Sphinx](http://sphinx.pocoo.org)
. It's just as easy as markdown, but it's a lot more powerful. |
92,959 | I am the creator of a growing open source project. Currently, I'm becoming frusterated trying to figure out the best way to manage documentation. Here are the options I have considered:
* HTML Website
* A Github Wiki
* Markdown Files Hosted On Github
* Placing All Docs in Github README.md
The documentation is already written in Markdown, I just can't figure out how I want to make it available. I'm really drawn towards Git since I can branch and tag the documentation just like I can branch and tag the source.
I could use a Markdown library to translate the Markdown to HTML and display it on a styled website. I would need to upload changes to the website anytime there was a change, and it would be difficult to manage all of the different "tags" of the documentation.
Github Wikis (as far as I know) do not change according to the branch you are on. So, I could only have the "master" version of the documentation in Github Wiki form at any given time.
Putting it all in the Github README is kinda neat. I get branching and tagging, but it's a little tiring to use and doesn't lend itself well to easy navigation.
Am I missing some awesome solution? What other options do I have? | 2011/07/14 | [
"https://softwareengineering.stackexchange.com/questions/92959",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/4881/"
] | If your project is a library, nothing beats javadoc-style documentation to document the API syntax from comments within the code itself.
As for the documentation on tutorials, usage examples, etc. I highly recommend using a wiki format. Other projects I've seen have separate pages for different branches. When you start a new branch you just copy over the things that haven't changed to a new page and update from there.
My reason for recommending a wiki is anecdotal, but from personal experience. I have contributed documentation updates to open source projects on several occasions, but they have all been on wikis. If I'm trying to figure something out and the documentation is misleading or unhelpful, after I figure it out I will update the wiki while I'm in the docs and it's fresh in my mind. If not out of a sense of giving back, at the least because I know I'm likely to need to look it up again myself in a year or two.
If there isn't a wiki, the barrier to entry is just too high to bother, between figuring out how the documentation is generated, where it's stored, getting the latest from source control, how to make edits, making the actual edits, and navigating the mailing lists to get a patch accepted.
If you want tight control over your documentation, by all means use whatever is most comfortable for you, because you'll mostly be the only one updating it. If you want to encourage community participation, use a wiki. | If you don't mind converting the docs from Markdown to reStructuredText, consider [Sphinx](http://sphinx.pocoo.org)
. It's just as easy as markdown, but it's a lot more powerful. |
9,646,214 | I have a byte array i.e **from byte[0] to byte[2]**. I want to first split byte[0] into 8 bits. Then bytes[1] and finally bytes[2]. By splitting I mean that if byte[0]=12345678 then i want to split as variable A=8,Variable B=7, variable C=6,Variable D=5,........ Variable H=0. How to split the byte and store the bits into variables? I want to do this in JAVA | 2012/03/10 | [
"https://Stackoverflow.com/questions/9646214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1166690/"
] | well the bitwise operations seem to be almost what you're talking about.
a byte is composed of 8 bits, and so it goes in the rage of 0 to 255.
written in binary that's 00000000 to 11111111.
Bitwise operations are those that basically use masks to get out as much info as possible out of a byte.
Say for instance you have your 1101 0011 byte (space added for visibility only) = 211 (decimal). You can split that into 2 "variables" b1 and b2 of half a byte each. they'll thus cover the range of 0 to 15.
How you do this is by defining some masks. A mask to get your first half-a-byte-value would be 0000 1111.
You take your value of 11010011 apply the bitwise and (& ) operator to it.
So saying byte b = 211; byte mask1=15; OR byte b=0x11010011; byte mask1=0x00001111;
you then have your variable byte b1=b & mask1;
Thus applying that operation would result in b1=00000011 = 3;
With a mask byte mask2=0x11110000; applying the same operation on b, you'd get byte b2=mask2 & b = 0x11010000;
Now of course that leaves the number b2 possibly too large for you. All you have to do if you want to grab the value 0x1101 is to right shift it. Thus b2>>=4;
You can have your masks in any form, but it's usual to have them in decimal as the powers of 2 (so that you can take any bit out of your byte) or decide what range you want on your variables and make the mask "larger" like 0x00000011, or ox00001100. Those 2 masks would respectively get you 2 values from a byte, each value ranging from 0 to 3, values that you can fit 4 inside a byte.
for more info, chek out the [relevant wiki](http://en.wikipedia.org/wiki/Bitwise_operation).
Sorry, the values were a little off (since byte seems to go from -128 to 127, but the idea is the same.
Second edit (never used bitwise operations myself lol)... the "0x" notation is for hexadecimals. So you'll actually have to calculate for yourself what 01001111 actually means... pretty sucky :| but it's gonna do the trick. | ```
boolean a = (theByte & 0x1) != 0;
boolean b = (theByte & 0x2) != 0;
boolean c = (theByte & 0x4) != 0;
boolean d = (theByte & 0x8) != 0;
boolean e = (theByte & 0x10) != 0;
boolean f = (theByte & 0x20) != 0;
boolean g = (theByte & 0x40) != 0;
boolean h = (theByte & 0x80) != 0;
``` |
59,681,970 | I have complex application with tons of fragments and sub-fragments, and I need listeners to listen in a fragment, not in activity. This usually works, but not with date or time pickers.
Here is the sample application with activity with one fragment inflated - TestFragmentMain. That inflated fragment have two more fragments - one with single EditText (TestFragment\_InputBox) and another with single TextView (TestFragment\_DateBox) and it is used to listen events (TextChangeListener and DateChangeListener).
On text change in first fragment, all works like a charm, main fragment is receiving result.
However, on date change, I receive and error:
```
java.lang.NullPointerException: Attempt to invoke interface method 'void com.gmail.xxx.xxx.test.DateChangeListener.dateChanged(int, int, int)' on a null object reference
at com.gmail.xxx.xxx.test.TestFragment_DatePicker.onDateSet(TestFragment_DatePicker.java:32)
```
I really do not understand why. Any help is appreciated.
Main activity:
```
public class TestClass extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_activity);
TestFragmentMain testFragmentMain = new TestFragmentMain();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.test_fragment_container, testFragmentMain);
ft.commitAllowingStateLoss();
}
}
```
Main fragment, with listeners
```
public class TestFragmentMain extends Fragment implements TextChangeListener, DateChangeListener {
@Override
public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test_fragment, container, false);
TestFragment_InputBox testFragmentInputBox = new TestFragment_InputBox();
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.test_fragment_inputbox_container, testFragmentInputBox);
ft.commitAllowingStateLoss();
TestFragment_DateBox testFragmentDateBox = new TestFragment_DateBox();
ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.test_fragment_date_container, testFragmentDateBox);
ft.commitAllowingStateLoss();
return view;
}
@Override
public void onAttach(@NotNull Context context) {
super.onAttach(context);
}
@Override
public void textChanged() {
Log.d("LISTEN","Text has been changed...");
}
@Override
public void dateChanged(int year, int month, int day) {
Log.d("LISTEN","Date has been changed to ...");
}
}
```
Fragment with input box:
```
public class TestFragment_InputBox extends Fragment {
private TextChangeListener textChangeListener;
@Override
public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test_input_box, container, false);
EditText editText = view.findViewById(R.id.input_view);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
textChangeListener.textChanged();
}
});
return view;
}
@Override
public void onAttach(@NotNull Context context) {
super.onAttach(context);
try {
textChangeListener = (TextChangeListener) getParentFragment();
} catch (ClassCastException e) {
e.printStackTrace();
}
}
}
```
Fragment with date box:
```
public class TestFragment_DateBox extends Fragment implements DateChangeListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test_date_box, container, false);
TextView textView = view.findViewById(R.id.date_view);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment datePicker = new TestFragment_DatePicker();
datePicker.show(getActivity().getSupportFragmentManager(), "datePicker");
}
});
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void dateChanged(int year, int month, int day) {
Log.d("LISTEN","Date has been changed in box fragment with box ...");
}
}
```
Date Picker fragment
```
public class TestFragment_DatePicker extends DialogFragment implements DatePickerDialog.OnDateSetListener {
public DateChangeListener dateChangeListener;
@NotNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(Objects.requireNonNull(getContext()), this, year, month, day);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
dateChangeListener.dateChanged(year,month,day);
}
@Override
public void onAttach(@NotNull Context context) {
super.onAttach(context);
try {
dateChangeListener = (DateChangeListener) getParentFragment();
} catch (ClassCastException e) {
e.printStackTrace();
}
}
}
```
And listeners:
```
public interface TextChangeListener {
void textChanged();
}
public interface DateChangeListener {
void dateChanged(int year,int month,int day);
}
``` | 2020/01/10 | [
"https://Stackoverflow.com/questions/59681970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2378249/"
] | Your fragment `TestFragment_DateBox` calls the date picker and inherits `DatePickerDialog.OnDateSetListener`
```
public class TestFragment_DateBox extends Fragment implements DatePickerDialog.OnDateSetListener
```
and show the date picker fragment like so
```
TestFragment_DatePicker().show(this.childFragmentManager, "datepicker")
```
and override onDateSet
```
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
// As you are in the calling fragment you can use the values as you see fit
TextView textView = view.findViewById(R.id.date_view);
textView.text = year.toString()
}
```
In `TestFragment_DatePicker` have a listener
```
private lateinit var listener: DatePickerDialog.OnDateSetListener
```
then override onAttach
```
override fun onAttach(context: Context) {
super.onAttach(context)
// Verify that the dialog parent implements the callback interface
try {
// Instantiate the OnDateSetListener so we can send events to the host
listener = parentFragment as DatePickerDialog.OnDateSetListener
} catch (e: ClassCastException) {
// The parent doesn't implement the interface, throw exception
throw ClassCastException(("$context must implement OnDateSetListener"))
}
}
```
Apologies for the mix of java and kotlin but you get the idea! | The problem is that you not inflate your `TestFragment_DatePicker` which is a `DialogFragment` which is a `Fragment` but return a `DatePickerDialog` which is an `AlertDialog` which is a `Dialog` which don't have a `mParentFragment`. That's why `getParentFragment()` return null.
This looks like a bad architecture design that we inherited from old versions of android. |
59,681,970 | I have complex application with tons of fragments and sub-fragments, and I need listeners to listen in a fragment, not in activity. This usually works, but not with date or time pickers.
Here is the sample application with activity with one fragment inflated - TestFragmentMain. That inflated fragment have two more fragments - one with single EditText (TestFragment\_InputBox) and another with single TextView (TestFragment\_DateBox) and it is used to listen events (TextChangeListener and DateChangeListener).
On text change in first fragment, all works like a charm, main fragment is receiving result.
However, on date change, I receive and error:
```
java.lang.NullPointerException: Attempt to invoke interface method 'void com.gmail.xxx.xxx.test.DateChangeListener.dateChanged(int, int, int)' on a null object reference
at com.gmail.xxx.xxx.test.TestFragment_DatePicker.onDateSet(TestFragment_DatePicker.java:32)
```
I really do not understand why. Any help is appreciated.
Main activity:
```
public class TestClass extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_activity);
TestFragmentMain testFragmentMain = new TestFragmentMain();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.test_fragment_container, testFragmentMain);
ft.commitAllowingStateLoss();
}
}
```
Main fragment, with listeners
```
public class TestFragmentMain extends Fragment implements TextChangeListener, DateChangeListener {
@Override
public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test_fragment, container, false);
TestFragment_InputBox testFragmentInputBox = new TestFragment_InputBox();
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.test_fragment_inputbox_container, testFragmentInputBox);
ft.commitAllowingStateLoss();
TestFragment_DateBox testFragmentDateBox = new TestFragment_DateBox();
ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.test_fragment_date_container, testFragmentDateBox);
ft.commitAllowingStateLoss();
return view;
}
@Override
public void onAttach(@NotNull Context context) {
super.onAttach(context);
}
@Override
public void textChanged() {
Log.d("LISTEN","Text has been changed...");
}
@Override
public void dateChanged(int year, int month, int day) {
Log.d("LISTEN","Date has been changed to ...");
}
}
```
Fragment with input box:
```
public class TestFragment_InputBox extends Fragment {
private TextChangeListener textChangeListener;
@Override
public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test_input_box, container, false);
EditText editText = view.findViewById(R.id.input_view);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
textChangeListener.textChanged();
}
});
return view;
}
@Override
public void onAttach(@NotNull Context context) {
super.onAttach(context);
try {
textChangeListener = (TextChangeListener) getParentFragment();
} catch (ClassCastException e) {
e.printStackTrace();
}
}
}
```
Fragment with date box:
```
public class TestFragment_DateBox extends Fragment implements DateChangeListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test_date_box, container, false);
TextView textView = view.findViewById(R.id.date_view);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment datePicker = new TestFragment_DatePicker();
datePicker.show(getActivity().getSupportFragmentManager(), "datePicker");
}
});
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void dateChanged(int year, int month, int day) {
Log.d("LISTEN","Date has been changed in box fragment with box ...");
}
}
```
Date Picker fragment
```
public class TestFragment_DatePicker extends DialogFragment implements DatePickerDialog.OnDateSetListener {
public DateChangeListener dateChangeListener;
@NotNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(Objects.requireNonNull(getContext()), this, year, month, day);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
dateChangeListener.dateChanged(year,month,day);
}
@Override
public void onAttach(@NotNull Context context) {
super.onAttach(context);
try {
dateChangeListener = (DateChangeListener) getParentFragment();
} catch (ClassCastException e) {
e.printStackTrace();
}
}
}
```
And listeners:
```
public interface TextChangeListener {
void textChanged();
}
public interface DateChangeListener {
void dateChanged(int year,int month,int day);
}
``` | 2020/01/10 | [
"https://Stackoverflow.com/questions/59681970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2378249/"
] | Your fragment `TestFragment_DateBox` calls the date picker and inherits `DatePickerDialog.OnDateSetListener`
```
public class TestFragment_DateBox extends Fragment implements DatePickerDialog.OnDateSetListener
```
and show the date picker fragment like so
```
TestFragment_DatePicker().show(this.childFragmentManager, "datepicker")
```
and override onDateSet
```
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
// As you are in the calling fragment you can use the values as you see fit
TextView textView = view.findViewById(R.id.date_view);
textView.text = year.toString()
}
```
In `TestFragment_DatePicker` have a listener
```
private lateinit var listener: DatePickerDialog.OnDateSetListener
```
then override onAttach
```
override fun onAttach(context: Context) {
super.onAttach(context)
// Verify that the dialog parent implements the callback interface
try {
// Instantiate the OnDateSetListener so we can send events to the host
listener = parentFragment as DatePickerDialog.OnDateSetListener
} catch (e: ClassCastException) {
// The parent doesn't implement the interface, throw exception
throw ClassCastException(("$context must implement OnDateSetListener"))
}
}
```
Apologies for the mix of java and kotlin but you get the idea! | I have found a solution.
In TestFragmentMain, TestFragment\_DateBox need to be transacted with same FragmentManager as DatePicker is. And this is the code in TestFragmentMain:
```
TestFragment_DateBox testFragmentDateBox = new TestFragment_DateBox();
FragmentTransaction ft2 = this.getChildFragmentManager().beginTransaction();
ft2.replace(R.id.test_fragment_date_container, testFragmentDateBox);
ft2.commitAllowingStateLoss();
```
Change is also in TestFragment\_DateBox when opening DatePicker:
```
DialogFragment datePicker = new TestFragment_DatePicker();
datePicker.setTargetFragment(this, 0);
datePicker.show(this.getFragmentManager(), "datePicker");
```
We need to run setTargetFragment in order to work.
Now this test works. |
18,741,271 | I need to create a program that reads a string " A = B" and searchs B in an array of variables. If it doesn't find B, then it asks its value and put it in another array.
Well, I don't know if the idea is clear, but here is an example:
```
while(1){
printf("Get string\n");
gets(L);
if(L[0]=='\0') break;
if(L[2] == '1') {
printf("Value of 1: ");
scanf(" %lf", &m);
}
}
printf("\nbreak");
```
I need that this program stops when we type enter, so I used if(L[0]=='\0') break; for it.
My problem is: Everytime I ask the value of B, my program read a "ghost string" L, it is, it doesn't let me put the value of L and the program stops. It is almost double reading the string, but it breaks because of the condition L[0] != '\0'. What am I doing wrong?
If we remove this condition, then the program print 2 times "Get string", without asking me to enter the string 2 times.. | 2013/09/11 | [
"https://Stackoverflow.com/questions/18741271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2768645/"
] | Don't (ever) use `gets()`. It's not good.
Use [`fgets()`](http://linux.die.net/man/3/fgets) instead, noting that it stores the linefeed. Use some higher-level function (like [`sscanf()`](http://linux.die.net/man/3/sscanf)) to parse out the input. Likewise, use another `fgets()` + `sscanf()` combo to do the value reading. | You're doing it wrong, since you never check for errors (including end of file). That's why you're reading twice.
Instead do e.g.
```
while ((fgets(L, sizeof(L), stdin) != NULL)
{
/* ... */
}
``` |
18,741,271 | I need to create a program that reads a string " A = B" and searchs B in an array of variables. If it doesn't find B, then it asks its value and put it in another array.
Well, I don't know if the idea is clear, but here is an example:
```
while(1){
printf("Get string\n");
gets(L);
if(L[0]=='\0') break;
if(L[2] == '1') {
printf("Value of 1: ");
scanf(" %lf", &m);
}
}
printf("\nbreak");
```
I need that this program stops when we type enter, so I used if(L[0]=='\0') break; for it.
My problem is: Everytime I ask the value of B, my program read a "ghost string" L, it is, it doesn't let me put the value of L and the program stops. It is almost double reading the string, but it breaks because of the condition L[0] != '\0'. What am I doing wrong?
If we remove this condition, then the program print 2 times "Get string", without asking me to enter the string 2 times.. | 2013/09/11 | [
"https://Stackoverflow.com/questions/18741271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2768645/"
] | Don't (ever) use `gets()`. It's not good.
Use [`fgets()`](http://linux.die.net/man/3/fgets) instead, noting that it stores the linefeed. Use some higher-level function (like [`sscanf()`](http://linux.die.net/man/3/sscanf)) to parse out the input. Likewise, use another `fgets()` + `sscanf()` combo to do the value reading. | You scanf doesn't consume the line terminator, just what is typed before it. So the gets() then sees the line terminator, and returns an empty string. |
56,670,534 | I'd like to write a decorator that does somewhat different things when it gets a function or a method.
for example, I'd like to write a cache decorator but I don't want to have `self` as part of the key if it's a method.
```py
def cached(f):
def _internal(*args, **kwargs):
if ismethod(f):
key = create_key(*args[1:], **kwargs) # ignore self from args
else: # this is a regular function
key = create_key(*args, **kwargs)
return actual_cache_mechanism(key, f, *args, **kwargs)
return _internal
class A:
@cached
def b(self, something):
...
@cached
def c(something):
...
```
the problem is that when `@cached` is called, it cannot distinguish between methods and functions as both are of type `function`.
can that even be done? As I'm thinking of it I feel that actually methods have no idea about the context in which they are being defined in...
Thanks! | 2019/06/19 | [
"https://Stackoverflow.com/questions/56670534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5435818/"
] | This seems like a very good use case for [Step Functions](https://aws.amazon.com/step-functions/).
Step functions allow you to create a workflow with AWS Services including Lambda that allow for decision branches and wait loops.
For example you could create a workflow that is invoked daily at 5am where you invoke the lambda, the lambda can return whether it could process the data or that it needs to wait more. The step function will inspect the results and either end the workflow since the data was processed or go into a wait state for an hour and then retry the function.
[Check out this article that includes code samples for a workflow that is similar to yours.](https://blog.scottlogic.com/2018/06/19/step-functions.html) | I had a similar situation, my lambda needed to change schedule on weekends and this is how I solved it.
```py
def lambda_handler(event, context):
reschedule_event()
keep_working()
REGULAR_SCHEDULE = 'rate(20 minutes)'
WEEKEND_SHEDULE = 'rate(1 hour)'
RULE_NAME = 'My Rule'
def reschedule_event():
"""
Cambia la planificación de la lambda, para que descanse los findes :D
"""
sched = boto3.client('events')
current = sched.describe_rule(Name=RULE_NAME)
if is_weekend() and 'minutes' in current['ScheduleExpression']:
sched.put_rule(
Name=RULE_NAME,
ScheduleExpression=WEEKEND_SCHEDULE,
)
if not is_weekend and 'hour' in current['ScheduleExpression']:
sched.put_rule(
Name=RULE_NAME,
ScheduleExpression=REGULAR_SCHEDULE,
)
```
I agree there must be some proper way to do this, but time was short at the moment and that lambda needed to go into production. You could do something alike to reschedule yours when there's no data to be retrieved and then go back to the original schedule. |
6,911,232 | i'm failing miserably trying to work out how to create a toolbar in css. "all" i'm trying to do is create a 22x22 button toolbar of 4 buttons.
I have this png:  and this code:
```
<style>
#nav {background: url(content/images/crtoolbar.png) no-repeat;height: 22px;width: 88px;}
#nav span {display: none;}
#nav li {list-style-type: none;float: left;width: 22px;}
#nav a {height: 22px;display: block;}
</style>
<ul id="nav">
<li id="b1"><a href="#"><span>b1</span></a></li>
<li id="b2"><a href="#"><span>b2</span></a></li>
<li id="b3"><a href="#"><span>b3</span></a></li>
<li id="b4"><a href="#"><span>b4</span></a></li>
</ul>
```
Which displays the bitmap ok, but the selection/hrefs are offset to the left by, roughly, 2 buttons and I can't work out how to "push" the buttons over or "drag" the hrefs back.
TIA | 2011/08/02 | [
"https://Stackoverflow.com/questions/6911232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170902/"
] | Browser might have a default padding for `ul`.
```
#nav { padding: 0; }
``` | Use a CSS reset. Most common:
```
* { margin: 0; padding: 0; }
``` |
6,911,232 | i'm failing miserably trying to work out how to create a toolbar in css. "all" i'm trying to do is create a 22x22 button toolbar of 4 buttons.
I have this png:  and this code:
```
<style>
#nav {background: url(content/images/crtoolbar.png) no-repeat;height: 22px;width: 88px;}
#nav span {display: none;}
#nav li {list-style-type: none;float: left;width: 22px;}
#nav a {height: 22px;display: block;}
</style>
<ul id="nav">
<li id="b1"><a href="#"><span>b1</span></a></li>
<li id="b2"><a href="#"><span>b2</span></a></li>
<li id="b3"><a href="#"><span>b3</span></a></li>
<li id="b4"><a href="#"><span>b4</span></a></li>
</ul>
```
Which displays the bitmap ok, but the selection/hrefs are offset to the left by, roughly, 2 buttons and I can't work out how to "push" the buttons over or "drag" the hrefs back.
TIA | 2011/08/02 | [
"https://Stackoverflow.com/questions/6911232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170902/"
] | Browser might have a default padding for `ul`.
```
#nav { padding: 0; }
``` | Additional to the answers by jimworm and Rikudo:
If you really only have colors as buttons, you may use CSS only:
```
<style>
/* insert css reset here */
nav li {
list-style-type: none;
display: inline; }
nav a {
display: inline-block;
width: 22px; height: 22px;
overflow: hidden;
text-indent: 25px; }
#b1 { background: #0ff; }
#b2 { background: #000; }
#b3 { background: #00f; }
#b4 { background: #f00; }
</style>
<nav>
<ul>
<li id="b1"><a href="#">b1</a></li>
<li id="b2"><a href="#">b2</a></li>
<li id="b3"><a href="#">b3</a></li>
<li id="b4"><a href="#">b4</a></li>
</ul>
</nav>
``` |
6,911,232 | i'm failing miserably trying to work out how to create a toolbar in css. "all" i'm trying to do is create a 22x22 button toolbar of 4 buttons.
I have this png:  and this code:
```
<style>
#nav {background: url(content/images/crtoolbar.png) no-repeat;height: 22px;width: 88px;}
#nav span {display: none;}
#nav li {list-style-type: none;float: left;width: 22px;}
#nav a {height: 22px;display: block;}
</style>
<ul id="nav">
<li id="b1"><a href="#"><span>b1</span></a></li>
<li id="b2"><a href="#"><span>b2</span></a></li>
<li id="b3"><a href="#"><span>b3</span></a></li>
<li id="b4"><a href="#"><span>b4</span></a></li>
</ul>
```
Which displays the bitmap ok, but the selection/hrefs are offset to the left by, roughly, 2 buttons and I can't work out how to "push" the buttons over or "drag" the hrefs back.
TIA | 2011/08/02 | [
"https://Stackoverflow.com/questions/6911232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170902/"
] | Additional to the answers by jimworm and Rikudo:
If you really only have colors as buttons, you may use CSS only:
```
<style>
/* insert css reset here */
nav li {
list-style-type: none;
display: inline; }
nav a {
display: inline-block;
width: 22px; height: 22px;
overflow: hidden;
text-indent: 25px; }
#b1 { background: #0ff; }
#b2 { background: #000; }
#b3 { background: #00f; }
#b4 { background: #f00; }
</style>
<nav>
<ul>
<li id="b1"><a href="#">b1</a></li>
<li id="b2"><a href="#">b2</a></li>
<li id="b3"><a href="#">b3</a></li>
<li id="b4"><a href="#">b4</a></li>
</ul>
</nav>
``` | Use a CSS reset. Most common:
```
* { margin: 0; padding: 0; }
``` |
19,683,922 | Chrome has started to warn me about my legacy gradients:
```
Invalid CSS property value: right no-repeat url('../Images/Logo_white.png'),
-moz-linear-gradient(bottom, #899fa6, #3e545c)
```
It is only for the extensions for o, moz and ms:
```
background: right no-repeat url('../Images/CompanyLogo.png'),
-moz-linear-gradient(bottom, #000000, #ffffff);
```
The one for webkit is fine:
```
background: right no-repeat url('../Images/CompanyLogo.png'),
-webkit-linear-gradient(bottom, #000000, #ffffff);
```
Am I doing something wrong?
The extension-gradients do not generate a warning when they are used alone as opposed to being combined with an image. | 2013/10/30 | [
"https://Stackoverflow.com/questions/19683922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1107908/"
] | The reason why you're getting warnings from Chrome's dev tool is because the values are indeed invalid for Chrome. However, this should not alarm you because this is the way that it was designed.
In CSS, if something is defined incorrectly or not recognized by the browser then it is simply passed over, nothing is done and it only gives a warning not an error. This behavior is exactly what allows vendor prefixes to work. Take for example your own situation:
```
background: right no-repeat url('../Images/CompanyLogo.png'),
-moz-linear-gradient(bottom, #000000, #ffffff);
background: right no-repeat url('../Images/CompanyLogo.png'),
-webkit-linear-gradient(bottom, #000000, #ffffff);
background: right no-repeat url('../Images/CompanyLogo.png'),
linear-gradient(bottom, #000000, #ffffff);
```
Chrome goes through each `background` property and sees which one it can interpret. It can't interpret the first gradient because it doesn't recognize `-moz-` like Firefox does. It *can* interpret the second one because it has a `-webkit-` prefix. It can *also* interpret the third background because Chrome supports un-prefixed CSS gradients.
Since more than one CSS attributes affect the same thing (`background`), the most recent one listed (the unprefixed version) will be used. A warning will display for the un-interpretted first `background`, but it will have no effect on the project.
Yes, **warnings should be looked at and analyzed, generally treated as errors**. With that being said, the case you bring up about browser prefixes is the correct way of doing it, so the warnings should be accepted. In a perfect world they would not show up at all, they'd understand that it is meant for another browser, but there is no reason to worry about it because it is indeed the correct way of doing it
But then again, this is all semi irrelevant because [all major browsers support CSS gradients unprefixed](http://caniuse.com/#search=gradient). | I found this bug on Chrome Developer Tools:
<http://code.google.com/p/chromium/issues/detail?id=309982>
Seems like they will temporarily disable CSS warnings because of too many false positives (including valid CSS for legacy browsers, if we are to go by the ticket author) until they have fixed it.
Chances are that these warnings are part of those false positives.
I will monitor the issue. |
3,912,319 | Consider the following initial value problem $$y’=x^2+y^2, y(0)=1$$
Which of the following statements is/ are
$1.$ there exist a unique solution in $[0,\frac{\pi}{4}]$.
$2.$ every solution is bounded on $[0,\frac{\pi}{4}]$.
$3.$ The solution has a singularity at some point in $[0,1]$.
$4.$ The solution because unbounded at some sub interval of $[\frac{\pi}{4}, 1]$.
**I tried to find interval for unique solution by using existence and uniqueness theorem as**
For $$|x|\leq a$$ $$|y-1|\leq b$$ we have
$$|f(x,y)|=|x^2+y^2|\leq a^2+(1+b^2)$$
$$h=min\{a,\frac{b}{M}\}=min\{a,\frac{b}{1+a^2 +b^2+2ab}\}$$ Now to find maximum of $$g(b)= \frac{b}{1+a^2 +b^2+2ab}$$ we have $$g’(b)= \frac{1+a^2-b^2}{(1+a^2 +b^2+2ab)^2}=0\iff b=\pm\sqrt{1+a^2}$$ So $$h=min\{ a,\frac{\sqrt{1+a^2}}{2+2a^2+2a\sqrt{1+a^2}}\}$$ $$a= \frac{\sqrt{1+a^2}}{2+2a^2+2a\sqrt{1+a^2}}$$ gives $$ 2a(1+a^2)=(1-2a^2)\sqrt{1+a^2}$$ $$a=\frac{1}{2\sqrt{2}}$$ Now it seems no conclusions. If it is unique( that I don’t know how ) in $[0,\frac{\pi}{4}]$ then it will be bounded also in this interval as continuous functions are bounded on compact set and if solution can’t be extended to $[0,1]$ then it is because of unboundedness of solution as I guess . I don’t know how to handle last two portions. Please help. Thanks. | 2020/11/18 | [
"https://math.stackexchange.com/questions/3912319",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/93918/"
] | You don't need to consider any factorisation. Let $p(x)=\sum\_{i=1}^ka\_ix^i$ be any monic polynomial. If $p(A)=0$, then
$$
p(A^T)=\sum\_{i=1}^ka\_i(A^T)^i=\left(\sum\_{i=1}^ka\_iA^i\right)^T=p(A)^T=0.
$$
Since $A=(A^T)^T$, it is also true that $p(A^T)=0\Rightarrow p(A)=0$. Therefore $A$ and $A^T$ share the same set of annihilating polynomials. The monic polynomial of the lowest degree in this set is the common minimal polynomial of $A$ and $A^T$. | $m\_A$ and $m\_{A^T}$ are the minimal polynomials for $A$ and $A^T$ respectively.
So we have $m\_A(A) = 0$ and $m\_{A^T}(A^T) = 0$ by definition. Let $m\_A(t) = p\_1(t)p\_2(t)...p\_k(t)$ where $p\_i(t)\forall 1\leq i\leq k$ are the irreducible factors of $m\_A(t)$.
$m\_A(A) = 0 \implies (m\_A(A))^T = 0$, which is just $(p\_1(A)p\_2(A)...p\_k(A))^T = 0$. Since polynomials in $A$ commute, this is just $(p\_1(A))^T(p\_2(A))^T...(p\_k(A))^T = 0 \implies p\_1(A^T)p\_2(A^T)...p\_k(A^T) = 0$. So $m\_A(A^T) = 0$, which means that $m\_{A^T}\vert m\_A$.
Starting with $m\_{A^T}(A^T) = 0$, we can similarly prove that $m\_A\vert m\_{A^T}$.
So $m\_A(t) = m\_{A^T}(t)$ |
23,000 | I picked up the phrase '*attention whore*' from [this question at ELU](https://english.stackexchange.com/questions/168752/is-there-a-less-colloquial-word-noun-or-adjective-to-describe-an-attention-wh). On the next day I remembered the phrase as '*attention hooker*.' It transformed and this one even sounds better for me, but I guess it is idiomatically flat wrong. I don't feel the difference since *hooker* and *whore* have the same meaning.
How do you feel the difference as a native speaker? Is the difference so striking that If I use it somewhere, I will be corrected by a native speaker: "We say whore, not hooker"? | 2014/05/08 | [
"https://ell.stackexchange.com/questions/23000",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/1616/"
] | The difference as far as I am concerned is that while the two words may have an essentially identical dictionary definition, *hooker* is never used as a direct insult; it is actually less pejorative and more literally descriptive.
If I catch my fiancee sleeping with my best friend, I would never say "You hooker! How dare you!", but only "You whore! How dare you!"
Conversely, if we spot someone actually out on a street corner trying to trade sex for money, I would be much more likely to say "wow, I didn't know hookers worked this part of town"
So to answer your final question, yes: if you were to call someone an "attention hooker" I would look at you funny and say "actually, the phrase is 'attention *whore*'." | The established term is *attention whore*.
There is certainly nothing to prevent you from employing the term *attention hooker*; but it has a different rhythm, it will not be familiar to your hearers, and it risks confusion with *The Hook*, which is common in the CW† trade I follow for any attention-grabbing device at the opening of a text or video.
---
† *Commercial Writer / Corporate Whore* |
23,000 | I picked up the phrase '*attention whore*' from [this question at ELU](https://english.stackexchange.com/questions/168752/is-there-a-less-colloquial-word-noun-or-adjective-to-describe-an-attention-wh). On the next day I remembered the phrase as '*attention hooker*.' It transformed and this one even sounds better for me, but I guess it is idiomatically flat wrong. I don't feel the difference since *hooker* and *whore* have the same meaning.
How do you feel the difference as a native speaker? Is the difference so striking that If I use it somewhere, I will be corrected by a native speaker: "We say whore, not hooker"? | 2014/05/08 | [
"https://ell.stackexchange.com/questions/23000",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/1616/"
] | The established term is *attention whore*.
There is certainly nothing to prevent you from employing the term *attention hooker*; but it has a different rhythm, it will not be familiar to your hearers, and it risks confusion with *The Hook*, which is common in the CW† trade I follow for any attention-grabbing device at the opening of a text or video.
---
† *Commercial Writer / Corporate Whore* | Your term Attention Hooker,appears to be garnering some confused responses from several people.
I assume these are mainly americans.
I am british ,of Irish descent,Yes i have lived there too.
And for me i like the word, it would indeed conjure up an attention seeker,in a more polite way then the word whore.
Culturally we Europeans are more receptive to ideas, and in the US people tend to be more literal and take it as read or said
Attention Hooker in Europe would be Fine. |
23,000 | I picked up the phrase '*attention whore*' from [this question at ELU](https://english.stackexchange.com/questions/168752/is-there-a-less-colloquial-word-noun-or-adjective-to-describe-an-attention-wh). On the next day I remembered the phrase as '*attention hooker*.' It transformed and this one even sounds better for me, but I guess it is idiomatically flat wrong. I don't feel the difference since *hooker* and *whore* have the same meaning.
How do you feel the difference as a native speaker? Is the difference so striking that If I use it somewhere, I will be corrected by a native speaker: "We say whore, not hooker"? | 2014/05/08 | [
"https://ell.stackexchange.com/questions/23000",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/1616/"
] | The difference as far as I am concerned is that while the two words may have an essentially identical dictionary definition, *hooker* is never used as a direct insult; it is actually less pejorative and more literally descriptive.
If I catch my fiancee sleeping with my best friend, I would never say "You hooker! How dare you!", but only "You whore! How dare you!"
Conversely, if we spot someone actually out on a street corner trying to trade sex for money, I would be much more likely to say "wow, I didn't know hookers worked this part of town"
So to answer your final question, yes: if you were to call someone an "attention hooker" I would look at you funny and say "actually, the phrase is 'attention *whore*'." | You shouldn't use the word *whore* in polite company. The correct phrase is *attention seeker*, but you could say *attention whore* if you are sure that you won't offend the company you are in.
The phrase *attention hooker* is just wrong. |
23,000 | I picked up the phrase '*attention whore*' from [this question at ELU](https://english.stackexchange.com/questions/168752/is-there-a-less-colloquial-word-noun-or-adjective-to-describe-an-attention-wh). On the next day I remembered the phrase as '*attention hooker*.' It transformed and this one even sounds better for me, but I guess it is idiomatically flat wrong. I don't feel the difference since *hooker* and *whore* have the same meaning.
How do you feel the difference as a native speaker? Is the difference so striking that If I use it somewhere, I will be corrected by a native speaker: "We say whore, not hooker"? | 2014/05/08 | [
"https://ell.stackexchange.com/questions/23000",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/1616/"
] | The difference as far as I am concerned is that while the two words may have an essentially identical dictionary definition, *hooker* is never used as a direct insult; it is actually less pejorative and more literally descriptive.
If I catch my fiancee sleeping with my best friend, I would never say "You hooker! How dare you!", but only "You whore! How dare you!"
Conversely, if we spot someone actually out on a street corner trying to trade sex for money, I would be much more likely to say "wow, I didn't know hookers worked this part of town"
So to answer your final question, yes: if you were to call someone an "attention hooker" I would look at you funny and say "actually, the phrase is 'attention *whore*'." | Your term Attention Hooker,appears to be garnering some confused responses from several people.
I assume these are mainly americans.
I am british ,of Irish descent,Yes i have lived there too.
And for me i like the word, it would indeed conjure up an attention seeker,in a more polite way then the word whore.
Culturally we Europeans are more receptive to ideas, and in the US people tend to be more literal and take it as read or said
Attention Hooker in Europe would be Fine. |
23,000 | I picked up the phrase '*attention whore*' from [this question at ELU](https://english.stackexchange.com/questions/168752/is-there-a-less-colloquial-word-noun-or-adjective-to-describe-an-attention-wh). On the next day I remembered the phrase as '*attention hooker*.' It transformed and this one even sounds better for me, but I guess it is idiomatically flat wrong. I don't feel the difference since *hooker* and *whore* have the same meaning.
How do you feel the difference as a native speaker? Is the difference so striking that If I use it somewhere, I will be corrected by a native speaker: "We say whore, not hooker"? | 2014/05/08 | [
"https://ell.stackexchange.com/questions/23000",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/1616/"
] | You shouldn't use the word *whore* in polite company. The correct phrase is *attention seeker*, but you could say *attention whore* if you are sure that you won't offend the company you are in.
The phrase *attention hooker* is just wrong. | Your term Attention Hooker,appears to be garnering some confused responses from several people.
I assume these are mainly americans.
I am british ,of Irish descent,Yes i have lived there too.
And for me i like the word, it would indeed conjure up an attention seeker,in a more polite way then the word whore.
Culturally we Europeans are more receptive to ideas, and in the US people tend to be more literal and take it as read or said
Attention Hooker in Europe would be Fine. |
24,241,285 | I've created a map having a vector as below:
```
map<int,vector<int>> mymap;
```
How can I sort this map according to the *n*th value of the vector contained by map? | 2014/06/16 | [
"https://Stackoverflow.com/questions/24241285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3744394/"
] | **You can't.** You can provide a custom comparator to make the underlying data get sorted another way than the default, but this only relates to *keys*, not *values*. If you have a requirement for your container's elements to exist in some specific, value-defined order, then you're using the wrong container.
You can switch to a `set`, and take advantage of the fact that there is no distinction there between "key" and "value", and hack the underlying sorting yourself:
```
template <std::size_t N>
struct MyComparator
{
typedef std::pair<int, std::vector<int>> value_type;
bool operator()(const value_type& lhs, const value_type& rhs)
{
return lhs.second.at(N) < rhs.second.at(N);
}
};
/**
* A set of (int, int{2,}) pairs, sorted by the 2nd element in
* the 2nd item of each pair.
*/
std::set<std::pair<int, std::vector<int>>, MyComparator<1>> my_data;
int main()
{
my_data.insert(std::make_pair(1, std::vector<int>{0,5,0,0}));
my_data.insert(std::make_pair(2, std::vector<int>{0,2,0,0}));
my_data.insert(std::make_pair(3, std::vector<int>{0,1,0,0}));
my_data.insert(std::make_pair(4, std::vector<int>{0,9,0,0}));
for (const auto& el : my_data)
std::cout << el.first << ' ';
}
// Output: 3 2 1 4
```
### ([live demo](http://coliru.stacked-crooked.com/a/391f8092eb08dee4))
However, if you still need to perform lookup on key *as well*, then you're really in trouble and need to rethink some things. You may need to duplicate your data or provide an indexing vector. | If I have understood correctly you can (build) add elements to the map the following way
```
std::vector<int> v = { 1, 2, 3 };
std::vector<int>::size_type n = 2;
mymap[v[n]] = v;
```
Here is an example
```
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <cstdlib>
#include <ctime>
int main()
{
std::srand( ( unsigned )time( 0 ) );
const size_t N = 10;
std::map<int, std::vector<int>> m;
for ( size_t i = 0; i < N; i++ )
{
std::vector<int> v( N );
std::generate( v.begin(), v.end(), []{ return std::rand() % N; } );
m[v[0]] = v;
}
for ( auto &p : m )
{
for ( int x : p.second ) std::cout << x << ' ';
std::cout << std::endl;
}
return 0;
}
```
The output is
```
0 1 7 8 1 2 9 0 0 9
1 6 3 1 3 5 0 3 1 5
3 8 0 0 0 7 1 2 9 7
5 9 5 0 7 1 2 0 6 3
6 4 7 5 4 0 0 4 2 0
7 9 8 6 5 5 9 9 4 5
8 3 8 0 5 9 6 6 8 3
9 5 4 7 4 0 3 5 1 9
```
Take into account that as there can be duplicated vectors (that is that have the same value of the n-th element (in my example n is equal to 0) then some vectors will not be added to the map. If you want to have duplicates then you should use for example `std::multimap`
Also you can build a new map according to the criteria based on an existent map. |
24,241,285 | I've created a map having a vector as below:
```
map<int,vector<int>> mymap;
```
How can I sort this map according to the *n*th value of the vector contained by map? | 2014/06/16 | [
"https://Stackoverflow.com/questions/24241285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3744394/"
] | If I have understood correctly you can (build) add elements to the map the following way
```
std::vector<int> v = { 1, 2, 3 };
std::vector<int>::size_type n = 2;
mymap[v[n]] = v;
```
Here is an example
```
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <cstdlib>
#include <ctime>
int main()
{
std::srand( ( unsigned )time( 0 ) );
const size_t N = 10;
std::map<int, std::vector<int>> m;
for ( size_t i = 0; i < N; i++ )
{
std::vector<int> v( N );
std::generate( v.begin(), v.end(), []{ return std::rand() % N; } );
m[v[0]] = v;
}
for ( auto &p : m )
{
for ( int x : p.second ) std::cout << x << ' ';
std::cout << std::endl;
}
return 0;
}
```
The output is
```
0 1 7 8 1 2 9 0 0 9
1 6 3 1 3 5 0 3 1 5
3 8 0 0 0 7 1 2 9 7
5 9 5 0 7 1 2 0 6 3
6 4 7 5 4 0 0 4 2 0
7 9 8 6 5 5 9 9 4 5
8 3 8 0 5 9 6 6 8 3
9 5 4 7 4 0 3 5 1 9
```
Take into account that as there can be duplicated vectors (that is that have the same value of the n-th element (in my example n is equal to 0) then some vectors will not be added to the map. If you want to have duplicates then you should use for example `std::multimap`
Also you can build a new map according to the criteria based on an existent map. | You can abuse the fact a c++ map uses a tree sorted by its keys. This means that you can either create a new map, with as keys the values you wish it to be sorted on, but you can also create a `vector` with references to the items in your map, and sort that vector (or the other way around: you could have a sorted vector, and use a `map` to create an index on your vector). Be sure to use a `multimap` in the case of duplicate keys. |
24,241,285 | I've created a map having a vector as below:
```
map<int,vector<int>> mymap;
```
How can I sort this map according to the *n*th value of the vector contained by map? | 2014/06/16 | [
"https://Stackoverflow.com/questions/24241285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3744394/"
] | **You can't.** You can provide a custom comparator to make the underlying data get sorted another way than the default, but this only relates to *keys*, not *values*. If you have a requirement for your container's elements to exist in some specific, value-defined order, then you're using the wrong container.
You can switch to a `set`, and take advantage of the fact that there is no distinction there between "key" and "value", and hack the underlying sorting yourself:
```
template <std::size_t N>
struct MyComparator
{
typedef std::pair<int, std::vector<int>> value_type;
bool operator()(const value_type& lhs, const value_type& rhs)
{
return lhs.second.at(N) < rhs.second.at(N);
}
};
/**
* A set of (int, int{2,}) pairs, sorted by the 2nd element in
* the 2nd item of each pair.
*/
std::set<std::pair<int, std::vector<int>>, MyComparator<1>> my_data;
int main()
{
my_data.insert(std::make_pair(1, std::vector<int>{0,5,0,0}));
my_data.insert(std::make_pair(2, std::vector<int>{0,2,0,0}));
my_data.insert(std::make_pair(3, std::vector<int>{0,1,0,0}));
my_data.insert(std::make_pair(4, std::vector<int>{0,9,0,0}));
for (const auto& el : my_data)
std::cout << el.first << ' ';
}
// Output: 3 2 1 4
```
### ([live demo](http://coliru.stacked-crooked.com/a/391f8092eb08dee4))
However, if you still need to perform lookup on key *as well*, then you're really in trouble and need to rethink some things. You may need to duplicate your data or provide an indexing vector. | You can abuse the fact a c++ map uses a tree sorted by its keys. This means that you can either create a new map, with as keys the values you wish it to be sorted on, but you can also create a `vector` with references to the items in your map, and sort that vector (or the other way around: you could have a sorted vector, and use a `map` to create an index on your vector). Be sure to use a `multimap` in the case of duplicate keys. |
24,241,285 | I've created a map having a vector as below:
```
map<int,vector<int>> mymap;
```
How can I sort this map according to the *n*th value of the vector contained by map? | 2014/06/16 | [
"https://Stackoverflow.com/questions/24241285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3744394/"
] | **You can't.** You can provide a custom comparator to make the underlying data get sorted another way than the default, but this only relates to *keys*, not *values*. If you have a requirement for your container's elements to exist in some specific, value-defined order, then you're using the wrong container.
You can switch to a `set`, and take advantage of the fact that there is no distinction there between "key" and "value", and hack the underlying sorting yourself:
```
template <std::size_t N>
struct MyComparator
{
typedef std::pair<int, std::vector<int>> value_type;
bool operator()(const value_type& lhs, const value_type& rhs)
{
return lhs.second.at(N) < rhs.second.at(N);
}
};
/**
* A set of (int, int{2,}) pairs, sorted by the 2nd element in
* the 2nd item of each pair.
*/
std::set<std::pair<int, std::vector<int>>, MyComparator<1>> my_data;
int main()
{
my_data.insert(std::make_pair(1, std::vector<int>{0,5,0,0}));
my_data.insert(std::make_pair(2, std::vector<int>{0,2,0,0}));
my_data.insert(std::make_pair(3, std::vector<int>{0,1,0,0}));
my_data.insert(std::make_pair(4, std::vector<int>{0,9,0,0}));
for (const auto& el : my_data)
std::cout << el.first << ' ';
}
// Output: 3 2 1 4
```
### ([live demo](http://coliru.stacked-crooked.com/a/391f8092eb08dee4))
However, if you still need to perform lookup on key *as well*, then you're really in trouble and need to rethink some things. You may need to duplicate your data or provide an indexing vector. | >
> `map<int,vector<int>> mymap;`
>
>
> How can i sort this map according to the nth value of the vector contained by map?
>
>
>
That's only possible if you're prepared to use that nth value as the integer key too, as in consistently assigning:
```
mymap[v[n - 1]] = v;
```
If you're doing that, you might consider a `set<vector<int>>`, which removes the redundant storage of that "key" element - you would then need to provide a custom comparison though....
If you envisage taking an existing populated map that doesn't have that ordering, then sorting its elements - that's totally impossible. You'll have to copy the elements out to another container, such as a `set` that's ordered on the nth element, or a `vector` that you `std::sort` after populating. |
24,241,285 | I've created a map having a vector as below:
```
map<int,vector<int>> mymap;
```
How can I sort this map according to the *n*th value of the vector contained by map? | 2014/06/16 | [
"https://Stackoverflow.com/questions/24241285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3744394/"
] | >
> `map<int,vector<int>> mymap;`
>
>
> How can i sort this map according to the nth value of the vector contained by map?
>
>
>
That's only possible if you're prepared to use that nth value as the integer key too, as in consistently assigning:
```
mymap[v[n - 1]] = v;
```
If you're doing that, you might consider a `set<vector<int>>`, which removes the redundant storage of that "key" element - you would then need to provide a custom comparison though....
If you envisage taking an existing populated map that doesn't have that ordering, then sorting its elements - that's totally impossible. You'll have to copy the elements out to another container, such as a `set` that's ordered on the nth element, or a `vector` that you `std::sort` after populating. | You can abuse the fact a c++ map uses a tree sorted by its keys. This means that you can either create a new map, with as keys the values you wish it to be sorted on, but you can also create a `vector` with references to the items in your map, and sort that vector (or the other way around: you could have a sorted vector, and use a `map` to create an index on your vector). Be sure to use a `multimap` in the case of duplicate keys. |
33,299,667 | I am making a C++ program to calculate the square root of a number. This program does not use the "sqrt" math built in operation. There are two variables, one for the number the user will enter and the other for the square root of that number. This program does not work really well and I am sure there is a better way to do so:
**Here is my full code:**
```
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot != number){
squareroot+=0.1;
}
cout << "the square root is" << squareroot << endl;
return 0;
}
```
I know there must be a better way. Pls help. Looked through Google but don't understand the complex programs there as I am still a beginner.
Thanks in advance. | 2015/10/23 | [
"https://Stackoverflow.com/questions/33299667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5303568/"
] | Below explanation is given for the integer square root calculation:
>
> In number theory, the integer square root of a positive
> integer n is the positive integer m which is the greatest integer less
> than or equal to the square root of n
>
>
>
The approach your started is good but needs several correction to make it work:
1. you are working with `int` you want to add 1 to `squareroot` not 0.1
2. you want to stop your calculation when you `squareroot * squareroot` is equal or greater than `number`. Think about the case were the number is 26, you don't have an integer that multiplies itself to 26.
3. in the case of number equal to 26, do you want to return 5 or 6? After your `while` loop the value of `squareroot` will be 6 so you might want to reverse it to 5 (if `squareroot * squareroot` is different than `number`)
Below the exemple:
```
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot < number){
squareroot+=1;
}
if (squareroot * squareroot != number) --squareroot;
cout << "the square root is" << squareroot << endl;
return 0;
}
```
Below a more efficient and elegant way of calculating the square root using binary search principle. O(log(n))
```
int mySqrt(int x) {
if (x==0) return 0;
int left = 1;
int right = x/2 + 1;
int res;
while (left <= right) {
int mid = left + ((right-left)/2);
if (mid<=x/mid){
left = mid+1;
res=mid;
}
else {
right=mid-1;
}
}
return res;
}
``` | This function will calculate the floor of square root if A is not a perfect square.This function basically uses binary search.Two things you know beforehand is that square root of a number will be less or equal to that number and it will be greater or equal to 1. So we can apply binary search in that range.Below is my implementation.Let me know if you don't understand anything in the code.Hope this helps.
```
int sqrt(int A) {
if(A<1)return 0;
if(A==1)return 1;
unsigned long long start,end,mid,i,val,lval;
start = 1;
end = A;
while(start<=end){
mid = start+(end-start)/2;
val = mid*mid;
lval = (mid-1)*(mid-1);
if(val == A)return mid;
else if(A>lval && A<val) return mid-1;
else if(val > A)end = mid;
else if(val < A)start = mid+1;
}
}
``` |
33,299,667 | I am making a C++ program to calculate the square root of a number. This program does not use the "sqrt" math built in operation. There are two variables, one for the number the user will enter and the other for the square root of that number. This program does not work really well and I am sure there is a better way to do so:
**Here is my full code:**
```
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot != number){
squareroot+=0.1;
}
cout << "the square root is" << squareroot << endl;
return 0;
}
```
I know there must be a better way. Pls help. Looked through Google but don't understand the complex programs there as I am still a beginner.
Thanks in advance. | 2015/10/23 | [
"https://Stackoverflow.com/questions/33299667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5303568/"
] | This function uses Nested Intervals (untested) and you can define the accuracy:
```
#include <math.h>
#include <stdio.h>
double mySqrt(double r) {
double l=0, m;
do {
m = (l+r)/2;
if (m*m<2) {
l = m;
} else {
r = m;
}
}
while(fabs(m*m-2) > 1e-10);
return m;
}
```
See <https://en.wikipedia.org/wiki/Nested_intervals> | The problem with your code, is that it only works if the square root of the number is exactly N\*0.1, where N is an integer, meaning that if the answer is 1.4142 and not 1.400000000 exactly your code will fail. There are better ways , but they're all more complicated and use numerical analysis to approximate the answer, the easiest of which is the Newton-Raphson method.
you can use the function below, this function uses the Newton–Raphson method to find the root, if you need more information about the Newton–Raphson method, check [this](https://en.wikipedia.org/wiki/Newton%27s_method) wikipedia article. and if you need better accuracy - but worse performance- you can decrease '0.001' to your likening,or increase it if you want better performance but less accuracy.
```
float mysqrt(float num) {
float x = 1;
while(abs(x*x - num) >= 0.001 )
x = ((num/x) + x) / 2;
return x;
}
```
if you don't want to import `math.h` you can write your own `abs()`:
```
float abs(float f) {
if(f < 0)
f = -1*f;
return f;
}
``` |
33,299,667 | I am making a C++ program to calculate the square root of a number. This program does not use the "sqrt" math built in operation. There are two variables, one for the number the user will enter and the other for the square root of that number. This program does not work really well and I am sure there is a better way to do so:
**Here is my full code:**
```
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot != number){
squareroot+=0.1;
}
cout << "the square root is" << squareroot << endl;
return 0;
}
```
I know there must be a better way. Pls help. Looked through Google but don't understand the complex programs there as I am still a beginner.
Thanks in advance. | 2015/10/23 | [
"https://Stackoverflow.com/questions/33299667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5303568/"
] | This function uses Nested Intervals (untested) and you can define the accuracy:
```
#include <math.h>
#include <stdio.h>
double mySqrt(double r) {
double l=0, m;
do {
m = (l+r)/2;
if (m*m<2) {
l = m;
} else {
r = m;
}
}
while(fabs(m*m-2) > 1e-10);
return m;
}
```
See <https://en.wikipedia.org/wiki/Nested_intervals> | Square Root of a number, given that the number is a perfect square.
The complexity is log(n)
```
/**
* Calculate square root if the given number is a perfect square.
*
* Approach: Sum of n odd numbers is equals to the square root of n*n, given
* that n is a perfect square.
*
* @param number
* @return squareRoot
*/
public static int calculateSquareRoot(int number) {
int sum=1;
int count =1;
int squareRoot=1;
while(sum<number) {
count+=2;
sum+=count;
squareRoot++;
}
return squareRoot;
}
``` |
33,299,667 | I am making a C++ program to calculate the square root of a number. This program does not use the "sqrt" math built in operation. There are two variables, one for the number the user will enter and the other for the square root of that number. This program does not work really well and I am sure there is a better way to do so:
**Here is my full code:**
```
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot != number){
squareroot+=0.1;
}
cout << "the square root is" << squareroot << endl;
return 0;
}
```
I know there must be a better way. Pls help. Looked through Google but don't understand the complex programs there as I am still a beginner.
Thanks in advance. | 2015/10/23 | [
"https://Stackoverflow.com/questions/33299667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5303568/"
] | Below explanation is given for the integer square root calculation:
>
> In number theory, the integer square root of a positive
> integer n is the positive integer m which is the greatest integer less
> than or equal to the square root of n
>
>
>
The approach your started is good but needs several correction to make it work:
1. you are working with `int` you want to add 1 to `squareroot` not 0.1
2. you want to stop your calculation when you `squareroot * squareroot` is equal or greater than `number`. Think about the case were the number is 26, you don't have an integer that multiplies itself to 26.
3. in the case of number equal to 26, do you want to return 5 or 6? After your `while` loop the value of `squareroot` will be 6 so you might want to reverse it to 5 (if `squareroot * squareroot` is different than `number`)
Below the exemple:
```
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot < number){
squareroot+=1;
}
if (squareroot * squareroot != number) --squareroot;
cout << "the square root is" << squareroot << endl;
return 0;
}
```
Below a more efficient and elegant way of calculating the square root using binary search principle. O(log(n))
```
int mySqrt(int x) {
if (x==0) return 0;
int left = 1;
int right = x/2 + 1;
int res;
while (left <= right) {
int mid = left + ((right-left)/2);
if (mid<=x/mid){
left = mid+1;
res=mid;
}
else {
right=mid-1;
}
}
return res;
}
``` | ```
#include <iostream>
using namespace std;
int main()
{
double x = 1, average, s, r;
cout << "Squareroot a Number: ";
cin >> s;
r = s * 2;
for ( ; ; ) //for ; ; ; is to run the code forever until it breaks
{
average = (x + s / x) / 2;
if (x == average)
{
cout << "Answer is : " << average << endl;
return 0;
}
x = average;
}
}
```
You can try my code :D
the method that i used here is the Babylonian Squareroot Method
which you can find it here <https://en.wikipedia.org/wiki/Methods_of_computing_square_roots> |
33,299,667 | I am making a C++ program to calculate the square root of a number. This program does not use the "sqrt" math built in operation. There are two variables, one for the number the user will enter and the other for the square root of that number. This program does not work really well and I am sure there is a better way to do so:
**Here is my full code:**
```
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot != number){
squareroot+=0.1;
}
cout << "the square root is" << squareroot << endl;
return 0;
}
```
I know there must be a better way. Pls help. Looked through Google but don't understand the complex programs there as I am still a beginner.
Thanks in advance. | 2015/10/23 | [
"https://Stackoverflow.com/questions/33299667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5303568/"
] | This function uses Nested Intervals (untested) and you can define the accuracy:
```
#include <math.h>
#include <stdio.h>
double mySqrt(double r) {
double l=0, m;
do {
m = (l+r)/2;
if (m*m<2) {
l = m;
} else {
r = m;
}
}
while(fabs(m*m-2) > 1e-10);
return m;
}
```
See <https://en.wikipedia.org/wiki/Nested_intervals> | ```
#include <iostream>
using namespace std;
int main()
{
double x = 1, average, s, r;
cout << "Squareroot a Number: ";
cin >> s;
r = s * 2;
for ( ; ; ) //for ; ; ; is to run the code forever until it breaks
{
average = (x + s / x) / 2;
if (x == average)
{
cout << "Answer is : " << average << endl;
return 0;
}
x = average;
}
}
```
You can try my code :D
the method that i used here is the Babylonian Squareroot Method
which you can find it here <https://en.wikipedia.org/wiki/Methods_of_computing_square_roots> |
33,299,667 | I am making a C++ program to calculate the square root of a number. This program does not use the "sqrt" math built in operation. There are two variables, one for the number the user will enter and the other for the square root of that number. This program does not work really well and I am sure there is a better way to do so:
**Here is my full code:**
```
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot != number){
squareroot+=0.1;
}
cout << "the square root is" << squareroot << endl;
return 0;
}
```
I know there must be a better way. Pls help. Looked through Google but don't understand the complex programs there as I am still a beginner.
Thanks in advance. | 2015/10/23 | [
"https://Stackoverflow.com/questions/33299667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5303568/"
] | This function will calculate the floor of square root if A is not a perfect square.This function basically uses binary search.Two things you know beforehand is that square root of a number will be less or equal to that number and it will be greater or equal to 1. So we can apply binary search in that range.Below is my implementation.Let me know if you don't understand anything in the code.Hope this helps.
```
int sqrt(int A) {
if(A<1)return 0;
if(A==1)return 1;
unsigned long long start,end,mid,i,val,lval;
start = 1;
end = A;
while(start<=end){
mid = start+(end-start)/2;
val = mid*mid;
lval = (mid-1)*(mid-1);
if(val == A)return mid;
else if(A>lval && A<val) return mid-1;
else if(val > A)end = mid;
else if(val < A)start = mid+1;
}
}
``` | ```
#include <iostream>
using namespace std;
int main()
{
double x = 1, average, s, r;
cout << "Squareroot a Number: ";
cin >> s;
r = s * 2;
for ( ; ; ) //for ; ; ; is to run the code forever until it breaks
{
average = (x + s / x) / 2;
if (x == average)
{
cout << "Answer is : " << average << endl;
return 0;
}
x = average;
}
}
```
You can try my code :D
the method that i used here is the Babylonian Squareroot Method
which you can find it here <https://en.wikipedia.org/wiki/Methods_of_computing_square_roots> |
33,299,667 | I am making a C++ program to calculate the square root of a number. This program does not use the "sqrt" math built in operation. There are two variables, one for the number the user will enter and the other for the square root of that number. This program does not work really well and I am sure there is a better way to do so:
**Here is my full code:**
```
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot != number){
squareroot+=0.1;
}
cout << "the square root is" << squareroot << endl;
return 0;
}
```
I know there must be a better way. Pls help. Looked through Google but don't understand the complex programs there as I am still a beginner.
Thanks in advance. | 2015/10/23 | [
"https://Stackoverflow.com/questions/33299667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5303568/"
] | The problem with your code, is that it only works if the square root of the number is exactly N\*0.1, where N is an integer, meaning that if the answer is 1.4142 and not 1.400000000 exactly your code will fail. There are better ways , but they're all more complicated and use numerical analysis to approximate the answer, the easiest of which is the Newton-Raphson method.
you can use the function below, this function uses the Newton–Raphson method to find the root, if you need more information about the Newton–Raphson method, check [this](https://en.wikipedia.org/wiki/Newton%27s_method) wikipedia article. and if you need better accuracy - but worse performance- you can decrease '0.001' to your likening,or increase it if you want better performance but less accuracy.
```
float mysqrt(float num) {
float x = 1;
while(abs(x*x - num) >= 0.001 )
x = ((num/x) + x) / 2;
return x;
}
```
if you don't want to import `math.h` you can write your own `abs()`:
```
float abs(float f) {
if(f < 0)
f = -1*f;
return f;
}
``` | ```
#include <iostream>
using namespace std;
int main()
{
double x = 1, average, s, r;
cout << "Squareroot a Number: ";
cin >> s;
r = s * 2;
for ( ; ; ) //for ; ; ; is to run the code forever until it breaks
{
average = (x + s / x) / 2;
if (x == average)
{
cout << "Answer is : " << average << endl;
return 0;
}
x = average;
}
}
```
You can try my code :D
the method that i used here is the Babylonian Squareroot Method
which you can find it here <https://en.wikipedia.org/wiki/Methods_of_computing_square_roots> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.