Here are 2 from infochimps.com:
http://www.infochimps.com/datasets/wikipedia-articles-abstract-search
http://www.infochimps.com/datasets/wikipedia-articles-title-autocomplete
The abstract.xml.gz
dump sounds like the one you want.
You can cast an integer to a string in this way
intval::text
and so in your case
SELECT * FROM table WHERE <some integer>::text = 'string of numbers'
$('.IsBestAnswer').addClass('bestanswer').removeClass('IsBestAnswer');
Case in method names is important, so no addclass
.
There is a jquery plugin for this. It scrolls document to a specific element, so that it would be perfectly in the middle of viewport. It also supports animation easings so that the scroll effect would look super smooth. Check out AnimatedScroll.js.
Be sure that Oracle understands that the starting time is PM, and to specify the HH24 format mask for the final output.
SELECT to_char((to_date('12:40 PM', 'HH:MI AM') + (1/24/60) * 30), 'HH24:MI') as time
FROM dual
TIME
---------
13:10
Note: the 'AM'
in the HH:MI is just the placeholder for the AM/PM meridian indicator. Could be also 'PM'
This worked for me...
Entitlements
file from the target
.Cleaned
the build in XcodeHope it works for you guys too :)
There are couple of ways this can be done.
First, is converting to list and then to array again:
List<int> tmpList = intArry.ToList();
tmpList.Add(anyInt);
intArry = tmpList.ToArray();
Now this is not recommended as you convert to list and back again to array. If you do not want to use a list, you can use the second way which is assigning values directly into the array:
int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
This is the direct approach and if you do not want to tangle with lists and conversions, this is recommended for you.
If you didn't specify a different fileformat
intentionally (say, :e ++ff=unix
for a Windows file), it's likely that the target file has mixed EOLs.
For example, if a file has some lines with <CR><NL>
endings and others with
<NL>
endings, and fileformat
is set to unix
automatically by Vim when reading it, ^M (<CR>)
will appear.
In such cases, fileformats
(note: there's an extra s
) comes into play. See :help ffs
for the details.
Or this:
f(x)=\begin{cases}
0, & -\pi\leqslant x <0\\
\pi, & 0 \leqslant x \leqslant +\pi
\end{cases}
exit(0); // at the end of main function before closing curly braces
Bootstrap modal exposes events. Listen for the the shown
event like this
$('#my-modal').on('shown', function(){
// code here
});
e
is the short var reference for event
object which will be passed to event handlers.
The event object essentially has lot of interesting methods and properties that can be used in the event handlers.
In the example you have posted is a click handler which is a MouseEvent
$(<element selector>).click(function(e) {
// does something
alert(e.type); //will return you click
}
DEMO - Mouse Events DEMO uses e.which
and e.type
Some useful references:
http://api.jquery.com/category/events/
http://www.quirksmode.org/js/events_properties.html
http://www.javascriptkit.com/jsref/event.shtml
The multiset container uses a red-black tree to keep elements sorted.
// using the multiset container to sort a list of strings.
#include <iostream>
#include <set>
#include <string>
#include <vector>
std::vector<std::string> people = {
"Joe",
"Adam",
"Mark",
"Jesse",
"Jess",
"Fred",
"Susie",
"Jill",
"Fred", // two freds.
"Adam",
"Jack",
"Adam", // three adams.
"Zeke",
"Phil"};
int main(int argc, char **argv) {
std::multiset<std::string> g(people.begin(), people.end()); // """sort"""
std::vector<std::string> all_sorted (g.begin(), g.end());
for (int i = 0; i < all_sorted.size(); i++) {
std::cout << all_sorted[i] << std::endl;
}
}
Sample Output:
Adam
Adam
Adam
Fred
Fred
Jack
Jess
Jesse
Jill
Joe
Mark
Phil
Susie
Zeke
Note the advantage is that the multiset stays sorted after insertions and deletions, great for displaying say active connections or what not.
its on you ul
in the file http://ratest4.com/wp-content/themes/HarnettArts-BP-2010/style.css on line 252
add this to your css
ul{
list-style:none;
}
This is an old question, but attempting to apply a new field (either NEWID() or ORDER BY rand()) to a table with a large number of rows would be prohibitively expensive. If you have incremental, unique IDs (and do not have any holes) it will be more efficient to calculate the X # of IDs to be selected instead of applying a GUID or similar to every single row and then taking the top X # of.
DECLARE @minValue int;
DECLARE @maxValue int;
SELECT @minValue = min(id), @maxValue = max(id) from [TABLE];
DECLARE @randomId1 int, @randomId2 int, @randomId3 int, @randomId4 int, @randomId5 int
SET @randomId1 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId2 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId3 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId4 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId5 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
--select @maxValue as MaxValue, @minValue as MinValue
-- , @randomId1 as SelectedId1
-- , @randomId2 as SelectedId2
-- , @randomId3 as SelectedId3
-- , @randomId4 as SelectedId4
-- , @randomId5 as SelectedId5
select * from [TABLE] el
where el.id in (@randomId1, @randomId2, @randomId3, @randomId4, @randomId5)
If you wanted to select many more rows I would look into populating a #tempTable with an ID and a bunch of rand() values then using each rand() value to scale to the min-max values. That way you do not have to define all of the @randomId1...n parameters. I've included an example below using a CTE to populate the initial table.
DECLARE @NumItems int = 100;
DECLARE @minValue int;
DECLARE @maxValue int;
SELECT @minValue = min(id), @maxValue = max(id) from [TABLE];
DECLARE @range int = @maxValue+1 - @minValue;
with cte (n) as (
select 1 union all
select n+1 from cte
where n < @NumItems
)
select cast( @range * rand(cast(newid() as varbinary(100))) + @minValue as int) tp
into #Nt
from cte;
select * from #Nt ntt
inner join [TABLE] i on i.id = ntt.tp;
drop table #Nt;
If you just need to output the date in ISO8601 format including the trailing Z and you are on at least SQL Server 2012, then you may use FORMAT
:
SELECT FORMAT(GetUtcDate(),'yyyy-MM-ddTHH:mm:ssZ')
This will give you something like:
2016-02-18T21:34:14Z
Just as @Pxtl points out in a comment FORMAT may have performance implications, a cost that has to be considered compared to any flexibility it brings.
When you're estimating testing you need to identify the scope of your testing - are we talking unit test, functional, UAT, interface, security, performance stress and volume?
If you're on a waterfall project you probably have some overhead tasks that are fairly constant. Allow time to prepare any planning documents, schedules and reports.
For a functional test phase (I'm a "system tester" so that's my main point of reference) don't forget to include planning! A test case often needs at least as much effort to extract from requirements / specs / user stories as it will take to execute. In addition you need to include some time for defect raising / retesting. For a larger team you'll need to factor in test management - scheduling, reporting, meetings.
Generally my estimates are based on the complexity of the features being delivered rather than a percentage of dev effort. However this does require access to at least a high-level set of instructions. Years of doing testing enables me to work out that a test of a particular complexity will take x hours of effort for preparation and execution. Some tests may require extra effort for data setup. Some tests may involve negotiating with external systems and have a duration far in excess of the effort required.
In the end, though, you need to review it in the context of the overall project. If your estimate is well above that for BA or Development then there may be something wrong with your underlying assumptions.
I know this is an old topic but it's something I'm revisiting at the moment and is of perennial interest to project managers.
Note that when you insert into a List at a position, you are really inserting at a dynamic position within the List's current elements. See here:
package com.tutorialspoint;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// create an empty array list with an initial capacity
ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
// use add() method to add elements in the list
arrlist.add(15, 15);
arrlist.add(22, 22);
arrlist.add(30, 30);
arrlist.add(40, 40);
// adding element 25 at third position
arrlist.add(2, 25);
// let us print all the elements available in list
for (Integer number : arrlist) {
System.out.println("Number = " + number);
}
}
}
$javac com/tutorialspoint/ArrayListDemo.java
$java -Xmx128M -Xms16M com/tutorialspoint/ArrayListDemo
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 15, Size: 0 at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:661) at java.util.ArrayList.add(ArrayList.java:473) at com.tutorialspoint.ArrayListDemo.main(ArrayListDemo.java:12)
This reverses the words in the given string. Words are assumed to be separated by a single space. Reversal is done in place (in the character buffer).
public static String reversePhrases(String s)
{
char[] buf = s.toCharArray();
int len = buf.length;
int start = 0;
for (int i = 0; i < len; i++) {
if (buf[i] == ' ' || i == (len-1)) {
if (i == (len-1)) {
i = len;
}
int end = (start + i)/2;
for (int j = start; j < end; j++) {
char c = buf[j];
int pos = (start + i) - j - 1;
buf[j] = buf[pos];
buf[pos] = c;
}
start = i + 1;
}
}
return new String(buf);
}
document.onkeydown = function(e) {
switch(e.which) {
case 37: // left
break;
case 38: // up
break;
case 39: // right
break;
case 40: // down
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
};
If you need to support IE8, start the function body as e = e || window.event; switch(e.which || e.keyCode) {
.
(edit 2020)
Note that KeyboardEvent.which
is now deprecated. See this example using KeyboardEvent.key
for a more modern solution to detect arrow keys.
I'd wrap the dictionary in another class:
public class MyListDictionary
{
private Dictionary<string, List<string>> internalDictionary = new Dictionary<string,List<string>>();
public void Add(string key, string value)
{
if (this.internalDictionary.ContainsKey(key))
{
List<string> list = this.internalDictionary[key];
if (list.Contains(value) == false)
{
list.Add(value);
}
}
else
{
List<string> list = new List<string>();
list.Add(value);
this.internalDictionary.Add(key, list);
}
}
}
It's case-sensitive, just make sure created branch and push to branch both are in same capital.
Example:
git checkout -b "TASK-135-hello-world"
WRONG way of doing:
git push origin task-135-hello-world #FATAL: task-135-hello-world cannot be resolved to branch
CORRECT way of doing:
git push origin TASK-135-hello-world
But, sometimes, even with user-select
and touch-callout
turned off, cursor: pointer;
may cause this effect, so, just set cursor: default;
and it'll work.
Generics are not reified at run-time. This means the information is not present at run-time.
Adding generics to Java while mantaining backward compatibility was a tour-de-force (you can see the seminal paper about it: Making the future safe for the past: adding genericity to the Java programming language).
There is a rich literature on the subject, and some people are dissatisfied with the current state, some says that actually it's a lure and there is no real need for it. You can read both links, I found them quite interesting.
This approach just uses css and html. You can actually stack a divs below the video easily. It is cover but not centered while you resize.
HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</script>
</head>
<body>
<div id = "contain">
<div id="vid">
<video autoplay>
<source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4" type="video/mp4" />
</video>
</div>
</div>
</body>
</html>
CCS:
/*
filename:style.css
*/
body {
margin:0;
}
#vid video{
position: absolute;
right: 0;
top: 0;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
}
#contain {
width:100%;
height:100%;
zoom:1%;/*Without this the video will be stretched and skewed*/
}
By doing so you'd be able to control any action of the framed page, which you cannot. Same-domain origin policy applies.
For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request
Big thanks to @swapnil for trying to help me debug this.
const data = {
grant_type: USER_GRANT_TYPE,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
scope: SCOPE_INT,
username: DEMO_EMAIL,
password: DEMO_PASSWORD
};
axios.post(TOKEN_URL, Querystring.stringify(data))
.then(response => {
console.log(response.data);
USER_TOKEN = response.data.access_token;
console.log('userresponse ' + response.data.access_token);
})
.catch((error) => {
console.log('error ' + error);
});
const AuthStr = 'Bearer '.concat(USER_TOKEN);
axios.get(URL, { headers: { Authorization: AuthStr } })
.then(response => {
// If request is good...
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
While @flaviodesousa's answer would work, it also makes it mandatory for all users (everyone else) to enter a password.
Sometime it makes sense to keep peer authentication for everyone else, but make an exception for a service user. In that case you would want to add a line to the pg_hba.conf that looks like:
local all some_batch_user md5
I would recommend that you add this line right below the commented header line:
# TYPE DATABASE USER ADDRESS METHOD
local all some_batch_user md5
You will need to restart PostgreSQL using
sudo service postgresql restart
If you're using 9.3, your pg_hba.conf would most likely be:
/etc/postgresql/9.3/main/pg_hba.conf
If your xml is written by java.lang.String
you can just using HttpClient
in this way
public void post() throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.baidu.com");
String xml = "<xml>xxxx</xml>";
HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
}
pay attention to the Exceptions.
BTW, the example is written by the httpclient version 4.x
This post is just an observation for Python behaviour I encountered. Maybe the advices you read above don't work for you if you made the same thing I did below.
Namely, I have a module which contains global/shared variables (as suggested above):
#sharedstuff.py
globaltimes_randomnode=[]
globalist_randomnode=[]
Then I had the main module which imports the shared stuff with:
import sharedstuff as shared
and some other modules that actually populated these arrays. These are called by the main module. When exiting these other modules I can clearly see that the arrays are populated. But when reading them back in the main module, they were empty. This was rather strange for me (well, I am new to Python). However, when I change the way I import the sharedstuff.py in the main module to:
from globals import *
it worked (the arrays were populated).
Just sayin'
Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?
Maybe like
myString[2:end]
?
Yes, this actually works if you assign, or bind, the name,end
, to constant singleton, None
:
>>> end = None
>>> myString = '1234567890'
>>> myString[2:end]
'34567890'
Slice notation has 3 important arguments:
Their defaults when not given are None
- but we can pass them explicitly:
>>> stop = step = None
>>> start = 2
>>> myString[start:stop:step]
'34567890'
If leaving the second part means 'till the end', if you leave the first part, does it start from the start?
Yes, for example:
>>> start = None
>>> stop = 2
>>> myString[start:stop:step]
'12'
Note that we include start in the slice, but we only go up to, and not including, stop.
When step is None
, by default the slice uses 1
for the step. If you step with a negative integer, Python is smart enough to go from the end to the beginning.
>>> myString[::-1]
'0987654321'
I explain slice notation in great detail in my answer to Explain slice notation Question.
The issue is how you're attempting to get the value. Things like...
if ( document.frm_new_user_request.u_isid.value == '' )
won't work. You need to find the element you want to get the value of first. It's not quite like a server side language where you can type in an object's reference name and a period to get or assign values.
document.getElementById('[id goes here]').value;
will work. Note: JavaScript is case-sensitive
I would recommend using:
var variablename = document.getElementById('[id goes here]');
or
var variablename = document.getElementById('[id goes here]').value;
git checkout /path/to/deleted.file
if(window.innerHeight > window.innerWidth){
alert("Please use Landscape!");
}
jQuery Mobile has an event that handles the change of this property... if you want to warn if someone rotates later - orientationchange
Also, after some googling, check out window.orientation
(which is I believe measured in degrees...)
EDIT: On mobile devices, if you open a keyboard then the above may fail, so can use screen.availHeight
and screen.availWidth
, which gives proper height and width even after the keyboard is opened.
if(screen.availHeight > screen.availWidth){
alert("Please use Landscape!");
}
Try using the following commands
//For make issues
sudo apt-get install build-essential
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.4/install.sh | bash
//To uninstall a node version
nvm uninstall <current version>
nvm install 6.10.3
nvm use 6.10.3
//check with
node -v
What I would do is use the same trick often use for hovering on buttons. Prepare an image that has 2 parts: (1) a top half which is greyed out, meaning incomplete, and (2) a bottom half which is colored in, meaning completed. Use the same image 4 times to make up the 4 steps of the progress bar, and align top for incomplete steps, and align bottom for incomplete steps.
In order to take advantage of image alignment, you'd have to use the image as the background for 4 divs, rather than using the img element.
This is the CSS for background image alignment:
div.progress-incomplete {
background-position: top;
}
div.progress-finished {
background-position: bottom;
}
Python 3.6.7 comparative:
#!/usr/bin/env python
import timeit
def time_it(fn):
"""
Measure time of execution of a function
"""
def wrapper(*args, **kwargs):
t0 = timeit.default_timer()
fn(*args, **kwargs)
t1 = timeit.default_timer()
print("{0:.10f} seconds".format(t1 - t0))
return wrapper
@time_it
def new_new_format(s):
print("new_new_format:", f"{s[0]} {s[1]} {s[2]} {s[3]} {s[4]}")
@time_it
def new_format(s):
print("new_format:", "{0} {1} {2} {3} {4}".format(*s))
@time_it
def old_format(s):
print("old_format:", "%s %s %s %s %s" % s)
def main():
samples = (("uno", "dos", "tres", "cuatro", "cinco"), (1,2,3,4,5), (1.1, 2.1, 3.1, 4.1, 5.1), ("uno", 2, 3.14, "cuatro", 5.5),)
for s in samples:
new_new_format(s)
new_format(s)
old_format(s)
print("-----")
if __name__ == '__main__':
main()
Output:
new_new_format: uno dos tres cuatro cinco
0.0000170280 seconds
new_format: uno dos tres cuatro cinco
0.0000046750 seconds
old_format: uno dos tres cuatro cinco
0.0000034820 seconds
-----
new_new_format: 1 2 3 4 5
0.0000043980 seconds
new_format: 1 2 3 4 5
0.0000062590 seconds
old_format: 1 2 3 4 5
0.0000041730 seconds
-----
new_new_format: 1.1 2.1 3.1 4.1 5.1
0.0000092650 seconds
new_format: 1.1 2.1 3.1 4.1 5.1
0.0000055340 seconds
old_format: 1.1 2.1 3.1 4.1 5.1
0.0000052130 seconds
-----
new_new_format: uno 2 3.14 cuatro 5.5
0.0000053380 seconds
new_format: uno 2 3.14 cuatro 5.5
0.0000047570 seconds
old_format: uno 2 3.14 cuatro 5.5
0.0000045320 seconds
-----
I've encountered string, which had mixings of English, Russian and some other alphabets, which caused exception. I need only Russian and English, and this currently works for me:
ec1 = Encoding::Converter.new "UTF-8","Windows-1251",:invalid=>:replace,:undef=>:replace,:replace=>""
ec2 = Encoding::Converter.new "Windows-1251","UTF-8",:invalid=>:replace,:undef=>:replace,:replace=>""
t = ec2.convert ec1.convert t
Its often difficult to get an exact color combination when you are planning to paint your house. Often, you have some color in mind, but it is not one of the colors, the vendor shows you.
Yesterday, my Prof. who is a GA researcher mentioned about a true story in Germany (sorry, I have no further references, yes, I can find it out if any one requests to). This guy (let's call him the color guy) used to go from door-door to help people to find the exact color code (in RGB) that would be the closet to what the customer had in mind. Here is how he would do it:
The color guy used to carry with him a software program which used GA. He used to start with 4 different colors- each coded as a coded Chromosome (whose decoded value would be a RGB value). The consumer picks 1 of the 4 colors (Which is the closest to which he/she has in mind). The program would then assign the maximum fitness to that individual and move onto the next generation using mutation/crossover. The above steps would be repeated till the consumer had found the exact color and then color guy used to tell him the RGB combination!
By assigning maximum fitness to the color closes to what the consumer have in mind, the color guy's program is increasing the chances to converge to the color, the consumer has in mind exactly. I found it pretty fun!
Now that I have got a -1, if you are planning for more -1's, pls. elucidate the reason for doing so!
I faced with familiar problem in my Maven multi-module project with Spring Boot 2. The problem was related to naming of my packages in sub Maven modules.
@SpringBootApplication incapsulate a lots of component like - @ComponentScan, @EnableAutoConfiguration, jpa-repositories, json-serialization and so on. And he places @ComponentScan in com.*******.space package. This part of packages com.*******.space must be common for all modules.
For fixing it:
In a multi-select option box, you can use $('#input1 :selected').length;
to get the number of selected options. This can be useful to disable buttons if a certain minimum number of options aren't met.
function refreshButtons () {
if ($('#input :selected').length == 0)
{
$('#submit').attr ('disabled', 'disabled');
}
else
{
$('#submit').removeAttr ('disabled');
}
}
To bind a control to your state you need to call a function on the component that updates the state from the control's event handler.
Rather than have an update function for all your form fields, you could create a generic update function using ES6 computed name feature and pass it the values it needs inline from the control like this:
class LovelyForm extends React.Component {_x000D_
constructor(props) {_x000D_
alert("Construct");_x000D_
super(props);_x000D_
this.state = {_x000D_
field1: "Default 1",_x000D_
field2: "Default 2"_x000D_
};_x000D_
}_x000D_
_x000D_
update = (name, e) => {_x000D_
this.setState({ [name]: e.target.value });_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<form>_x000D_
<p><input type="text" value={this.state.field1} onChange={(e) => this.update("field1", e)} />_x000D_
{this.state.field1}</p>_x000D_
<p><input type="text" value={this.state.field2} onChange={(e) => this.update("field2", e)} />_x000D_
{this.state.field2}</p>_x000D_
</form>_x000D_
);_x000D_
}_x000D_
}_x000D_
ReactDOM.render(<LovelyForm/>, document.getElementById('example'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="example"></div>
_x000D_
My solution involved a bit of javascript. Keep the 100% or 100vh on the div (this will avoid the div not appearing on initial page load). Then when the page loads, grab the window height and apply it to the element in question. Avoids the jump because now you have a static height on your div.
var $hero = $('#hero-wrapper'),
h = window.innerHeight;
$hero.css('height', h);
6 7
x is a global variable that is visible only from foo(). 5 is its initial value, as stored in the .data section of the code. Any subsequent modification overwrite previous value. There is no assignment code generated in the function body.
var numeric = [
['input1','input2'],
['input3','input4']
];
numeric[0][0] == 'input1';
numeric[0][1] == 'input2';
numeric[1][0] == 'input3';
numeric[1][1] == 'input4';
var obj = {
'row1' : {
'key1' : 'input1',
'key2' : 'input2'
},
'row2' : {
'key3' : 'input3',
'key4' : 'input4'
}
};
obj.row1.key1 == 'input1';
obj.row1.key2 == 'input2';
obj.row2.key1 == 'input3';
obj.row2.key2 == 'input4';
var mixed = {
'row1' : ['input1', 'inpu2'],
'row2' : ['input3', 'input4']
};
mixed.row1[0] == 'input1';
mixed.row1[1] == 'input2';
mixed.row2[0] == 'input3';
mixed.row2[1] == 'input4';
And if you're wanting to store DOM elements:
var inputs = [
[
document.createElement('input'),
document.createElement('input')
],
[
document.createElement('input'),
document.createElement('input')
]
];
inputs[0][0].id = 'input1';
inputs[0][1].id = 'input2';
inputs[1][0].id = 'input3';
inputs[1][1].id = 'input4';
Not real sure how useful the above is until you attach the elements. The below may be more what you're looking for:
<input text="text" id="input5"/>
<input text="text" id="input6"/>
<input text="text" id="input7"/>
<input text="text" id="input8"/>
var els = [
[
document.getElementById('input5'),
document.getElementById('input6')
],
[
document.getElementById('input7'),
document.getElementById('input8')
]
];
els[0][0].id = 'input5';
els[0][1].id = 'input6';
els[1][0].id = 'input7';
els[1][1].id = 'input8';
Or, maybe this:
<input text="text" value="4" id="input5"/>
<input text="text" value="4" id="input6"/>
<br/>
<input text="text" value="2" id="input7"/>
<input text="text" value="4" id="input8"/>
var els = [
[
document.getElementById('input5'),
document.getElementById('input6')
],
[
document.getElementById('input7'),
document.getElementById('input8')
]
];
var result = [];
for (var i = 0; i < els.length; i++) {
result[result.length] = els[0][i].value - els[1][i].value;
}
Which gives:
[2, 0]
In the console. If you want to output that to text, you can result.join(' ');
, which would give you 2 0
.
EDIT
And a working demonstration:
<input text="text" value="4" id="input5"/>
<input text="text" value="4" id="input6"/>
<br/>
<input text="text" value="2" id="input7"/>
<input text="text" value="4" id="input8"/>
<br/>
<input type="button" value="Add" onclick="add()"/>
// This would just go in a script block in the head
function add() {
var els = [
[
document.getElementById('input5'),
document.getElementById('input6')
],
[
document.getElementById('input7'),
document.getElementById('input8')
]
];
var result = [];
for (var i = 0; i < els.length; i++) {
result[result.length] = parseInt(els[0][i].value) - parseInt(els[1][i].value);
}
alert(result.join(' '));
}
If you're using the MVC framework, this should work. I used Milox's FakeHttpContext and added a few additional lines of code. The idea came from this post:
This seems to work in MVC 5. I haven't tried this in earlier versions of MVC.
HttpContext.Current = MockHttpContext.FakeHttpContext();
var wrapper = new HttpContextWrapper(HttpContext.Current);
MyController controller = new MyController();
controller.ControllerContext = new ControllerContext(wrapper, new RouteData(), controller);
string result = controller.MyMethod();
I just wanted to add these from TLDP:
~:$ echo $SHELL
/bin/bash
~:$ echo ${#SHELL}
9
~:$ ARRAY=(one two three)
~:$ echo ${#ARRAY}
3
~:$ echo ${TEST:-test}
test
~:$ echo $TEST
~:$ export TEST=a_string
~:$ echo ${TEST:-test}
a_string
~:$ echo ${TEST2:-$TEST}
a_string
~:$ echo $TEST2
~:$ echo ${TEST2:=$TEST}
a_string
~:$ echo $TEST2
a_string
~:$ export STRING="thisisaverylongname"
~:$ echo ${STRING:4}
isaverylongname
~:$ echo ${STRING:6:5}
avery
~:$ echo ${ARRAY[*]}
one two one three one four
~:$ echo ${ARRAY[*]#one}
two three four
~:$ echo ${ARRAY[*]#t}
one wo one hree one four
~:$ echo ${ARRAY[*]#t*}
one wo one hree one four
~:$ echo ${ARRAY[*]##t*}
one one one four
~:$ echo $STRING
thisisaverylongname
~:$ echo ${STRING%name}
thisisaverylong
~:$ echo ${STRING/name/string}
thisisaverylongstring
The location has changed from Java 6 (provided by Apple) to Java 7 and onwards (provided by Oracle). The best generic way to find this out is to run
/usr/libexec/java_home
This is the natively supported way to find out both the path to the default Java installation as well as all alternative ones present.
If you check out its help text (java_home -h
), you'll see that you can use this command to reliably start a Java program on OS X (java_home --exec ...
), with the ability to explicitly specify the desired Java version and architecture, or even request the user to install it if missing.
A more pedestrian approach, but one which will help you trace specifically which Java installation the command java
resolves into, goes like this:
run
which java
if that gives you something like /usr/bin/java
, which is a symbolic link to the real location, run
ls -l `which java`
On my system, this outputs
/usr/bin/java -> /Library/Java/JavaVirtualMachines/jdk1.7.0_25.jdk/Contents/Home/bin/java
and therefrom you can read the Java home directory;
if usr/bin/java
points to another symbolic link, recursively apply the same approach with
ls -l <whatever the /usr/bin/java symlink points to>
An important variation is the setup you get if you start by installing Apple's Java and later install Oracle's. In that case Step 2 above will give you
/usr/bin/java -> /System/Library/Frameworks/JavaVM.framework/Commands/java
and that particular java
binary is a stub which will resolve the actual java
command to call by consulting the JAVA_HOME
environment variable and, if it's not set or doesn't point to a Java home directory, will fall back to calling java_home
. It is important to have this in mind when debugging your setup.
You need to use runat="server"
like this:
<textarea id="TextArea1" cols="20" rows="2" runat="server"></textarea>
You can use the runat=server attribute with any standard HTML element, and later use it from codebehind.
I think you are looking for this ?
$('#your_id').html('<p>name</p><p><span style="font-size:xx-small;">ajde</span></p><p><em>da</em></p>').text();
You need to specify how you'll authenticate with the database. If you want to use integrated security (this means using Windows authentication using your local or domain Windows account), add this to the connection string:
Integrated Security = True;
If you want to use SQL Server authentication (meaning you specify a login and password rather than using a Windows account), add this:
User ID = "username"; Password = "password";
I am having the same issue; Intellisense randomly will stop showing in some files, but not others. I just had it happen to me again. Hitting Ctrl + Space won't show anything in Form1
, switching to Form2
or any other class will pop up the list as expected. Restarting Visual Studio usually does the trick, though it's highly annoying and ridiculous for such a basic feature to be broken...
Other posts here have made it clear that the result is an "empty" IQueryable, which ToList() will correctly change to be an empty list etc.
Do be careful with some of the operators, as they will throw if you send them an empty enumerable. This can happen when you chain them together.
You can get the selected option this way:
$('#mySelectBox option:selected')...
But if you want to iterate all the options, do it with this.selected
instead of this.isChecked
which doesn't exist:
$('#mySelectBox option').each(function() {
if (this.selected)
alert('this option is selected');
else
alert('this is not');
});
Update:
You got plenty of answers suggesting you to use this:
$(this).is(':selected')
well, it can be done a lot faster and easier with this.selected
so why should you use it and not the native DOM element method?!
Read Know Your DOM Properties and Functions in the jQuery
tag info
this one works for me (plain javascript)
var fixScroll = function (className, border) { // className = class of scrollElement(s), border: borderTop + borderBottom, due to offsetHeight
var reg = new RegExp(className,"i"); var off = +border + 1;
function _testClass(e) { var o = e.target; while (!reg.test(o.className)) if (!o || o==document) return false; else o = o.parentNode; return o;}
document.ontouchmove = function(e) { var o = _testClass(e); if (o) { e.stopPropagation(); if (o.scrollTop == 0) { o.scrollTop += 1; e.preventDefault();}}}
document.ontouchstart = function(e) { var o = _testClass(e); if (o && o.scrollHeight >= o.scrollTop + o.offsetHeight - off) o.scrollTop -= off;}
}
fixScroll("fixscroll",2); // assuming I have a 1px border in my DIV
html:
<div class="fixscroll" style="border:1px gray solid">content</div>
This will hide your console. Implement these lines in your code first to start hiding your console at first.
import win32gui, win32con
the_program_to_hide = win32gui.GetForegroundWindow()
win32gui.ShowWindow(the_program_to_hide , win32con.SW_HIDE)
Update May 2020 :
If you've got trouble on pip install win32con
on Command Prompt, you can simply pip install pywin32
.Then on your python script, execute import win32.lib.win32con as win32con
instead of import win32con
.
To show back your program again win32con.SW_SHOW
works fine:
win32gui.ShowWindow(the_program_to_hide , win32con.SW_SHOW)
Type IF /? to get help about if, it clearly explains how to use IF EXIST.
To delete a complete tree except some folders, see the answer of this question: Windows batch script to delete everything in a folder except one
Finally copying just means calling COPY and calling another bat file can be done like this:
MYOTHERBATFILE.BAT sync.bat myprogram.ini
I needed something to call scripts with named parameters. We have a policy of not using ordinal positioning of parameters and requiring the parameter name.
My approach is similar to the ones above but gets the content of the script file that you want to call and sends a parameter block containing the parameters and values.
One of the advantages of this is that you can optionally choose which parameters to send to the script file allowing for non-mandatory parameters with defaults.
Assuming there is a script called "MyScript.ps1" in the temporary path that has the following parameter block:
[CmdletBinding(PositionalBinding = $False)]
param
(
[Parameter(Mandatory = $True)] [String] $MyNamedParameter1,
[Parameter(Mandatory = $True)] [String] $MyNamedParameter2,
[Parameter(Mandatory = $False)] [String] $MyNamedParameter3 = "some default value"
)
This is how I would call this script from another script:
$params = @{
MyNamedParameter1 = $SomeValue
MyNamedParameter2 = $SomeOtherValue
}
If ($SomeCondition)
{
$params['MyNamedParameter3'] = $YetAnotherValue
}
$pathToScript = Join-Path -Path $env:Temp -ChildPath MyScript.ps1
$sb = [scriptblock]::create(".{$(Get-Content -Path $pathToScript -Raw)} $(&{
$args
} @params)")
Invoke-Command -ScriptBlock $sb
I have used this in lots of scenarios and it works really well. One thing that you occasionally need to do is put quotes around the parameter value assignment block. This is always the case when there are spaces in the value.
e.g. This param block is used to call a script that copies various modules into the standard location used by PowerShell C:\Program Files\WindowsPowerShell\Modules
which contains a space character.
$params = @{
SourcePath = "$WorkingDirectory\Modules"
DestinationPath = "'$(Join-Path -Path $([System.Environment]::GetFolderPath('ProgramFiles')) -ChildPath 'WindowsPowershell\Modules')'"
}
Hope this helps!
I generally map :noh
to the backslash key. To reenable the highlighting, just hit n, and it will highlight again.
If you have a large number of images, look into a Bloom filter, which uses multiple hashes for a probablistic but efficient result. If the number of images is not huge, then a cryptographic hash like md5 should be sufficient.
var fav = [];
$.each($("input[name='name']:checked"), function(){
fav.push($(this).val());
});
It will give you the value separeted by commas
const {Builder, By, Key, util} = require('selenium-webdriver')
// FUNÇÃO PARA PAUSA
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function example() {
// chrome
let driver = await new Builder().forBrowser("firefox").build()
await driver.get('https://www.google.com.br')
// await driver.findElement(By.name('q')).sendKeys('Selenium' ,Key.RETURN)
await sleep(2000)
await driver.findElement(By.name('q')).sendKeys('Selenium')
await sleep(2000)
// CLICAR
driver.findElement(By.name('btnK')).click()
}
example()
Com essas últimas linhas, você pode clicar !
I also ran into the same issue the other day. Google search got me here and several other places, but none gave the solution to this issue. I ended up saving the uploaded file (MultiPartFile) as a tmp file, then use FileSystemResource to upload it via RestTemplate. Here's the code I use,
String tempFileName = "/tmp/" + multiFile.getOriginalFileName();
FileOutputStream fo = new FileOutputStream(tempFileName);
fo.write(asset.getBytes());
fo.close();
parts.add("file", new FileSystemResource(tempFileName));
String response = restTemplate.postForObject(uploadUrl, parts, String.class, authToken, path);
//clean-up
File f = new File(tempFileName);
f.delete();
I am still looking for a more elegant solution to this problem.
In case of Request to a REST Service:
You need to allow the CORS (cross origin sharing of resources) on the endpoint of your REST Service with Spring annotation:
@CrossOrigin(origins = "http://localhost:8080")
Very good tutorial: https://spring.io/guides/gs/rest-service-cors/
Convert Timestamp to Date as mentioned below, it will work for sure -
select TO_DATE(TO_CHAR(TO_TIMESTAMP ('2015-04-15 18:00:22.000', 'YYYY-MM-DD HH24:MI:SS.FF'),'MM/DD/YYYY HH24:MI:SS'),'MM/DD/YYYY HH24:MI:SS') dt from dual
I think it actually depends on what are you going to do inside your doSomething
function. If you are going to access MyObject
properties using this keyword then you have to use that. But I think that the following code fragment will also work if you are not doing any special things using object(MyObject)
properties.
function doSomething(){
.........
}
$("#foobar").ready('click', function(){
});
Had the same problem on Windows 10. The user's %Path% environment already had the required "C:\Users\ user \AppData\Roaming\npm".
path command would not show it, but it did show tons of other paths added earlier by other installations.
Turned out I needed to delete some of them from the system's PATH environment variable.
As far as I understand this happens because there's a length limit on these variables: https://software.intel.com/en-us/articles/limitation-to-the-length-of-the-system-path-variable
Probably happens often on dev machines who install lots of stuff that needs to be in the PATH.
Android Support V7 GridLayout library makes excess space distribution easy by accommodating the principle of weight. To make a column stretch, make sure the components inside it define a weight or a gravity. To prevent a column from stretching, ensure that one of the components in the column does not define a weight or a gravity. Remember to add dependency for this library. Add com.android.support:gridlayout-v7:25.0.1 in build.gradle.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:columnCount="2"
app:rowCount="2">
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
android:text="First"
app:layout_columnWeight="1"
app:layout_rowWeight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
android:text="Second"
app:layout_columnWeight="1"
app:layout_rowWeight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
android:text="Third"
app:layout_columnWeight="1"
app:layout_rowWeight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
app:layout_columnWeight="1"
app:layout_rowWeight="1"
android:text="fourth"/>
</android.support.v7.widget.GridLayout>
They aren't comparable.
Ajax (Asynchronous Javascript and XML) is a subset of javascript. Ajax is way for the client-side browser to communicate with the server (for example: retrieve data from a database) without having to perform a page refresh.
jQuery is a javascript library that standardizes the javascript differences cross-browser. jQuery includes some ajax functions.
VB6 Installs just fine on Windows 7 (and Windows 8 / Windows 10) with a few caveats.
Here is how to install it:
C:\Windows
called MSJAVA.DLL
. The setup process will look for this file, and if it doesn't find it, will force an installation of old, old Java, and require a reboot. By creating the zero-byte file, the installation of moldy Java is bypassed, and no reboot will be required.SETUP.EXE
, select Run As Administrator
.C:\Program Files\Microsoft Visual Studio\VB98\
After changing these settings, fire up the IDE, and things should be back to normal, and the IDE is no longer sluggish.
Edit: Updated dead link to point to a different page with the same instructions
Edit: Updated the answer with the actual instructions in the post as the link kept dying
For those who are using Oracle 12.1.0 for development purposes:
I found that the above methods would have no effect on the db user: "system", because the account_status would remain in the expired-grace period.
The easiest solution was for me to use SQL Developer:
within SQL Developer, I had to go to: View / DBA / Security and then Users / System and then on the right side: Actions / Expire pw and then: Actions / Edit and I could untick the option for expired.
This cleared the account_status, it shows OPEN again, and the SQL Developer is no longer showing the ORA-28002 message.
Simply You can do it
import time
delay=60*15 ###for 15 minutes delay
close_time=time.time()+delay
while True:
##bla bla
###bla bla
if time.time()>close_time
break
Usually, we want to divide our vector into a number of intervals. In this case, you can use a function where (a) is a vector and (b) is the number of intervals. (Let's suppose you want 4 intervals)
a <- 1:10
b <- 4
FunctionIntervalM <- function(a,b) {
seq(from=min(a), to = max(a), by = (max(a)-min(a))/b)
}
FunctionIntervalM(a,b)
# 1.00 3.25 5.50 7.75 10.00
Therefore you have 4 intervals:
1.00 - 3.25
3.25 - 5.50
5.50 - 7.75
7.75 - 10.00
You can also use a cut function
cut(a, 4)
# (0.991,3.25] (0.991,3.25] (0.991,3.25] (3.25,5.5] (3.25,5.5] (5.5,7.75]
# (5.5,7.75] (7.75,10] (7.75,10] (7.75,10]
#Levels: (0.991,3.25] (3.25,5.5] (5.5,7.75] (7.75,10]
Since version 2.1 of the Maven Dependency Plugin, there is a dependency:get goal for this purpose. To make sure you are using the right version of the plugin, you'll need to use the "fully qualified name":
mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get \ -DrepoUrl=http://download.java.net/maven/2/ \ -Dartifact=robo-guice:robo-guice:0.4-SNAPSHOT
If you want the executable:
System.Reflection.Assembly.GetEntryAssembly().Location
If you want the assembly that's consuming your library (which could be the same assembly as above, if your code is called directly from a class within your executable):
System.Reflection.Assembly.GetCallingAssembly().Location
If you'd like just the filename and not the path, use:
Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location)
Since PyYAML's yaml.load()
function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:
import yaml
with open('tree.yaml', 'r') as f:
doc = yaml.load(f)
To access branch1 text
you would use:
txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"
because, in your YAML document, the value of the branch1
key is under the treeroot
key.
It is possible also that one may want to have personalized feature branches where code is just placed at the end of day. That permits to track development in finer detail.
I would not want to pollute master development with non-working code, thus doing --no-ff may just be what one is looking for.
As a side note, it may not be necessary to commit working code on a personalized branch, since history can be rewritten git rebase -i
and forced on the server as long as nobody else is working on that same branch.
You can achieve this by adding this simple php code block
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
the_content();
endwhile; else: ?>
<p>!Sorry no posts here</p>
<?php endif; ?>
While it is not possible to write a switch statement, it is possible to branch out to specific processing for each given type. One way of doing this is to use standard double dispatch mechanism. An example where we want to "switch" based on type is Jersey Exception mapper where we need to map multitude of exceptions to error responses. While for this specific case there is probably a better way (i.e. using a polymorphic method that translates each exception to an error response), using double dispatch mechanism is still useful and practical.
interface Processable {
<R> R process(final Processor<R> processor);
}
interface Processor<R> {
R process(final A a);
R process(final B b);
R process(final C c);
// for each type of Processable
...
}
class A implements Processable {
// other class logic here
<R> R process(final Processor<R> processor){
return processor.process(this);
}
}
class B implements Processable {
// other class logic here
<R> R process(final Processor<R> processor){
return processor.process(this);
}
}
class C implements Processable {
// other class logic here
<R> R process(final Processor<R> processor){
return processor.process(this);
}
}
Then where ever the "switch" is needed, you can do it as follows:
public class LogProcessor implements Processor<String> {
private static final Logger log = Logger.for(LogProcessor.class);
public void logIt(final Processable base) {
log.info("Logging for type {}", process(base));
}
// Processor methods, these are basically the effective "case" statements
String process(final A a) {
return "Stringifying A";
}
String process(final B b) {
return "Stringifying B";
}
String process(final C c) {
return "Stringifying C";
}
}
The solution to this is actually very easy, but not at all obvious. You have to trigger something called a "block formatting context" (BFC), which interacts with floats in a specific way.
Just take that second div, remove the float, and give it overflow:hidden
instead. Any overflow value other than visible makes the block it's set on become a BFC. BFCs don't allow descendant floats to escape them, nor do they allow sibling/ancestor floats to intrude into them. The net effect here is that the floated div will do its thing, then the second div will be an ordinary block, taking up all available width except that occupied by the float.
This should work across all current browsers, though you may have to trigger hasLayout in IE6 and 7. I can't recall.
Demos:
Yes they do.
You shouldn't really be overriding the constructor anyway. You should have a newInstance()
static method defined and pass any parameters via arguments (bundle)
For example:
public static final MyFragment newInstance(int title, String message) {
MyFragment f = new MyFragment();
Bundle bdl = new Bundle(2);
bdl.putInt(EXTRA_TITLE, title);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
And of course grabbing the args this way:
@Override
public void onCreate(Bundle savedInstanceState) {
title = getArguments().getInt(EXTRA_TITLE);
message = getArguments().getString(EXTRA_MESSAGE);
//...
//etc
//...
}
Then you would instantiate from your fragment manager like so:
@Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState == null){
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content, MyFragment.newInstance(
R.string.alert_title,
"Oh no, an error occurred!")
)
.commit();
}
}
This way if detached and re-attached the object state can be stored through the arguments. Much like bundles attached to Intents.
Reason - Extra reading
I thought I would explain why for people wondering why.
If you check: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/Fragment.java
You will see the instantiate(..)
method in the Fragment
class calls the newInstance
method:
public static Fragment instantiate(Context context, String fname, @Nullable Bundle args) {
try {
Class<?> clazz = sClassMap.get(fname);
if (clazz == null) {
// Class not found in the cache, see if it's real, and try to add it
clazz = context.getClassLoader().loadClass(fname);
if (!Fragment.class.isAssignableFrom(clazz)) {
throw new InstantiationException("Trying to instantiate a class " + fname
+ " that is not a Fragment", new ClassCastException());
}
sClassMap.put(fname, clazz);
}
Fragment f = (Fragment) clazz.getConstructor().newInstance();
if (args != null) {
args.setClassLoader(f.getClass().getClassLoader());
f.setArguments(args);
}
return f;
} catch (ClassNotFoundException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (java.lang.InstantiationException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (IllegalAccessException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (NoSuchMethodException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": could not find Fragment constructor", e);
} catch (InvocationTargetException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": calling Fragment constructor caused an exception", e);
}
}
http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance() Explains why, upon instantiation it checks that the accessor is public
and that that class loader allows access to it.
It's a pretty nasty method all in all, but it allows the FragmentManger
to kill and recreate Fragments
with states. (The Android subsystem does similar things with Activities
).
Example Class
I get asked a lot about calling newInstance
. Do not confuse this with the class method. This whole class example should show the usage.
/**
* Created by chris on 21/11/2013
*/
public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener {
public static final StationInfoAccessibilityFragment newInstance(String crsCode) {
StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment();
final Bundle args = new Bundle(1);
args.putString(EXTRA_CRS_CODE, crsCode);
fragment.setArguments(args);
return fragment;
}
// Views
LinearLayout mLinearLayout;
/**
* Layout Inflater
*/
private LayoutInflater mInflater;
/**
* Station Crs Code
*/
private String mCrsCode;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCrsCode = getArguments().getString(EXTRA_CRS_CODE);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mInflater = inflater;
return inflater.inflate(R.layout.fragment_station_accessibility, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mLinearLayout = (LinearLayout)view.findViewBy(R.id.station_info_accessibility_linear);
//Do stuff
}
@Override
public void onResume() {
super.onResume();
getActivity().getSupportActionBar().setTitle(R.string.station_info_access_mobility_title);
}
// Other methods etc...
}
I'd do it like this:
f = open('test.txt')
l = [l for l in f.readlines() if l.strip()]
f.close()
print l
You can use Visual Studio 2012.
Simply update your NuGet package in Visual Studio to Microsoft.AspNet.Mvc 5.0
.
You may have to search pre-release.
Also the default project comes with Entity Framework 6.0, and ASP.NET Razor 3.0.
You may also need ASP.NET Identity Core and OWIN.
All of these can be downloaded/updated through menu Tools ? Library package manager ? Manage NuGet Packages for Solution....
If you don't yet have NuGet, follow this tutorial:
For Angular 1.3+ (credits to @Tom)
Use an alias expression (Docs: Angular 1.3.0: ngRepeat, scroll down to the Arguments section):
<div ng-repeat="person in data | filter:query as filtered">
</div>
For Angular prior to 1.3
Assign the results to a new variable (e.g. filtered
) and access it:
<div ng-repeat="person in filtered = (data | filter: query)">
</div>
Display the number of results:
Showing {{filtered.length}} Persons
Fiddle a similar example. Credits go to Pawel Kozlowski
Bit of a long shot, but on a lab a while back, we had a situation where a SQL Server appeared unresponsive, not because we had spiked the CPU or anything we could track within SQL Server, it appeared operational to all tests but connections failed under some load.
The issue turned out to be due to the volume of traffic against the server meant we were triggering the in built windows Syn Attack Flood Protection within Windows. Annoyingly when you hit this, there is no logged message within windows server, or within SQL - you only see the symtpoms which are connections failing to be made - this is because windows slows down on accepting the messages and let's a queue build. From the connection standpoint, the server appears to not respond when it should (it doesn't even acknowledge the message arrived)
http://msdn.microsoft.com/en-us/library/ee377084(v=bts.10).aspx
Scroll down to SynAttackProtect and you will see the default in windows server 2003 sp1 onwards was to enable this feature by default. It is a DDOS protection mechanism in effect, and the lack of logging that it is triggering makes it incredibly difficult to detect when your server does this.
It took 3 days within the MS lab before it was figured out.
You mentioned 100 conenctions, we had an app that constantly connected, ran queries and then disconnected, it did not hold the connections open. This meant that we had multiple threads on each machine connectiong doing this, 10 machines, multiple threads per machine, and it was considered enough different connections consistently being made / dropped to trigger the defense.
Whether you are at that level (since it is not a clearly defined threshold by MS) is hard to say.
GitHub doesn't support pushing over the Git protocol, which is indicated by your use of the URL beginning git://
. As the error message says, if you want to push, you should use either the SSH URL [email protected]:my_user_name/my_repo.git
or the "smart HTTP" protocol by using the https://
URL that GitHub shows you for your repository.
(Update: to my surprise, some people apparently thought that by this I was suggesting that "https" means "smart HTTP", which I wasn't. Git used to have a "dumb HTTP" protocol which didn't allow pushing before the "smart HTTP" that GitHub uses was introduced - either could be used over either http
or https
. The differences between the transfer protocols used by Git are explained in the link below.)
If you want to change the URL of origin, you can just do:
git remote set-url origin [email protected]:my_user_name/my_repo.git
or
git remote set-url origin https://github.com/my_user_name/my_repo.git
More information is available in 10.6 Git Internals - Transfer Protocols.
Since a lot of programmers were overwhelmed with the [DataContract]
and [DataMember]
attributes, with .NET 3.5 SP1, Microsoft made the data contract serializer handle all classes - even without any of those attributes - much like the old XML serializer.
So as of .NET 3.5 SP1, you don't have to add data contract or data member attributes anymore - if you don't then the data contract serializer will serialize all public properties on your class, just like the XML serializer would.
HOWEVER: by not adding those attributes, you lose a lot of useful capabilities:
[DataContract]
, you cannot define an XML namespace for your data to live in[DataMember]
, you cannot serialize non-public properties or fields[DataMember]
, you cannot define an order of serialization (Order=
) and the DCS will serialize all properties alphabetically[DataMember]
, you cannot define a different name for your property (Name=
)[DataMember]
, you cannot define things like IsRequired=
or other useful attributes[DataMember]
, you cannot leave out certain public properties - all public properties will be serialized by the DCSSo for a "quick'n'dirty" solution, leaving away the [DataContract]
and [DataMember]
attributes will work - but it's still a good idea to have them on your data classes - just to be more explicit about what you're doing, and to give yourself access to all those additional features that you don't get without them...
This happened to me when I have multiple angular modules in the same page
I encountered this error when I used partial views
One partial view had
<script src="~/Scripts/Items.js"></script>
<div ng-app="SearchModule">
<div ng-controller="SearchSomething" class="col-md-1">
<input class="searchClass" type="text" placeholder="Search" />
</div>
</div>
Other had
<div ng-app="FeaturedItems" ng-controller="featured">
<ul>
<li ng-repeat="item in Items">{{item.Name}}</li>
</ul>
</div>
I had them in same module with different controller and it started working
Actually, I believe you want to use the __getattr__
special method instead.
Quote from the Python docs:
__getattr__( self, name)
Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.
Note that if the attribute is found through the normal mechanism,__getattr__()
is not called. (This is an intentional asymmetry between__getattr__()
and__setattr__()
.) This is done both for efficiency reasons and because otherwise__setattr__()
would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the__getattribute__()
method below for a way to actually get total control in new-style classes.
Note: for this to work, the instance should not have a test
attribute, so the line self.test=20
should be removed.
With reference to man ssh-keygen
, the length of a DSA key is restricted to exactly 1024 bit to remain compliant with NIST's FIPS 186-2. Nonetheless, longer DSA keys are theoretically possible; FIPS 186-3 explicitly allows them. Furthermore, security is no longer guaranteed with 1024 bit long RSA or DSA keys.
In conclusion, a 2048 bit RSA key is currently the best choice.
Establishing a secure SSH connection entails more than selecting safe encryption key pair technology. In view of Edward Snowden's NSA revelations, one has to be even more vigilant than what previously was deemed sufficient.
To name just one example, using a safe key exchange algorithm is equally important. Here is a nice overview of current best SSH hardening practices.
I use JuJu which basically allows to have a really tiny linux distribution (containing just the package manager) inside your $HOME/.juju directory.
It allows to have your custom system inside the home directory accessible via proot and, therefore, you can install any packages without root privileges. It will run properly to all the major linux distributions, the only limitation is that JuJu can run on linux kernel with minimum reccomended version 2.6.32.
For instance, after installed JuJu to install pip just type the following:
$>juju -f
(juju)$> pacman -S python-pip
(juju)> pip
This will work on 5 sec.
5000 milliseconds = 5 seconds
Use this with target _self
or what ever you want and what ever page you want including itself:
<script type="text/javascript">
function load()
{
setTimeout("window.open('http://YourPage.com', '_self');", 5000);
}
</script>
<body onload="load()">
Or this with automatic self and no target code with what ever page you want, including itself:
<script type="text/javascript">
function load()
{
setTimeout("location.href = 'http://YourPage.com';", 5000);
}
</script>
<body onload="load()">
Or this if it is the same page to reload itself only and targeted tow hat ever you want:
<script type="text/javascript">
function load()
{
setTimeout("window.open(self.location, '_self');", 5000);
}
</script>
<body onload="load()">
All 3 do similar things, just in different ways.
In Java 7:
String folderPath = "C:/folderOfMyFile";
Path path = Paths.get(folderPath, "myFileName.csv"); //or any text file eg.: txt, bat, etc
Charset charset = Charset.forName("UTF-8");
try (BufferedReader reader = Files.newBufferedReader(path , charset)) {
while ((line = reader.readLine()) != null ) {
//separate all csv fields into string array
String[] lineVariables = line.split(",");
}
} catch (IOException e) {
System.err.println(e);
}
Update 2016-05-27
As of React v15, support for SVG in React is (close to?) 100% parity with current browser support for SVG (source). You just need to apply some syntax transformations to make it JSX compatible, like you already have to do for HTML (class
? className
, style="color: purple"
? style={{color: 'purple'}}
). For any namespaced (colon-separated) attribute, e.g. xlink:href
, remove the :
and capitalize the second part of the attribute, e.g. xlinkHref
. Here’s an example of an svg with <defs>
, <use>
, and inline styles:
function SvgWithXlink (props) {
return (
<svg
width="100%"
height="100%"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
>
<style>
{ `.classA { fill:${props.fill} }` }
</style>
<defs>
<g id="Port">
<circle style={{fill:'inherit'}} r="10"/>
</g>
</defs>
<text y="15">black</text>
<use x="70" y="10" xlinkHref="#Port" />
<text y="35">{ props.fill }</text>
<use x="70" y="30" xlinkHref="#Port" className="classA"/>
<text y="55">blue</text>
<use x="0" y="50" xlinkHref="#Port" style={{fill:'blue'}}/>
</svg>
);
}
For more details on specific support, check the docs’ list of supported SVG attributes. And here’s the (now closed) GitHub issue that tracked support for namespaced SVG attributes.
Previous answer
You can do a simple SVG embed without having to use dangerouslySetInnerHTML
by just stripping the namespace attributes. For example, this works:
render: function() {
return (
<svg viewBox="0 0 120 120">
<circle cx="60" cy="60" r="50"/>
</svg>
);
}
At which point you can think about adding props like fill
, or whatever else might be useful to configure.
Visibility change itself can be easy animated by overriding setVisibility method. Look at complete code:
public class SimpleViewAnimator extends FrameLayout
{
private Animation inAnimation;
private Animation outAnimation;
public SimpleViewAnimator(Context context)
{
super(context);
}
public void setInAnimation(Animation inAnimation)
{
this.inAnimation = inAnimation;
}
public void setOutAnimation(Animation outAnimation)
{
this.outAnimation = outAnimation;
}
@Override
public void setVisibility(int visibility)
{
if (getVisibility() != visibility)
{
if (visibility == VISIBLE)
{
if (inAnimation != null) startAnimation(inAnimation);
}
else if ((visibility == INVISIBLE) || (visibility == GONE))
{
if (outAnimation != null) startAnimation(outAnimation);
}
}
super.setVisibility(visibility);
}
}
The LogManager
class determines which log4j config to use in a static block which runs when the class is loaded. There are three options intended for end-users:
log4j.defaultInitOverride
to false, it will not configure log4j at all.Specify the path to the configuration file manually yourself and override the classpath search. You can specify the location of the configuration file directly by using the following argument to java
:
-Dlog4j.configuration=<path to properties file>
in your test runner configuration.
Allow log4j to scan the classpath for a log4j config file during your test. (the default)
See also the online documentation.
If the above solution does not work for you it is may be possible to obtain the same result with the following pure nodejs code. The above did not work for me and resulted in a compilation exception when running 'npm install iconv' on OSX:
npm install iconv
npm WARN package.json [email protected] No README.md file found!
npm http GET https://registry.npmjs.org/iconv
npm http 200 https://registry.npmjs.org/iconv
npm http GET https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
npm http 200 https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
> [email protected] install /Users/markboyd/git/portal/app/node_modules/iconv
> node-gyp rebuild
gyp http GET http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
gyp http 200 http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
xcode-select: Error: No Xcode is selected. Use xcode-select -switch <path-to-xcode>, or see the xcode-select manpage (man xcode-select) for further information.
fs.readFileSync() returns a Buffer if no encoding is specified. And Buffer has a toString() method that will convert to UTF8 if no encoding is specified giving you the file's contents. See the nodejs documentation. This worked for me.
Notice that this doesn't work in Windows.
The module pxssh does exactly what you want:
For example, to run 'ls -l' and to print the output, you need to do something like that :
from pexpect import pxssh
s = pxssh.pxssh()
if not s.login ('localhost', 'myusername', 'mypassword'):
print "SSH session failed on login."
print str(s)
else:
print "SSH session login successful"
s.sendline ('ls -l')
s.prompt() # match the prompt
print s.before # print everything before the prompt.
s.logout()
Some links :
Pxssh docs : http://dsnra.jpl.nasa.gov/software/Python/site-packages/Contrib/pxssh.html
Pexpect (pxssh is based on pexpect) : http://pexpect.readthedocs.io/en/stable/
Use jdbc url
as :
jdbc:mysql://localhost:3306/Database_dbName?allowPublicKeyRetrieval=true&useSSL=false;
PortNo: 3306
can be different in your configuation
Use the range's NumberFormat
property to force the format of the range like this:
Sheet1.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
Hello guys I am stucked with this. I've a Document Profile who has a reference to User,and I've tried to list the profiles where user ref is not null (because I already filtered by rol during the population), but after googleing a few hours I cannot figure out how to get this. I have this query:
const profiles = await Profile.find({ user: {$exists: true, $ne: null }}) .select("-gallery") .sort( {_id: -1} ) .skip( skip ) .limit(10) .select(exclude) .populate({ path: 'user', match: { role: {$eq: customer}}, select: '-password -verified -_id -__v' }) .exec(); And I get this result, how can I remove from the results the user:null colletions? . I meant, I dont want to get the profile when user is null (the role does not match). { "code": 200, "profiles": [ { "description": null, "province": "West Midlands", "country": "UK", "postal_code": "83000", "user": null }, { "description": null, "province": "Madrid", "country": "Spain", "postal_code": "43000", "user": { "role": "customer", "name": "pedrita", "email": "[email protected]", "created_at": "2020-06-05T11:05:36.450Z" } } ], "page": 1 }
Thanks in advance.
In [39]: df
Out[39]:
index a b c
0 1 2 3 4
1 2 3 4 5
In [40]: df1 = df[['b', 'c']]
In [41]: df1
Out[41]:
b c
0 3 4
1 4 5
The problem is you are not in the correct directory. A simple fix in Jupyter is to do the following command:
Here is an example command to use in Jupyter:
%%bash
cd /home/ec2-user/ml_volume/GitHub_BMM
git show
Note you need to do the commands in the same cell.
For those who use java/android and struggle with this matter try:
"^\\p{L}+[\\p{L}\\p{Z}\\p{P}]{0,}"
This works with names like
I had the same error and could not figure it out with the other answers. I found that we can "Consolidate" NuGet packages.
Check this out : http://codepen.io/Rowno/pen/Afykb
.carousel-fade {
.carousel-inner {
.item {
opacity: 0;
transition-property: opacity;
}
.active {
opacity: 1;
}
.active.left,
.active.right {
left: 0;
opacity: 0;
z-index: 1;
}
.next.left,
.prev.right {
opacity: 1;
}
}
Works marvellously, I hope it works
Some answers already pointed out background-size: cover
is useful in the case, but none points out the browser support details. Here it is:
Add this CSS into your stylesheet:
body {
background: url(background.jpg) no-repeat center center fixed;
background-size: cover; /* for IE9+, Safari 4.1+, Chrome 3.0+, Firefox 3.6+ */
-webkit-background-size: cover; /* for Safari 3.0 - 4.0 , Chrome 1.0 - 3.0 */
-moz-background-size: cover; /* optional for Firefox 3.6 */
-o-background-size: cover; /* for Opera 9.5 */
margin: 0; /* to remove the default white margin of body */
padding: 0; /* to remove the default white margin of body */
}
-moz-background-size: cover;
is optional for Firefox, as Firefox starts supporting the value cover
since version 3.6. If you need to support Konqueror 3.5.4+ as well, add -khtml-background-size: cover;
.
As you're using CSS3, it's suggested to change your DOCTYPE to HTML5. Also, HTML5 CSS Reset stylesheet is suggested to be added BEFORE your our stylesheet to provide a consistent look & feel for modern browsers.
Reference: background-size at MDN
If you ever need to support old browsers like IE 8 or below, you can still go for Javascript way (scroll down to jQuery section)
Last, if you predict your users will use mobile phones to browse your website, do not use the same background image for mobile web, as your desktop image is probably large in file size, which will be a burden to mobile network usage. Use media query to branch CSS.
For my part I had enabled ufw
but I forgot to expose my upstreams ports ._.
function genPass(){
//https://sita.app/password-generator
let stringInclude = '';
stringInclude += "!\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~";
stringInclude += '0123456789';
stringInclude += 'abcdefghijklmnopqrstuvwxyz';
stringInclude += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var password ='';
for (let i = 0; i < 40; i++) {
password += stringInclude.charAt(Math.floor(Math.random() * stringInclude.length));
}
return password;
}
Do use NULL. It is just #defined as 0 anyway and it is very useful to semantically distinguish it from the integer 0.
There are problems with using 0 (and hence NULL). For example:
void f(int);
void f(void*);
f(0); // Ambiguous. Calls f(int).
The next version of C++ (C++0x) includes nullptr
to fix this.
f(nullptr); // Calls f(void*).
lets say all your static assets are in a folder "static" at the root level and you want copy them to the build folder maintaining the structure of subfolder, then in your entry file) just put
//index.js or index.jsx
require.context("!!file?name=[path][name].[ext]&context=./static!../static/", true, /^\.\/.*\.*/);
This issue started surfacing on my terminal after I enabled GitHub 2FA.
Now, I face this issue whenever I clone a private repository. This error:
remote: Repository not found.
fatal: repository 'https://github.com/kmario23/repo-name.git/' not found
is so awkward. Of course, I have this repo and I'm the owner of it.
Anyway, it seems the fix is now that we have to enter the GitHub username
one more time when cloning a private repo. Below is an example:
add your username
|-------|
$ git clone --recursive https://[email protected]/kmario23/repo-name.git
In php 7 you can do:
$_POST['value'] ?? null;
If value is equal to '' as said in other answers it will also send you null.
Both of these classes are smart pointers, which means that they automatically (in most cases) will deallocate the object that they point at when that object can no longer be referenced. The difference between the two is how many different pointers of each type can refer to a resource.
When using unique_ptr
, there can be at most one unique_ptr
pointing at any one resource. When that unique_ptr
is destroyed, the resource is automatically reclaimed. Because there can only be one unique_ptr
to any resource, any attempt to make a copy of a unique_ptr
will cause a compile-time error. For example, this code is illegal:
unique_ptr<T> myPtr(new T); // Okay
unique_ptr<T> myOtherPtr = myPtr; // Error: Can't copy unique_ptr
However, unique_ptr
can be moved using the new move semantics:
unique_ptr<T> myPtr(new T); // Okay
unique_ptr<T> myOtherPtr = std::move(myPtr); // Okay, resource now stored in myOtherPtr
Similarly, you can do something like this:
unique_ptr<T> MyFunction() {
unique_ptr<T> myPtr(/* ... */);
/* ... */
return myPtr;
}
This idiom means "I'm returning a managed resource to you. If you don't explicitly capture the return value, then the resource will be cleaned up. If you do, then you now have exclusive ownership of that resource." In this way, you can think of unique_ptr
as a safer, better replacement for auto_ptr
.
shared_ptr
, on the other hand, allows for multiple pointers to point at a given resource. When the very last shared_ptr
to a resource is destroyed, the resource will be deallocated. For example, this code is perfectly legal:
shared_ptr<T> myPtr(new T); // Okay
shared_ptr<T> myOtherPtr = myPtr; // Sure! Now have two pointers to the resource.
Internally, shared_ptr
uses reference counting to track how many pointers refer to a resource, so you need to be careful not to introduce any reference cycles.
In short:
unique_ptr
when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed.shared_ptr
when you want multiple pointers to the same resource.Hope this helps!
.*[^a]$
the regex above will match strings which is not ending with a
.
echo -e "open <ftp.hostname>\nuser <username> <password>\nbinary\nmkdir New_Folder\nquit"|ftp -nv
Try that:
var defaultEmailNews = "Email address";
$('input[name=email]').focus(function() {
if($(this).val() == defaultEmailNews) $(this).val("");
});
$('input[name=email]').focusout(function() {
if($(this).val() == "") $(this).val(defaultEmailNews);
});
Here is code you can directly copy paste :
String imageName = "picture1.jpg";
String [] imageNameArray = imageName.split("\\.");
for(int i =0; i< imageNameArray.length ; i++)
{
system.out.println(imageNameArray[i]);
}
And what if mistakenly there are spaces left before or after "." in such cases? It's always best practice to consider those spaces also.
String imageName = "picture1 . jpg";
String [] imageNameArray = imageName.split("\\s*.\\s*");
for(int i =0; i< imageNameArray.length ; i++)
{
system.out.println(imageNameArray[i]);
}
Here, \\s* is there to consider the spaces and give you only required splitted strings.
Here is my solution for maintaining an 16:9 aspect ratio in portrait or landscape on a div with optional fixed margins.
It's a combination of width/height and max-width/max-height properties with vw units.
In this sample, 50px top and bottom margins are added on hover.
html {
height: 100%;
}
body {
margin: 0;
height: 100%;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.fixedRatio {
max-width: 100vw;
max-height: calc(9 / 16 * 100vw);
width: calc(16 / 9 * 100vh);
height: 100vh;
/* DEBUG */
display: flex;
justify-content: center;
align-items: center;
background-color: blue;
font-size: 2rem;
font-family: 'Arial';
color: white;
transition: width 0.5s ease-in-out, height 0.5s ease-in-out;
}
.fixedRatio:hover {
width: calc(16 / 9 * (100vh - 100px));
height: calc(100vh - 100px);
}
_x000D_
<div class='container'>
<div class='fixedRatio'>
16:9
</div>
</div>
_x000D_
Use the ALTER DATABASE
and ALTER TABLE
commands.
ALTER DATABASE databasename CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Or if you're still on MySQL 5.5.2 or older which didn't support 4-byte UTF-8, use utf8
instead of utf8mb4
:
ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
Eclipse is looking for eclipse projects, meaning its is searching for eclipse-specific files in the root directory, namely .project
and .classpath
. You either gave Eclipse the wrong directory (if you are importing a eclipse project) or you actually want to create a new project from existing source(new
->java project
->create project from existing source
).
I think you probably want the second one, because Eclipse projects usually have separate source & build directories. If your sources and .class files are in the same directory, you probably didn't have a eclipse project.
Apart from the possible solutions in other answers, it is also possible that somehow Maven dependency corruption has occurred on your machine. I was facing the same error on trying to run my (Web) Spring boot application, and it got resolved by running the following -
mvn dependency:purge-local-repository -DreResolve=true
followed by
mvn package
I came onto this solution looking into another issue where Eclipse wouldn't let me run the main application class from the IDE, due to a different error, similar to one on this SO thread -> The type org.springframework.context.ConfigurableApplicationContext cannot be resolved. It is indirectly referenced from required .class files
Definition:
JOINS are way to query the data that combined together from multiple tables simultaneously.
Concern to RDBMS there are 5-types of joins:
Equi-Join: Combines common records from two tables based on equality condition. Technically, Join made by using equality-operator (=) to compare values of Primary Key of one table and Foreign Key values of another table, hence result set includes common(matched) records from both tables. For implementation see INNER-JOIN.
Natural-Join: It is enhanced version of Equi-Join, in which SELECT operation omits duplicate column. For implementation see INNER-JOIN
Non-Equi-Join: It is reverse of Equi-join where joining condition is uses other than equal operator(=) e.g, !=, <=, >=, >, < or BETWEEN etc. For implementation see INNER-JOIN.
Self-Join:: A customized behavior of join where a table combined with itself; This is typically needed for querying self-referencing tables (or Unary relationship entity). For implementation see INNER-JOINs.
Cartesian Product: It cross combines all records of both tables without any condition. Technically, it returns the result set of a query without WHERE-Clause.
As per SQL concern and advancement, there are 3-types of joins and all RDBMS joins can be achieved using these types of joins.
INNER-JOIN: It merges(or combines) matched rows from two tables. The matching is done based on common columns of tables and their comparing operation. If equality based condition then: EQUI-JOIN performed, otherwise Non-EQUI-Join.
OUTER-JOIN: It merges(or combines) matched rows from two tables and unmatched rows with NULL values. However, can customized selection of un-matched rows e.g, selecting unmatched row from first table or second table by sub-types: LEFT OUTER JOIN and RIGHT OUTER JOIN.
2.1. LEFT Outer JOIN (a.k.a, LEFT-JOIN): Returns matched rows from two tables and unmatched from the LEFT table(i.e, first table) only.
2.2. RIGHT Outer JOIN (a.k.a, RIGHT-JOIN): Returns matched rows from two tables and unmatched from the RIGHT table only.
2.3. FULL OUTER JOIN (a.k.a OUTER JOIN): Returns matched and unmatched from both tables.
CROSS-JOIN: This join does not merges/combines instead it performs Cartesian product.
Note: Self-JOIN can be achieved by either INNER-JOIN, OUTER-JOIN and CROSS-JOIN based on requirement but the table must join with itself.
1.1: INNER-JOIN: Equi-join implementation
SELECT *
FROM Table1 A
INNER JOIN Table2 B ON A.<Primary-Key> =B.<Foreign-Key>;
1.2: INNER-JOIN: Natural-JOIN implementation
Select A.*, B.Col1, B.Col2 --But no B.ForeignKeyColumn in Select
FROM Table1 A
INNER JOIN Table2 B On A.Pk = B.Fk;
1.3: INNER-JOIN with NON-Equi-join implementation
Select *
FROM Table1 A INNER JOIN Table2 B On A.Pk <= B.Fk;
1.4: INNER-JOIN with SELF-JOIN
Select *
FROM Table1 A1 INNER JOIN Table1 A2 On A1.Pk = A2.Fk;
2.1: OUTER JOIN (full outer join)
Select *
FROM Table1 A FULL OUTER JOIN Table2 B On A.Pk = B.Fk;
2.2: LEFT JOIN
Select *
FROM Table1 A LEFT OUTER JOIN Table2 B On A.Pk = B.Fk;
2.3: RIGHT JOIN
Select *
FROM Table1 A RIGHT OUTER JOIN Table2 B On A.Pk = B.Fk;
3.1: CROSS JOIN
Select *
FROM TableA CROSS JOIN TableB;
3.2: CROSS JOIN-Self JOIN
Select *
FROM Table1 A1 CROSS JOIN Table1 A2;
//OR//
Select *
FROM Table1 A1,Table1 A2;
Use a Queue
Queue<String> qe=new LinkedList<String>();
qe.add("a");
qe.add("b");
qe.add("c");
qe.add("d");
System.out.println(qe.poll()); //returns a
System.out.println(qe.poll()); //returns b
System.out.println(qe.poll()); //returns c
System.out.println(qe.poll()); //returns d
There's five simple methods of a Queue
element() -- Retrieves, but does not remove, the head of this queue.
offer(E o) -- Inserts the specified element into this queue, if
possible.
peek() -- Retrieves, but does not remove, the head of this queue, returning null if this queue is empty.
poll() -- Retrieves and removes the head of this queue, or null if this queue is empty.
It should be exclude module: 'net.milkbowl:vault:1.2.27'
(add module:
) as explained in documentation for DependencyHandler
linked from http://www.gradle.org/docs/current/javadoc/org/gradle/api/Project.html#dependencies(groovy.lang.Closure) because ModuleDependency.exclude(java.util.Map)
method is used.
Everything else ie. Params, Authorization, Body, Pre-request Script, Tests is empty, just open the Headers tab and add as shown in image. Its the same for GET request as well.
FIXNUM_MAX = (2**(0.size * 8 -2) -1)
FIXNUM_MIN = -(2**(0.size * 8 -2))
In addition to the answers above, you can check the type of object using type(plt.subplots())
which returns a tuple, on the other hand, type(plt.subplot())
returns matplotlib.axes._subplots.AxesSubplot
which you can't unpack.
Easy way
from IPython.display import Image
Image(filename ="Covid.jpg" size )
<html>
<head>
<title>Date picker works for all browsers(IE, Firefox, Chrome)</title>
<script>
var datefield = document.createElement("input")
datefield.setAttribute("type", "date")
if (datefield.type != "date") { // if browser doesn't support input type="date", load files for jQuery UI Date Picker
document.write('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"><\/script>\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"><\/script>\n')
}
</script>
<script>
if (datefield.type != "date") { // if browser doesn't support input type="date", initialize date picker widget:
jQuery(function($) { // on document.ready
$('#start_date').datepicker({
dateFormat: 'yy-mm-dd'
});
$('#end_date').datepicker({
dateFormat: 'yy-mm-dd'
});
})
}
</script>
</head>
<body>
<input name="start_date" id="start_date" type="date" required>
<input name="end_date" id="end_date" required>
</body>
</html>
The target. dot works on objects; arrow works on pointers to objects.
std::string str("foo");
std::string * pstr = new std::string("foo");
str.size ();
pstr->size ();
Just add overflow:auto; to parent div
<div style="width: 100%;overflow:auto;">
<div style="float:left; width: 80%">
</div>
<div style="float:right;">
</div>
</div>
I tried the example here of the Mvc Controls Toolkit grid. It appears a quite powerful and easy to use grid. The tutorial not only explain how to use the grid but also how to do paging, organize a view model and data annotations. It is worth to read it.
Logically, Cody's answer should work. However I don't think the command prompt handles a code block logically. For the life of me I can't get that to work properly with any more than a single command within the block. In my case, extensive testing revealed that all of the commands within the block are being cached, and executed simultaneously at the end of the block. This of course doesn't yield the expected results. Here is an oversimplified example:
if %ERRORLEVEL%==0 (
set var1=blue
set var2=cheese
set var3=%var1%_%var2%
)
This should provide var3 with the following value:
blue_cheese
but instead yields:
_
because all 3 commands are cached and executed simultaneously upon exiting the code block.
I was able to overcome this problem by re-writing the if block to only execute one command - goto - and adding a few labels. Its clunky, and I don't much like it, but at least it works.
if %ERRORLEVEL%==0 goto :error0
goto :endif
:error0
set var1=blue
set var2=cheese
set var3=%var1%_%var2%
:endif
I don't see any problem, unless you are not managing them using a connection pool.
If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.
I have checked the links in Gumbo's answer, and I wanted to paste some part of those things here to exist on Stack Overflow as well.
"...Some people are under the misconception that Unicode is simply a 16-bit code where each character takes 16 bits and therefore there are 65,536 possible characters. This is not, actually, correct. It is the single most common myth about Unicode, so if you thought that, don't feel bad.
In fact, Unicode has a different way of thinking about characters, and you have to understand the Unicode way of thinking of things or nothing will make sense.
Until now, we've assumed that a letter maps to some bits which you can store on disk or in memory:
A -> 0100 0001
In Unicode, a letter maps to something called a code point which is still just a theoretical concept. How that code point is represented in memory or on disk is a whole other story..."
"...Every platonic letter in every alphabet is assigned a magic number by the Unicode consortium which is written like this: U+0639. This magic number is called a code point. The U+ means "Unicode" and the numbers are hexadecimal. U+0639 is the Arabic letter Ain. The English letter A would be U+0041...."
"...OK, so say we have a string:
Hello
which, in Unicode, corresponds to these five code points:
U+0048 U+0065 U+006C U+006C U+006F.
Just a bunch of code points. Numbers, really. We haven't yet said anything about how to store this in memory or represent it in an email message..."
"...That's where encodings come in.
The earliest idea for Unicode encoding, which led to the myth about the two bytes, was, hey, let's just store those numbers in two bytes each. So Hello becomes
00 48 00 65 00 6C 00 6C 00 6F
Right? Not so fast! Couldn't it also be:
48 00 65 00 6C 00 6C 00 6F 00 ? ..."
As explained in other answers, context
is the this
context to be used inside callback passed to each
.
I'll explain this with the help of source code of relevant methods from underscore source code
The definition of _.each
or _.forEach
is as follows:
_.each = _.forEach = function(obj, iteratee, context) {
iteratee = optimizeCb(iteratee, context);
var i, length;
if (isArrayLike(obj)) {
for (i = 0, length = obj.length; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
Second statement is important to note here
iteratee = optimizeCb(iteratee, context);
Here, context
is passed to another method optimizeCb
and the returned function from it is then assigned to iteratee
which is called later.
var optimizeCb = function(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1:
return function(value) {
return func.call(context, value);
};
case 2:
return function(value, other) {
return func.call(context, value, other);
};
case 3:
return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4:
return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};
As can be seen from the above method definition of optimizeCb
, if context
is not passed then func
is returned as it is. If context
is passed, callback function is called as
func.call(context, other_parameters);
^^^^^^^
func
is called with call()
which is used to invoke a method by setting this
context of it. So, when this
is used inside func
, it'll refer to context
.
// Without `context`_x000D_
_.each([1], function() {_x000D_
console.log(this instanceof Window);_x000D_
});_x000D_
_x000D_
_x000D_
// With `context` as `arr`_x000D_
var arr = [1, 2, 3];_x000D_
_.each([1], function() {_x000D_
console.log(this);_x000D_
}, arr);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
You can consider context
as the last optional parameter to forEach
in JavaScript.
In our case didn't work because our production server has missing
Microsoft Visual C++ 2010 SP1 Redistributable Package (x86)
We installed it and all work fine. The Application Pool must have Enable 32-bit Applications set to true and you must the x86 version of the library
Use String.Format with alignment values.
For example:
String.Format("|{0,5}|{1,5}|{2,5}|{3,5}|", arg0, arg1, arg2, arg3);
To create one formatted row.
The other answer didn't work for me (on Windows 7). But this worked:
telnet localhost 5554
kill
A pretty simple solution is to check for the screen width. Since almost all mobile devices have a max screen width of 480px (at present), it's pretty reliable:
if( screen.width <= 480 ) {
location.href = '/mobile.html';
}
The user-agent string is also a place to look. However, the former solution is still better since even if some freaking device does not respond correctly for the user-agent, the screen width doesn't lie.
The only exception here are tablet pc's like the ipad. Those devices have a higher screen width than smartphones and I would probably go with the user-agent-string for those.
var map = new google.maps.Map(document.getElementById('map_canvas'), {_x000D_
zoom: 10,_x000D_
center: new google.maps.LatLng(13.103, 80.274),_x000D_
mapTypeId: google.maps.MapTypeId.ROADMAP_x000D_
});_x000D_
_x000D_
var myMarker = new google.maps.Marker({_x000D_
position: new google.maps.LatLng(18.103, 80.274),_x000D_
draggable: true_x000D_
});_x000D_
_x000D_
google.maps.event.addListener(myMarker, 'dragend', function(evt) {_x000D_
document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';_x000D_
});_x000D_
google.maps.event.addListener(myMarker, 'dragstart', function(evt) {_x000D_
document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';_x000D_
});_x000D_
map.setCenter(myMarker.position);_x000D_
myMarker.setMap(map);_x000D_
_x000D_
function getLocation() {_x000D_
if (navigator.geolocation) {_x000D_
navigator.geolocation.getCurrentPosition(showPosition);_x000D_
} else {_x000D_
x.innerHTML = "Geolocation is not supported by this browser.";_x000D_
}_x000D_
}_x000D_
_x000D_
function showPosition(position) {_x000D_
document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + position.coords.latitude + ' Current Lng: ' + position.coords.longitude + '</p>';_x000D_
var myMarker = new google.maps.Marker({_x000D_
position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),_x000D_
draggable: true_x000D_
});_x000D_
google.maps.event.addListener(myMarker, 'dragend', function(evt) {_x000D_
document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';_x000D_
});_x000D_
google.maps.event.addListener(myMarker, 'dragstart', function(evt) {_x000D_
document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';_x000D_
});_x000D_
map.setCenter(myMarker.position);_x000D_
myMarker.setMap(map);_x000D_
}_x000D_
getLocation();
_x000D_
#map_canvas {_x000D_
width: 980px;_x000D_
height: 500px;_x000D_
}_x000D_
_x000D_
#current {_x000D_
padding-top: 25px;_x000D_
}
_x000D_
<script src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<section>_x000D_
<div id='map_canvas'></div>_x000D_
<div id="current">_x000D_
<p>Marker dropped: Current Lat:18.103 Current Lng:80.274</p>_x000D_
</div>_x000D_
</section>_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
I think we will have to wait a couple of years more to see more progress. However, there are now more frameworks and tools available:
Here a list of 5 options:
The basic idea here is to force a resync of the database Intellisense is using.
If the reference is to a project within your solution. Remove the project. Then add the reference using browse option from the exact path of the project you just removed. Do a quick build and check to ensure reference is picked up correctly. Now add the old project back to the solution and remove the old reference and add it as part of the solution.
This idea of forcing the resync of the database could also be done in other ways too. For example by using an absolute folder path.
Your issue is with attempting to change your month by adding 1. 1 in date serials in Excel is equal to 1 day. Try changing your month by using the following:
NewDate = Format(DateAdd("m",1,StartDate),"dd/mm/yyyy")
Using C++11
there is a nice version for a manually defined byte type:
enum class byte : std::uint8_t {};
That's at least what the GSL does.
Starting with C++17
(almost) this very version is defined in the standard as std::byte
(thanks Neil Macintosh for both).
flag = 0
requiredCals =12
from itertools import chain, combinations
def powerset(iterable):
s = list(iterable) # allows duplicate elements
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
stuff = [2,9,5,1,6]
for i, combo in enumerate(powerset(stuff), 1):
if(len(combo)>0):
#print(combo , sum(combo))
if(sum(combo)== requiredCals):
flag = 1
break
if(flag==1):
print('True')
else:
print('else')
I know the answer is quite late, but the best way to get rid of milliseconds is
var currentDateTime = DateTime.Now.ToString("s");
Try printing the value of the variable, it will show the date time, without milliseconds.
Below code helped my object to be refreshed with fresh database values. The Entry(object).Reload() command forces the object to recall database values
GM_MEMBERS member = DatabaseObjectContext.GM_MEMBERS.FirstOrDefault(p => p.Username == username && p.ApplicationName == this.ApplicationName);
DatabaseObjectContext.Entry(member).Reload();
This will do it:
window.history.pushState(null,null,'https://www.google.com');
You can overload the method with different parameters:
public int doSomething(int arg1, int arg2)
{
//some logic here
return 0;
}
public int doSomething(
{
doSomething(0,0)
}
There are two solutions to fix this:
clear:both
after the last floated tag. This works good.overflow: hidden
I have a suspicion that you either copy/pasted a part of your Haml template into the file, or you're working with a non-Unicode/non-UTF-8 friendly editor.
See if you can recreate that file from the scratch in a UTF-8 friendly editor. There are plenty for any platform and see whether this fixes your problem. Start by erasing the line with #content
and retyping it manually.
You can simply use DataFrame.fillna
to fill the nan
's directly:
In [27]: df
Out[27]:
A B C
0 -0.166919 0.979728 -0.632955
1 -0.297953 -0.912674 -1.365463
2 -0.120211 -0.540679 -0.680481
3 NaN -2.027325 1.533582
4 NaN NaN 0.461821
5 -0.788073 NaN NaN
6 -0.916080 -0.612343 NaN
7 -0.887858 1.033826 NaN
8 1.948430 1.025011 -2.982224
9 0.019698 -0.795876 -0.046431
In [28]: df.mean()
Out[28]:
A -0.151121
B -0.231291
C -0.530307
dtype: float64
In [29]: df.fillna(df.mean())
Out[29]:
A B C
0 -0.166919 0.979728 -0.632955
1 -0.297953 -0.912674 -1.365463
2 -0.120211 -0.540679 -0.680481
3 -0.151121 -2.027325 1.533582
4 -0.151121 -0.231291 0.461821
5 -0.788073 -0.231291 -0.530307
6 -0.916080 -0.612343 -0.530307
7 -0.887858 1.033826 -0.530307
8 1.948430 1.025011 -2.982224
9 0.019698 -0.795876 -0.046431
The docstring of fillna
says that value
should be a scalar or a dict, however, it seems to work with a Series
as well. If you want to pass a dict, you could use df.mean().to_dict()
.
Utilities.sleep(milliseconds) creates a 'pause' in program execution, meaning it does nothing during the number of milliseconds you ask. It surely slows down your whole process and you shouldn't use it between function calls. There are a few exceptions though, at least that one that I know : in SpreadsheetApp when you want to remove a number of sheets you can add a few hundreds of millisecs between each deletion to allow for normal script execution (but this is a workaround for a known issue with this specific method). I did have to use it also when creating many sheets in a spreadsheet to avoid the Browser needing to be 'refreshed' after execution.
Here is an example :
function delsheets(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var numbofsheet=ss.getNumSheets();// check how many sheets in the spreadsheet
for (pa=numbofsheet-1;pa>0;--pa){
ss.setActiveSheet(ss.getSheets()[pa]);
var newSheet = ss.deleteActiveSheet(); // delete sheets begining with the last one
Utilities.sleep(200);// pause in the loop for 200 milliseconds
}
ss.setActiveSheet(ss.getSheets()[0]);// return to first sheet as active sheet (useful in 'list' function)
}
Here is another option that outputs mm/dd/yy:
const date = new Date('2012-11-29 17:00:34 UTC');
date.toLocaleString();
//output 11/29/2012
I got this error when I was missing a closing brace in a component method:
const Whoops = props => {
const wonk = () => {props.wonk(); // <- note missing } brace!
return (
<View onPress={wonk} />
)
}
The above answers using layout_didn't work for me, but the following did.
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight="0.1"
android:layout_gravity="center_horizontal"
>
<android.support.design.widget.FloatingActionButton
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center"
/>
<android.support.design.widget.FloatingActionButton
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginLeft="40dp"
android:layout_marginStart="40dp"/>
<android.support.design.widget.FloatingActionButton
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginLeft="40dp"
android:layout_marginStart="40dp"
/>
<android.support.design.widget.FloatingActionButton
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginLeft="40dp"
android:layout_marginStart="40dp"/>
</LinearLayout>
This is how it looks on screen,
The base difference that which already everyone mentioned is that one is heavy weight and other is light weight. Let me explain, basically what the term heavy weight means is that when you're using the awt components the native code used for getting the view component is generated by the Operating System, thats why it the look and feel changes from OS to OS. Where as in swing components its the responsibility of JVM to generate the view for the components. Another statement which i saw is that swing is MVC based and awt is not.
Several people misread this as a question about how to store passwords in a database. That is wrong. It is about how to store the password that lets you get to the database.
The usual solution is to move the password out of source-code into a configuration file. Then leave administration and securing that configuration file up to your system administrators. That way developers do not need to know anything about the production passwords, and there is no record of the password in your source-control.
select
(select count(*) from foo) as foo
, (select count(*) from bar) as bar
, ...
This is what worked for me.
<!DOCTYPE html>
<form action="desired Link">
<button> <img src="desired image URL"/>
</button>
</form>
<style>
</style>
michael's suggestions works like a charm for me :) If you replace $http.post with $http.get, remember that the .get method accepts 2 parameters instead of 3... this is where is wasted my time... ;)
controller:
$http.get('/getdoc/' + $stateParams.id,
{responseType:'arraybuffer'})
.success(function (response) {
var file = new Blob([(response)], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
});
view:
<object ng-show="content" data="{{content}}" type="application/pdf" style="width: 100%; height: 400px;"></object>
I also rarely want to print my google docs, and the breaks annoyed me as well.
I installed the Page Sizer add-on from the add-ons menu within google docs, and made the page really long.
The page settings work globally. So your collaborators will also enjoy a page page-break-free experience in google docs, unlike the style-bot solution.
this worked for me..
<Location />
Allow from all
Order Deny,Allow
</Location>
I have included this code in my /etc/apache2/apache2.conf
Pass the date into the function.
<?php
function getTheDay($date)
{
$curr_date=strtotime(date("Y-m-d H:i:s"));
$the_date=strtotime($date);
$diff=floor(($curr_date-$the_date)/(60*60*24));
switch($diff)
{
case 0:
return "Today";
break;
case 1:
return "Yesterday";
break;
default:
return $diff." Days ago";
}
}
?>
You can simply use this one line code to resize your image in visual basic .net
Public Shared Function ResizeImage(ByVal InputImage As Image) As Image
Return New Bitmap(InputImage, New Size(64, 64))
End Function
Where;
I made an animated GIF of the steps in the accepted answer. This is from MSSQL Server 2012
When you want a flex item to occupy an entire row, set it to width: 100%
or flex-basis: 100%
, and enable wrap
on the container.
The item now consumes all available space. Siblings are forced on to other rows.
.parent {
display: flex;
flex-wrap: wrap;
}
#range, #text {
flex: 1;
}
.error {
flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
border: 1px dashed black;
}
_x000D_
<div class="parent">
<input type="range" id="range">
<input type="text" id="text">
<label class="error">Error message (takes full width)</label>
</div>
_x000D_
More info: The initial value of the flex-wrap
property is nowrap
, which means that all items will line up in a row. MDN
echo "Sending emails ..."
NOW=$(date +"%F %H:%M")
echo $NOW " Running service" >> open_files.log
header=`echo "Service Restarting: " $NOW`
mail -s "$header" [email protected], \
[email protected], \ < open_files.log
Here's the proper way to do things:
<?PHP
$sql = 'some query...';
$result = mysql_query($q);
if (! $result){
throw new My_Db_Exception('Database error: ' . mysql_error());
}
while($row = mysql_fetch_assoc($result)){
//handle rows.
}
Note the check on (! $result) -- if your $result is a boolean, it's certainly false, and it means there was a database error, meaning your query was probably bad.
If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):
function hasDuplicates(array) {
return (new Set(array)).size !== array.length;
}
If you only need string values in the array, the following will work:
function hasDuplicates(array) {
var valuesSoFar = Object.create(null);
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (value in valuesSoFar) {
return true;
}
valuesSoFar[value] = true;
}
return false;
}
We use a "hash table" valuesSoFar
whose keys are the values we've seen in the array so far. We do a lookup using in
to see if that value has been spotted already; if so, we bail out of the loop and return true
.
If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).
function hasDuplicates(array) {
var valuesSoFar = [];
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (valuesSoFar.indexOf(value) !== -1) {
return true;
}
valuesSoFar.push(value);
}
return false;
}
The difference is simply that we use an array instead of a hash table for valuesSoFar
, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of in
, instead getting an O(n) lookup time of indexOf
.
This works without having to use forms or import any DLLs:
using System.Windows;
using System.Windows.Input;
/// <summary>
/// Gets the current mouse position on screen
/// </summary>
private Point GetMousePosition()
{
// Position of the mouse relative to the window
var position = Mouse.GetPosition(Window);
// Add the window position
return new Point(position.X + Window.Left, position.Y + Window.Top);
}
You can create you own exception by inheriting from java.lang.Exception
Here is an example that can help you do that.
As a basic example...
HTML:
<input type="text" name="Thing" value="" />
Script:
/* event listener */
document.getElementsByName("Thing")[0].addEventListener('change', doThing);
/* function */
function doThing(){
alert('Horray! Someone wrote "' + this.value + '"!');
}
Here's a fiddle: http://jsfiddle.net/Niffler/514gg4tk/
Try
CREATE TABLE foo LIKE bar;
so the keys and indexes are copied over as, well.
A bat file has no structure...it is how you would type it on the command line. So just open your favourite editor..copy the line of code you want to run..and save the file as whatever.bat or whatever.cmd
it takes this command about 2 mins to return the data as there is a lot of data
Probably, Bad Design. Consider using paging here.
default connection time is 30 secs, how do I increase this
As you are facing a timeout on your command, therefore you need to increase the timeout of your sql command. You can specify it in your command like this
// Setting command timeout to 2 minutes
scGetruntotals.CommandTimeout = 120;
var dateOffset = (24*60*60*1000) * 5; //5 days
var myDate = new Date();
myDate.setTime(myDate.getTime() - dateOffset);
If you're performing lots of headachy date manipulation throughout your web application, DateJS will make your life much easier:
just use //id instead of /id. It works fine in my code
The best example is this one, No hiding, No jQuery, It's completely pure CSS
http://css-tricks.com/snippets/css/custom-file-input-styling-webkitblink/
.custom-file-input::-webkit-file-upload-button {_x000D_
visibility: hidden;_x000D_
}_x000D_
_x000D_
.custom-file-input::before {_x000D_
content: 'Select some files';_x000D_
display: inline-block;_x000D_
background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);_x000D_
border: 1px solid #999;_x000D_
border-radius: 3px;_x000D_
padding: 5px 8px;_x000D_
outline: none;_x000D_
white-space: nowrap;_x000D_
-webkit-user-select: none;_x000D_
cursor: pointer;_x000D_
text-shadow: 1px 1px #fff;_x000D_
font-weight: 700;_x000D_
font-size: 10pt;_x000D_
}_x000D_
_x000D_
.custom-file-input:hover::before {_x000D_
border-color: black;_x000D_
}_x000D_
_x000D_
.custom-file-input:active::before {_x000D_
background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);_x000D_
}
_x000D_
<input type="file" class="custom-file-input">
_x000D_
Do this:
$( '#wrapper' ).on( 'click', 'a', function () { ... });
where #wrapper
is a static element in which you add the dynamic links.
So, you have a wrapper which is hard-coded into the HTML source code:
<div id="wrapper"></div>
and you fill it with dynamic content. The idea is to delegate the events to that wrapper, instead of binding handlers directly on the dynamic elements.
Btw, I recommend Backbone.js - it gives structure to this process:
var YourThing = Backbone.View.extend({
// the static wrapper (the root for event delegation)
el: $( '#wrapper' ),
// event bindings are defined here
events: {
'click a': 'anchorClicked'
},
// your DOM event handlers
anchorClicked: function () {
// handle click event
}
});
new YourThing; // initializing your thing
<?php
date_default_timezone_set('America/Toronto');
require_once('class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$body = "gdssdh";
//$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); // telling the class to use SMTP
//$mail->Host = "ssl://smtp.gmail.com"; // SMTP server
$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "[email protected]"; // GMAIL username
$mail->Password = "password"; // GMAIL password
$mail->SetFrom('[email protected]', 'PRSPS');
//$mail->AddReplyTo("[email protected]', 'First Last");
$mail->Subject = "PRSPS password";
//$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$address = "[email protected]";
$mail->AddAddress($address, "user2");
//$mail->AddAttachment("images/phpmailer.gif"); // attachment
//$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
Per this other post: Insert all values of a..., you can do the following:
INSERT INTO new_table (Foo, Bar, Fizz, Buzz)
SELECT Foo, Bar, Fizz, Buzz
FROM initial_table
It's important to specify the column names as indicated by the other answers.
Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....
You need to increase the Android emulator's memory capacity. There are two ways for that:
Right click the root of your Android Project, go to "Run As" and then go to "Run Configurations...". Locate the "Android Application" node in the tree at the left, and then select your project and go to the "Target" tab on the right side of the window look down for the "Additional Emulator Command Line Options" field (sometimes you'll need to make the window larger) and finally paste "-partition-size 1024" there. Click Apply and then Run to use your emulator.
Go to Eclipse's Preferences, and then select “Launch” Add “-partition-size 1024” on the “Default emulator option” field. Click “Apply” and use your emulator as usual.
In case anyone is having this issue but none of the above answers solve their problems, I was having this same issue and had the hardest time tracking it down since my config files were correct, my ngnix and php-fpm jobs were running fine, and there were no errors coming through any error logs.
Dumb mistake but I never checked the Short Open Tag variable in my php.ini file which was set to short_open_tag = Off
. Since my php files were using <?
instead of <?php
, the pages were showing up blank. Short Open Tag should have been set to On
in my case.
Hope this helps someone.
You need to install Package Control first (from the Python console in Sublime. Visit http://wbond.net/sublime_packages/package_control for more info), and then install emmet from their repository.
For googlers:
This jquery-workaround makes #containment get a height automatically (by, height: auto), then gets the actual height assigned as a pixel value.
<script type="text/javascript">
<!--
$(function () {
// workaround for webkit-bug http://stackoverflow.com/a/8468131/348841
var rz = function () {
$('#containment')
.css('height', 'auto')
.css('height', $('#containment').height() + 'px');
};
$(window).resize(function () {
rz();
});
rz();
})
-->
</script>
Here is the optimized code snippet to remove empty arrays/objects as well:
function removeNullsInObject(obj) {
if( typeof obj === 'string' ){ return; }
$.each(obj, function(key, value){
if (value === "" || value === null){
delete obj[key];
} else if ($.isArray(value)) {
if( value.length === 0 ){ delete obj[key]; return; }
$.each(value, function (k,v) {
removeNullsInObject(v);
});
} else if (typeof value === 'object') {
if( Object.keys(value).length === 0 ){
delete obj[key]; return;
}
removeNullsInObject(value);
}
});
}
Thanks @Alexis king :)
If you want to call the incremented number directly in a function, this solution works bettter:
Function inc(ByRef data As Integer)
data = data + 1
inc = data
End Function
for example:
Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))
If the function inc()
returns no value, the above line will generate an error.
You can use the CSS property max-width
and use it with ch
unit.
And, as this is a <span>
, use a display: inline-block;
(or block).
Here is an example:
<span style="
display:inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 13ch;">
Lorem ipsum dolor sit amet
</span>
Which outputs:
Lorem ipsum...
<span style="_x000D_
display:inline-block;_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
max-width: 13ch;">_x000D_
Lorem ipsum dolor sit amet_x000D_
</span>
_x000D_
var y = $(window).scrollTop(); //your current y position on the page
$(window).scrollTop(y+150);
I tried "ManiIOT"'s solution and it worked surprisingly. I've added another role (Compute Admin Role) for my google user account from IAM admin. Then stopped and restarted the VM. Afterwards 'sudo passwd' let me to generate a new password for the user.
So here are steps.
You can use this:
NumberFormat formatter = new DecimalFormat("00");
String s = formatter.format(1); // ----> 01
<?php
if(isset($_FILES[$input_name]) && is_array($_FILES[$input_name]['name'])){
$image_path = array();
$count = count($_FILES[$input_name]['name']);
for($key =0; $key <$count; $key++){
$_FILES['file']['name'] = $_FILES[$input_name]['name'][$key];
$_FILES['file']['type'] = $_FILES[$input_name]['type'][$key];
$_FILES['file']['tmp_name'] = $_FILES[$input_name]['tmp_name'][$key];
$_FILES['file']['error'] = $_FILES[$input_name]['error'][$key];
$_FILES['file']['size'] = $_FILES[$input_name]['size'][$key];
$config['file_name'] = $_FILES[$input_name]['name'][$key];
$this->upload->initialize($config);
if($this->upload->do_upload('file')) {
$data = $this->upload->data();
$image_path[$key] = $path ."$data[file_name]";
}else{
$error = $this->upload->display_errors();
$this->session->set_flashdata('msg_error',"image upload! ".$error);
}
}
return json_encode($image_path);
}
?>
_x000D_
Here is a trick I use with GNU make for creating compiler-output directories. First define this rule:
%/.d:
mkdir -p $(@D)
touch $@
Then make all files that go into the directory dependent on the .d file in that directory:
obj/%.o: %.c obj/.d
$(CC) $(CFLAGS) -c -o $@ $<
Note use of $< instead of $^.
Finally prevent the .d files from being removed automatically:
.PRECIOUS: %/.d
Skipping the .d file, and depending directly on the directory, will not work, as the directory modification time is updated every time a file is written in that directory, which would force rebuild at every invocation of make.
I wrote a very simple class for exporting to "Excel XML" aka SpreadsheetML. It's not quite as convenient for the end user as XSLX (depending on file extension and Excel version, they may get a warning message), but it's a lot easier to work with than XLS or XLSX.
It will work for sure
import java.io.*;
import java.util.*;
public class JavaPingExampleProgram
{
public static void main(String args[])
throws IOException
{
// create the ping command as a list of strings
JavaPingExampleProgram ping = new JavaPingExampleProgram();
List<String> commands = new ArrayList<String>();
commands.add("ping");
commands.add("-c");
commands.add("5");
commands.add("74.125.236.73");
ping.doCommand(commands);
}
public void doCommand(List<String> command)
throws IOException
{
String s = null;
ProcessBuilder pb = new ProcessBuilder(command);
Process process = pb.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null)
{
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null)
{
System.out.println(s);
}
}
}