Q: The function was called with no arguments, thus making data an undefined variable, and raising an error on data != null.
A: Yes, data
will be set to undefined. See section 10.5 Declaration Binding Instantiation of the spec. But accessing an undefined value does not raise an error. You're probably confusing this with accessing an undeclared variable in strict mode which does raise an error.
Q: The function was called specifically with null (or undefined), as its argument, in which case data != null already protects the inner code, rendering && data !== undefined useless.
Q: The function was called with a non-null argument, in which case it will trivially pass both data != null and data !== undefined.
A: Correct. Note that the following tests are equivalent:
data != null
data != undefined
data !== null && data !== undefined
See section 11.9.3 The Abstract Equality Comparison Algorithm and section 11.9.6 The Strict Equality Comparison Algorithm of the spec.
for item in a:
if 1 in item:
print item
Seems like the general query log is the file that you need. A good introduction to this is at http://dev.mysql.com/doc/refman/5.1/en/query-log.html
After adding the JDK
repo, before Installing you might want to run an update first so the repo can be added
run
apt update
an then continue with your installation
sudo apt install adoptopenjdk-8-hotspot
Are you running Skype? This has been the best solution I have found to get rid of the "cannot empty the clipboard error" in Excel 2007 & 2010. Delete the Skype add-on in IE and/or Firefox and good-bye annoying error!
In reply to rjacobs7 post on February 28, 2011
Cannot clear clipboard error - Windows 7, Excel 2010 - This error occurs nearly every time a drag and drop of cell contents is attempted. I've had this same error over the past 10 years on older computers and older versions of Windows and Office. It has now reoccurred with a new laptop running Windows 7 64 bit and Office 2010. The issue can be replicated only if a browser - IE or Firefox - is open at the same time that Excel is open. Having Word and/or Outlook open at the same time will not cause the problem to occur unless a browser is also open. This error is extremely irritating and no solutions from Microsoft or other posts on this issue resolve it.
I have a solution - at least for me! Delete the Skype add-in in IE and Firefox and the "cannot clear clipboard" error after a drag and drop goes away when IE and/or Firefox are running. Apparently some sort of memory-management issue with Skype, Office and the browsers.
Try like this.It should work
Response.Redirect(String.Format("yourpage.aspx?strId={0}&strName={1}&strDate{2}", Server.UrlEncode(strId), Server.UrlEncode(strName),Server.UrlEncode(strDate)));
You can try this code
Dictionary<string,string> AllFields = new Dictionary<string,string>();
string value = (AllFields.TryGetValue(key, out index) ? AllFields[key] : null);
If the key is not present, it simply returns a null value.
ls -lR
is what you were looking for, or atleast I was. cheers
First order your object based on key using this function
function sortObject(o) {
return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
}
Then, compare the stringified version of your object, using this funtion
function isEqualObject(a,b){
return JSON.stringify(sortObject(a)) == JSON.stringify(sortObject(b));
}
Here is an example
Assuming objects keys are ordered differently and are of the same values
var obj1 = {"hello":"hi","world":"earth"}
var obj2 = {"world":"earth","hello":"hi"}
isEqualObject(obj1,obj2);//returns true
I wrote something like this for Sails a while back, in case it saves you some time:
Example usage:
// Delete the user with id=4
User.findAndDelete(4,function(error,result){
// all done
});
// Delete all users with type === 'suspended'
User.findAndDelete({
type: 'suspended'
},function(error,result){
// all done
});
Source:
/**
* Retrieve models which match `where`, then delete them
*/
function findAndDelete (where,callback) {
// Handle *where* argument which is specified as an integer
if (_.isFinite(+where)) {
where = {
id: where
};
}
Model.findAll({
where:where
}).success(function(collection) {
if (collection) {
if (_.isArray(collection)) {
Model.deleteAll(collection, callback);
}
else {
collection.destroy().
success(_.unprefix(callback)).
error(callback);
}
}
else {
callback(null,collection);
}
}).error(callback);
}
/**
* Delete all `models` using the query chainer
*/
deleteAll: function (models) {
var chainer = new Sequelize.Utils.QueryChainer();
_.each(models,function(m,index) {
chainer.add(m.destroy());
});
return chainer.run();
}
from: orm.js.
Hope that helps!
Python long
can be arbitrarily large. If you need a value that's greater than any other value, you can use float('inf')
, since Python has no trouble comparing numeric values of different types. Similarly, for a value lesser than any other value, you can use float('-inf')
.
You can test-drive this code exactly as is using the public GitHub API (don't go over the request limit):
public class App {
public static void main(String[] args) throws IOException {
CloseableHttpClient client = HttpClients.custom().build();
// (1) Use the new Builder API (from v4.3)
HttpUriRequest request = RequestBuilder.get()
.setUri("https://api.github.com")
// (2) Use the included enum
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
// (3) Or your own
.setHeader("Your own very special header", "value")
.build();
CloseableHttpResponse response = client.execute(request);
// (4) How to read all headers with Java8
List<Header> httpHeaders = Arrays.asList(response.getAllHeaders());
httpHeaders.stream().forEach(System.out::println);
// close client and response
}
}
you should change cr_date(str) to datetime object then you 'll change the date to the specific format:
cr_date = '2013-10-31 18:23:29.000227'
cr_date = datetime.datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
cr_date = cr_date.strftime("%m/%d/%Y")
In short
window.onload
is not supported by IE 6-8document.onload
is not supported by any modern browser (event is never fired)window.onload = () => console.log('window.onload works'); // fired
document.onload = () => console.log('document.onload works'); // not fired
_x000D_
Using base-n mini lib, you can do the following:
some_data_t in[] { ... };
constexpr int len = sizeof(in)/sizeof(in[0]);
std::string encoded;
bn::encode_b64(in, in + len, std::back_inserter(encoded));
some_data_t out[len];
bn::decode_b64(encoded.begin(), encoded.end(), out);
The API is generic, iterator-based.
Disclosure: I'm the author.
Note that Mongo essentially stores JSON. If your app is dealing with a lot of JS Objects (with nesting) and you want to persist these objects then there is a very strong argument for using Mongo. It makes your DAL and MVC layers ultra thin, because they are not un-packaging all the JS object properties and trying to force-fit them into a structure (schema) that they don't naturally fit into.
We have a system that has several complex JS Objects at its heart, and we love Mongo because we can persist everything really, really easily. Our objects are also rather amorphous and unstructured, and Mongo soaks up that complication without blinking. We have a custom reporting layer that deciphers the amorphous data for human consumption, and that wasn't that difficult to develop.
this is exactly how it CAN work without jQuery and AJAX and it's working very well using a simple iFrame. I LOVE IT, works in Opera10, FF3 and IE6. Thanks to some of the above posters pointing me the right direction, that's the only reason I am posting here:
<select name="aAddToPage[65654]"
onchange="
if (bCanAddMore) {
addToPage(65654,this);
}
else {
alert('Could not add another, wait until previous is added.');
this.options[0].selected = true;
};
" />
<option value="">Add to page..</option>
[more options with values here]</select>
<script type="text/javascript">
function addToPage(iProduct, oSelect){
iPage = oSelect.options[oSelect.selectedIndex].value;
if (iPage != "") {
bCanAddMore = false;
window.hiddenFrame.document.formFrame.iProduct.value = iProduct;
window.hiddenFrame.document.formFrame.iAddToPage.value = iPage;
window.hiddenFrame.document.formFrame.submit();
}
}
var bCanAddMore = true;</script>
<iframe name="hiddenFrame" style="display:none;" src="frame.php?p=addProductToPage" onload="bCanAddMore = true;"></iframe>
the php code generating the page that is being called above:
if( $_GET['p'] == 'addProductToPage' ){ // hidden form processing
if(!empty($_POST['iAddToPage'])) {
//.. do something with it..
}
print('
<html>
<body>
<form name="formFrame" id="formFrameId" style="display:none;" method="POST" action="frame.php?p=addProductToPage" >
<input type="hidden" name="iProduct" value="" />
<input type="hidden" name="iAddToPage" value="" />
</form>
</body>
</html>
');
}
void main ()
{
int temp,integer,count=0,i,cnd=0;
char ascii[10]={0};
printf("enter a number");
scanf("%d",&integer);
if(integer>>31)
{
/*CONVERTING 2's complement value to normal value*/
integer=~integer+1;
for(temp=integer;temp!=0;temp/=10,count++);
ascii[0]=0x2D;
count++;
cnd=1;
}
else
for(temp=integer;temp!=0;temp/=10,count++);
for(i=count-1,temp=integer;i>=cnd;i--)
{
ascii[i]=(temp%10)+0x30;
temp/=10;
}
printf("\n count =%d ascii=%s ",count,ascii);
}
I've written a script to get all child process pids of a parent process. Here is the code. Hope it will help.
function getcpid() {
cpids=`pgrep -P $1|xargs`
# echo "cpids=$cpids"
for cpid in $cpids;
do
echo "$cpid"
getcpid $cpid
done
}
getcpid $1
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Email Validation</h2>
<input id="textEmail">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo" style="color: red;"></p>
<script>
function myFunction() {
var email;
email = document.getElementById("textEmail").value;
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(textEmail.value) == false)
{
document.getElementById("demo").style.color = "red";
document.getElementById("demo").innerHTML ="Invalid EMail ->"+ email;
alert('Invalid Email Address ->'+email);
return false;
} else{
document.getElementById("demo").style.color = "DarkGreen";
document.getElementById("demo").innerHTML ="Valid Email ->"+email;
}
return true;
}
</script>
</body>
</html>
You said:
I want them to always come out as Tanzanian time and not in the local times that various collaborator are in.
If this is the case, then you should not use UTC. All you need to do is to use a DATETIME
type in MySQL instead of a TIMESTAMP
type.
MySQL converts
TIMESTAMP
values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such asDATETIME
.)
If you are already using a DATETIME
type, then you must be not setting it by the local time to begin with. You'll need to focus less on the database, and more on your application code - which you didn't show here. The problem, and the solution, will vary drastically depending on language, so be sure to tag the question with the appropriate language of your application code.
You Can Now Delete App.
On October 4, 2018, Apple released a new update of the appstoreconnect (previously iTunesConnect).
It's now easier to manage apps you no longer need in App Store Connect by removing them from your main view in My Apps, even if they haven't been submitted for approval. You must have the Legal or Admin role to remove apps.
From the homepage, click My Apps, then choose the app you want to remove. Scroll to the Additional Information section, then click Remove App. In the dialog that appears, click Remove. You can restore a removed app at any time, as long as the app name is not currently in use by another developer.
From the homepage, click My Apps. In the upper right-hand corner, click the arrow next to All Statuses. From the drop-down menu, choose Removed Apps. Choose the app you want to restore. Scroll to the Additional Information section, then click Restore App.
You can show the removed app by clicking on all Statuses on the top right of the screen and then select Removed Apps. Thank you @Daniel for the tips.
Please note:
you can only remove apps if all versions of that app are in one of the following states: Prepare for Submission, Invalid Binary, Developer Rejected, Rejected, Metadata Rejected, Developer, Removed from Sale.
The reason normalization is needed is because if you look at how an adaptive step proceeds in one place in the domain of the function, and you just simply transport the problem to the equivalent of the same step translated by some large value in some direction in the domain, then you get different results. It boils down to the question of adapting a linear piece to a data point. How much should the piece move without turning and how much should it turn in response to that one training point? It makes no sense to have a changed adaptation procedure in different parts of the domain! So normalization is required to reduce the difference in the training result. I haven't got this written up, but you can just look at the math for a simple linear function and how it is trained by one training point in two different places. This problem may have been corrected in some places, but I am not familiar with them. In ALNs, the problem has been corrected and I can send you a paper if you write to wwarmstrong AT shaw.ca
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
Reference Resolution is described by RFC 3986 Uniform Resource Identifier (URI): Generic Syntax. And that is exactly how it supposed to work. To preserve base URI path you need to add slash at the end of the base URI and remove slash at the beginning of relative URI.
If base URI contains non-empty path, merge procedure discards it's last part (after last /
). Relevant section:
5.2.3. Merge Paths
The pseudocode above refers to a "merge" routine for merging a relative-path reference with the path of the base URI. This is accomplished as follows:
If the base URI has a defined authority component and an empty path, then return a string consisting of "/" concatenated with the reference's path; otherwise
return a string consisting of the reference's path component appended to all but the last segment of the base URI's path (i.e., excluding any characters after the right-most "/" in the base URI path, or excluding the entire base URI path if it does not contain any "/" characters).
If relative URI starts with a slash, it is called a absolute-path relative URI. In this case merge procedure ignore all base URI path. For more information check 5.2.2. Transform References section.
I was in exactly the same situation recently, mate, and I can tell you what I did.
Josh Smith "WPF Apps With The Model-View-ViewModel Design Pattern" read again, again and again :-) download the code, examine, compile and keep it around
No real start-to-finish tutorials, sorry...
My personal favorite: Just add the code below to App_Start/WebApiConfig.cs
. This will return json instead of XML by default and also prevent the error you had. No need to edit Global.asax
to remove XmlFormatter
etc.
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
I am reading a book (Effective Python) by Brett Slatkin and he shows another way to iterate over a list and also know the index of the current item in the list but he suggests that it is better not to use it and to use enumerate
instead.
I know you asked what enumerate means, but when I understood the following, I also understood how enumerate
makes iterating over a list while knowing the index of the current item easier (and more readable).
list_of_letters = ['a', 'b', 'c']
for i in range(len(list_of_letters)):
letter = list_of_letters[i]
print (i, letter)
The output is:
0 a
1 b
2 c
I also used to do something, even sillier before I read about the enumerate
function.
i = 0
for n in list_of_letters:
print (i, n)
i += 1
It produces the same output.
But with enumerate
I just have to write:
list_of_letters = ['a', 'b', 'c']
for i, letter in enumerate(list_of_letters):
print (i, letter)
Both means "every item in a set of two things". The two things being "left" and "right"
Check again. Use debugger if must. My guess is that for some item in userResponseDetails this query finds no elements:
.Where(y => y.ResponseId.Equals(item.ResponseId))
so you can't call
.First()
on it. Maybe try
.FirstOrDefault()
if it solves the issue.
Do NOT return NULL value! This is purely so that you can see and diagnose where problem is. Handle these cases properly.
Fiddle with 3 working solutions in action.
Given an external JSON:
myurl = 'http://wikidata.org/w/api.php?action=wbgetentities&sites=frwiki&titles=France&languages=zh-hans|zh-hant|fr&props=sitelinks|labels|aliases|descriptions&format=json'
Solution 1: $.ajax() + jsonp:
$.ajax({
dataType: "jsonp",
url: myurl ,
}).done(function ( data ) {
// do my stuff
});
Solution 2: $.ajax()+json+&calback=?:
$.ajax({
dataType: "json",
url: myurl + '&callback=?',
}).done(function ( data ) {
// do my stuff
});
Solution 3: $.getJSON()+calback=?:
$.getJSON( myurl + '&callback=?', function(data) {
// do my stuff
});
Documentations: http://api.jquery.com/jQuery.ajax/ , http://api.jquery.com/jQuery.getJSON/
You can make a back-tracker character, ex, you could append any special character say "%" to the end of your string and then check the occurrence of that character.
But this is a very risky way as that character can be in other places also in the char*
char* stringVar = new char[4] ;
stringVar[0] = 'H' ;
stringVar[1] = 'E' ;
stringVar[2] = '$' ; // back-tracker character.
int i = 0 ;
while(1)
{
if (stringVar[i] == '$')
break ;
i++ ;
}
// i is the length of the string.
// you need to make sure, that there is no other $ in the char*
Otherwise define a custom structure to keep track of length and allocate memory.
To get the index
values as a list
/list
of tuple
s for Index
/MultiIndex
do:
df.index.values.tolist() # an ndarray method, you probably shouldn't depend on this
or
list(df.index.values) # this will always work in pandas
Multiple ways of searching for the program.
Type mysql
in your terminal, see the result.
Search the /usr/bin
, /bin
directories for the binary.
Type apt-cache show mysql
to see if it is installed
locate mysql
You can't access form inputs via their name. Use document.getElements
methods instead.
A picture's worth a thousand words:
>>> class c:
pass
o = c()
>>> setattr(o, "foo", "bar")
>>> o.foo
'bar'
>>> getattr(o, "foo")
'bar'
1.First run your Application 2.Go to Tool-->Android-->Android Device Monitor
You have your slash backwards, it should be "\n"
Neither of the highest voted answers are correct on SQL Server 2000. Perhaps they were using a different version.
Here are the correct versions of both of them on SQL Server 2000.
select t.range as [score range], count(*) as [number of occurences]
from (
select case
when score between 0 and 9 then ' 0- 9'
when score between 10 and 19 then '10-19'
else '20-99' end as range
from scores) t
group by t.range
or
select t.range as [score range], count(*) as [number of occurrences]
from (
select user_id,
case when score >= 0 and score< 10 then '0-9'
when score >= 10 and score< 20 then '10-19'
else '20-99' end as range
from scores) t
group by t.range
Solution working with different types and with upper and lower cases.
For example, without the toLowerCase
statement, "Goodyear" will come before "doe" with an ascending sort. Run the code snippet at the bottom of my answer to view the different behaviors.
JSON DATA:
var people = [
{
"f_name" : "john",
"l_name" : "doe", // lower case
"sequence": 0 // int
},
{
"f_name" : "michael",
"l_name" : "Goodyear", // upper case
"sequence" : 1 // int
}];
JSON Sort Function:
function sortJson(element, prop, propType, asc) {
switch (propType) {
case "int":
element = element.sort(function (a, b) {
if (asc) {
return (parseInt(a[prop]) > parseInt(b[prop])) ? 1 : ((parseInt(a[prop]) < parseInt(b[prop])) ? -1 : 0);
} else {
return (parseInt(b[prop]) > parseInt(a[prop])) ? 1 : ((parseInt(b[prop]) < parseInt(a[prop])) ? -1 : 0);
}
});
break;
default:
element = element.sort(function (a, b) {
if (asc) {
return (a[prop].toLowerCase() > b[prop].toLowerCase()) ? 1 : ((a[prop].toLowerCase() < b[prop].toLowerCase()) ? -1 : 0);
} else {
return (b[prop].toLowerCase() > a[prop].toLowerCase()) ? 1 : ((b[prop].toLowerCase() < a[prop].toLowerCase()) ? -1 : 0);
}
});
}
}
Usage:
sortJson(people , "l_name", "string", true);
sortJson(people , "sequence", "int", true);
var people = [{_x000D_
"f_name": "john",_x000D_
"l_name": "doe",_x000D_
"sequence": 0_x000D_
}, {_x000D_
"f_name": "michael",_x000D_
"l_name": "Goodyear",_x000D_
"sequence": 1_x000D_
}, {_x000D_
"f_name": "bill",_x000D_
"l_name": "Johnson",_x000D_
"sequence": 4_x000D_
}, {_x000D_
"f_name": "will",_x000D_
"l_name": "malone",_x000D_
"sequence": 2_x000D_
}, {_x000D_
"f_name": "tim",_x000D_
"l_name": "Allen",_x000D_
"sequence": 3_x000D_
}];_x000D_
_x000D_
function sortJsonLcase(element, prop, asc) {_x000D_
element = element.sort(function(a, b) {_x000D_
if (asc) {_x000D_
return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);_x000D_
} else {_x000D_
return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
function sortJson(element, prop, propType, asc) {_x000D_
switch (propType) {_x000D_
case "int":_x000D_
element = element.sort(function(a, b) {_x000D_
if (asc) {_x000D_
return (parseInt(a[prop]) > parseInt(b[prop])) ? 1 : ((parseInt(a[prop]) < parseInt(b[prop])) ? -1 : 0);_x000D_
} else {_x000D_
return (parseInt(b[prop]) > parseInt(a[prop])) ? 1 : ((parseInt(b[prop]) < parseInt(a[prop])) ? -1 : 0);_x000D_
}_x000D_
});_x000D_
break;_x000D_
default:_x000D_
element = element.sort(function(a, b) {_x000D_
if (asc) {_x000D_
return (a[prop].toLowerCase() > b[prop].toLowerCase()) ? 1 : ((a[prop].toLowerCase() < b[prop].toLowerCase()) ? -1 : 0);_x000D_
} else {_x000D_
return (b[prop].toLowerCase() > a[prop].toLowerCase()) ? 1 : ((b[prop].toLowerCase() < a[prop].toLowerCase()) ? -1 : 0);_x000D_
}_x000D_
});_x000D_
}_x000D_
}_x000D_
_x000D_
function sortJsonString() {_x000D_
sortJson(people, 'l_name', 'string', $("#chkAscString").prop("checked"));_x000D_
display();_x000D_
}_x000D_
_x000D_
function sortJsonInt() {_x000D_
sortJson(people, 'sequence', 'int', $("#chkAscInt").prop("checked"));_x000D_
display();_x000D_
}_x000D_
_x000D_
function sortJsonUL() {_x000D_
sortJsonLcase(people, 'l_name', $('#chkAsc').prop('checked'));_x000D_
display();_x000D_
}_x000D_
_x000D_
function display() {_x000D_
$("#data").empty();_x000D_
$(people).each(function() {_x000D_
$("#data").append("<div class='people'>" + this.l_name + "</div><div class='people'>" + this.f_name + "</div><div class='people'>" + this.sequence + "</div><br />");_x000D_
});_x000D_
}
_x000D_
body {_x000D_
font-family: Arial;_x000D_
}_x000D_
.people {_x000D_
display: inline-block;_x000D_
width: 100px;_x000D_
border: 1px dotted black;_x000D_
padding: 5px;_x000D_
margin: 5px;_x000D_
}_x000D_
.buttons {_x000D_
border: 1px solid black;_x000D_
padding: 5px;_x000D_
margin: 5px;_x000D_
float: left;_x000D_
width: 20%;_x000D_
}_x000D_
ul {_x000D_
margin: 5px 0px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="buttons" style="background-color: rgba(240, 255, 189, 1);">_x000D_
Sort the JSON array <strong style="color: red;">with</strong> toLowerCase:_x000D_
<ul>_x000D_
<li>Type: string</li>_x000D_
<li>Property: lastname</li>_x000D_
</ul>_x000D_
<button onclick="sortJsonString(); return false;">Sort JSON</button>_x000D_
Asc Sort_x000D_
<input id="chkAscString" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<div class="buttons" style="background-color: rgba(255, 214, 215, 1);">_x000D_
Sort the JSON array <strong style="color: red;">without</strong> toLowerCase:_x000D_
<ul>_x000D_
<li>Type: string</li>_x000D_
<li>Property: lastname</li>_x000D_
</ul>_x000D_
<button onclick="sortJsonUL(); return false;">Sort JSON</button>_x000D_
Asc Sort_x000D_
<input id="chkAsc" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<div class="buttons" style="background-color: rgba(240, 255, 189, 1);">_x000D_
Sort the JSON array:_x000D_
<ul>_x000D_
<li>Type: int</li>_x000D_
<li>Property: sequence</li>_x000D_
</ul>_x000D_
<button onclick="sortJsonInt(); return false;">Sort JSON</button>_x000D_
Asc Sort_x000D_
<input id="chkAscInt" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<br />_x000D_
<br />_x000D_
<div id="data" style="float: left; border: 1px solid black; width: 60%; margin: 5px;">Data</div>
_x000D_
ex="test1,test2,test3,test4,test5"
all_but_first=ex.split(/,/)[1..-1]
docker exec -t your-db-container pg_dumpall -c -U postgres > dump_`date +%d-%m-%Y"_"%H_%M_%S`.sql
cat your_dump.sql | docker exec -i your-db-container psql -U postgres
Some great news! Since version 3.6 the cPython implementation has preserved the insertion order of dictionaries (https://mail.python.org/pipermail/python-dev/2016-September/146327.html). This means that the json library is now order preserving by default. Observe the difference in behaviour between python 3.5 and 3.6. The code:
import json
data = json.loads('{"foo":1, "bar":2, "fiddle":{"bar":2, "foo":1}}')
print(json.dumps(data, indent=4))
In py3.5 the resulting order is undefined:
{
"fiddle": {
"bar": 2,
"foo": 1
},
"bar": 2,
"foo": 1
}
In the cPython implementation of python 3.6:
{
"foo": 1,
"bar": 2,
"fiddle": {
"bar": 2,
"foo": 1
}
}
The really great news is that this has become a language specification as of python 3.7 (as opposed to an implementation detail of cPython 3.6+): https://mail.python.org/pipermail/python-dev/2017-December/151283.html
So the answer to your question now becomes: upgrade to python 3.6! :)
Meld (http://meldmerge.org/) does a great job at comparing directories and the files within.
You can use oraji. It can install/uninstall both JDK or JRE from oracle java (.tar.gz).
sudo oraji '/path/to/the/jdk_or_jre_archive'
oraji -u
and confirm the version number.If i remember correctly (it's been a while since i dabbed with SQL Server) you may be able to use something like this: (2005 and up)
SELECT
*
,ROW_NUMBER() OVER(ORDER BY SomeFields) AS [RowNum]
FROM SomeTable
WHERE RowNum BETWEEN 10 AND 20
find this line in php.ini :
;extension=soap
then remove the semicolon ;
and restart Apache server
Objective C for iOS 13+, courtesy of Wasif Saood's answer
Copy and paste below code into AppDelegate.m to print the device APN token.
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSUInteger dataLength = deviceToken.length;
if (dataLength == 0) {
return;
}
const unsigned char *dataBuffer = (const unsigned char *)deviceToken.bytes;
NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (int i = 0; i < dataLength; ++i) {
[hexString appendFormat:@"%02x", dataBuffer[i]];
}
NSLog(@"APN token:%@", hexString);
}
Try going to "Manage Jenkins"->"Manage Users" go to the specific user, edit his/her configuration "My Views section" default view.
len(yourdict.keys())
or just
len(yourdict)
If you like to count unique words in the file, you could just use set
and do like
len(set(open(yourdictfile).read().split()))
In my case, it was also caused by old dlls. Clean all your files then rebuild.
If you want to include render prop components:
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node,
PropTypes.func
])
If somebody is really against programming in more languages than one, I suggest GWT. Theoretically, you can avoid all the JavaScript and HTML elements, because Google Toolkit transforms all the client and shared code to JavaScript. You won't have problem with them, so you have a webservice without coding in any other languages. You can even use some default CSS from somewhere as it is given by extensions (smartGWT or Vaadin). You don't need to learn dozens of annotations.
Of course, if you want, you can hack yourself into the depths of the code and inject JavaScript and enrich your HTML page, but really you can avoid it if you want, and the result will be good as it was written in any other frameworks. I it's say worth a try, and the basic GWT is well-documented.
And of course many fellow programmers hereby described or recommended several other solutions. GWT is for people who really don't want to deal with the web part or to minimize it.
This could happen when you have several projects that include each other in JAR form. What I did was remove all libraries and project dependencies on buildpath, for all projects. Then, one at a time, I added the project dependencies on the Project Tab, but only the ones needed. This is because you can add a project which in turn has itself referenced or another project which is referencing some other project with this self-referencing issue.
This resolved my issue.
Download the .NET Core Hosting Bundle installer using the following link:
Current .NET Core Hosting Bundle installer (direct download)
I'll add that arrays are very low-level constructs in C++ and you should try to stay away from them as much as possible when "learning the ropes" -- even Bjarne Stroustrup recommends this (he's the designer of C++).
Vectors come very close to the same performance as arrays, but with a great many conveniences and safety features. You'll probably start using arrays when interfacing with API's that deal with raw arrays, or when building your own collections.
In your edit action, store the requesting url in the session hash, which is available across multiple requests:
session[:return_to] ||= request.referer
Then redirect to it in your update action, after a successful save:
redirect_to session.delete(:return_to)
Try with following:
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo." +table;
SqlConnection sqlConn = new SqlConnection(conSTR);
sqlConn.Open();
SqlCommand cmd = new SqlCommand(query, sqlConn);
SqlDataAdapter da=new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
sqlConn.Close();
return dt;
}
Hope it is helpful.
Use Any()
instead of Contains()
:
buildingStatus.Any(item => item.GetCharValue() == v.Status)
If you want to check if the dialog's open on a particular element you can do this:
if ($('#elem').closest('.ui-dialog').is(':visible')) {
// do something
}
Or if you just want to check if the element itself is visible you can do:
if ($('#elem').is(':visible')) {
// do something
}
Or...
if ($('#elem:visible').length) {
// do something
}
Use a list comprehension:
res_list = [x[0] for x in rows]
Below is a demonstration:
>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> [x[0] for x in rows]
[1, 3, 5]
>>>
Alternately, you could use unpacking instead of x[0]
:
res_list = [x for x,_ in rows]
Below is a demonstration:
>>> lst = [(1, 2), (3, 4), (5, 6)]
>>> [x for x,_ in lst]
[1, 3, 5]
>>>
Both methods practically do the same thing, so you can choose whichever you like.
return "default" if x is None else x
try the above.
You can use ET for this. ET is a small Java 8 library for exception conversion/translation.
With ET it looks like this:
// Do this once
ExceptionTranslator et = ET.newConfiguration().done();
...
// if your method returns something
Function<String, Integer> f = (t) -> et.withReturningTranslation(() -> myMethod(t));
// if your method returns nothing
Consumer<String> c = (t) -> et.withTranslation(() -> myMethod(t));
ExceptionTranslator
instances are thread safe an can be shared by multiple components. You can configure more specific exception conversion rules (e.g. FooCheckedException -> BarRuntimeException
) if you like.
If no other rules are available, checked exceptions are automatically converted to RuntimeException
.
(Disclaimer: I am the author of ET)
Try the event delegation method, this works in almost all cases.
$(document.body).on('change',"#selectID",function (e) {
//doStuff
var optVal= $("#selectID option:selected").val();
});
rand(3..10)
When max is a Range, rand returns a random number where range.member?(number) == true.
The short answer is "yes". A sample ldapsearch
command to query an Active Directory server is:
ldapsearch \
-x -h ldapserver.mydomain.com \
-D "[email protected]" \
-W \
-b "cn=users,dc=mydomain,dc=com" \
-s sub "(cn=*)" cn mail sn
This would connect to an AD server at hostname ldapserver.mydomain.com
as user [email protected]
, prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com
subtree.
See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.
You can use something like this.
var {height, width} = Dimensions.get('window'); var textFontSize = width * 0.03;
inputText: {
color : TEXT_COLOR_PRIMARY,
width: '80%',
fontSize: textFontSize
}
Hope this helps without installing any third party libraries.
To find the directory where your executable is, you can use:
TCHAR szFilePath[_MAX_PATH];
::GetModuleFileName(NULL, szFilePath, _MAX_PATH);
The parent of the row is not the object you think, this is what I understand from the error.
Try detecting the parent of the row first, then you can be sure what to write into getElementById
part of the parent.
Regarding parameters:
See this answer first. To get a list of all the builds for a project (obtained as per that answer):
project.builds
When you find your particular build, you need to get all actions of type ParametersAction with build.getActions(hudson.model.ParametersAction)
. You then query the returned object for your specific parameters.
Regarding p4.change: I suspect that it is also stored as an action. In Jenkins Groovy console get all actions for a build that contains p4.change and examine them - it will give you an idea what to look for in your code.
Excel Interop:
This method prevents Dates getting flipped from dd-mm-yyyy to mm-dd-yyyy
public bool DataTableToExcelFile(DataTable dt, string targetFile)
{
const bool dontSave = false;
bool success = true;
//Exit if there is no rows to export
if (dt.Rows.Count == 0) return false;
object misValue = System.Reflection.Missing.Value;
List<int> dateColIndex = new List<int>();
Excel.Application excelApp = new Excel.Application();
Excel.Workbook excelWorkBook = excelApp.Workbooks.Add(misValue);
Excel.Worksheet excelWorkSheet = excelWorkBook.Sheets("sheet1");
//Iterate through the DataTable and populate the Excel work sheet
try {
for (int i = -1; i <= dt.Rows.Count - 1; i++) {
for (int j = 0; j <= dt.Columns.Count - 1; j++) {
if (i < 0) {
//Take special care with Date columns
if (dt.Columns(j).DataType is typeof(DateTime)) {
excelWorkSheet.Cells(1, j + 1).EntireColumn.NumberFormat = "d-MMM-yyyy;@";
dateColIndex.Add(j);
}
//else if ... Feel free to add more Formats
else {
//Otherwise Format the column as text
excelWorkSheet.Cells(1, j + 1).EntireColumn.NumberFormat = "@";
}
excelWorkSheet.Cells(1, j + 1) = dt.Columns(j).Caption;
}
else if (dateColIndex.IndexOf(j) > -1) {
excelWorkSheet.Cells(i + 2, j + 1) = Convert.ToDateTime(dt.Rows(i).ItemArray(j)).ToString("d-MMM-yyyy");
}
else {
excelWorkSheet.Cells(i + 2, j + 1) = dt.Rows(i).ItemArray(j).ToString();
}
}
}
//Add Autofilters to the Excel work sheet
excelWorkSheet.Cells.AutoFilter(1, Type.Missing, Excel.XlAutoFilterOperator.xlAnd, Type.Missing, true);
//Autofit columns for neatness
excelWorkSheet.Columns.AutoFit();
if (File.Exists(exportFile)) File.Delete(exportFile);
excelWorkSheet.SaveAs(exportFile);
} catch {
success = false;
} finally {
//Do this irrespective of whether there was an exception or not.
excelWorkBook.Close(dontSave);
excelApp.Quit();
releaseObject(excelWorkSheet);
releaseObject(excelWorkBook);
releaseObject(excelApp);
}
return success;
}
If you dont care about Dates being flipped, then use see link that shows how to populate all the cells in the Excel spreadsheet in one line of code:
Excel Interop - Efficiency and performance
CSV:
public string DataTableToCSV(DataTable dt, bool includeHeader, string rowFilter, string sortFilter, bool useCommaDelimiter = false, bool truncateTimesFromDates = false)
{
dt.DefaultView.RowFilter = rowFilter;
dt.DefaultView.Sort = sortFilter;
DataView dv = dt.DefaultView;
string csv = DataTableToCSV(dv.ToTable, includeHeader, useCommaDelimiter, truncateTimesFromDates);
//reset the Filtering
dt.DefaultView.RowFilter = string.Empty;
return csv;
}
public string DataTableToCsv(DataTable dt, bool includeHeader, bool useCommaDelimiter = false, bool truncateTimesFromDates = false)
{
StringBuilder sb = new StringBuilder();
string delimter = Constants.vbTab;
if (useCommaDelimiter)
delimter = ",";
if (includeHeader) {
foreach (DataColumn dc in dt.Columns) {
sb.AppendFormat("{0}" + Constants.vbTab, dc.ColumnName);
}
//remove the last Tab
sb.Remove(sb.ToString.Length - 1, 1);
sb.Append(Environment.NewLine);
}
foreach (DataRow dr in dt.Rows) {
foreach (DataColumn dc in dt.Columns) {
if (Information.IsDate(dr(dc.ColumnName).ToString()) & dr(dc.ColumnName).ToString().Contains(".") == false & truncateTimesFromDates) {
sb.AppendFormat("{0}" + delimter, Convert.ToDateTime(dr(dc.ColumnName).ToString()).Date.ToShortDateString());
} else {
sb.AppendFormat("{0}" + delimter, CheckDBNull(dr(dc.ColumnName).ToString().Replace(",", "")));
}
}
//remove the last Tab
sb.Remove(sb.ToString.Length - 1, 1);
sb.Append(Environment.NewLine);
}
return sb.ToString;
}
public enum enumObjectType
{
StrType = 0,
IntType = 1,
DblType = 2
}
public object CheckDBNull(object obj, enumObjectType ObjectType = enumObjectType.StrType)
{
object objReturn = null;
objReturn = obj;
if (ObjectType == enumObjectType.StrType & Information.IsDBNull(obj)) {
objReturn = "";
} else if (ObjectType == enumObjectType.IntType & Information.IsDBNull(obj)) {
objReturn = 0;
} else if (ObjectType == enumObjectType.DblType & Information.IsDBNull(obj)) {
objReturn = 0.0;
}
return objReturn;
}
In Simple one liner for deleting null values in Hash,
rec_hash.each {|key,value| rec_hash.delete(key) if value.blank? }
Try this:
<?php
/*
Template Name: [contact us]
*/
get_header();
echo do_shortcode('[CONTACT-US-FORM]');
?>
You are right. If you want to delete the User and all associated objects -> destroy_all
However, if you just want to delete the User without suppressing all associated objects -> delete_all
According to this post : Rails :dependent => :destroy VS :dependent => :delete_all
destroy
/ destroy_all
: The associated objects are destroyed alongside this object by calling their destroy methoddelete
/ delete_all
: All associated objects are destroyed immediately without calling their :destroy methodThis works for me!
def removeBOMs(fileName):
BOMs = ['',#Bytes as CP1252 characters
'þÿ',
'ÿþ',
'^@^@þÿ',
'ÿþ^@^@',
'+/v',
'÷dL',
'Ýsfs',
'Ýsfs',
'^Nþÿ',
'ûî(',
'„1•3']
inputFile = open(fileName, 'r')
contents = inputFile.read()
for BOM in BOMs:
if not BOM in contents:#no BOM in the file...
pass
else:
newContents = contents.replace(BOM,'', 1)
newFile = open(fileName, 'w')
newFile.write(newContents)
return None
I like the @Rule
answer. However, if for some reason you don't want to use rules. There is a third option.
@Test (expected = RuntimeException.class)
public void myTestMethod()
{
try
{
//Run exception throwing operation here
}
catch(RuntimeException re)
{
String message = "Employee ID is null";
assertEquals(message, re.getMessage());
throw re;
}
fail("Employee Id Null exception did not throw!");
}
You can get the maximum key this way:
<?php
$arr = array("a"=>"test", "b"=>"ztest");
$max = max(array_keys($arr));
?>
Try this:
def monthdelta(date, delta):
m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12
if not m: m = 12
d = min(date.day, [31,
29 if y%4==0 and (not y%100==0 or y%400 == 0) else 28,
31,30,31,30,31,31,30,31,30,31][m-1])
return date.replace(day=d,month=m, year=y)
>>> for m in range(-12, 12):
print(monthdelta(datetime.now(), m))
2009-08-06 16:12:27.823000
2009-09-06 16:12:27.855000
2009-10-06 16:12:27.870000
2009-11-06 16:12:27.870000
2009-12-06 16:12:27.870000
2010-01-06 16:12:27.870000
2010-02-06 16:12:27.870000
2010-03-06 16:12:27.886000
2010-04-06 16:12:27.886000
2010-05-06 16:12:27.886000
2010-06-06 16:12:27.886000
2010-07-06 16:12:27.886000
2010-08-06 16:12:27.901000
2010-09-06 16:12:27.901000
2010-10-06 16:12:27.901000
2010-11-06 16:12:27.901000
2010-12-06 16:12:27.901000
2011-01-06 16:12:27.917000
2011-02-06 16:12:27.917000
2011-03-06 16:12:27.917000
2011-04-06 16:12:27.917000
2011-05-06 16:12:27.917000
2011-06-06 16:12:27.933000
2011-07-06 16:12:27.933000
>>> monthdelta(datetime(2010,3,30), -1)
datetime.datetime(2010, 2, 28, 0, 0)
>>> monthdelta(datetime(2008,3,30), -1)
datetime.datetime(2008, 2, 29, 0, 0)
Edit Corrected to handle the day as well.
Edit See also the answer from puzzlement which points out a simpler calculation for d
:
d = min(date.day, calendar.monthrange(y, m)[1])
$(document).on( "keydown", keyPressed);
function keyPressed (e){
e = e || window.e;
var newchar = e.which || e.keyCode;
alert(newchar)
}
Simply use this
echo date('Y-m-d',strtotime("yesterday"));
echo date('Y-m-d',strtotime("tomorrow"));
Old but still valid question, so heres what I created based on the info provided by others here.
create function fnLastIndexOf(@text varChar(max),@char varchar(1))
returns int
as
begin
return len(@text) - charindex(@char, reverse(@text)) -1
end
Use the css property overflow . For example:
.item{
width : 100px;
overflow:hidden;
}
The overflow property can have one of many values like ( hidden , scroll , visible ) .. you can als control the overflow in one direction only using overflow-x or overflow-y.
I hope this helps.
The main problem which I faced was dynamical adding headers and logging them into debug logcat. I've tried to add two interceptors. One for logging and one for adding headers on-the-go (token authorization). The problem was that we may .addInterceptor or .addNetworkInterceptor. As Jake Wharton said to me: "Network interceptors always come after application interceptors. See https://github.com/square/okhttp/wiki/Interceptors". So here is working example with headers and logs:
OkHttpClient httpClient = new OkHttpClient.Builder()
//here we can add Interceptor for dynamical adding headers
.addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("test", "test").build();
return chain.proceed(request);
}
})
//here we adding Interceptor for full level logging
.addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build();
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(httpClient)
.baseUrl(AppConstants.SERVER_ADDRESS)
.build();
Well, given your constraints, I think setting overflow: scroll;
on the .page
div is probably your only option. 280 px is pretty narrow, and given your font size, word wrapping alone isn't going to do it. Some words are just long and can't be wrapped. You can either reduce your font size drastically or go with overflow: scroll.
If using PostgreSql 9.5.1, please follow the below configuration:
As Sotirios Delimanolis already pointed out in the comments, there are two options:
ResponseEntity
with error messageChange your method like this:
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity getUser(@RequestHeader(value="Access-key") String accessKey,
@RequestHeader(value="Secret-key") String secretKey) {
try {
// see note 1
return ResponseEntity
.status(HttpStatus.CREATED)
.body(this.userService.chkCredentials(accessKey, secretKey, timestamp));
}
catch(ChekingCredentialsFailedException e) {
e.printStackTrace(); // see note 2
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body("Error Message");
}
}
Note 1: You don't have to use the ResponseEntity
builder but I find it helps with keeping the code readable. It also helps remembering, which data a response for a specific HTTP status code should include. For example, a response with the status code 201 should contain a link to the newly created resource in the Location
header (see Status Code Definitions). This is why Spring offers the convenient build method ResponseEntity.created(URI)
.
Note 2: Don't use printStackTrace()
, use a logger instead.
@ExceptionHandler
Remove the try-catch block from your method and let it throw the exception. Then create another method in a class annotated with @ControllerAdvice
like this:
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler(ChekingCredentialsFailedException.class)
public ResponseEntity handleException(ChekingCredentialsFailedException e) {
// log exception
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body("Error Message");
}
}
Note that methods which are annotated with @ExceptionHandler
are allowed to have very flexible signatures. See the Javadoc for details.
Might I suggest WinSnap http://www.ntwind.com/software/winsnap/download-free-version.html. It provides an autosave option and capture the alt+printscreen and other key combinations to capture screen, windows, dialog, etc.
It might help you!!
The AngularJs code-sample
var app = angular.module('app', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
// For any unmatched url, send to /index
$urlRouterProvider.otherwise("/login");
$stateProvider
.state('login', {
url: "/login",
templateUrl: "login.html",
controller: "LoginCheckController"
})
.state('SuccessPage', {
url: "/SuccessPage",
templateUrl: "SuccessPage.html",
//controller: "LoginCheckController"
});
});
app.controller('LoginCheckController', ['$scope', '$location', LoginCheckController]);
function LoginCheckController($scope, $location) {
$scope.users = [{
UserName: 'chandra',
Password: 'hello'
}, {
UserName: 'Harish',
Password: 'hi'
}, {
UserName: 'Chinthu',
Password: 'hi'
}];
$scope.LoginCheck = function() {
$location.path("SuccessPage");
};
$scope.go = function(path) {
$location.path("/SuccessPage");
};
}
If you used this to secure your server: http://www.thonky.com/how-to/prevent-base-64-decode-hack/
And then got the error: Code Igniter needs mysql_pconnect() in order to run
.
I figured it out once I realized all the Code Igniter websites on the server were broken, so it wasn't a localized connection issue.
This looks like Dijstra's algorithm. In any case, the time taken to run will depend on N. If it takes more than 3 seconds there isn't any way I can see of speeding it up, as all the calculations that it is doing need to be done.
Depending on what problem you're trying to solve, there might be a faster algorithm.
How can it ever be longer than
tmp = my_list[indexOfPwd2]
my_list[indexOfPwd2] = my_list[indexOfPwd2 + 1]
my_list[indexOfPwd2 + 1] = tmp
That's just a plain swap using temporary storage.
I was having the same problem. It seems that passing Me.ComboBox1.Value
as an argument for the Vlookup
function is causing the issue. What I did was assign this value to a double and then put it into the Vlookup function.
Dim x As Double
x = Me.ComboBox1.Value
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(x, Worksheets("Sheet3").Range("Names"), 2, False)
Or, for a shorter method, you can just convert the type within the Vlookup function using Cdbl(<Value>)
.
So it would end up being
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(Cdbl(Me.ComboBox1.Value), Worksheets("Sheet3").Range("Names"), 2, False)
Strange as it may sound, it works for me.
Hope this helps.
I think you can use prtdiag or prtconf on many UNIXs
You should use
this.router.parent.navigate(['/About']);
As well as specifying the route path, you can also specify your route's name:
{ path:'/About', name: 'About', ... }
this.router.parent.navigate(['About']);
this works only if WebResponse is a HttpWebResponse.
try
{
...
}
catch (System.Net.WebException exc)
{
var webResponse = exc.Response as System.Net.HttpWebResponse;
if (webResponse != null &&
webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
MessageBox.Show("401");
}
else
throw;
}
To get the time in millis at GMT all you need is
long millis = System.currentTimeMillis();
You can also do
long millis = new Date().getTime();
and
long millis =
Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis();
but these are inefficient ways of making the same call.
You can transpose the array if you want to get the length of the other dimension.
len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]]).T)
Something like this works:
input + label::after {_x000D_
content: 'click my input';_x000D_
color: black;_x000D_
}_x000D_
_x000D_
input:focus + label::after {_x000D_
content: 'not valid yet';_x000D_
color: red;_x000D_
}_x000D_
_x000D_
input:valid + label::after {_x000D_
content: 'looks good';_x000D_
color: green;_x000D_
}
_x000D_
<input id="input" type="number" required />_x000D_
<label for="input"></label>
_x000D_
Then add some floats or positioning to order stuff.
I suppose subqueries and PIVOT would qualify, as well as multiple joins, unions and the like.
Hi another solution to this problem is to simply add the node nodejs binary folder to your PATH using the following command:
ln -s /usr/bin/nodejs /usr/bin/node
See NPM GitHub for better explanation
Read two integers from the user. Then compute/display the remainder and quotient,
// When the larger integer is divided by the smaller integer
Console.WriteLine("Enter integer 1 please :");
double a5 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter integer 2 please :");
double b5 = double.Parse(Console.ReadLine());
double div = a5 / b5;
Console.WriteLine(div);
double mod = a5 % b5;
Console.WriteLine(mod);
Console.ReadLine();
my helpful code for others(just one aspx to do text area post)::
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication45.WebForm1" %>
<!DOCTYPE html>
enter code here
<html ng-app="htmldoc" xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="angular.min.js"></script>
<script src="angular-sanitize.min.js"></script>
<script>
angular.module('htmldoc', ['ngSanitize']).controller('x', function ($scope, $sce) {
//$scope.htmlContent = '<script> (function () { location = \"http://moneycontrol.com\"; } )()<\/script> In last valid content';
$scope.htmlContent = '';
$scope.withoutSanitize = function () {
return $sce.getTrustedHtml($scope.htmlContent);
};
$scope.postMessage = function () {
var ValidContent = $sce.trustAsHtml($scope.htmlContent);
//your ajax call here
};
});
</script>
</head>
<body>
<form id="form1" runat="server">
Example to show posting valid content to server with two way binding
<div ng-controller="x">
<p ng-bind-html="htmlContent"></p>
<textarea ng-model="htmlContent" ng-trim="false"></textarea>
<button ng-click="postMessage()">Send</button>
</div>
</form>
</body>
</html>
You need to use the change directory command 'cd' to change directory
cd C:\Users\MyName\Desktop
you can use cd \d
to change the drive as well.
link for additional resources http://ss64.com/nt/cd.html
I've encapsulated tags manipulation in an experimental plugin of mine.
Regarding C++ development in vim, I've already answered there: I use my own suite, and a few other plugins.
In my case root cause of this issue was multiple http bindings defined at parent web site i.e. InetMgr->Sites->Mysite->properties->EditBindings. I deleted one http binding which was not required and problem got resolved.
If you're using the git GUI (on Windows) under the Repository menu you can use "Visualize master's History". Highlight a commit in the top pane and a file in the lower right and you'll see the diff for that commit in the lower left.
SELECT *
FROM (
SELECT *
FROM users
WHERE 1
ORDER BY
rand()
LIMIT 20
) q
ORDER BY
name
Just for the record I would specify the following:
/^[xX]?[0-9a-fA-F]{6}$/
Which differs in that it checks that it has to contain the six valid characters and on lowercase or uppercase x in case we have one.
tr -d '\15\32' < winfile.txt > unixfile.txt
if (document.getElementById('remember').checked) {
alert("checked");
}
else {
alert("You didn't check it! Let me check it for you.");
}
One more way:
git diff stash@{N}^! -- path/to/file1 path/to/file2 | git apply -R
You can't return two (or multiple) columns in your subquery to do the comparison in the WHERE A_ID IN (subquery)
clause - which column is it supposed to compare A_ID
to? Your subquery must only return the one column needed for the comparison to the column on the other side of the IN
. So the query needs to be of the form:
SELECT * From ThisTable WHERE ThisColumn IN (SELECT ThatColumn FROM ThatTable)
You also want to add sorting so you can select just from the top rows, but you don't need to return the COUNT as a column in order to do your sort; sorting in the ORDER
clause is independent of the columns returned by the query.
Try something like this:
select count(distinct dNum)
from myDB.dbo.AQ
where A_ID in
(SELECT DISTINCT TOP (0.1) PERCENT A_ID
FROM myDB.dbo.AQ
WHERE M > 1 and B = 0
GROUP BY A_ID
ORDER BY COUNT(DISTINCT dNum) DESC)
This is an issue with Jackson. To prevent this, instruct Jackson not to serialize nested relationship or nested class.
Look at the following example. Address class mapped to City, State, and Country classes and the State itself is pointing to Country and Country pointing to Region. When your get address values through Spring boot REST API you will get the above error. To prevent it, just serialize mapped class ( which reflects level one JSON) and ignore nested relationships with @JsonIgnoreProperties(value = {"state"})
,@JsonIgnoreProperties(value = {"country"})
and
@JsonIgnoreProperties(value = {"region"})
This will prevent Lazyload exception along with the above error. Use the below code as an example and change your model classes.
Address.java
@Entity
public class Address extends AbstractAuditingEntity
{
private static final long serialVersionUID = 4203344613880544060L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "street_name")
private String streetName;
@Column(name = "apartment")
private String apartment;
@ManyToOne
@JoinColumn(name = "city_id")
@JsonIgnoreProperties(value = {"state"})
private City city;
@ManyToOne
@JoinColumn(name = "state_id")
@JsonIgnoreProperties(value = {"country"})
private State state;
@ManyToOne
@JoinColumn(name = "country_id")
@JsonIgnoreProperties(value = {"region"})
private Country country;
@ManyToOne
@JoinColumn(name = "region_id")
private Region region;
@Column(name = "zip_code")
private String zipCode;
@ManyToOne
@JoinColumn(name = "address_type_id", referencedColumnName = "id")
private AddressType addressType;
}
City.java
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "city")
@Cache(region = "cityCache",usage = CacheConcurrencyStrategy.READ_WRITE)
@Data
public class City extends AbstractAuditingEntity
{
private static final long serialVersionUID = -8825045541258851493L;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
//@Length(max = 100,min = 2)
private String name;
@ManyToOne
@JoinColumn(name = "state_id")
private State state;
}
State.java
@Entity
@Table(name = "state")
@Data
@EqualsAndHashCode(callSuper = true)
public class State extends AbstractAuditingEntity
{
private static final long serialVersionUID = 5553856435782266275L;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "code")
private String code;
@Column(name = "name")
@Length(max = 200, min = 2)
private String name;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "country_id")
private Country country;
}
Country.java
@Entity
@Table(name = "country")
@Data
@EqualsAndHashCode(callSuper = true)
public class Country extends AbstractAuditingEntity
{
private static final long serialVersionUID = 6396100319470393108L;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
@Length(max = 200, min = 2)
private String name;
@Column(name = "code")
@Length(max = 3, min = 2)
private String code;
@Column(name = "iso_code")
@Length(max = 3, min = 2)
private String isoCode;
@ManyToOne
@JoinColumn(name = "region_id")
private Region region;
}
When I printed response.read()
I noticed that b
was preprended to the string (e.g. b'{"a":1,..
). The "b" stands for bytes and serves as a declaration for the type of the object you're handling. Since, I knew that a string could be converted to a dict by using json.loads('string')
, I just had to convert the byte type to a string type. I did this by decoding the response to utf-8 decode('utf-8')
. Once it was in a string type my problem was solved and I was easily able to iterate over the dict
.
I don't know if this is the fastest or most 'pythonic' way of writing this but it works and theres always time later of optimization and improvement! Full code for my solution:
from urllib.request import urlopen
import json
# Get the dataset
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)
# Convert bytes to string type and string type to dict
string = response.read().decode('utf-8')
json_obj = json.loads(string)
print(json_obj['source_name']) # prints the string with 'source_name' key
I start the app with F11 and get a breakpoint somewhere in unit_test_main.ipp (can be assembly code). I use shift-f11 (Step out) to run the unit test and get the next assembly instruction in the CRT (normally in mainCRTStartup()). I use F9 to set a breakpoint at that instruction.
On the next invocation, I can start the app with F5 and the app will break after running the tests, therefore giving me a chance to peek at the console window
You can access a string using []
, as you do for arrays:
$stringLength = strlen($str);
for ($i = 0; $i < $stringLength; $i++)
$char = $str[$i];
$type_array = array();
while($row = mysql_fetch_assoc($result)) {
$type_array[] = $row['type'];
}
String String_firstNumber = JOptionPane.showInputDialog("Input Semisecond");
int Int_firstNumber = Integer.parseInt(firstNumber);
Now your Int_firstnumber
contains integer value of String_fristNumber
.
hope it helped
Under Windows 7, open the Event Viewer. You can do this the way Gishu suggested for XP, typing eventvwr
from the command line, or by opening the Control Panel, selecting System and Security, then Administrative Tools and finally Event Viewer. It may require UAC approval or an admin password.
In the left pane, expand Windows Logs and then System. You can filter the logs with Filter Current Log... from the Actions pane on the right and selecting "Service Control Manager." Or, depending on why you want this information, you might just need to look through the Error entries.
The actual log entry pane (not shown) is pretty user-friendly and self-explanatory. You'll be looking for messages like the following:
"The Praxco Assistant service entered the stopped state."
"The Windows Image Acquisition (WIA) service entered the running state."
"The MySQL service terminated unexpectedly. It has done this 3 time(s)."
Android wifi ADB was earlier working on my IDE but after Updating Android Studio (my current is Android Studio 3.3) it is not working and always prompt as "Unable to connect to device......Same network"
After spending much time i was unbale to resolve the issue.
Then i tried - WIFI ADB ULTIMATE by
https://github.com/huazhouwang/WIFIADB/tree/master/WIFIADBIntelliJPlugin
It worked for me.
As it happens I was just reading about this this morning on my way to work in Java Concurrency In Practice by Brian Goetz. Basically he says you should do one of three things
Propagate the InterruptedException
- Declare your method to throw the checked InterruptedException
so that your caller has to deal with it.
Restore the Interrupt - Sometimes you cannot throw InterruptedException
. In these cases you should catch the InterruptedException
and restore the interrupt status by calling the interrupt()
method on the currentThread
so the code higher up the call stack can see that an interrupt was issued, and quickly return from the method. Note: this is only applicable when your method has "try" or "best effort" semantics, i. e. nothing critical would happen if the method doesn't accomplish its goal. For example, log()
or sendMetric()
may be such method, or boolean tryTransferMoney()
, but not void transferMoney()
. See here for more details.
Uninterruptibles
. Uninterruptibles
take over the boilerplate code like in the Noncancelable Task example in JCIP § 7.1.3.The project npm-install-peers
will detect peers and install them.
As of v1.0.1
it doesn't support writing back to the package.json
automatically, which would essentially solve our need here.
Please add your support to issue in flight: https://github.com/spatie/npm-install-peers/issues/4
Function can be further improved to render images as well:
function renderHTML(text) {
var rawText = strip(text)
var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return rawText.replace(urlRegex, function(url) {
if ( ( url.indexOf(".jpg") > 0 ) || ( url.indexOf(".png") > 0 ) || ( url.indexOf(".gif") > 0 ) ) {
return '<img src="' + url + '">' + '<br/>'
} else {
return '<a href="' + url + '">' + url + '</a>' + '<br/>'
}
})
}
or for a thumbnail image that links to fiull size image:
return '<a href="' + url + '"><img style="width: 100px; border: 0px; -moz-border-radius: 5px; border-radius: 5px;" src="' + url + '">' + '</a>' + '<br/>'
And here is the strip() function that pre-processes the text string for uniformity by removing any existing html.
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return tmp.innerText.replace(urlRegex, function(url) {
return '\n' + url
})
}
When git push [$there]
does not say what to push, we have used the
traditional "matching" semantics so far (all your branches were sent
to the remote as long as there already are branches of the same name
over there). In Git 2.0, the default is now the "simple" semantics,
which pushes:
only the current branch to the branch with the same name, and only when the current branch is set to integrate with that remote branch, if you are pushing to the same remote as you fetch from; or
only the current branch to the branch with the same name, if you are pushing to a remote that is not where you usually fetch from.
You can use the configuration variable "push.default" to change this. If you are an old-timer who wants to keep using the "matching" semantics, you can set the variable to "matching", for example. Read the documentation for other possibilities.
When git add -u
and git add -A
are run inside a subdirectory
without specifying which paths to add on the command line, they
operate on the entire tree for consistency with git commit -a
and
other commands (these commands used to operate only on the current
subdirectory). Say git add -u .
or git add -A .
if you want to
limit the operation to the current directory.
git add <path>
is the same as git add -A <path>
now, so that
git add dir/
will notice paths you removed from the directory and
record the removal. In older versions of Git, git add <path>
used
to ignore removals. You can say git add --ignore-removal <path>
to
add only added or modified paths in <path>
, if you really want to.
You might read up on FILESTREAM. Here is some info from the docs that should help you decide:
If the following conditions are true, you should consider using FILESTREAM:
- Objects that are being stored are, on average, larger than 1 MB.
- Fast read access is important.
- You are developing applications that use a middle tier for application logic.
For smaller objects, storing varbinary(max) BLOBs in the database often provides better streaming performance.
As c-smile mentioned: Just need to remove the apostrophes in the url()
:
<div style="background-image: url(http://i54.tinypic.com/4zuxif.jpg)"></div>
Try the following:
for i in {1..600}; do echo wget http://example.com/search/link$(($i % 5)); done
The $(( ))
syntax does an arithmetic evaluation of the contents.
Use this one:
function onKeyPress(evt){
evt = (evt) ? evt : (window.event) ? event : null;
if (evt)
{
var charCode = (evt.charCode) ? evt.charCode :((evt.keyCode) ? evt.keyCode :((evt.which) ? evt.which : 0));
if (charCode == 13)
alert('User pressed Enter');
}
}
Here is a robust function for using UTL_File.putline that includes the necessary error handling. It also handles headers, footers and a few other exceptional cases.
PROCEDURE usp_OUTPUT_ToFileAscii(p_Path IN VARCHAR2, p_FileName IN VARCHAR2, p_Input IN refCursor, p_Header in VARCHAR2, p_Footer IN VARCHAR2, p_WriteMode VARCHAR2) IS
vLine VARCHAR2(30000);
vFile UTL_FILE.file_type;
vExists boolean;
vLength number;
vBlockSize number;
BEGIN
UTL_FILE.fgetattr(p_path, p_FileName, vExists, vLength, vBlockSize);
FETCH p_Input INTO vLine;
IF p_input%ROWCOUNT > 0
THEN
IF vExists THEN
vFile := UTL_FILE.FOPEN_NCHAR(p_Path, p_FileName, p_WriteMode);
ELSE
--even if the append flag is passed if the file doesn't exist open it with W.
vFile := UTL_FILE.FOPEN(p_Path, p_FileName, 'W');
END IF;
--GET HANDLE TO FILE
IF p_Header IS NOT NULL THEN
UTL_FILE.PUT_LINE(vFile, p_Header);
END IF;
UTL_FILE.PUT_LINE(vFile, vLine);
DBMS_OUTPUT.PUT_LINE('Record count > 0');
--LOOP THROUGH CURSOR VAR
LOOP
FETCH p_Input INTO vLine;
EXIT WHEN p_Input%NOTFOUND;
UTL_FILE.PUT_LINE(vFile, vLine);
END LOOP;
IF p_Footer IS NOT NULL THEN
UTL_FILE.PUT_LINE(vFile, p_Footer);
END IF;
CLOSE p_Input;
UTL_FILE.FCLOSE(vFile);
ELSE
DBMS_OUTPUT.PUT_LINE('Record count = 0');
END IF;
EXCEPTION
WHEN UTL_FILE.INVALID_PATH THEN
DBMS_OUTPUT.PUT_LINE ('invalid_path');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_MODE THEN
DBMS_OUTPUT.PUT_LINE ('invalid_mode');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_FILEHANDLE THEN
DBMS_OUTPUT.PUT_LINE ('invalid_filehandle');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_OPERATION THEN
DBMS_OUTPUT.PUT_LINE ('invalid_operation');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.READ_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('read_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.WRITE_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('write_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INTERNAL_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('internal_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE ('other write error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
END;
This would be a pure JS version (adapted from cowboy's):
var obj = {a: 123, b: "4 5 6"};
var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));
var a = document.createElement('a');
a.href = 'data:' + data;
a.download = 'data.json';
a.innerHTML = 'download JSON';
var container = document.getElementById('container');
container.appendChild(a);
For those looking for a dplyr/tidyverse version. Building on Gavin Simpson solution:
# Create DF
set.seed(123)
x <- rnorm(100)
DF <- data.frame(x = x,
y = 4 + (1.5*x) + rnorm(100, sd = 2),
b = gl(5, 20))
# Change reference level
DF = DF %>% mutate(b = relevel(b, 3))
m2 <- lm(y ~ x + b, data = DF)
summary(m2)
Pedantic makes it so that the gcc compiler rejects all GNU C extensions not just the ones that make it ANSI compatible.
Checking out more than one repo at a time in a single workspace is not possible with Jenkins + Git Plugin.
As a workaround, you can either have multiple upstream jobs which checkout a single repo each and then copy to your final project workspace (Problematic on a number of levels), or you can set up a shell scripting step which checks out each needed repo to the job workspace at build time.
Previously the Multiple SCM plugin could help with this issue but it is now deprecated. From the Multiple SCM plugin page: "Users should migrate to https://wiki.jenkins-ci.org/display/JENKINS/Pipeline+Plugin . Pipeline offers a better way of checking out of multiple SCMs, and is supported by the Jenkins core development team."
Try this from the box you are pushing from
ssh [email protected]
You should then get a welcome response from github and will be fine to then push.
Not in PHP.
phpinfo(32)
contains everything PHP able to know about particular client, and there is no [windows] computer name
I had similar issue, but in the end I found out that ~/.bashrc was all I needed.
However, in Ubuntu, I had to comment the line that stops processing ~/.bashrc :
#If not running interactively, don't do anything
[ -z "$PS1" ] && return
This should do it:
for (var i = 0; i < bank_holidays.length; i++) {
if (bank_holidays[i] === '06/04/2012') {
alert('LOL');
}
}
Use application/javascript
as content type instead of text/javascript
text/javascript
is mentioned obsolete. See reference docs.
http://www.iana.org/assignments/media-types/application
Also see this question on SO.
UPDATE:
I have tried executing the code you have given and the below didn't work.
res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);
This is what worked for me.
res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);
As robertklep has suggested, please refer to the node http docs, there is no response.send()
there.
SQL Server doesn't have regular expressions. It uses the LIKE pattern matching syntax which isn't the same.
As it happens, you are close. Just need leading+trailing wildcards and move the NOT
WHERE whatever NOT LIKE '%[a-z0-9]%'
var currencyInput = document.querySelector('input[type="currency"]')
var currency = 'GBP' // https://www.currency-iso.org/dam/downloads/lists/list_one.xml
// format inital value
onBlur({target:currencyInput})
// bind event listeners
currencyInput.addEventListener('focus', onFocus)
currencyInput.addEventListener('blur', onBlur)
function localStringToNumber( s ){
return Number(String(s).replace(/[^0-9.-]+/g,""))
}
function onFocus(e){
var value = e.target.value;
e.target.value = value ? localStringToNumber(value) : ''
}
function onBlur(e){
var value = e.target.value
var options = {
maximumFractionDigits : 2,
currency : currency,
style : "currency",
currencyDisplay : "symbol"
}
e.target.value = (value || value === 0)
? localStringToNumber(value).toLocaleString(undefined, options)
: ''
}
_x000D_
input{
padding: 10px;
font: 20px Arial;
width: 70%;
}
_x000D_
<input type='currency' value="123" placeholder='Type a number & click outside' />
_x000D_
Here's a very simple demo illustrating the above method (HTML-only)
I've made a tiny React component if anyone's interested
I found that biggest speed gain with Laravel 4 you can achieve choosing right session drivers;
Sessions "driver" file;
Requests per second: 188.07 [#/sec] (mean)
Time per request: 26.586 [ms] (mean)
Time per request: 5.317 [ms] (mean, across all concurrent requests)
Session "driver" database;
Requests per second: 41.12 [#/sec] (mean)
Time per request: 121.604 [ms] (mean)
Time per request: 24.321 [ms] (mean, across all concurrent requests)
Hope that helps
If you use docker in your dev you can do this in another shell: docker attach running_node_app_container_name
That will show you STDOUT and STDERR.
with $.getJSON()) there is no any error callback only you can track succeed callback and there no standard setting supported like beforeSend, statusCode, mimeType etc, if you want it use $.ajax().
can you have the forms side by side on the page, but not nested. then use CSS to make all the buttons line up pretty?
<form method="post" action="delete_processing_page">
<input type="hidden" name="id" value="foo" />
<input type="submit" value="delete" class="css_makes_me_pretty" />
</form>
<form method="post" action="add_edit_processing_page">
<input type="text" name="foo1" />
<input type="text" name="foo2" />
<input type="text" name="foo3" />
...
<input type="submit" value="post/edit" class="css_makes_me_pretty" />
</form>
try this
var radio_button=false;_x000D_
$('.radio-button').on("click", function(event){_x000D_
var this_input=$(this);_x000D_
if(this_input.attr('checked1')=='11') {_x000D_
this_input.attr('checked1','11')_x000D_
} else {_x000D_
this_input.attr('checked1','22')_x000D_
}_x000D_
$('.radio-button').prop('checked', false);_x000D_
if(this_input.attr('checked1')=='11') {_x000D_
this_input.prop('checked', false);_x000D_
this_input.attr('checked1','22')_x000D_
} else {_x000D_
this_input.prop('checked', true);_x000D_
this_input.attr('checked1','11')_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
You can download SEVER JRE it contains jdk. server jre 7
tar xzvf file.tar.gz
any other tar extractor will also workNow extracted JDK folder will be created in same folder.
I had a similar issue with the iteration and I landed here. Maybe someone else is also doing the same mistake I did.
In my case, the selector was not the problem at all. The problem was that I had messed up the javascript code:
I had a loop and a subloop. The subloop was also using i
as a counter, instead of j
, so because the subloop was overriding the value of i
of the main loop, this one never got to the second iteration.
var dayContainers = document.getElementsByClassName('day-container');
for(var i = 0; i < dayContainers.length; i++) { //loop of length = 2
var thisDayDiv = dayContainers[i];
// do whatever
var inputs = thisDayDiv.getElementsByTagName('input');
for(var j = 0; j < inputs.length; j++) { //loop of length = 4
var thisInput = inputs[j];
// do whatever
};
};
If lists always have the same structure, as in the example, then a simpler solution is
mapply(c, first, second, SIMPLIFY=FALSE)
As others have said you can do this but you should define the map with generics like so:
Map<String, Map<String, String>> map = new HashMap<String, Map<String,String>>();
However, if you just blindly run the following:
map.get("keyname").get("nestedkeyname");
you will get a null pointer exception whenever keyname is not in the map and your program will crash. You really should add the following check:
String valueFromMap = null;
if(map.containsKey("keyname")){
valueFromMap = map.get("keyname").get("nestedkeyname");
}
For web application, i normally will write this method and just call it with the key.
private String GetConfigValue(String key)
{
return System.Web.Configuration.WebConfigurationManager.AppSettings[key].ToString();
}
iOS doens't update screen.width
& screen.height
when orientation changes. Android doens't update window.orientation
when it changes.
My solution to this problem:
var isAndroid = /(android)/i.test(navigator.userAgent);
if(isAndroid)
{
if(screen.width < screen.height){
//portrait mode on Android
}
} else {
if(window.orientation == 0){
//portrait mode iOS and other devices
}
}
You can detect this change in orientation on Android as well as iOS with the following code:
var supportsOrientationChange = "onorientationchange" in window,
orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";
window.addEventListener(orientationEvent, function() {
alert("the orientation has changed");
}, false);
If the onorientationchange
event is not supported, the event bound will be the resize
event.
For loops are a bad construct for this.
while
var numbers = new List<int>(Enumerable.Range(1, 3));
while (numbers.Count > 0)
{
numbers.RemoveAt(0);
}
But, if you absolutely must use for
var numbers = new List<int>(Enumerable.Range(1, 3));
for (; numbers.Count > 0;)
{
numbers.RemoveAt(0);
}
Or, this:
public static class Extensions
{
public static IList<T> Remove<T>(
this IList<T> numbers,
Func<T, bool> predicate)
{
numbers.ForEachBackwards(predicate, (n, index) => numbers.RemoveAt(index));
return numbers;
}
public static void ForEachBackwards<T>(
this IList<T> numbers,
Func<T, bool> predicate,
Action<T, int> action)
{
for (var i = numbers.Count - 1; i >= 0; i--)
{
if (predicate(numbers[i]))
{
action(numbers[i], i);
}
}
}
}
Usage:
var numbers = new List<int>(Enumerable.Range(1, 10)).Remove((n) => n > 5);
If you hadn't made any commit yet, only (1: branch) and (3: checkout) would be enough.
Or, in one command: git checkout -b newBranch
As mentioned in the git reset
man page:
$ git branch topic/wip # (1)
$ git reset --hard HEAD~3 # (2) NOTE: use $git reset --soft HEAD~3 (explanation below)
$ git checkout topic/wip # (3)
master
" branch. You want to continue polishing them in a topic branch, so create "topic/wip
" branch off of the current HEAD
.master
branch to get rid of those three commits.topic/wip
" branch and keep working.Note: due to the "destructive" effect of a git reset --hard
command (it does resets the index and working tree. Any changes to tracked files in the working tree since <commit>
are discarded), I would rather go with:
$ git reset --soft HEAD~3 # (2)
This would make sure I'm not losing any private file (not added to the index).
The --soft
option won't touch the index file nor the working tree at all (but resets the head to <commit>
, just like all modes do).
With Git 2.23+, the new command git switch
would create the branch in one line (with the same kind of reset --hard
, so beware of its effect):
git switch -f -c topic/wip HEAD~3
Unfortunately the xkcd comic isn't completely up to date anymore.
Since Python 3.0 you have to write:
print("Hello world!")
And someone still has to write that antigravity
library :(
userInfos.GroupBy(userInfo => userInfo.metric)
.OrderBy(group => group.Key)
.Select(group => Tuple.Create(group.Key, group.Count()));
Sometimes you want to run a function via CLI, sometimes you want to require
it from another module. Here's how to do both.
// file to run
const runMe = () => {}
if (require.main === module) {
runMe()
}
module.exports = runMe
Remove static
keyword in method definition. Keep it just in your class definition.
static
keyword placed in .cpp file means that a certain function has a static linkage, ie. it is accessible only from other functions in the same file.
var EmployeeController = ["$scope", "EmployeeService",
function ($scope, EmployeeService) {
$scope.Employee = {};
$scope.Save = function (Employee) {
if ($scope.EmployeeForm.$valid) {
EmployeeService
.Save(Employee)
.then(function (response) {
if (response.HasError) {
$scope.HasError = response.HasError;
$scope.ErrorMessage = response.ResponseMessage;
} else {
}
})
.catch(function (response) {
});
}
}
}]
var EmployeeService = ["$http", "$q",
function ($http, $q) {
var self = this;
self.Save = function (employee) {
var deferred = $q.defer();
$http
.post("/api/EmployeeApi/Create", angular.toJson(employee))
.success(function (response, status, headers, config) {
deferred.resolve(response, status, headers, config);
})
.error(function (response, status, headers, config) {
deferred.reject(response, status, headers, config);
});
return deferred.promise;
};
You can run 2 processes in foreground by using wait
. Just make a bash script with the following content. Eg start.sh
:
# runs 2 commands simultaneously:
mongod & # your first application
P1=$!
python script.py & # your second application
P2=$!
wait $P1 $P2
In your Dockerfile, start it with
CMD bash start.sh
if you need to decompile standalone jar try JD-GUI by the same autor (of JD-Eclipse). It is a standalone application (does not need eclipse). It can open both *.class and *.jar files. Interesting enough it needs .Net installed (as do JD-Eclipse indeed), but otherwise works like a charm.
Find it here:
Regards,
You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .
public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
JSONObject value = json.getJSONObject(key);
parse(value,out);
}catch(Exception e){
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
public static void main(String[] args) throws JSONException {
String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";
JSONObject object = new JSONObject(json);
JSONObject info = object.getJSONObject("ipinfo");
Map<String,String> out = new HashMap<String, String>();
parse(info,out);
String latitude = out.get("latitude");
String longitude = out.get("longitude");
String city = out.get("city");
String state = out.get("state");
String country = out.get("country");
String postal = out.get("postal_code");
System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);
System.out.println("ALL VALUE " + out);
}
Output:
Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}
we have 3 choices to get the first row in Oracle DB table.
1) select * from table_name where rownum= 1
is the best way
2) select * from table_name where id = ( select min(id) from table_name)
3)
select * from
(select * from table_name order by id)
where rownum = 1
Good questions I have been asked are
It would be interesting to see what a candidate would come up with and you'll certainly learn quite a bit about how he/she uses the framework.
urllib
has been split up in Python 3
.
The urllib.urlencode()
function is now urllib.parse.urlencode()
,
the urllib.urlopen()
function is now urllib.request.urlopen()
.
You could convert the dataframe to be a single column with stack
(this changes the shape from 5x3 to 15x1) and then take the standard deviation:
df.stack().std() # pandas default degrees of freedom is one
Alternatively, you can use values
to convert from a pandas dataframe to a numpy array before taking the standard deviation:
df.values.std(ddof=1) # numpy default degrees of freedom is zero
Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.
A couple of additional notes:
The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).
The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.
Perhaps involve the activity's life-cycle methods to achieve this:
Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler.post(sendData);
}
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(sendData);
}
private final Runnable sendData = new Runnable(){
public void run(){
try {
//prepare and send the data here..
handler.postDelayed(this, 1000);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
In this approach, if you press back-key on your activity or call finish();
, it will also stop the postDelayed callings.
You can get with node.getScene
, if you don't call from Platform.runLater
, the result is a null value.
example null value:
node.getScene();
example no null value:
Platform.runLater(() -> {
node.getScene().addEventFilter(KeyEvent.KEY_PRESSED, event -> {
//your event
});
});
Here are three ways to parse strings into integers, from fastest runtime to slowest:
strconv.ParseInt(...)
fasteststrconv.Atoi(...)
still very fastfmt.Sscanf(...)
not terribly fast but most flexibleHere's a benchmark that shows usage and example timing for each function:
package main
import "fmt"
import "strconv"
import "testing"
var num = 123456
var numstr = "123456"
func BenchmarkStrconvParseInt(b *testing.B) {
num64 := int64(num)
for i := 0; i < b.N; i++ {
x, err := strconv.ParseInt(numstr, 10, 64)
if x != num64 || err != nil {
b.Error(err)
}
}
}
func BenchmarkAtoi(b *testing.B) {
for i := 0; i < b.N; i++ {
x, err := strconv.Atoi(numstr)
if x != num || err != nil {
b.Error(err)
}
}
}
func BenchmarkFmtSscan(b *testing.B) {
for i := 0; i < b.N; i++ {
var x int
n, err := fmt.Sscanf(numstr, "%d", &x)
if n != 1 || x != num || err != nil {
b.Error(err)
}
}
}
You can run it by saving as atoi_test.go
and running go test -bench=. atoi_test.go
.
goos: darwin
goarch: amd64
BenchmarkStrconvParseInt-8 100000000 17.1 ns/op
BenchmarkAtoi-8 100000000 19.4 ns/op
BenchmarkFmtSscan-8 2000000 693 ns/op
PASS
ok command-line-arguments 5.797s
window.onbeforeunload = function ()
{
if (isProcess > 0)
{
return true;
}
else
{
//do something
}
};
This function show a confirmation dialog box if you close window or refresh page during any process in browser.This function work in all browsers.You have to set isProcess var in your ajax process.
you are getting math domain error for either one of the reason : either you are trying to use a negative number inside log function or a zero value.
The default IsSelected trigger changes 3 properties, Background, Foreground & BorderBrush. If you want to change the border as well as the background, just include this in your style trigger.
<Style TargetType="{x:Type dg:DataGridCell}">
<Style.Triggers>
<Trigger Property="dg:DataGridCell.IsSelected" Value="True">
<Setter Property="Background" Value="#CCDAFF" />
<Setter Property="BorderBrush" Value="Black" />
</Trigger>
</Style.Triggers>
</Style>
Based on answer by @Cici I give here a more generic solution:
=SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))
In Italian version of Excel:
=SOMMA(INDIRETTO(CONCATENA(B1;C1)):INDIRETTO(CONCATENA(B2;C2)))
Where B1-C2 cells hold these values:
You can change these valuese to change the final range at wish.
Splitting the formula in parts:
Hence:
=SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))
results in
=SUM(A1:A5)
I'll write down here a couple of SEO keywords for Italian users:
Con la formula indicata qui sopra basta scrivere nelle caselle da B1 a C2 gli estremi dell'intervallo per vedelo cambiare dentro la formula stessa.
Okay here is a quick lesson about CSS Importance. I hope that the below helps!
First of all the every part of the styles name as a weighting, so the more elements you have that relate to that style the more important it is. For example
#P1 .Page {height:100px;}
is more important than:
.Page {height:100px;}
So when using important, ideally this should only ever be used, when really really needed. So to overide the decleration, make the style more specific, but also with an override. See below:
td {width:100px !important;}
table tr td .override {width:150px !important;}
I hope this helps!!!
This is solution for AWS JavaScript SDK users, it is almost same for other languages.
Result.data.Count will give you what you are looking for
apigClient.getitemPost({}, body, {})
.then(function(result){
var dataoutput = result.data.Items[0];
console.log(result.data.Count);
}).catch( function(result){
});
If you would need to disable E_DEPRACATED also, use:
php_value error_reporting 22527
In my case CMS Made Simple was complaining "E_STRICT is enabled in the error_reporting" as well as "E_DEPRECATED is enabled". Adding that one line to .htaccess solved both misconfigurations.
Use the new clipboard API, via navigator.clipboard
. It can be used like this:
navigator.clipboard.readText()
.then(text => {
console.log('Pasted content: ', text);
})
.catch(err => {
console.error('Failed to read clipboard contents: ', err);
});
Or with async syntax:
const text = await navigator.clipboard.readText();
Keep in mind that this will prompt the user with a permission request dialog box, so no funny business possible.
The above code will not work if called from the console. It only works when you run the code in an active tab. To run the code from your console you can set a timeout and click in the website window quickly:
setTimeout(async () => {
const text = await navigator.clipboard.readText();
console.log(text);
}, 2000);
Read more on the API and usage in the Google developer docs.
Some Linux based MySQL installations require case sensitive. Work around is to apply nativeQuery
.
@Query(value = 'select ID, CLUMN2, CLUMN3 FROM VENDOR c where c.ID = :ID', nativeQuery = true)
Your HTML code:
<div>Stack Overflow is the BEST !!!</div>
CSS:
div {
width: 100px;
white-space:nowrap;
overflow:hidden;
text-overflow:ellipsis;
}
Now the result should be:
Stack Overf...
In my case I fixed this issue by opening .iml file of project (it is located in project root folder and have name same as the name of project) and changing line <orderEntry type="jdk" jdkName="1.7" jdkType="JavaSDK" />
to <orderEntry type="jdk" jdkName="1.8" jdkType="JavaSDK" />
I had everything configured as in others answers here but by some reason Idea updated .iml file incorrectly.
Simple groovy way to check object type:
somObject in Date
Can be applied also to interfaces.
and if you don't have the option to go on java8 better use 'yyyy-MM-dd'T'HH:mm:ssXXX' as this gets correctly parsed again (while with only one X this may not be the case... depending on your parsing function)
X generates: +01
XXX generates: +01:00
From the documentation:
Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called
static
in your package or next to your module and it will be available at/static
on the application.To generate URLs for static files, use the special
'static'
endpoint name:url_for('static', filename='style.css')
The file has to be stored on the filesystem as
static/style.css
.
You have to do this to echo it:
echo $row['note'];
(The data is coming as an array)
For anyone struggling with this after trying the above solutions, ensure that the channel id used when creating the notification channel is identical to the channel id you set in the Notification builder.
const val CHANNEL_ID = "EXAMPLE_CHANNEL_ID"
// create notification channel
val notificationChannel = NotificationChannel(CHANNEL_ID,
NOTIFICATION_NAME, NotificationManager.IMPORTANCE_HIGH)
// building notification
NotificationCompat.Builder(context)
.setSmallIcon(android.R.drawable.ic_input_add)
.setContentTitle("Title")
.setContentText("Subtitle")
.setPriority(NotificationCompat.PRIORITY_MAX)
.setChannelId(CHANNEL_ID)
CSS height: 100% only works if the element's parent has an explicitly defined height. For example, this would work as expected:
td {
height: 200px;
}
td div {
/* div will now take up full 200px of parent's height */
height: 100%;
}
Since it seems like your <td>
is going to be variable height, what if you added the bottom right icon with an absolutely positioned image like so:
.thatSetsABackgroundWithAnIcon {
/* Makes the <div> a coordinate map for the icon */
position: relative;
/* Takes the full height of its parent <td>. For this to work, the <td>
must have an explicit height set. */
height: 100%;
}
.thatSetsABackgroundWithAnIcon .theIcon {
position: absolute;
bottom: 0;
right: 0;
}
With the table cell markup like so:
<td class="thatSetsABackground">
<div class="thatSetsABackgroundWithAnIcon">
<dl>
<dt>yada
</dt>
<dd>yada
</dd>
</dl>
<img class="theIcon" src="foo-icon.png" alt="foo!"/>
</div>
</td>
Edit: using jQuery to set div's height
If you keep the <div>
as a child of the <td>
, this snippet of jQuery will properly set its height:
// Loop through all the div.thatSetsABackgroundWithAnIcon on your page
$('div.thatSetsABackgroundWithAnIcon').each(function(){
var $div = $(this);
// Set the div's height to its parent td's height
$div.height($div.closest('td').height());
});
You can use input text with "list" attribute, which refers to the datalist of values.
<input type="text" name="city" list="cityname">_x000D_
<datalist id="cityname">_x000D_
<option value="Boston">_x000D_
<option value="Cambridge">_x000D_
</datalist>
_x000D_
This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist
I'm going to use the streams api to convert a stream of integers into a single string. The problem with some of the provided answers is that they produce a O(n^2) runtime because of String building. A better solution is to use a StringBuilder, and then join the strings together as the final step.
// Create a stream of integers
String result = Arrays.stream(new int[]{1,2,3,4,5,6 })
// collect into a single StringBuilder
.collect(StringBuilder::new, // supplier function
// accumulator - converts cur integer into a string and appends it to the string builder
(builder, cur) -> builder.append(Integer.toString(cur)),
// combiner - combines two string builders if running in parallel
StringBuilder::append)
// convert StringBuilder into a single string
.toString();
You can take this process a step further by converting the collection of object to a single string.
// Start with a class definition
public static class AClass {
private int value;
public int getValue() { return value; }
public AClass(int value) { this.value = value; }
@Override
public String toString() {
return Integer.toString(value);
}
}
// Create a stream of AClass objects
String resultTwo = Arrays.stream(new AClass[]{
new AClass(1),
new AClass(2),
new AClass(3),
new AClass(4)
})
// transform stream of objects into a single string
.collect(StringBuilder::new,
(builder, curObj) -> builder.append(curObj.toString()),
StringBuilder::append
)
// finally transform string builder into a single string
.toString();
@Eddie has given a perfect answer of the question asked. But I would like to draw attention to using an more efficient approach of Pub/Sub.
As this answer suggests,
The $broadcast/$on approach is not terribly efficient as it broadcasts to all the scopes(Either in one direction or both direction of Scope hierarchy). While the Pub/Sub approach is much more direct. Only subscribers get the events, so it isn't going to every scope in the system to make it work.
you can use angular-PubSub
angular module. once you add PubSub
module to your app dependency, you can use PubSub
service to subscribe and unsubscribe events/topics.
Easy to subscribe:
// Subscribe to event
var sub = PubSub.subscribe('event-name', function(topic, data){
});
Easy to publish
PubSub.publish('event-name', {
prop1: value1,
prop2: value2
});
To unsubscribe, use PubSub.unsubscribe(sub);
OR PubSub.unsubscribe('event-name');
.
NOTE Don't forget to unsubscribe to avoid memory leaks.
For c++ use std::array<int/*type*/, 10/*size*/>
instead of c-style array. This is available with c++11 standard, and which is a good practice. See it here for standard and examples. If you want to stick to old c-style arrays for reasons, there two possible ways:
int *a = new int[5]();
Here leave the parenthesis empty, otherwise it will give compile error. This will initialize all the elements in the allocated array. Here if you don't use the parenthesis, it will still initialize the integer values with zeros because new will call the constructor, which is in this case int()
.int *a = new int[5] {0, 0, 0};
This is allowed in c++11 standard. Here you can initialize array elements with any value you want. Here make sure your initializer list(values in {}) size should not be greater than your array size. Initializer list size less than array size is fine. Remaining values in array will be initialized with 0.You can show changes that have been staged with the --cached
flag:
$ git diff --cached
In more recent versions of git, you can also use the --staged
flag (--staged
is a synonym for --cached
):
$ git diff --staged
If you want to use global variable i of file1.c in file2.c, then below are the points to remember:
EDIT
I think the reason that your table is not responsive to start with was you did not wrap in .container
, .row
and .col-md-x
classes like this one
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- or use any other number .col-md- -->
<div class="table-responsive">
<div class="table">
</div>
</div>
</div>
</div>
</div>
With this, you can still use <p>
tags and even make it responsive.
Please see the Bootply example here
You could also add the external jar file to the project. Go to your project-->properties-->java build path-->libraries, add external JARS. Then add your downloaded jar file.
The easiest way to find the best fit in R is to code the model as:
lm.1 <- lm(y ~ x + I(x^2) + I(x^3) + I(x^4) + ...)
After using step down AIC regression
lm.s <- step(lm.1)
I had both my 'polyfill import' and my 'async function' in the same file, however I was using the function syntax that hoists it above the polyfill which would give me the ReferenceError: regeneratorRuntime is not defined
error.
import "babel-polyfill"
async function myFunc(){ }
import "babel-polyfill"
var myFunc = async function(){}
to prevent it being hoisted above the polyfill import.
I have a little module which does this well and is used by quite a few other projects npm readline Note thay in node v10 there is a native readline module so I republished my module as linebyline https://www.npmjs.com/package/linebyline
if you dont want to use the module the function is very simple:
var fs = require('fs'),
EventEmitter = require('events').EventEmitter,
util = require('util'),
newlines = [
13, // \r
10 // \n
];
var readLine = module.exports = function(file, opts) {
if (!(this instanceof readLine)) return new readLine(file);
EventEmitter.call(this);
opts = opts || {};
var self = this,
line = [],
lineCount = 0,
emit = function(line, count) {
self.emit('line', new Buffer(line).toString(), count);
};
this.input = fs.createReadStream(file);
this.input.on('open', function(fd) {
self.emit('open', fd);
})
.on('data', function(data) {
for (var i = 0; i < data.length; i++) {
if (0 <= newlines.indexOf(data[i])) { // Newline char was found.
lineCount++;
if (line.length) emit(line, lineCount);
line = []; // Empty buffer.
} else {
line.push(data[i]); // Buffer new line data.
}
}
}).on('error', function(err) {
self.emit('error', err);
}).on('end', function() {
// Emit last line if anything left over since EOF won't trigger it.
if (line.length){
lineCount++;
emit(line, lineCount);
}
self.emit('end');
}).on('close', function() {
self.emit('close');
});
};
util.inherits(readLine, EventEmitter);
This statement will definitely help you:
env = env.OrderByDescending(c => c.ReportDate).ToList();
You could add the user to the Database Level Role db_datareader.
Members of the db_datareader fixed database role can run a SELECT statement against any table or view in the database.
See Books Online for reference:
http://msdn.microsoft.com/en-us/library/ms189121%28SQL.90%29.aspx
You can add a database user to a database role using the following query:
EXEC sp_addrolemember N'db_datareader', N'userName'