I had a slighlty different scenario. My checkboxes were created in dynamic and they were not of same group. But atleast any one of them had to be checked. My approach (never say this is perfect), I created a genric validator for all of them:
jQuery.validator.addMethod("validatorName", function(value, element) {
if (($('input:checkbox[name=chkBox1]:checked').val() == "Val1") ||
($('input:checkbox[name=chkBox2]:checked').val() == "Val2") ||
($('input:checkbox[name=chkBox3]:checked').val() == "Val3"))
{
return true;
}
else
{
return false;
}
}, "Please Select any one value");
Now I had to associate each of the chkbox to this one single validator.
Again I had to trigger the validation when any of the checkboxes were clicked triggering the validator.
$('#piRequest input:checkbox[name=chkBox1]').click(function(e){
$("#myform").valid();
});
I would go for it.next()
for the simple reason that next()
is guaranteed to be implemented, while remove()
is an optional operation.
E next()
Returns the next element in the iteration.
void remove()
Removes from the underlying collection the last element returned by the iterator (optional operation).
Readonly will not "grayout" the textbox and will still submit the value on a postback.
This should do the trick...
'recalculate all open workbooks
Application.Calculate
'recalculate a specific worksheet
Worksheets(1).Calculate
' recalculate a specific range
Worksheets(1).Columns(1).Calculate
I suggest using JavaScript's Array method filter()
to identify an element by value. It filters data by using a "function to test each element of the array. Return true to keep the element, false otherwise.."
The following function filters the data, returning data for which the callback returns true
, i.e. where data.code
equals the requested country code.
function getCountryByCode(code) {
return data.filter(
function(data){ return data.code == code }
);
}
var found = getCountryByCode('DZ');
See the demonstration below:
var data = [{_x000D_
"name": "Afghanistan",_x000D_
"code": "AF"_x000D_
}, {_x000D_
"name": "Åland Islands",_x000D_
"code": "AX"_x000D_
}, {_x000D_
"name": "Albania",_x000D_
"code": "AL"_x000D_
}, {_x000D_
"name": "Algeria",_x000D_
"code": "DZ"_x000D_
}];_x000D_
_x000D_
_x000D_
function getCountryByCode(code) {_x000D_
return data.filter(_x000D_
function(data) {_x000D_
return data.code == code_x000D_
}_x000D_
);_x000D_
}_x000D_
_x000D_
var found = getCountryByCode('DZ');_x000D_
_x000D_
document.getElementById('output').innerHTML = found[0].name;
_x000D_
<div id="output"></div>
_x000D_
req.query
is the query string sent to the server, example /page?
test=1, req.param
is the parameters passed to the handler.
app.get('/user/:id', handler);
, going to /user/blah
, req.param.id
would return blah
;
you don't need to declare Map groovy internally recognizes it
def personDetails = [firstName:'John', lastName:'Doe', fullName:'John Doe']
// print the values..
println "First Name: ${personDetails.firstName}"
println "Last Name: ${personDetails.lastName}"
For images, open an image in google viewer. i.e.
https://docs.google.com/file/d/0Bz7qe_olclTwWDNJRDRmb1pJamM/edit
then view source> find word "texmex-thumb" and aside it there will be link.
new AsyncRoute({path: '/demo/:demoKey1/:demoKey2', loader: () => {
return System.import('app/modules/demo/demo').then(m =>m.demoComponent);
}, name: 'demoPage'}),
export class demoComponent {
onClick(){
this._router.navigate( ['/demoPage', {demoKey1: "123", demoKey2: "234"}]);
}
}
Hint - with a saving file:
$pdf->Output('sandbox/pdf/example.pdf', 'F');
I've found this absolutely invaluable when unable to grab something in a custom class or changing id's:
driver.find_element_by_xpath("//*[contains(text(), 'Show Next Date Available')]").click()
driver.find_element_by_xpath("//*[contains(text(), 'Show Next Date Available')]").text
driver.find_element_by_xpath("//*[contains(text(), 'Available')]").text
driver.find_element_by_xpath("//*[contains(text(), 'Avail')]").text
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())
var port = 9000;
app.post('/post/data', function(req, res) {
console.log('receiving data...');
console.log('body is ',req.body);
res.send(req.body);
});
// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);
This will help you. I assume you are sending body in json.
Center vertically and horizontally:
.parent{
height: 100%;
position: absolute;
width: 100%;
top: 0;
left: 0;
}
.c{
position: absolute;
top: 50%;
left: 0;
right: 0;
transform: translateY(-50%);
}
you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.
Not IsNull(Fields!W_O_Count.Value)
You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.
Split Function Works Great when you are getting One String
containing multiple values but when you are passing Multiple values you need to do something like this....
TABLE TYPE
CREATE TYPE dbo.TYPENAME AS TABLE ( arg int ) GO
Stored Procedure to Accept That Type Param
CREATE PROCEDURE mainValues @TableParam TYPENAME READONLY AS BEGIN SET NOCOUNT ON; --Temp table to store split values declare @tmp_values table ( value nvarchar(255) not null); --function splitting values INSERT INTO @tmp_values (value) SELECT arg FROM @TableParam SELECT * FROM @tmp_values --<-- For testing purpose END
EXECUTE PROC
Declare a variable of that type and populate it with your values.
DECLARE @Table TYPENAME --<-- Variable of this TYPE INSERT INTO @Table --<-- Populating the variable VALUES (331),(222),(876),(932) EXECUTE mainValues @Table --<-- Stored Procedure Executed
Result
╔═══════╗ ║ value ║ ╠═══════╣ ║ 331 ║ ║ 222 ║ ║ 876 ║ ║ 932 ║ ╚═══════╝
You can use <script>
's defer
attribute. It specifies that the script will be executed when the page has finished parsing.
<script defer src="path/to/yourscript.js">
A nice article about this: http://davidwalsh.name/script-defer
Browser support seems pretty good: http://caniuse.com/#search=defer
Another great article about loading JS using defer and async: https://flaviocopes.com/javascript-async-defer/
You have to change the ID of the button to be different from the function name JSFiddle
var counter = 0;_x000D_
_x000D_
_x000D_
function moreFields() {_x000D_
counter++;_x000D_
var newFields = document.getElementById('readroot').cloneNode(true);_x000D_
newFields.id = '';_x000D_
newFields.style.display = 'block';_x000D_
var newField = newFields.childNodes;_x000D_
for (var i = 0; i < newField.length; i++) {_x000D_
var theName = newField[i].name_x000D_
if (theName) newField[i].name = theName + counter;_x000D_
}_x000D_
var insertHere = document.getElementById('writeroot');_x000D_
insertHere.parentNode.insertBefore(newFields, insertHere);_x000D_
}_x000D_
_x000D_
window.onload = moreFields();
_x000D_
<div id="readroot" style="display: none">_x000D_
<input type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />_x000D_
<br />_x000D_
<br />_x000D_
<input name="cd" value="title" />_x000D_
<select name="rankingsel">_x000D_
<option>Rating</option>_x000D_
<option value="excellent">Excellent</option>_x000D_
<option value="good">Good</option>_x000D_
<option value="ok">OK</option>_x000D_
<option value="poor">Poor</option>_x000D_
<option value="bad">Bad</option>_x000D_
</select>_x000D_
<br />_x000D_
<br />_x000D_
<textarea rows="5" cols="20" name="review">Short review</textarea>_x000D_
<br />Radio buttons included to test them in Explorer:_x000D_
<br />_x000D_
<input type="radio" name="something" value="test1" />Test 1_x000D_
<br />_x000D_
<input type="radio" name="something" value="test2" />Test 2</div>_x000D_
<form method="post" action="index1.php"> <span id="writeroot"></span>_x000D_
_x000D_
<input type="button" onclick="moreFields();" id="moreFieldsButton" value="Give me more fields!" />_x000D_
<input type="submit" value="Send form" />_x000D_
</form>
_x000D_
You could also use the "Last" function from Ron de Bruin (http://www.rondebruin.nl/win/s9/win005.htm), it worked perfectly for me and also gives back the last column and cell if you want. To get the last row use it like
lastRow = Last(1,yourRange)
I found this quite handy.
Function Last(choice As Long, rng As Range)
'Ron de Bruin, 5 May 2008
' 1 = last row
' 2 = last column
' 3 = last cell
Dim lrw As Long
Dim lcol As Long
Select Case choice
Case 1:
On Error Resume Next
Last = rng.Find(What:="*", _
After:=rng.Cells(1), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
Case 2:
On Error Resume Next
Last = rng.Find(What:="*", _
After:=rng.Cells(1), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
Case 3:
On Error Resume Next
lrw = rng.Find(What:="*", _
After:=rng.Cells(1), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
On Error Resume Next
lcol = rng.Find(What:="*", _
After:=rng.Cells(1), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
On Error Resume Next
Last = rng.Parent.Cells(lrw, lcol).Address(False, False)
If Err.Number > 0 Then
Last = rng.Cells(1).Address(False, False)
Err.Clear
End If
On Error GoTo 0
End Select
End Function
Here you go... kit is the obvious winner!
N = 1e6
x = rnorm(N)
maxN <- function(x, N=2){
len <- length(x)
if(N>len){
warning('N greater than length(x). Setting N=length(x)')
N <- length(x)
}
sort(x,partial=len-N+1)[len-N+1]
}
microbenchmark::microbenchmark(
Rfast = Rfast::nth(x,5,descending = T),
maxN = maxN(x,5),
order = x[order(x, decreasing = T)[5]],
kit = x[kit::topn(x, 5L,decreasing = T)[5L]]
)
# Unit: milliseconds
# expr min lq mean median uq max neval
# Rfast 12.311168 12.473771 16.36982 12.702134 16.110779 102.749873 100
# maxN 12.922118 13.124358 17.49628 18.977537 20.053139 28.928694 100
# order 50.443100 50.926975 52.54067 51.270163 52.323116 66.561606 100
# kit 1.177202 1.216371 1.29542 1.240228 1.297286 2.771715 100
Edit: I forgot that kit::topn
has hasna
option...let's do another run.
microbenchmark::microbenchmark(
Rfast = Rfast::nth(x,5,descending = T),
maxN = maxN(x,5),
order = x[order(x, decreasing = T)[5]],
kit = x[kit::topn(x, 5L,decreasing = T)[5L]],
kit2 = x[kit::topn(x, 5L,decreasing = T,hasna = F)[5L]],
unit = "ms"
)
# Unit: milliseconds
# expr min lq mean median uq max neval
# Rfast 13.194314 13.358787 14.7227116 13.4560340 14.551194 24.524105 100
# maxN 7.378960 7.527661 10.0747803 7.7119715 12.217756 67.409526 100
# order 50.088927 50.488832 52.4714347 50.7415680 52.267003 70.062662 100
# kit 1.180698 1.217237 1.2975441 1.2429790 1.278243 3.263202 100
# kit2 0.842354 0.876329 0.9398055 0.9109095 0.944407 2.135903 100
The docs give a fair indicator of what's required., however requests
allow us to skip a few steps:
You only need to install the security
package extras (thanks @admdrew for pointing it out)
$ pip install requests[security]
or, install them directly:
$ pip install pyopenssl ndg-httpsclient pyasn1
Requests will then automatically inject pyopenssl
into urllib3
If you're on ubuntu, you may run into trouble installing pyopenssl
, you'll need these dependencies:
$ apt-get install libffi-dev libssl-dev
When a cookie is set with an explicit domain of 'localhost' as follows...
Set-Cookie: name=value; domain=localhost; expires=Thu, 16-Jul-2009 21:25:05 GMT; path=/
...then browsers ignore it because it does not include at least two periods and is not one of seven specially handled, top level domains.
...domains must have at least two (2) or three (3) periods in them to prevent domains of the form: ".com", ".edu", and "va.us". Any domain that fails within one of the seven special top level domains listed below only require two periods. Any other domain requires at least three. The seven special top level domains are: "COM", "EDU", "NET", "ORG", "GOV", "MIL", and "INT".
Note that the number of periods above probably assumes that a leading period is required. This period is however ignored in modern browsers and it should probably read...
at least one (1) or two (2) periods
Note that the default value for the domain attribute is the host name of the server which generated the cookie response.
So a workaround for cookies not being set for localhost is to simply not specify a domain attribute and let the browser use the default value - this does not appear to have the same constraints that an explicit value in the domain attribute does.
you can use simply write the code in a .bat
format extension ,the code of the batch file :
c:/ copy /b Image1.jpg + Archive.rar Image2.jpg
use this c# code :
Process.Start("file_name.bat")
Add
.container {
display: flex;
justify-content: center;
align-items: center;
}
to the container element of whatever you want to center. Documentation: justify-content and align-items.
I had the same error today. I had installed Djangostack and when I checked my task manager there were two instances of mysqld running. I checked one was for wamp server and the other was for django stack. I ended the one for django stack, restarted all services in wamp server and I was able to access phpmyadmin
If you use C/C++, there's no "range" syntax. You can only list all values after each "case" segment. Language Ada or Pascal support range syntax.
Open "command or conda prompt" and run:
conda update conda
conda update anaconda
It's a good idea to run both command twice (one after the other) to be sure that all the basic files are updated.
This should put you back on the latest 'releases', which contains packages that are selected by the people at Continuum to work well together.
If you want the last version of each package run (this can lead to an unstable environment):
conda update --all
Hope this helps.
Sources:
I found that my version of Xcode was too outdated and installing command-line-tools wasn't helping. Here's what I did:
If you are running a 64-bit distribution on your development machine, you need to install additional packages first. For Ubuntu 13.10 (Saucy Salamander) and above, install the
libncurses5:i386
,libstdc++6:i386
, andzlib1g:i386
packages usingapt-get
:
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386
I changed all support library versions to 25.3.1 and worked like a charm:
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
You also need to change compileSdkVersion and targetSdkVersion to 25:
compileSdkVersion 25
targetSdkVersion 25
I know this is an old question, but I wanted to make an answer of my own. here is another way to do this if you "really" want to add to the end of the list instead of using list.add(str)
you can do it this way, but I don't recommend.
String[] items = new String[]{"Hello", "World"};
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, items);
int endOfList = list.size();
list.add(endOfList, "This goes end of list");
System.out.println(Collections.singletonList(list));
this is the 'Compact' way of adding the item to the end of list. here is a safer way to do this, with null checking and more.
String[] items = new String[]{"Hello", "World"};
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, items);
addEndOfList(list, "Safer way");
System.out.println(Collections.singletonList(list));
private static void addEndOfList(List<String> list, String item){
try{
list.add(getEndOfList(list), item);
} catch (IndexOutOfBoundsException e){
System.out.println(e.toString());
}
}
private static int getEndOfList(List<String> list){
if(list != null) {
return list.size();
}
return -1;
}
Heres another way to add items to the end of list, happy coding :)
git update-index should do what you want
This will tell git you want to start ignoring the changes to the file
git update-index --assume-unchanged path/to/file
When you want to start keeping track again
git update-index --no-assume-unchanged path/to/file
The standard Servlet API doesn't support this facility. You may want either to use a rewrite-URL filter for this like Tuckey's one (which is much similar Apache HTTPD's mod_rewrite
), or to add a check in the doFilter()
method of the Filter listening on /*
.
String path = ((HttpServletRequest) request).getRequestURI();
if (path.startsWith("/specialpath/")) {
chain.doFilter(request, response); // Just continue chain.
} else {
// Do your business stuff here for all paths other than /specialpath.
}
You can if necessary specify the paths-to-be-ignored as an init-param
of the filter so that you can control it in the web.xml
anyway. You can get it in the filter as follows:
private String pathToBeIgnored;
public void init(FilterConfig config) {
pathToBeIgnored = config.getInitParameter("pathToBeIgnored");
}
If the filter is part of 3rd party API and thus you can't modify it, then map it on a more specific url-pattern
, e.g. /otherfilterpath/*
and create a new filter on /*
which forwards to the path matching the 3rd party filter.
String path = ((HttpServletRequest) request).getRequestURI();
if (path.startsWith("/specialpath/")) {
chain.doFilter(request, response); // Just continue chain.
} else {
request.getRequestDispatcher("/otherfilterpath" + path).forward(request, response);
}
To avoid that this filter will call itself in an infinite loop you need to let it listen (dispatch) on REQUEST
only and the 3rd party filter on FORWARD
only.
You can just get the individual time components and calculate the total. You seem to be expecting Moment to already have this feature neatly packaged up for you, but it doesn't. I doubt it's something that people have a need for very often.
Example:
var m = moment();_x000D_
_x000D_
var ms = m.milliseconds() + 1000 * (m.seconds() + 60 * (m.minutes() + 60 * m.hours()));_x000D_
_x000D_
console.log(ms);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
Set an EmptyBorder
around your JPanel
.
Example:
JPanel p =new JPanel();
p.setBorder(new EmptyBorder(10, 10, 10, 10));
For the legend, you can use this
plt.setp(g._legend.get_title(), fontsize=20)
Where g is your facetgrid object returned after you call the function making it.
You can use JavaScript to disable the context menu (right-click), but it's easily overwrittable. For example, in Firefox, go to Options -> Content and next to the "Enable JavaScript" check box, click Advanced. Uncheck the "Disable or replace context menus" option. Now you can right-click all you want.
A simple CTRL + U will view the source. That can never be disabled.
I also encountered the same problem, but trying the hints here didn't help, unfortunately.
The only thing that helped was to download the newest version from the Boost page, compile and install it as described in Installing Boost 1.50 on Ubuntu 12.10.
In my case I worked with Boost 1.53.
this type of error usually occur when you try to access data through the index in which data data has not been assign. for example
//assign of data in to array
for(int i=0; i<10; i++){
arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}
the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.
This was happening to me in Chrome (though not in Firefox). I've found out that the outline
property was being set by Bootstrap as outline: 5px auto -webkit-focus-ring-color;
. Solved by overriding the outline
property later in my custom CSS as follows:
.btn.active.focus, .btn.active:focus, .btn.focus, .btn:active.focus, .btn:active:focus, .btn:focus {
outline: 0;
}
Your regex says the following:
/^ - if the line starts with
( - start a capture group
Clinton| - "Clinton"
| - or
[^Bush] - Any single character except "B", "u", "s" or "h"
| - or
Reagan) - "Reagan". End capture group.
/i - Make matches case-insensitive
So, in other words, your middle part of the regex is screwing you up. As it is a "catch-all" kind of group, it will allow any line that does not begin with any of the upper or lower case letters in "Bush". For example, these lines would match your regex:
Our president, George Bush
In the news today, pigs can fly
012-3123 33
You either make a negative look-ahead, as suggested earlier, or you simply make two regexes:
if( ($string =~ m/^(Clinton|Reagan)/i) and
($string !~ m/^Bush/i) ) {
print "$string\n";
}
As mirod has pointed out in the comments, the second check is quite unnecessary when using the caret (^
) to match only beginning of lines, as lines that begin with "Clinton" or "Reagan" could never begin with "Bush".
However, it would be valid without the carets.
<<
is the left-shift operator, as it is in many other languages.
Here RAM_DEPTH
will be 1
left-shifted by 8 bits
, which is equivalent to 2^8
, or 256
.
One way of doing it is to use the ClientScriptManager
:
Page.ClientScript.RegisterStartupScript(
GetType(),
"MyKey",
"Myfunction();",
true);
I think the answer is there but only in bits and pieces, which makes it difficult to quickly fix the problem such as
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 2818: ordinal not in range(128)
Let's take an example, Suppose I have file which has some data in the following form ( containing ascii and non-ascii chars )
1/10/17, 21:36 - Land : Welcome ��
and we want to ignore and preserve only ascii characters.
This code will do:
import unicodedata
fp = open(<FILENAME>)
for line in fp:
rline = line.strip()
rline = unicode(rline, "utf-8")
rline = unicodedata.normalize('NFKD', rline).encode('ascii','ignore')
if len(rline) != 0:
print rline
and type(rline) will give you
>type(rline)
<type 'str'>
yes please download curl-devel as instructed above. also don't forget to link to lib curl:
-L/path/of/curl/lib/libcurl.a (g++)
cheers
This is not as complicated as some of the other answers make it.
Just use auto layout to add constraints to pin the left and top sides of the label.
After that it will automatically resize.
No need to set sizeToFit
when using auto layout. My complete code for the example project is here:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myLabel: UILabel!
@IBAction func changeTextButtonTapped(sender: UIButton) {
myLabel.text = "my name is really long i want it to fit in this box"
}
}
myLabel.preferredMaxLayoutWidth = 150 // or whatever
in code. (I also pinned my button to the bottom of the label so that it would move down when the label height increased.)UITableViewCell
then see this answer.Very simply, a delegate provides functionality for how a function pointer SHOULD work. There are many limitations of function pointers in C++. A delegate uses some behind-the-scenes template nastyness to create a template-class function-pointer-type-thing that works in the way you might want it to.
ie - you can set them to point at a given function and you can pass them around and call them whenever and wherever you like.
There are some very good examples here:
Follow this:
List<string> name = new List<string>();
name.Add("Latif");
name.Add("Ram");
name.Add("Adam");
string nameOfString = (string.Join(",", name.Select(x => x.ToString()).ToArray()));
You cannot do this in C#. What you can do is have a out
parameter or return your own class (or struct if you want it to be immutable).
public int GetDay(DateTime date, out string name)
{
// ...
}
Using custom class (or struct)
public DayOfWeek GetDay(DateTime date)
{
// ...
}
public class DayOfWeek
{
public int Day { get; set; }
public string Name { get; set; }
}
Here I get only three specific columns from mainDataTable and use the filter
DataTable checkedParams = mainDataTable.Select("checked = true").CopyToDataTable()
.DefaultView.ToTable(false, "lagerID", "reservePeriod", "discount");
Use String.Format
Pre C# 6.0
string data = "FlightA, B,C,D";
var str = String.Format("Hi We have these flights for you: {0}. Which one do you want?", data);
C# 6.0 -- String Interpolation
string data = "FlightA, B,C,D";
var str = $"Hi We have these flights for you: {data}. Which one do you want?";
svn log -v
Generally Server JDK version will be lower than the deployed application (built with higher jdk version)
Using $injector to call service methods in config
I had a similar issue and resolved it by using the $injector service as shown above. I tried injecting the service directly but ended up with a circular dependency on $http. The service displays a modal with the error and I am using ui-bootstrap modal which also has a dependency on $https.
$httpProvider.interceptors.push(function($injector) {
return {
"responseError": function(response) {
console.log("Error Response status: " + response.status);
if (response.status === 0) {
var myService= $injector.get("myService");
myService.showError("An unexpected error occurred. Please refresh the page.")
}
}
}
I was also experiencing the same issue. 5.5.24 was the latest version that worked for me. The Apache Friends blog has a post, https://www.apachefriends.org/blog/new_xampp_20150723.html, that mentions the newer versions shipping with the 'Dashboard'.
eval
takes a string as its argument, and evaluates it as if you'd typed that string on a command line. (If you pass several arguments, they are first joined with spaces between them.)
${$n}
is a syntax error in bash. Inside the braces, you can only have a variable name, with some possible prefix and suffixes, but you can't have arbitrary bash syntax and in particular you can't use variable expansion. There is a way of saying “the value of the variable whose name is in this variable”, though:
echo ${!n}
one
$(…)
runs the command specified inside the parentheses in a subshell (i.e. in a separate process that inherits all settings such as variable values from the current shell), and gathers its output. So echo $($n)
runs $n
as a shell command, and displays its output. Since $n
evaluates to 1
, $($n)
attempts to run the command 1
, which does not exist.
eval echo \${$n}
runs the parameters passed to eval
. After expansion, the parameters are echo
and ${1}
. So eval echo \${$n}
runs the command echo ${1}
.
Note that most of the time, you must use double quotes around variable substitutions and command substitutions (i.e. anytime there's a $
): "$foo", "$(foo)"
. Always put double quotes around variable and command substitutions, unless you know you need to leave them off. Without the double quotes, the shell performs field splitting (i.e. it splits value of the variable or the output from the command into separate words) and then treats each word as a wildcard pattern. For example:
$ ls
file1 file2 otherfile
$ set -- 'f* *'
$ echo "$1"
f* *
$ echo $1
file1 file2 file1 file2 otherfile
$ n=1
$ eval echo \${$n}
file1 file2 file1 file2 otherfile
$eval echo \"\${$n}\"
f* *
$ echo "${!n}"
f* *
eval
is not used very often. In some shells, the most common use is to obtain the value of a variable whose name is not known until runtime. In bash, this is not necessary thanks to the ${!VAR}
syntax. eval
is still useful when you need to construct a longer command containing operators, reserved words, etc.
You should set the max width and if you want you can also set some padding on one of the sides. In my case the max-width: 100% was good but the image was right next to the end of the screen.
max-width: 100%;
padding-right: 30px;
/*add more paddings if needed*/
Use upper-case HH
for 24h format:
String s = curr.ToString("HH:mm");
in HTML, you do this backwards: You define a text input:
<input type="text" list="browsers" />
and attach a datalist to it. (note the list attribute of the input).
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
Create the reference of image....
UIImage *rainyImage = [UIImage imageNamed:@"rainy.jpg"];
displaying image in image view... imagedisplay is reference of imageview:
imagedisplay.image = rainyImage;
convert it into NSData
by passing UIImage
reference and provide compression quality in float values:
NSData *imgData = UIImageJPEGRepresentation(rainyImage, 0.9);
JSONB is a "better" version of JSON.
Let's look at an example:
SELECT '{"c":0, "a":2,"a":1}'::json, '{"c":0, "a":2,"a":1}'::jsonb;
json | jsonb
------------------------+---------------------
{"c":0, "a":2,"a":1} | {"a": 1, "c": 0}
(1 row)
In general, one should prefer JSONB , unless there are specialized needs, such as legacy assumptions about ordering of object keys.
If you're using IntelliJ & Mac just go to Project structure -> SDK and make sure that there is Java listed but it points to sth like
/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home
Rather than user home...
Very simply, use this
as the context: http://api.jquery.com/jQuery/#selector-context
var a_href = $('div.cpt', this).find('h2 a').attr('href');
Which says, find 'div.cpt'
only inside this
With pure javascript you can just call the length on the id of the select box. It will be more faster. Typically with everything native javascript is performing better and better with modern browsers
This can be achieved in javascript by
var dropdownFilterSite = document.querySelector( '#dropDownId' ); //Similar to jQuery
var length = dropdownFilterSite.length.
Good website for some learning
www.youmightnotneedjquery.com
A good video to watch by Todd Motto
Yes it is 100% possible
set classpath= %classpath%;d:\jansi-1.4.jar;
Try this below code:
import org.fusesource.jansi.AnsiConsole;
import static org.fusesource.jansi.Ansi.*;
import static org.fusesource.jansi.Ansi.Color.*;
public class Sample
{
public static void main(String[] args)
{
AnsiConsole.systemInstall();
System.out.println(ansi().fg(RED).a("Hello World").reset());
System.out.println("My Name is Raman");
AnsiConsole.systemUninstall();
}
}
You need just to delete your older connector and download new version (mysql-connector-java-5.1.46)
Try this one too:
SELECT CONVERT(CHAR(8),GETDATE(),108)
I got this working by installing the various plugins below.
Most of the time things just import by themselves as soon as I type the class name. Alternatively, a lightbulb appears that you can click on. Or you can push F1, and type "import..." and there are various options there too. I kinda use all of them. Also F1 Implement for implementing an interface is helpful, but doesn't always work.
Screenshot of Extensions
Expanding on John La Rooy (Python - List of unique dictionaries) answer, making it a bit more flexible:
def dedup_dict_list(list_of_dicts: list, columns: list) -> list:
return list({''.join(row[column] for column in columns): row
for row in list_of_dicts}.values())
Calling Function:
sorted_list_of_dicts = dedup_dict_list(
unsorted_list_of_dicts, ['id', 'name'])
you can get a files modified date using vbscript too
Set objFS=CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
strFile= objArgs(0)
WScript.Echo objFS.GetFile(strFile).DateLastModified
save the above as mygetdate.vbs and on command line
c:\test> cscript //nologo mygetdate.vbs myfile
Yep you should start anaconda's python in order to use python libs which come with anaconda. Or otherwise you have to manually add anaconda\lib
to pythonpath
which is less trivial. You can start anaconda's python by a full path:
path\to\anaconda\python.exe
or you can run the following two commands as an admin in cmd to make windows pipe every .py
file to anaconda's python:
assoc .py=Python.File
ftype Python.File=C:\path\to\Anaconda\python.exe "%1" %*
after this you'll be able just to call python scripts without specifying the python executable at all.
If you want to remove all control characters, including CR and LF, you can use this:
myString.replace(/[^\x20-\x7E]/gmi, "")
It will remove all non-printable characters. This are all characters NOT within the ASCII HEX space 0x20-0x7E
. Feel free to modify the HEX range as needed.
both your conditions are the same:
if(s < f) { calc = f - s; n = s; }else if(f > s){ calc = s - f; n = f; }
so
if(s < f)
and
}else if(f > s){
are the same
change to
}else if(f < s){
You need to use the TO_DATE
function.
SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;
Assuming you want to show an Image thumbnail which is 50x50 pixels and link to the the actual image you can do
<a href="path/to/image.jpg" alt="Image description" target="_blank" style="display: inline-block; width: 50px; height; 50px; background-image: url('path/to/image.jpg');"></a>
Of course it's best to give that link a class or id and put it in your css
Or if the role is not the owner of any db objects one can use:
DROP ROLE IF EXISTS my_user;
CREATE ROLE my_user LOGIN PASSWORD 'my_password';
But only if dropping this user will not make any harm.
to make it simple, just add a class="form-inline"
before the input.
example:
<div class="col-md-4 form-inline"> //add the class here...
<label>Lot Size:</label>
<input type="text" value="" name="" class="form-control" >
</div>
man wget: -O file --output-document=file
wget "url" -O /tmp/cron_test/<file>
As of Android studio 3.4, You need to put this line in your Layout which holds the RecyclerView
.
app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior"
We are using the cordova-custom-config
plugin to manage our Android configuration. In this case the solution was to add a new custom-preference
to our config.xml
:
<platform name="android">
<preference name="orientation" value="portrait" />
<!-- ... other settings ... -->
<!-- Allow http connections (by default Android only allows https) -->
<!-- See: https://stackoverflow.com/questions/54752716/ -->
<custom-preference
name="android-manifest/application/@android:usesCleartextTraffic"
value="true" />
</platform>
Does anybody know how to do this only for development builds? I would be happy for release builds to leave this setting false
.
(I see the iOS configuration offers buildType="debug"
for that, but I'm not sure if this applies to Android configuration.)
Well, if user write 1,00,000 then floatvar will show error. So -
floatval(preg_replace("/[^-0-9\.]/","",$input));
This is much more reliable.
Usage :
$input = '1,03,24,23,434,500.6798633 this';
echo floatval(preg_replace("/[^-0-9\.]/","",$input));
I am using selinux and with the following shell command (as root) I was able to allow PHP to make SOAP calls:
sudo setsebool -P httpd_can_network_connect on
When you are reading the file, have you considered reading it line by line? This would allow you to check if your line contains the file as your are reading, and you could then perform whatever logic you needed based on that?
Scanner scanner = new Scanner("Student.txt");
String currentLine;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Perform logic
}
}
You could use a variable to hold the line number, or you could also have a boolean indicating if you have passed the line that contains your string:
Scanner scanner = new Scanner("Student.txt");
String currentLine;
int lineNumber = 0;
Boolean passedLine = false;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Do task
passedLine = true;
}
if(passedLine)
{
//Do other task after passing the line.
}
lineNumber++;
}
The easiest way to freeze the UI would be to make the AJAX call synchronous.
Usually synchronous AJAX calls defeat the purpose of using AJAX because it freezes the UI, but if you want to prevent the user from interacting with the UI, then do it.
public class ImageButton extends JButton {
protected ImageButton(){
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Image img = Toolkit.getDefaultToolkit().getImage("water.bmp");
g2.drawImage(img, 45, 35, this);
g2.finalize();
}
}
OR use this code
class MyButton extends JButton {
Image image;
ImageObserver imageObserver;
MyButtonl(String filename) {
super();
ImageIcon icon = new ImageIcon(filename);
image = icon.getImage();
imageObserver = icon.getImageObserver();
}
public void paint( Graphics g ) {
super.paint( g );
g.drawImage(image, 0 , 0 , getWidth() , getHeight() , imageObserver);
}
}
this happened again around last quarter of 2017 . greasemonkey firing too late . after domcontentloaded event already been fired.
what to do:
@run-at document-start
instead of document-endfrom : https://github.com/greasemonkey/greasemonkey/issues/2769
Even as a (private) script writer I'm confused why my script isn't working.
The most likely problem is that the 'DOMContentLoaded' event is fired before the script is run. Now before you come back and say @run-at document-start is set, that directive isn't fully supported at the moment. Due to the very asynchronous nature of WebExtensions there's little guarantee on when something will be executed. When FF59 rolls around we'll have #2663 which will help. It'll actually help a lot of things, debugging too.
Swift 2.0 Version:
let paddingView: UIView = UIView(frame: CGRectMake(0, 0, 5, 20))
textField.leftView = paddingView
textField.leftViewMode = UITextFieldViewMode.Always;
You may try this (using jQuery
)
$(function(){_x000D_
$('#MainPopupIframe').load(function(){_x000D_
$(this).show();_x000D_
console.log('iframe loaded successfully')_x000D_
});_x000D_
_x000D_
$('#click').on('click', function(){_x000D_
$('#MainPopupIframe').attr('src', 'https://heera.it'); _x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
Update: Using plain javascript
window.onload=function(){_x000D_
var ifr=document.getElementById('MainPopupIframe');_x000D_
ifr.onload=function(){_x000D_
this.style.display='block';_x000D_
console.log('laod the iframe')_x000D_
};_x000D_
var btn=document.getElementById('click'); _x000D_
btn.onclick=function(){_x000D_
ifr.src='https://heera.it'; _x000D_
};_x000D_
};
_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
Update: Also you can try this (dynamic iframe)
$(function(){_x000D_
$('#click').on('click', function(){_x000D_
var ifr=$('<iframe/>', {_x000D_
id:'MainPopupIframe',_x000D_
src:'https://heera.it',_x000D_
style:'display:none;width:320px;height:400px',_x000D_
load:function(){_x000D_
$(this).show();_x000D_
alert('iframe loaded !');_x000D_
}_x000D_
});_x000D_
$('body').append(ifr); _x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button><br />
_x000D_
All Google Maps JavaScript API applications require authentication( API KEY )
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=(Paste YOUR API KEY)"></script>
I keep this extension method around for this:
public static void Each<T>(this IEnumerable<T> ie, Action<T, int> action)
{
var i = 0;
foreach (var e in ie) action(e, i++);
}
And use it like so:
var strings = new List<string>();
strings.Each((str, n) =>
{
// hooray
});
Or to allow for break
-like behaviour:
public static bool Each<T>(this IEnumerable<T> ie, Func<T, int, bool> action)
{
int i = 0;
foreach (T e in ie) if (!action(e, i++)) return false;
return true;
}
var strings = new List<string>() { "a", "b", "c" };
bool iteratedAll = strings.Each ((str, n)) =>
{
if (str == "b") return false;
return true;
});
I was looking up on this for myself, found this, and then a solution. People are using confusing methods and some methods that don't work in certain situations or not at all.
I know it's too late now, considering this was posted 6 years ago, but hopefully future visitors find this (and hopefully, it can clean up their, and your, code.)
Simple solution:
if not @players.include?(p.name) do
....
end
Use Scanner.hasNextInt()
:
Returns
true
if the next token in this scanner's input can be interpreted as anint
value in the default radix using thenextInt()
method. The scanner does not advance past any input.
Here's a snippet to illustrate:
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int num1 = sc.nextInt();
int num2;
System.out.print("Enter number 2: ");
do {
while (!sc.hasNextInt()) sc.next();
num2 = sc.nextInt();
} while (num2 < num1);
System.out.println(num1 + " " + num2);
You don't have to parseInt
or worry about NumberFormatException
. Note that since the hasNextXXX
methods don't advance past any input, you may have to call next()
if you want to skip past the "garbage", as shown above.
There are two ways to go about this. You can either use the IDE to generate a WSDL, or you can do it via the command line.
1. To create it via the IDE:
In the solution explorer pane, right click on the project that you would like to add the Service to:
Then, you can enter the path to your service WSDL and hit go:
2. To create it via the command line:
Open a VS 2010 Command Prompt (Programs -> Visual Studio 2010 -> Visual Studio Tools)
Then execute:
WSDL /verbose C:\path\to\wsdl
WSDL.exe will then output a .cs file for your consumption.
If you have other dependencies that you received with the file, such as xsd's, add those to the argument list:
WSDL /verbose C:\path\to\wsdl C:\path\to\some\xsd C:\path\to\some\xsd
If you need VB output, use /language:VB
in addition to the /verbose
.
You can also try using runuser
(as root) to run a command as a different user
*/1 * * * * runuser php5 \
--command="/var/www/web/includes/crontab/queue_process.php \
>> /var/www/web/includes/crontab/queue.log 2>&1"
See also: man runuser
To check if variable is null or empty use this:
IF LEN(ISNULL(@var, '')) = 0
-- Is empty or NULL
ELSE
-- Is not empty and is not NULL
In an early version of PeopleSoft Financials PeopleCode:
/* I don't know how you can ever get here so I'll have to fix it later */
as of 12.03.2019 FusionTables is no more...
Import the Shapefile into Google FusionTables ( http://www.google.com/fusiontables ) using http://www.shpescape.com/ and from there you can use the data in a number of ways, eg. display it using GoogleMaps.
This question -- Why do Sublime Text 3 Themes not affect the sidebar? -- helped me out.
The steps I followed:
%AppData%\Sublime Text 3\Packages\User
)Default.sublime-theme
The C99 way is
#include <inttypes.h>
int64_t my_int = 999999999999999999;
printf("%" PRId64 "\n", my_int);
Or you could cast!
printf("%ld", (long)my_int);
printf("%lld", (long long)my_int); /* C89 didn't define `long long` */
printf("%f", (double)my_int);
If you're stuck with a C89 implementation (notably Visual Studio) you can perhaps use an open source <inttypes.h>
(and <stdint.h>
): http://code.google.com/p/msinttypes/
(del
can be your friend, as it marks objects as being deletable when there no other references to them. Now, often the CPython interpreter keeps this memory for later use, so your operating system might not see the "freed" memory.)
Maybe you would not run into any memory problem in the first place by using a more compact structure for your data.
Thus, lists of numbers are much less memory-efficient than the format used by the standard array
module or the third-party numpy
module. You would save memory by putting your vertices in a NumPy 3xN array and your triangles in an N-element array.
use this tag {!! description text !!}
If you are Windows guy and using "Tortoise SVN' user.
Select the File. Right Click. Option 'Tortoise SVN' --> get Lock. Use option 'Steal The Lock'.
@last_run_time
is a 9.4. User-Defined Variables and last_run_time datetime
one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.
Try: SELECT last_run_time;
UPDATE
Example:
/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$
CREATE PROCEDURE `sp_test`()
BEGIN
DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
DECLARE last_run_time DATETIME DEFAULT NULL;
DECLARE current_run_time DATETIME DEFAULT NOW();
-- Define the last run time
SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);
-- if there is no last run time found then use yesterday as starting point
IF(last_run_time IS NULL) THEN
SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
END IF;
SELECT last_run_time;
-- Insert variables in table2
INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$
DELIMITER ;
Please note that in the accepted answer, the first option stages the entire file from the other branch (like git add ...
had been performed), and that the second option just results in copying the file, but doesn't stage the changes (as if you had just edited the file manually and had outstanding differences).
Git copy file from another branch without staging it
Changes staged (e.g. git add filename)
:
$ git checkout directory/somefile.php feature-B
$ git status
On branch feature-A
Your branch is up-to-date with 'origin/feature-A'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: directory/somefile.php
Changes outstanding (not staged or committed):
$ git show feature-B:directory/somefile.php > directory/somefile.php
$ git status
On branch feature-A
Your branch is up-to-date with 'origin/feature-A'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: directory/somefile.php
no changes added to commit (use "git add" and/or "git commit -a")
you may try this one, used CONCAT
WHERE LastName LIKE Concat('%',@LastName,'%')
If VBA meets the rules for VB Script then it can be called from command line by simply placing it into a text file - in this case there's no need to specifically open Outlook.
I had a need to send automated text messages to myself from the command line, so I used the code below, which is just a compressed version of @Geoff's answer above.
Most mobile phone carriers worldwide provide an email address "version" of your mobile phone number. For example in Canada with Rogers or Chatr Wireless, an email sent to <YourPhoneNumber>
@pcs.rogers.com
will be immediately delivered to your Rogers/Chatr phone as a text message.
* You may need to "authorize" the first message on your phone, and some carriers may charge an additional fee for theses message although as far as I know, all Canadian carriers provide this little-known service for free. Check your carrier's website for details.
There are further instructions and various compiled lists of worldwide carrier's Email-to-Text addresses available online such as this and this and this.
.VBS
extension, such as TextMyself.vbs
. That's all!
Just double-click the file to send a test message, or else run it from a batch file using START
.
Sub SendMessage()
Const EmailToSMSAddy = "[email protected]"
Dim objOutlookRecip
With CreateObject("Outlook.Application").CreateItem(0)
Set objOutlookRecip = .Recipients.Add(EmailToSMSAddy)
objOutlookRecip.Type = 1
.Subject = "The computer needs your attention!"
.Body = "Go see why Windows Command Line is texting you!"
.Save
.Send
End With
End Sub
START x:\mypath\TextMyself.vbs
Of course there are endless possible ways this could be adapted and customized to suit various practical or creative needs.
Goto View -> Show Symbol Select as per screen-shot, you will get correct
A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.
This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.
Whereas a GridLayout is a layout that places its children in a rectangular grid.
It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.
I just found out you can also do a
array_splice($ar, 0, 0);
That does the re-indexing inplace, so you don't end up with a copy of the original array.
Let me answer this specifically for ubuntu users. First start by installing the gtest development package.
sudo apt-get install libgtest-dev
Note that this package only install source files. You have to compile the code yourself to create the necessary library files. These source files should be located at /usr/src/gtest. Browse to this folder and use cmake to compile the library:
sudo apt-get install cmake # install cmake
cd /usr/src/gtest
sudo mkdir build
cd build
sudo cmake ..
sudo make
sudo make install
Now to compile your programs that uses gtest, you have to link it with:
-lgtest -lgtest_main -lpthread
This worked perfectly for me on Ubuntu 14.04LTS.
JavaScript
/**
* Main AngularJS Web Application
*/
var app = angular.module('yourWebApp', [
'ngRoute'
]);
/**
* Setup Main Menu
*/
app.controller('MainNavCtrl', [ '$scope', '$location', function ( $scope, $location) {
$scope.menuItems = [
{
name: 'Home',
url: '/home',
title: 'Welcome to our Website'
},
{
name: 'ABOUT',
url: '/about',
title: 'Know about our work culture'
},
{
name: 'CONTACT',
url: '/contact',
title: 'Get in touch with us'
}
];
$scope.isActive = function (viewLocation) {
return viewLocation === $location.path();
};
}]);
HTML
<div class="navbar-collapse collapse" ng-controller="MainNavCtrl">
<ul id="add-magic-line" class="nav navbar-nav navbar-right">
<li data-ng-class="{current_page_item: isActive('{{ menuItem.url }}')}" data-ng-repeat="menuItem in menuItems">
<a data-ng-href="#{{menuItem.url}}" title="{{menuItem.title}}">
{{menuItem.name}}
</a>
</li>
</ul>
</div>
if by .add
you mean .append
, then the result is the same if #myDiv
is empty.
is the performance the same? dont know.
.html(x)
ends up doing the same thing as .empty().append(x)
Sorry to bring up an old thread, but if someone doesn't want to use jQuery you can use this:
function foo(){....};
window.onresize=foo;
For non-object return types, you have to assign the value to the name of your function, like this:
Public Function test() As Integer
test = 1
End Function
Example usage:
Dim i As Integer
i = test()
If the function returns an Object type, then you must use the Set
keyword like this:
Public Function testRange() As Range
Set testRange = Range("A1")
End Function
Example usage:
Dim r As Range
Set r = testRange()
Note that assigning a return value to the function name does not terminate the execution of your function. If you want to exit the function, then you need to explicitly say Exit Function
. For example:
Function test(ByVal justReturnOne As Boolean) As Integer
If justReturnOne Then
test = 1
Exit Function
End If
'more code...
test = 2
End Function
Documentation: http://msdn.microsoft.com/en-us/library/office/gg264233%28v=office.14%29.aspx
I just tried the same and came up with following solution:
public enum Countries {
TEXAS,
FLORIDA,
OKLAHOMA,
KENTUCKY;
private static Countries[] list = Countries.values();
public static Countries getCountry(int i) {
return list[i];
}
public static int listGetLastIndex() {
return list.length - 1;
}
}
The class has it's own values saved inside an array, and I use the array to get the enum at indexposition. As mentioned above arrays begin to count from 0, if you want your index to start from '1' simply change these two methods to:
public static String getCountry(int i) {
return list[(i - 1)];
}
public static int listGetLastIndex() {
return list.length;
}
Inside my Main I get the needed countries-object with
public static void main(String[] args) {
int i = Countries.listGetLastIndex();
Countries currCountry = Countries.getCountry(i);
}
which sets currCountry to the last country, in this case Countries.KENTUCKY.
Just remember this code is very affected by ArrayOutOfBoundsExceptions if you're using hardcoded indicies to get your objects.
Aside from the parameter-sniffing issue, I've found that SSRS is generally slower at client side processing than (in my case) Crystal reports. The SSRS engine just doesn't seem as capable when it has a lot of rows to locally filter or aggregate. Granted, these are result set design problems which can frequently be addressed (though not always if the details are required for drilldown) but the more um...mature...reporting engine is more forgiving.
You can use the TextView for the same purpose, But if you want to use the same with the ImageView then you have to create a class and extends the ImageView then use onDraw() method to paint the text on to the canvas. for more details visit to http://developer.android.com/reference/android/graphics/Canvas.html
The only way I was able to do this is via this code (TD tables). I tested in outlook client 2010. I also tested via webmail client and it worked for both.
The only things you have to do is change your_image.jpg (there are two instances of this for the same image make sure you update both for your code) and #your_color.
<td bgcolor="#your_color" background="your_image.jpg">
<!--[if gte mso 9]>
<v:image xmlns:v="urn:schemas-microsoft-com:vml" id="theImage" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:0; left:0; border:0; z-index:1;' src="your_image.jpg"/>
<v:shape xmlns:v="urn:schemas-microsoft-com:vml" id="theText" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:-5; left:-10; border:0; z-index:2;'>
<![endif]-->
<p>Text over background image.</p>
<!--[if gte mso 9]>
</v:shape>
<![endif]-->
</td>
Via Puppet ATG installation Centos.
ERROR:
No Java virtual machine could be found from your PATH
SOLUTION:
Declear variable :
$java_home="/opt/oracle/product/java/jdk1.8.0_45/bin"
Add This "{$java_home}" Java Exec
require common, java
Exec {
path => [ "${java_home}", "/usr/bin", "/bin", "/usr/sbin", "${temp_directory}"]
}
This is perhaps more succinct:
function toggle(element, klass) {
var classes = element.className.match(/\S+/g) || [],
index = classes.indexOf(klass);
index >= 0 ? classes.splice(index, 1) : classes.push(klass);
element.className = classes.join(' ');
}
In phpmyadmin, you can assign Foreign key simply by its GUI. Click on the table and go to Structure tab. find the Relation View on just bellow of table (shown in below image).
You can assign the forging key from the list box near by the primary key.(See image below). and save
corresponding SQL query automatically generated and executed.
How large is your aws server? If it only has 1gb of ram, setting the memory limit of 2gb in php.ini won't help.
If you can't/don't want to also increase the server side to get more RAM available, you can enable SWAP as well.
See here for how to enable swap. It enables 4gb, although I typically only do 1GB myself.
Source: Got from laracast site
If you just want to see what's in the database without installing anything extra, you might already have SQLite CLI on your system. To check, open a command prompt and try:
sqlite3 database.sqlite
Replace database.sqlite
with your database file. Then, if the database is small enough, you can view the entire contents with:
sqlite> .dump
Or you can list the tables:
sqlite> .tables
Regular SQL works here as well:
sqlite> select * from some_table;
Replace some_table
as appropriate.
No need to use second ajax function, you can get it back on success inside a function, another issue here is you don't know when the first ajax call finished, then, even if you use SESSION you may not get it within second AJAX call.
SO, I recommend using one AJAX call and get the value with success.
example: in first ajax call
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
console.log(data);
alert(data);
//or if the data is JSON
var jdata = jQuery.parseJSON(data);
}
});
Just some other formatting options:
printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n",
a, b, c, d);
printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n",
a, b, c, d);
printf("name: %s\t" "args: %s\t" "value %d\t" "arraysize %d\n",
very_long_name_a, very_long_name_b, very_long_name_c, very_long_name_d);
You can add variations on the theme. The idea is that the printf()
conversion speficiers and the respective variables are all lined up "nicely" (for some values of "nicely").
I had to have new lines in a tooltip. I had to add this CSS on my :after :
.tooltip:after {
width: 500px;
white-space: pre;
word-wrap: break-word;
}
The word-wrap seems necessary.
In addition, the \A didn't work in the middle of the text to display, to force a new line.
worked. I was then able to get such a tooltip :
I admire all these efforts to convert a menu to a menubar because I detest trying to hack CSS. It just feels like I'm meddling with powers I can't possibly ever understand! I think it's much easier to add the menubar files available at the menubar branch of jquery ui.
I downloaded the full jquery ui css bundled file from the jquery ui download site
In the head of my document I put the jquery ui css file that contains everything (I'm on version 1.9.x at the moment) followed by the specific CSS file for the menubar widget downloaded from the menubar branch of jquery ui
<link type="text/css" href="css/jquery-ui.css" rel="stylesheet" />
<link type="text/css" href="css/jquery.ui.menubar.css" rel="stylesheet" />
Don't forget the images folder with all the little icons used by jQuery UI needs to be in the same folder as the jquery-ui.css file.
Then at the end the body I have:
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.9.0.custom.min.js"></script>
<script type="text/javascript" src="js/menubar/jquery.ui.menubar.js"></script>
That's a copy of an up-to-date version of jQuery, followed by a copy of the jQuery UI file, then the menubar module downloaded from the menubar branch of jquery ui
The menubar CSS file is refreshingly short:
.ui-menubar { list-style: none; margin: 0; padding-left: 0; }
.ui-menubar-item { float: left; }
.ui-menubar .ui-button { float: left; font-weight: normal; border-top-width: 0 !important; border-bottom-width: 0 !important; margin: 0; outline: none; }
.ui-menubar .ui-menubar-link { border-right: 1px dashed transparent; border-left: 1px dashed transparent; }
.ui-menubar .ui-menu { width: 200px; position: absolute; z-index: 9999; font-weight: normal; }
but the menubar JavaScript file is 328 lines - too long to quote here. With it, you can simply call menubar() like this example:
$("#menu").menubar({
autoExpand: true,
menuIcon: true,
buttons: true,
select: select
});
As I said, I admire all the attempts to hack the menu object to turn it into a horizontal bar, but I found all of them lacked some standard feature of a horizontal menu bar. I'm not sure why this widget is not bundled with jQuery UI yet, but presumably there are still some bugs to iron out. For instance, I tried it in IE 7 Quirks Mode and the positioning was strange, but it looks great in Firefox, Safari and IE 8+.
WARNING
This solution, as mentioned by Golo Roden is not correct. It is just a quick fix to help people to have their actual jQuery code running using a Node app structure, but it's not Node philosophy because the jQuery is still running on the client side instead of on the server side. I'm sorry for giving a wrong answer.
You can also render Jade with node and put your jQuery code inside. Here is the code of the jade file:
!!! 5
html(lang="en")
head
title Holamundo!
script(type='text/javascript', src='http://code.jquery.com/jquery-1.9.1.js')
body
h1#headTitle Hello, World
p#content This is an example of Jade.
script
$('#headTitle').click(function() {
$(this).hide();
});
$('#content').click(function() {
$(this).hide();
});
This was the solution for me:
-- Check how it is now
select * from patient
select * from patient_address
-- Alter your DB
alter table patient_address nocheck constraint FK__patient_a__id_no__27C3E46E
update patient
set id_no='7008255601088'
where id_no='8008255601088'
alter table patient_address nocheck constraint FK__patient_a__id_no__27C3E46E
update patient_address
set id_no='7008255601088'
where id_no='8008255601088'
-- Check how it is now
select * from patient
select * from patient_address
I haven't tried it, but this pysftp module might help, which in turn uses paramiko. I believe everything is client-side.
The interesting command is probably .execute()
which executes an arbitrary command on the remote machine. (The module also features .get()
and .put
methods which allude more to its FTP character).
UPDATE:
I've re-written the answer after the blog post I originally linked to is not available anymore. Some of the comments that refer to the old version of this answer will now look weird.
Assuming that you are using UTF-8 encoding:
string convert = "This is the string to be converted";
// From string to byte array
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(convert);
// From byte array to string
string s = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);
setState is asynchronous. You can use callback method to get updated state.
changeHandler(event) {
this.setState({ yourName: event.target.value }, () =>
console.log(this.state.yourName));
}
Are you looking to do something like this http://jsfiddle.net/robert/xhHkG/
$('#transactionType').attr({
'multiple': true,
'size' : 10
});
Put that in a $(function() {...})
or some other onload
Reread your question, you're not really looking for a multiple select... but a dropdown box that allows you to select multiple. Yeah, probably best to use a plugin for that or write it from the ground up, it's not a "quick answer" type deal though.
Time for the modern answer.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");
String validUntil = "1/1/1990";
LocalDate validDate = LocalDate.parse(validUntil, dateFormatter);
LocalDate currentDate = LocalDate.now(ZoneId.of("Pacific/Efate"));
if (currentDate.isAfter(validDate)) {
System.out.println("Catalog is outdated");
}
When I ran this code just now, the output was:
Catalog is outdated
Since it is never the same date in all times zones, give explicit time zone to LocalDate.now
. If you want the catalog to expire at the same time in all time zones, you may give ZoneOffset.UTC
as long as you inform you users that you are using UTC.
I am using java.time, the modern Java date and time API. The date-time classes that you used, Calendar
, SimpleDateFormat
and Date
, are all poorly designed and fortunately long outdated. Also despite the name a Date
doesn’t represent a date, but a point in time. One consequence of this is: even though today is February 15, 2019, a newly created Date
object is already after (so not equal to) a Date
object from parsing 15/02/2019
. This confuses some. Contrary to this the modern LocalDate
is a date without time of day (and without time zone), so two LocalDate
s representing today’s date will always be equal.
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Apache common lang3 has Pair class and few other libraries mentioned in this thread What is the equivalent of the C++ Pair<L,R> in Java?
Example matching the requirement from your original question:
List<Pair<String, Integer>> myPairs = new ArrayList<Pair<String, Integer>>();
myPairs.add(Pair.of("val1", 11));
myPairs.add(Pair.of("val2", 17));
//...
for(Pair<String, Integer> pair : myPairs) {
//following two lines are equivalent... whichever is easier for you...
System.out.println(pair.getLeft() + ": " + pair.getRight());
System.out.println(pair.getKey() + ": " + pair.getValue());
}
Just to note that prefixing the tagName in a selector is slower than just using the id. In your case jQuery will get all the inputs rather than just using the getElementById. Just use $('#textbox')
This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.
The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(42, 68)
);
As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.
Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:
The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null
. In other words, leaving the anchor null ensures the tip points where it is supposed to point.
However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.
By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.
var pinShadow = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
null,
null,
/* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
new google.maps.Point(40, 110),
new google.maps.Size(120, 110));
to give this:
There's a very important characteristic of Decimal
that isn't obvious:
A
Decimal
'knows' how many decimal places it has based upon where it came from
The following may be unexpected :
Decimal.Parse("25").ToString() => "25"
Decimal.Parse("25.").ToString() => "25"
Decimal.Parse("25.0").ToString() => "25.0"
Decimal.Parse("25.0000").ToString() => "25.0000"
25m.ToString() => "25"
25.000m.ToString() => "25.000"
Doing the same operations with Double
will result in zero decimal places ("25"
) for all of the above examples.
If you want a decimal to 2 decimal places there's a high likelyhood it's because it's currency in which case this is probably fine for 95% of the time:
Decimal.Parse("25.0").ToString("c") => "$25.00"
Or in XAML you would use {Binding Price, StringFormat=c}
One case I ran into where I needed a decimal AS a decimal was when sending XML to Amazon's webservice. The service was complaining because a Decimal value (originally from SQL Server) was being sent as 25.1200
and rejected, (25.12
was the expected format).
All I needed to do was Decimal.Round(...)
with 2 decimal places to fix the problem regardless of the source of the value.
// generated code by XSD.exe
StandardPrice = new OverrideCurrencyAmount()
{
TypedValue = Decimal.Round(product.StandardPrice, 2),
currency = "USD"
}
TypedValue
is of type Decimal
so I couldn't just do ToString("N2")
and needed to round it and keep it as a decimal
.
I am a beginner with Angular and I did the basic mistake of not including the app name in the angular root element. So, changing the code from
<html data-ng-app>
to
<html data-ng-app="myApp">
worked for me. @PSL, has covered this already in his answer above.
You can simply use setInterval
to create such timer in Angular, Use this Code for timer -
timeLeft: number = 60;
interval;
startTimer() {
this.interval = setInterval(() => {
if(this.timeLeft > 0) {
this.timeLeft--;
} else {
this.timeLeft = 60;
}
},1000)
}
pauseTimer() {
clearInterval(this.interval);
}
<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>
<p>{{timeLeft}} Seconds Left....</p>
import { timer } from 'rxjs';
observableTimer() {
const source = timer(1000, 2000);
const abc = source.subscribe(val => {
console.log(val, '-');
this.subscribeTimer = this.timeLeft - val;
});
}
<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}
For more information read here
As per latest api docs:
$(document).ready(function() {
$('#example').dataTable({
"order": []
});
});
For read-only controls they are the same. For 2 way databinding, using a datasource in which you want to update, insert, etc with declarative databinding, you'll need to use Bind
.
Imagine for example a GridView with a ItemTemplate
and EditItemTemplate
. If you use Bind
or Eval
in the ItemTemplate
, there will be no difference. If you use Eval
in the EditItemTemplate
, the value will not be able to be passed to the Update
method of the DataSource
that the grid is bound to.
UPDATE: I've come up with this example:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Data binding demo</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView
ID="grdTest"
runat="server"
AutoGenerateEditButton="true"
AutoGenerateColumns="false"
DataSourceID="mySource">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox
ID="edtName"
runat="server"
Text='<%# Bind("Name") %>'
/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
<asp:ObjectDataSource
ID="mySource"
runat="server"
SelectMethod="Select"
UpdateMethod="Update"
TypeName="MyCompany.CustomDataSource" />
</body>
</html>
And here's the definition of a custom class that serves as object data source:
public class CustomDataSource
{
public class Model
{
public string Name { get; set; }
}
public IEnumerable<Model> Select()
{
return new[]
{
new Model { Name = "some value" }
};
}
public void Update(string Name)
{
// This method will be called if you used Bind for the TextBox
// and you will be able to get the new name and update the
// data source accordingly
}
public void Update()
{
// This method will be called if you used Eval for the TextBox
// and you will not be able to get the new name that the user
// entered
}
}
Identify all the fields that could be related to your search and then use a query like:
SELECT * FROM clients
WHERE field1 LIKE '%Mary%'
OR field2 LIKE '%Mary%'
OR field3 LIKE '%Mary%'
OR field4 LIKE '%Mary%'
....
(do that for each field you want to check)
Using LIKE '%Mary%'
instead of = 'Mary'
will look for the fields that contains someCaracters + 'Mary' + someCaracters.
If you need run code after 100% loaded with image and files, test this in mounted()
:
document.onreadystatechange = () => {
if (document.readyState == "complete") {
console.log('Page completed with image and files!')
// fetch to next page or some code
}
}
More info: MDN Api onreadystatechange
This is reviving an old question, but in Python 3, you can just use bytes
directly:
>>> bytes([17, 24, 121, 1, 12, 222, 34, 76])
b'\x11\x18y\x01\x0c\xde"L'
You can use attachEvent(ie8) and addEventListener instead
addEvent(window, 'load', function(){ some_methods_1() });
addEvent(window, 'load', function(){ some_methods_2() });
function addEvent(element, eventName, fn) {
if (element.addEventListener)
element.addEventListener(eventName, fn, false);
else if (element.attachEvent)
element.attachEvent('on' + eventName, fn);
}
declare @maxColumnCount int=0;
declare @Query varchar(max)='';
declare @DynamicColumnName nvarchar(MAX)='';
-- table type variable that store all values of column row no
DECLARE @TotalRows TABLE( row_count int)
INSERT INTO @TotalRows (row_count)
SELECT (ROW_NUMBER() OVER(PARTITION BY InvoiceNo order by InvoiceNo Desc)) as row_no FROM tblExportPartProforma
-- Get the MAX value from @TotalRows table
set @maxColumnCount= (select max(row_count) from @TotalRows)
-- loop to create Dynamic max/case and store it into local variable
DECLARE @cnt INT = 1;
WHILE @cnt <= @maxColumnCount
BEGIN
set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then InvoiceType end )as InvoiceType'+cast(@cnt as varchar)+''
set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then BankRefno end )as BankRefno'+cast(@cnt as varchar)+''
set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then AmountReceived end )as AmountReceived'+cast(@cnt as varchar)+''
set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then AmountReceivedDate end )as AmountReceivedDate'+cast(@cnt as varchar)+''
SET @cnt = @cnt + 1;
END;
-- Create dynamic CTE and store it into local variable @query
set @Query='
with CTE_tbl as
(
SELECT InvoiceNo,InvoiceType,BankRefno,AmountReceived,AmountReceivedDate,
ROW_NUMBER() OVER(PARTITION BY InvoiceNo order by InvoiceNo Desc) as row_no
FROM tblExportPartProforma
)
select
InvoiceNo
'+@DynamicColumnName+'
FROM CTE_tbl
group By InvoiceNo'
-- Execute the Query
execute (@Query)
_x000D_
Use where_in()
$ids = array('20', '15', '22', '46', '86');
$this->db->where_in('id', $ids );
You would do it like this:
std::string prefix("--foo=");
if (!arg.compare(0, prefix.size(), prefix))
foo_value = std::stoi(arg.substr(prefix.size()));
Looking for a lib such as Boost.ProgramOptions that does this for you is also a good idea.
You might like to consider ADO - a worksheet or range can be used as a table.
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adPersistXML = 1
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
''It wuld probably be better to use the proper name, but this is
''convenient for notes
strFile = Workbooks(1).FullName
''Note HDR=Yes, so you can use the names in the first row of the set
''to refer to columns, note also that you will need a different connection
''string for >=2007
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
cn.Open strCon
rs.Open "Select * from [Sheet1$]", cn, adOpenStatic, adLockOptimistic
If Not rs.EOF Then
rs.MoveFirst
rs.Save "C:\Docs\Table1.xml", adPersistXML
End If
rs.Close
cn.Close
import java.io.*;
public class FileRead {
public static void main(String[] args) throws IOException {
File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf");
OutputStream oos = new FileOutputStream("test.pdf");
byte[] buf = new byte[8192];
InputStream is = new FileInputStream(f);
int c = 0;
while ((c = is.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
}
oos.close();
System.out.println("stop");
is.close();
}
}
The easiest way so far. Hope this helps.
add an ALIAS
on the subquery,
SELECT COUNT(made_only_recharge) AS made_only_recharge
FROM
(
SELECT DISTINCT (identifiant) AS made_only_recharge
FROM cdr_data
WHERE CALLEDNUMBER = '0130'
EXCEPT
SELECT DISTINCT (identifiant) AS made_only_recharge
FROM cdr_data
WHERE CALLEDNUMBER != '0130'
) AS derivedTable -- <<== HERE
There actually is a way to do exactly what OP is asking. Just render and call an anonymous function like so:
render () {
return (
<div>
{(() => {
if (someCase) {
return (
<div>someCase</div>
)
} else if (otherCase) {
return (
<div>otherCase</div>
)
} else {
return (
<div>catch all</div>
)
}
})()}
</div>
)
}
solution
from operator import itemgetter
from typing import List, Dict, Union
def subdict(d: Union[Dict, List], columns: List[str]) -> Union[Dict, List[Dict]]:
"""Return a dict or list of dicts with subset of
columns from the d argument.
"""
getter = itemgetter(*columns)
if isinstance(d, list):
result = []
for subset in map(getter, d):
record = dict(zip(columns, subset))
result.append(record)
return result
elif isinstance(d, dict):
return dict(zip(columns, getter(d)))
raise ValueError('Unsupported type for `d`')
examples of use
# pure dict
d = dict(a=1, b=2, c=3)
print(subdict(d, ['a', 'c']))
>>> In [5]: {'a': 1, 'c': 3}
# list of dicts
d = [
dict(a=1, b=2, c=3),
dict(a=2, b=4, c=6),
dict(a=4, b=8, c=12),
]
print(subdict(d, ['a', 'c']))
>>> In [5]: [{'a': 1, 'c': 3}, {'a': 2, 'c': 6}, {'a': 4, 'c': 12}]
Since dplyr 1.0.0
, the across()
function could be used:
df %>%
group_by(Category) %>%
summarise(across(Frequency, sum))
Category Frequency
<chr> <int>
1 First 30
2 Second 5
3 Third 34
If interested in multiple variables:
df %>%
group_by(Category) %>%
summarise(across(c(Frequency, Frequency2), sum))
Category Frequency Frequency2
<chr> <int> <int>
1 First 30 55
2 Second 5 29
3 Third 34 190
And the selection of variables using select helpers:
df %>%
group_by(Category) %>%
summarise(across(starts_with("Freq"), sum))
Category Frequency Frequency2 Frequency3
<chr> <int> <int> <dbl>
1 First 30 55 110
2 Second 5 29 58
3 Third 34 190 380
Sample data:
df <- read.table(text = "Category Frequency Frequency2 Frequency3
1 First 10 10 20
2 First 15 30 60
3 First 5 15 30
4 Second 2 8 16
5 Third 14 70 140
6 Third 20 120 240
7 Second 3 21 42",
header = TRUE,
stringsAsFactors = FALSE)
var div = getElementsByTagName('div')[0]; /* first div found; you can use getElementById for more specific element */
div.onclick = null; // OR:
div.onclick = function(){};
//edit
I didn't knew what method are you using for attaching events. For addEventListener
you can use this:
div.removeEventListener('click',functionName,false); // functionName is the name of your callback function
Cool tricks here, I've got a nit pick with a lot of the safe traditional answers not caching the length of the array.
function arraySum(array){
var total = 0,
len = array.length;
for (var i = 0; i < len; i++){
total += array[i];
}
return total;
};
var my_array = [1,2,3,4];
// Returns 10
console.log( arraySum( my_array ) );
Without caching the length of the array the JS compiler needs to go through the array with every iteration of the loop to calculate the length, it's unnecessary overhead in most cases. V8 and a lot of modern browsers optimize this for us, so it is less of a concern then it was, but there are older devices that benefit from this simple caching.
If the length is subject to change, caching's that could cause some unexpected side effects if you're unaware of why you're caching the length, but for a reusable function who's only purpose is to take an array and add the values together it's a great fit.
Here's a CodePen link for this arraySum function. http://codepen.io/brandonbrule/pen/ZGEJyV
It's possible this is an outdated mindset that's stuck with me, but I don't see a disadvantage to using it in this context.
By the way, you can use serialization technology to send strings, numbers or any objects which are support serialization (most of .NET data-storing classes & structs are [Serializable]). There, you should at first send Int32-length in four bytes to the stream and then send binary-serialized (System.Runtime.Serialization.Formatters.Binary.BinaryFormatter) data into it.
On the other side or the connection (on both sides actually) you definetly should have a byte[] buffer which u will append and trim-left at runtime when data is coming.
Something like that I am using:
namespace System.Net.Sockets
{
public class TcpConnection : IDisposable
{
public event EvHandler<TcpConnection, DataArrivedEventArgs> DataArrive = delegate { };
public event EvHandler<TcpConnection> Drop = delegate { };
private const int IntSize = 4;
private const int BufferSize = 8 * 1024;
private static readonly SynchronizationContext _syncContext = SynchronizationContext.Current;
private readonly TcpClient _tcpClient;
private readonly object _droppedRoot = new object();
private bool _dropped;
private byte[] _incomingData = new byte[0];
private Nullable<int> _objectDataLength;
public TcpClient TcpClient { get { return _tcpClient; } }
public bool Dropped { get { return _dropped; } }
private void DropConnection()
{
lock (_droppedRoot)
{
if (Dropped)
return;
_dropped = true;
}
_tcpClient.Close();
_syncContext.Post(delegate { Drop(this); }, null);
}
public void SendData(PCmds pCmd) { SendDataInternal(new object[] { pCmd }); }
public void SendData(PCmds pCmd, object[] datas)
{
datas.ThrowIfNull();
SendDataInternal(new object[] { pCmd }.Append(datas));
}
private void SendDataInternal(object data)
{
if (Dropped)
return;
byte[] bytedata;
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
try { bf.Serialize(ms, data); }
catch { return; }
bytedata = ms.ToArray();
}
try
{
lock (_tcpClient)
{
TcpClient.Client.BeginSend(BitConverter.GetBytes(bytedata.Length), 0, IntSize, SocketFlags.None, EndSend, null);
TcpClient.Client.BeginSend(bytedata, 0, bytedata.Length, SocketFlags.None, EndSend, null);
}
}
catch { DropConnection(); }
}
private void EndSend(IAsyncResult ar)
{
try { TcpClient.Client.EndSend(ar); }
catch { }
}
public TcpConnection(TcpClient tcpClient)
{
_tcpClient = tcpClient;
StartReceive();
}
private void StartReceive()
{
byte[] buffer = new byte[BufferSize];
try
{
_tcpClient.Client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, DataReceived, buffer);
}
catch { DropConnection(); }
}
private void DataReceived(IAsyncResult ar)
{
if (Dropped)
return;
int dataRead;
try { dataRead = TcpClient.Client.EndReceive(ar); }
catch
{
DropConnection();
return;
}
if (dataRead == 0)
{
DropConnection();
return;
}
byte[] byteData = ar.AsyncState as byte[];
_incomingData = _incomingData.Append(byteData.Take(dataRead).ToArray());
bool exitWhile = false;
while (exitWhile)
{
exitWhile = true;
if (_objectDataLength.HasValue)
{
if (_incomingData.Length >= _objectDataLength.Value)
{
object data;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream(_incomingData, 0, _objectDataLength.Value))
try { data = bf.Deserialize(ms); }
catch
{
SendData(PCmds.Disconnect);
DropConnection();
return;
}
_syncContext.Post(delegate(object T)
{
try { DataArrive(this, new DataArrivedEventArgs(T)); }
catch { DropConnection(); }
}, data);
_incomingData = _incomingData.TrimLeft(_objectDataLength.Value);
_objectDataLength = null;
exitWhile = false;
}
}
else
if (_incomingData.Length >= IntSize)
{
_objectDataLength = BitConverter.ToInt32(_incomingData.TakeLeft(IntSize), 0);
_incomingData = _incomingData.TrimLeft(IntSize);
exitWhile = false;
}
}
StartReceive();
}
public void Dispose() { DropConnection(); }
}
}
That is just an example, you should edit it for your use.
Another possible root cause is that your tomcat has not completely started yet.
If you do a ps -ef| grep apache
, you would see the server running and if you check the catalina.out
, it will show that the server initialized in 123ms - but it might still be deploying the applications in your webapps directory.
You could use a negative look-ahead assertion:
^(?!tbd_).+
Or a negative look-behind assertion:
(^.{1,3}$|^.{4}(?<!tbd_).*)
Or just plain old character sets and alternations:
^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*
As others have said, you're not using the right function name and it doesn't exist univerally in all browsers.
If you need to do cross-browser fetching of anything other than an element with an id with document.getElementById()
, then I would strongly suggest you get a library that supports CSS3 selectors across all browsers. It will save you a massive amount of development time, testing and bug fixing. The easiest thing to do is to just use jQuery because it's so widely available, has excellent documentation, has free CDN access and has an excellent community of people behind it to answer questions. If that seems like more than you need, then you can get Sizzle which is just a selector library (it's actually the selector engine inside of jQuery and others). I've used it by itself in other projects and it's easy, productive and small.
If you want to select multiple nodes at once, you can do that many different ways. If you give them all the same class, you can do that with:
var list = document.getElementsByClassName("myButton");
for (var i = 0; i < list.length; i++) {
// list[i] is a node with the desired class name
}
and it will return a list of nodes that have that class name.
In Sizzle, it would be this:
var list = Sizzle(".myButton");
for (var i = 0; i < list.length; i++) {
// list[i] is a node with the desired class name
}
In jQuery, it would be this:
$(".myButton").each(function(index, element) {
// element is a node with the desired class name
});
In both Sizzle and jQuery, you can put multiple class names into the selector like this and use much more complicated and powerful selectors:
$(".myButton, .myInput, .homepage.gallery, #submitButton").each(function(index, element) {
// element is a node that matches the selector
});
Define your XML layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.neoecosystem.samplex.SwitchActivity">
<Switch
android:id="@+id/myswitch"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
</RelativeLayout>
Then create an Activity
public class SwitchActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener {
Switch mySwitch = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch);
mySwitch = (Switch) findViewById(R.id.myswitch);
mySwitch.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// do something when check is selected
} else {
//do something when unchecked
}
}
****
}
======== For below API 14 use SwitchCompat =========
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.neoecosystem.samplex.SwitchActivity">
<android.support.v7.widget.SwitchCompat
android:id="@+id/myswitch"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
</RelativeLayout>
Activity
public class SwitchActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener {
SwitchCompat mySwitch = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch);
mySwitch = (SwitchCompat) findViewById(R.id.myswitch);
mySwitch.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// do something when checked is selected
} else {
//do something when unchecked
}
}
*****
}
Since C++ 11 simply:
#include <cmath>
std::round(1.1)
or to get int
static_cast<int>(std::round(1.1))
With PHP brackets:
ul li {_x000D_
display: inline-block;_x000D_
}
_x000D_
<ul>_x000D_
<li>_x000D_
<div>first</div>_x000D_
</li><?_x000D_
?><li>_x000D_
<div>first</div>_x000D_
</li><?_x000D_
?><li>_x000D_
<div>first</div>_x000D_
</li>_x000D_
</ul>
_x000D_
the "file://" url protocol can only be used to locate files in the file system of the local machine. since this html code is interpreted by a browser, the "local machine" is the machine that is running the browser.
if you are getting file not found errors, i suspect it is because the file is not found. however, it could also be a security limitation of the browser. some browsers will not let you reference a filesystem file from a non-filesystem html page. you could try using the file path from the command line on the machine running the browser to confirm that this is a browser limitation and not a legitimate missing file.
To preserve file extension:
<log4net>
<root>
<level value="DEBUG"/>
<appender-ref ref="RollingLogFileAppender"/>
</root>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="D:\\LogFolder\\%date{yyyyMM}\\SchT.log" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<maximumFileSize value="30MB" />
<staticLogFileName value="true" />
<preserveLogFileNameExtension value="true"/>
<datePattern value="ddMMyyyy" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
</log4net>
I encountered this error working in Talend. I was able to store S3 CSV files created from Redshift without a problem. The error occurred when I was trying to load the same S3 CSV files into an Amazon RDS MySQL database. I tried the default timestamp Talend timestamp formats but they were throwing exception:unparseable date when loading into MySQL.
This from the accepted answer helped me solve this problem:
By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern
The key to my solution was changing the Talend schema. Talend set the timestamp field to "date" so I changed it to "timestamp" then I inserted "yyyy-MM-dd HH:mm:ss z" into the format string column view a screenshot here talend schema
I had other issues with 12 hour and 24 hour timestamp translations until I added the "z" at the end of the timestamp string.
isNull()/isNotNull() will return the respective rows which have dt_mvmt as Null or !Null.
method_1 = df.filter(df['dt_mvmt'].isNotNull()).count()
method_2 = df.filter(df.dt_mvmt.isNotNull()).count()
Both will return the same result
Use ANSI escape sequences. This article goes into some detail about them. You can use them with printf
as well.
Use \nolinebreak
\nolinebreak[number]
The \nolinebreak command prevents LaTeX from breaking the current line at the point of the command. With the optional argument, number, you can convert the \nolinebreak command from a demand to a request. The number must be a number from 0 to 4. The higher the number, the more insistent the request is.
Source: http://www.personal.ceu.hu/tex/breaking.htm#nolinebreak
You can use
$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);
or define auto-size:
$objWorksheet->getRowDimension('1')->setRowHeight(-1);
I use:
@ComponentScan(basePackages = {"com.package1","com.package2","com.package3", "com.packagen"})
Usign fs with node.
var fs = require('fs');
try {
var data = fs.readFileSync('file.txt', 'utf8');
console.log(data.toString());
} catch(e) {
console.log('Error:', e.stack);
}
Whenever you come across this problem just go to Project > Clean, then select Clean all projects. It should get resolved, otherwise try to delete those jars and add them again. Last thing would be to try restarting Eclipse.
while spring.jpa.open-in-view was true, I didn't have any problem with getOne but after setting it to false , i got LazyInitializationException. Then problem was solved by replacing with findById.
Although there is another solution without replacing the getOne method, and that is put @Transactional at method which is calling repository.getOne(id). In this way transaction will exists and session will not be closed in your method and while using entity there would not be any LazyInitializationException.
Most people responding don't even seem to know what an array pointer is...
The problem is that you do pointer arithmetics with an array pointer: ptr + 1 will mean "jump 5 bytes ahead since ptr points at a 5 byte array".
Do like this instead:
#include <stdio.h>
int main()
{
char (*ptr)[5];
char arr[5] = {'a','b','c','d','e'};
int i;
ptr = &arr;
for(i=0; i<5; i++)
{
printf("\nvalue: %c", (*ptr)[i]);
}
}
Take the contents of what the array pointer points at and you get an array. So they work just like any pointer in C.
I know this question has been satisfactorily answered, but I wanted to mention a fix that worked in my case. I added {{ csrf_field() }}
and it still didn't work.
Then I remembered that I blocked all cookies for development purposes, which can be nice when you change the page and want to refresh it.
Once I changed the settings to stop blocking all cookies in MS Edge browser
the problem went away.
If you wanna hide that column while grid populating, you can do it in aspx page itself like this
<asp:BoundField DataField="test" HeaderText="test" Visible="False" />
declare @x INT = 1 /* Declares an integer variable named "x" with the value of 1 */
PRINT 'There are ' + CAST(@x AS VARCHAR) + ' alias combinations did not match a record' /* Prints a string concatenated with x casted as a varchar */
You will also get this if you try to connect to the wrong URL ;)
I have two endpoints and services defined in my system, with similar names.
Got this exact error when the URLs got swapped on my client at some point. Really scratched the head until finally figuring out this dumb mistake.
This is the simple solution for converting string to int
NSString *strNum = @"10";
int num = [strNum intValue];
but when you are getting value from the textfield then,
int num = [txtField.text intValue];
where txtField is an outlet of UITextField
There are some misconceptions here.
Frequencies above 500 can be represented in an FFT result of length 1000. Unfortunately these frequencies are all folded together and mixed into the first 500 FFT result bins. So normally you don't want to feed an FFT a signal containing any frequencies at or above half the sampling rate, as the FFT won't care and will just mix the high frequencies together with the low ones (aliasing) making the result pretty much useless. That's why data should be low-pass filtered before being sampled and fed to an FFT.
The FFT returns amplitudes without frequencies because the frequencies depend, not just on the length of the FFT, but also on the sample rate of the data, which isn't part of the FFT itself or it's input. You can feed the same length FFT data at any sample rate, as thus get any range of frequencies out of it.
The reason the result plots ends at 500 is that, for any real data input, the frequencies above half the length of the FFT are just mirrored repeats (complex conjugated) of the data in the first half. Since they are duplicates, most people just ignore them. Why plot duplicates? The FFT calculates the other half of the result for people who feed the FFT complex data (with both real and imaginary components), which does create two different halves.
If one wants to have the conf\logging.properties
read one must (see also here) dump this file into the Servers\Tomcat v7.0 Server at localhost-config\
folder and then add the lines :
-Djava.util.logging.config.file="${workspace_loc}\Servers\Tomcat v7.0 Server at localhost-config\logging.properties" -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
to the VM arguments of the launch configuration one is using.
This may have taken a restart or two (or not) but finally I saw in the console in bright red :
FINE: No TLD files were found in [file:/C:/Dropbox/eclipse_workspaces/javaEE/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ted2012/WEB-INF/lib/logback-classic-1.0.7.jar]. Consider adding the JAR to the tomcat.util.scan.DefaultJarScanner.jarsToSkip or org.apache.catalina.startup.TldConfig.jarsToSkip property in CATALINA_BASE/conf/catalina.properties file. //etc
I still don't know when exactly this EDIT: from the comment by @Stephan: "The FINE warning appears each time any change is done in the JSP file".FINE
warning appears - does not appear immediately on tomcat launch
Bonus: To make the warning go away add in catalina.properties
:
# Additional JARs (over and above the default JARs listed above) to skip when
# scanning for TLDs. The list must be a comma separated list of JAR file names.
org.apache.catalina.startup.TldConfig.jarsToSkip=logback-classic-1.0.7.jar,\
joda-time-2.1.jar,joda-time-2.1-javadoc.jar,mysql-connector-java-5.1.24-bin.jar,\
logback-core-1.0.7.jar,javax.servlet.jsp.jstl-api-1.2.1.jar
I found a solution. Please follow the following steps:
Right Click the My comp. Icon
Click Advanced Setting.
CLick Environment Variable. On the top part of Environment Variable Click New
Set Variable name as: PATH then Set Variable Value as: (" the location of g++ .exe" ) For ex. C:\Program Files (x86)\Dev-Cpp\MinGW64\bin
Click OK
Let video muted first to ensure autoplay in ios, then unmute it if you want.
<video autoplay loop muted playsinline>
<source src="video.mp4?123" type="video/mp4">
</video>
<script type="text/javascript">
$(function () {
if (!navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
$("video").prop('muted', false);
}
});
</script>
Just test and get the result.
// output: /myproject/index.php
$currentPath = $_SERVER['PHP_SELF'];
// output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index )
$pathInfo = pathinfo($currentPath);
// output: localhost
$hostName = $_SERVER['HTTP_HOST'];
// output: http://
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https://'?'https://':'http://';
// return: http://localhost/myproject/
echo $protocol.$hostName.$pathInfo['dirname']."/";
It is ES-6 feature. It means you extract all the properties of props in
div.{... }
operator is used to extract properties of an object.
If I understand your question, here's one way. Say you have:
a = [4.1, 6.21, 1.0]
so here's some code...
def array_in_array(scalarlist):
return [(x,) for x in scalarlist]
Which leads to:
In [72]: a = [4.1, 6.21, 1.0]
In [73]: a
Out[73]: [4.1, 6.21, 1.0]
In [74]: def array_in_array(scalarlist):
....: return [(x,) for x in scalarlist]
....:
In [75]: b = array_in_array(a)
In [76]: b
Out[76]: [(4.1,), (6.21,), (1.0,)]
For me there was only one solution to remove .idea folder than commit file .gitignore with ".idea" and than use IDE again
Are you sure the odbc connector is well created ? if not check the step "Create an ODBC Connection" again
EDIT: Connection without DSN from php.net
// Microsoft Access
$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename", $user, $password);
in your case it might be if your filename is northwind and your file extension mdb:
$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=northwind", "", "");
I don't have the reputation yet to up vote Steve's suggestion, but it solved my problem.
In my case, I received this error because the two table where created using different database engines--one was Innodb and the other MyISAM.
You can change the database type using : ALTER TABLE t ENGINE = MYISAM;
@see http://dev.mysql.com/doc/refman/5.1/en/storage-engine-setting.html
If you want to know what impact has single object context for WPF / WinForm application check this article. It is about NHibernate Session but the idea is same.
Edit:
When you use EF it by default loads each entity only once per context. The first query creates entity instace and stores it internally. Any subsequent query which requires entity with the same key returns this stored instance. If values in the data store changed you still receive the entity with values from the initial query. This is called Identity map pattern. You can force the object context to reload the entity but it will reload a single shared instance.
Any changes made to the entity are not persisted until you call SaveChanges
on the context. You can do changes in multiple entities and store them at once. This is called Unit of Work pattern. You can't selectively say which modified attached entity you want to save.
Combine these two patterns and you will see some interesting effects. You have only one instance of entity for the whole application. Any changes to the entity affect the whole application even if changes are not yet persisted (commited). In the most times this is not what you want. Suppose that you have an edit form in WPF application. You are working with the entity and you decice to cancel complex editation (changing values, adding related entities, removing other related entities, etc.). But the entity is already modified in shared context. What will you do? Hint: I don't know about any CancelChanges or UndoChanges on ObjectContext
.
I think we don't have to discuss server scenario. Simply sharing single entity among multiple HTTP requests or Web service calls makes your application useless. Any request can just trigger SaveChanges
and save partial data from another request because you are sharing single unit of work among all of them. This will also have another problem - context and any manipulation with entities in the context or a database connection used by the context is not thread safe.
Even for a readonly application a global context is not a good choice because you probably want fresh data each time you query the application.
With the onclick parameter...
<a href='http://www.google.com' onclick='myJavaScriptFunction();'>mylink</a>
Try npm cache clean --force
if it doesn't work then manually delete %appdata%\npm-cache
folder.
It worked for me.
I had that problem too and I solve it by:
$today = date("Ymd");
$expire = str_replace('-', '', $row->expireDate); //from db
if(($today - $expire) > $NUMBER_OF_DAYS)
{
//do something;
}
This topic is discussed at CProgramming.com:
https://www.cprogramming.com/compilingandlinking.html
Here is what the author there wrote:
Compiling isn't quite the same as creating an executable file! Instead, creating an executable is a multistage process divided into two components: compilation and linking. In reality, even if a program "compiles fine" it might not actually work because of errors during the linking phase. The total process of going from source code files to an executable might better be referred to as a build.
Compilation
Compilation refers to the processing of source code files (.c, .cc, or .cpp) and the creation of an 'object' file. This step doesn't create anything the user can actually run. Instead, the compiler merely produces the machine language instructions that correspond to the source code file that was compiled. For instance, if you compile (but don't link) three separate files, you will have three object files created as output, each with the name .o or .obj (the extension will depend on your compiler). Each of these files contains a translation of your source code file into a machine language file -- but you can't run them yet! You need to turn them into executables your operating system can use. That's where the linker comes in.
Linking
Linking refers to the creation of a single executable file from multiple object files. In this step, it is common that the linker will complain about undefined functions (commonly, main itself). During compilation, if the compiler could not find the definition for a particular function, it would just assume that the function was defined in another file. If this isn't the case, there's no way the compiler would know -- it doesn't look at the contents of more than one file at a time. The linker, on the other hand, may look at multiple files and try to find references for the functions that weren't mentioned.
You might ask why there are separate compilation and linking steps. First, it's probably easier to implement things that way. The compiler does its thing, and the linker does its thing -- by keeping the functions separate, the complexity of the program is reduced. Another (more obvious) advantage is that this allows the creation of large programs without having to redo the compilation step every time a file is changed. Instead, using so called "conditional compilation", it is necessary to compile only those source files that have changed; for the rest, the object files are sufficient input for the linker. Finally, this makes it simple to implement libraries of pre-compiled code: just create object files and link them just like any other object file. (The fact that each file is compiled separately from information contained in other files, incidentally, is called the "separate compilation model".)
To get the full benefits of condition compilation, it's probably easier to get a program to help you than to try and remember which files you've changed since you last compiled. (You could, of course, just recompile every file that has a timestamp greater than the timestamp of the corresponding object file.) If you're working with an integrated development environment (IDE) it may already take care of this for you. If you're using command line tools, there's a nifty utility called make that comes with most *nix distributions. Along with conditional compilation, it has several other nice features for programming, such as allowing different compilations of your program -- for instance, if you have a version producing verbose output for debugging.
Knowing the difference between the compilation phase and the link phase can make it easier to hunt for bugs. Compiler errors are usually syntactic in nature -- a missing semicolon, an extra parenthesis. Linking errors usually have to do with missing or multiple definitions. If you get an error that a function or variable is defined multiple times from the linker, that's a good indication that the error is that two of your source code files have the same function or variable.
Ruby automatically converts integers to a large integer class when they overflow, so there's (practically) no limit to how big they can be.
If you are looking for the machine's size, i.e. 64- or 32-bit, I found this trick at ruby-forum.com:
machine_bytes = ['foo'].pack('p').size
machine_bits = machine_bytes * 8
machine_max_signed = 2**(machine_bits-1) - 1
machine_max_unsigned = 2**machine_bits - 1
If you are looking for the size of Fixnum objects (integers small enough to store in a single machine word), you can call 0.size
to get the number of bytes. I would guess it should be 4 on 32-bit builds, but I can't test that right now. Also, the largest Fixnum is apparently 2**30 - 1
(or 2**62 - 1
), because one bit is used to mark it as an integer instead of an object reference.
You could just do this:
var rnd = new Random();
return (MyEnum) rnd.Next(Enum.GetNames(typeof(MyEnum)).Length);
No need to store arrays