If you are creating an array then there is no difference, however, the following is neater:
String[] suit = {
"spades",
"hearts",
"diamonds",
"clubs"
};
But, if you want to pass an array into a method you have to call it like this:
myMethod(new String[] {"spades", "hearts"});
myMethod({"spades", "hearts"}); //won't compile!
I think you mean to update it back to the OLD
password, when the NEW one is not supplied.
DROP TRIGGER IF EXISTS upd_user;
DELIMITER $$
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
IF (NEW.password IS NULL OR NEW.password = '') THEN
SET NEW.password = OLD.password;
ELSE
SET NEW.password = Password(NEW.Password);
END IF;
END$$
DELIMITER ;
However, this means a user can never blank out a password.
DELIMITER $$
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
IF (NEW.password IS NULL OR NEW.password = '' OR NEW.password = OLD.password) THEN
SET NEW.password = OLD.password;
ELSE
SET NEW.password = Password(NEW.Password);
END IF;
END$$
DELIMITER ;
git config --get remote.origin.url
In some cases we could have a couple of tables, and then we need to detect click just for particular table. My solution is this:
<table id="elitable" border="1" cellspacing="0" width="100%">
<tr>
<td>100</td><td>AAA</td><td>aaa</td>
</tr>
<tr>
<td>200</td><td>BBB</td><td>bbb</td>
</tr>
<tr>
<td>300</td><td>CCC</td><td>ccc</td>
</tr>
</table>
<script>
$(function(){
$("#elitable tr").click(function(){
alert (this.rowIndex);
});
});
</script>
You can also request for access programmatically, which I prefer because in most cases you need to know if you took the access or not.
Swift 4 update:
//Camera
AVCaptureDevice.requestAccess(for: AVMediaType.video) { response in
if response {
//access granted
} else {
}
}
//Photos
let photos = PHPhotoLibrary.authorizationStatus()
if photos == .notDetermined {
PHPhotoLibrary.requestAuthorization({status in
if status == .authorized{
...
} else {}
})
}
You do not share code so I cannot be sure if this would be useful for you, but general speaking use it as a best practice.
Nothing here worked for me, I found this command in another SO answer though and it solved my problem. Just start command prompt as an administrator and run this command:
run->cmd
run "c:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i"
Credit: User Vicxx
A solution without reference to a Bean:
<h:button value="login"
outcome="content/configuration.xhtml?i=1" />
In my project I needed this approach:
<h:commandButton value="login"
action="content/configuration.xhtml?faces-redirect=true&i=1" />
Use getRGB(), it helps ( no complicated programs )
Returns an array of integer pixels in the default RGB color model (TYPE_INT_ARGB) and default sRGB color space, from a portion of the image data.
The way I have sorted HTML tables in the browser uses plain, unadorned Javascript.
The basic process is:
The table should, of course, be nice HTML. Something like this...
<table>
<thead>
<tr><th>Name</th><th>Age</th></tr>
</thead>
<tbody>
<tr><td>Sioned</td><td>62</td></tr>
<tr><td>Dylan</td><td>37</td></tr>
...etc...
</tbody>
</table>
So, first adding the click handlers...
const table = document.querySelector('table'); //get the table to be sorted
table.querySelectorAll('th') // get all the table header elements
.forEach((element, columnNo)=>{ // add a click handler for each
element.addEventListener('click', event => {
sortTable(table, columnNo); //call a function which sorts the table by a given column number
})
})
This won't work right now because the sortTable
function which is called in the event handler doesn't exist.
Lets write it...
function sortTable(table, sortColumn){
// get the data from the table cells
const tableBody = table.querySelector('tbody')
const tableData = table2data(tableBody);
// sort the extracted data
tableData.sort((a, b)=>{
if(a[sortColumn] > b[sortColumn]){
return 1;
}
return -1;
})
// put the sorted data back into the table
data2table(tableBody, tableData);
}
So now we get to the meat of the problem, we need to make the functions table2data
to get data out of the table, and data2table
to put it back in once sorted.
Here they are ...
// this function gets data from the rows and cells
// within an html tbody element
function table2data(tableBody){
const tableData = []; // create the array that'll hold the data rows
tableBody.querySelectorAll('tr')
.forEach(row=>{ // for each table row...
const rowData = []; // make an array for that row
row.querySelectorAll('td') // for each cell in that row
.forEach(cell=>{
rowData.push(cell.innerText); // add it to the row data
})
tableData.push(rowData); // add the full row to the table data
});
return tableData;
}
// this function puts data into an html tbody element
function data2table(tableBody, tableData){
tableBody.querySelectorAll('tr') // for each table row...
.forEach((row, i)=>{
const rowData = tableData[i]; // get the array for the row data
row.querySelectorAll('td') // for each table cell ...
.forEach((cell, j)=>{
cell.innerText = rowData[j]; // put the appropriate array element into the cell
})
tableData.push(rowData);
});
}
And that should do it.
A couple of things that you may wish to add (or reasons why you may wish to use an off the shelf solution): An option to change the direction and type of sort i.e. you may wish to sort some columns numerically ("10" > "2"
is false because they're strings, probably not what you want). The ability to mark a column as sorted. Some kind of data validation.
We can do a nested loop to visit all the elements of elements in your list:
for (Gun g: gunList) {
System.out.print(g.toString() + "\n ");
for(Bullet b : g.getBullet() {
System.out.print(g);
}
System.out.println();
}
Very simple, no library required:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
or you might prefer:
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
Some browsers will treat two digit years as being in the 20th century, so that:
new Date(14, 0, 1);
gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:
var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14
In a second level cache, domain hbm files can be of key mutable and value false. For example, In this domain class some of the duration in a day remains constant as the universal truth. So, it can be marked as immutable across application.
To call the function on click of some html element (control).
$('#controlID').click(myFunction);
You will need to ensure you bind the event when your html element is ready on which you binding the event. You can put the code in document.ready
$(document).ready(function(){
$('#controlID').click(myFunction);
});
You can use anonymous function to bind the event to the html element.
$(document).ready(function(){
$('#controlID').click(function(){
$.messager.show({
title:'My Title',
msg:'The message content',
showType:'fade',
style:{
right:'',
bottom:''
}
});
});
});
If you want to bind click with many elements you can use class selector
$('.someclass').click(myFunction);
Edit based on comments by OP, If you want to call function under some condition
You can use if for conditional execution, for example,
if(a == 3)
myFunction();
You might have some luck calling the Win32 API's MessageBoxA, although whether Win16 supports that particular method is for someone else to answer.
The question is a bit old... but just in case somebody faces the error 400, it may also come from the need to post csrfToken as a parameter to the post request.
You have to get name and value from craft in your template :
<script type="text/javascript">
window.csrfTokenName = "{{ craft.config.csrfTokenName|e('js') }}";
window.csrfTokenValue = "{{ craft.request.csrfToken|e('js') }}";
</script>
and pass them in your request
data: window.csrfTokenName+"="+window.csrfTokenValue
In Java 8, an interface looks like an abstract class although their might be some differences such as :
1) Abstract classes are classes, so they are not restricted to other restrictions of the interface in Java e.g. abstract class can have the state, but you cannot have the state on the interface in Java.
2) Another semantic difference between interface with default methods and abstract class is that you can define constructors inside an abstract class, but you cannot define constructor inside interface in Java
You can fix the .
form by using --exclude
:
tar -czf workspace.tar.gz --exclude=workspace.tar.gz .
It depends on the output you expect.
A cross join matches all rows in one table to all rows in another table. An inner join matches on a field or fields. If you have one table with 10 rows and another with 10 rows then the two joins will behave differently.
The cross join will have 100 rows returned and they won't be related, just what is called a Cartesian product. The inner join will match records to each other. Assuming one has a primary key and that is a foreign key in the other you would get 10 rows returned.
A cross join has limited general utility, but exists for completeness and describes the result of joining tables with no relations added to the query. You might use a cross join to make lists of combinations of words or something similar. An inner join on the other hand is the most common join.
Tested as working:
#Must be the first statement in your script (not coutning comments)
param([Int32]$step=30)
$iTunes = New-Object -ComObject iTunes.Application
if ($iTunes.playerstate -eq 1)
{
$iTunes.PlayerPosition = $iTunes.PlayerPosition + $step
}
Call it with
powershell.exe -file itunesForward.ps1 -step 15
Multiple parameters syntax (comments are optional, but allowed):
<#
Script description.
Some notes.
#>
param (
# height of largest column without top bar
[int]$h = 4000,
# name of the output image
[string]$image = 'out.png'
)
Here is the implementation of the Hash Map using python For the simplicity hash map is of a fixed size 16. This can be changed easily. Rehashing is out of scope of this code.
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
class HashMap:
def __init__(self):
self.store = [None for _ in range(16)]
def get(self, key):
index = hash(key) & 15
if self.store[index] is None:
return None
n = self.store[index]
while True:
if n.key == key:
return n.value
else:
if n.next:
n = n.next
else:
return None
def put(self, key, value):
nd = Node(key, value)
index = hash(key) & 15
n = self.store[index]
if n is None:
self.store[index] = nd
else:
if n.key == key:
n.value = value
else:
while n.next:
if n.key == key:
n.value = value
return
else:
n = n.next
n.next = nd
hm = HashMap()
hm.put("1", "sachin")
hm.put("2", "sehwag")
hm.put("3", "ganguly")
hm.put("4", "srinath")
hm.put("5", "kumble")
hm.put("6", "dhoni")
hm.put("7", "kohli")
hm.put("8", "pandya")
hm.put("9", "rohit")
hm.put("10", "dhawan")
hm.put("11", "shastri")
hm.put("12", "manjarekar")
hm.put("13", "gupta")
hm.put("14", "agarkar")
hm.put("15", "nehra")
hm.put("16", "gawaskar")
hm.put("17", "vengsarkar")
print(hm.get("1"))
print(hm.get("2"))
print(hm.get("3"))
print(hm.get("4"))
print(hm.get("5"))
print(hm.get("6"))
print(hm.get("7"))
print(hm.get("8"))
print(hm.get("9"))
print(hm.get("10"))
print(hm.get("11"))
print(hm.get("12"))
print(hm.get("13"))
print(hm.get("14"))
print(hm.get("15"))
print(hm.get("16"))
print(hm.get("17"))
Output:
sachin
sehwag
ganguly
srinath
kumble
dhoni
kohli
pandya
rohit
dhawan
shastri
manjarekar
gupta
agarkar
nehra
gawaskar
vengsarkar
new Integer(i).toString()
first creates a (redundant) wrapper object around i
(which itself may be a wrapper object Integer
).
Integer.toString(i)
is preferred because it doesn't create any unnecessary objects.
Clip.exe is an executable in Windows to set the clipboard. Note that this does not work for other operating systems other than Windows, which still sucks.
/// <summary>
/// Sets clipboard to value.
/// </summary>
/// <param name="value">String to set the clipboard to.</param>
public static void SetClipboard(string value)
{
if (value == null)
throw new ArgumentNullException("Attempt to set clipboard with null");
Process clipboardExecutable = new Process();
clipboardExecutable.StartInfo = new ProcessStartInfo // Creates the process
{
RedirectStandardInput = true,
FileName = @"clip",
};
clipboardExecutable.Start();
clipboardExecutable.StandardInput.Write(value); // CLIP uses STDIN as input.
// When we are done writing all the string, close it so clip doesn't wait and get stuck
clipboardExecutable.StandardInput.Close();
return;
}
Two ways I can think of are
var TestApp = React.createClass({
getComponent: function(index) {
$(this.getDOMNode()).find('li:nth-child(' + index + ')').css({
'background-color': '#ccc'
});
},
render: function() {
return (
<div>
<ul>
<li onClick={this.getComponent.bind(this, 1)}>Component 1</li>
<li onClick={this.getComponent.bind(this, 2)}>Component 2</li>
<li onClick={this.getComponent.bind(this, 3)}>Component 3</li>
</ul>
</div>
);
}
});
React.renderComponent(<TestApp /> , document.getElementById('soln1'));
This is my personal favorite.
var ListItem = React.createClass({
getInitialState: function() {
return {
isSelected: false
};
},
handleClick: function() {
this.setState({
isSelected: true
})
},
render: function() {
var isSelected = this.state.isSelected;
var style = {
'background-color': ''
};
if (isSelected) {
style = {
'background-color': '#ccc'
};
}
return (
<li onClick={this.handleClick} style={style}>{this.props.content}</li>
);
}
});
var TestApp2 = React.createClass({
getComponent: function(index) {
$(this.getDOMNode()).find('li:nth-child(' + index + ')').css({
'background-color': '#ccc'
});
},
render: function() {
return (
<div>
<ul>
<ListItem content="Component 1" />
<ListItem content="Component 2" />
<ListItem content="Component 3" />
</ul>
</div>
);
}
});
React.renderComponent(<TestApp2 /> , document.getElementById('soln2'));
Here is a DEMO
I hope this helps.
Its strange that such a simple setting would require this amount of 'hocus-pocus' to work.
To answer your question now, for me it seemed to work with the combination of the following:
:set wrap linebreak nolist
(this seems to prevent existing lines from breaking, just wrap.)
AND
set formatoptions=l
(this prevents new/edited lines from breaking, while += does not do it for me as other settings/plugins seem to find space and add their own options which override mine.)
I have modified the regex pattern from http://regexlib.com/REDetails.aspx?regexp_id=610. The following pattern should match your case.
^(?=\d)(?:(?:1[6-9]|[2-9]\d)?\d\d([-.\/])(?:1[012]|0?[1-9])\1(?:31(?<!.(?:0[2469]|11))|(?:30|29)(?<!.02)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$
YYYY-MM-DD HH:MM:SS
Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?
By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...
-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications
If you are running you should be able to access any of those system properties to see if they have been set:
if (System.getProperty("com.sun.management.jmxremote") == null) {
System.out.println("JMX remote is disabled");
} else [
String portString = System.getProperty("com.sun.management.jmxremote.port");
if (portString != null) {
System.out.println("JMX running on port "
+ Integer.parseInt(portString));
}
}
Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts
or if it is set to an incorrect interface address then you can override it with the following:
-Djava.rmi.server.hostname=<IP address>
As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port
is actually the RMI port. This tells the client what port the JMX server is running on.
A smart script that can both read data from PIPE and command line arguments:
#!/bin/bash
if [[ -p /proc/self/fd/0 ]]
then
PIPE=$(cat -)
echo "PIPE=$PIPE"
fi
echo "ARGS=$@"
Output:
$ bash test arg1 arg2
ARGS=arg1 arg2
$ echo pipe_data1 | bash test arg1 arg2
PIPE=pipe_data1
ARGS=arg1 arg2
Explanation: When a script receives any data via pipe, then the stdin /proc/self/fd/0 will be a symlink to a pipe.
/proc/self/fd/0 -> pipe:[155938]
If not, it will point to the current terminal:
/proc/self/fd/0 -> /dev/pts/5
The bash [[ -p
option can check it it is a pipe or not.
cat -
reads the from stdin
.
If we use cat -
when there is no stdin
, it will wait forever, that is why we put it inside the if
condition.
If you just want to have your header font a little bit bigger then the rest, you can use ScaleTransform. so you do not depend on the real fontsize.
<TextBlock x:Name="headerText" Text="Lorem ipsum dolor">
<TextBlock.LayoutTransform>
<ScaleTransform ScaleX="1.1" ScaleY="1.1" />
</TextBlock.LayoutTransform>
</TextBlock>
If you know some unix you could try the following:
Notes: $ means the command prompt
Say you have a file my_data.txt with content as such:
$ cat my_data.txt
This is a data file
with all of my data in it.
Then using the os
module you can use the usual sed
commands
import os
# Identifiers used are:
my_data_file = "my_data.txt"
command = "sed -i 's/all/none/' my_data.txt"
# Execute the command
os.system(command)
If you aren't aware of sed, check it out, it is extremely useful.
@objc
, see below example!#selector(name)
.private
or public
doesn't matter; you can use private.override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let menuButtonImage = UIImage(systemName: "flame")
let menuButton = UIBarButtonItem(image: menuButtonImage, style: .plain, target: self, action: #selector(didTapMenuButton))
navigationItem.rightBarButtonItem = menuButton
}
@objc public func didTapMenuButton() {
print("Hello World")
}
well I think I have something interesting for you... https://github.com/whizzzkid/phpimageresize. I wrote it for the exact same purpose. Highly customizable, and does it in a great way.
There is no installation per se.
You download jQuery and include it in your html files like this:
<script src="jquery.js" type="text/javascript"></script>
Of course, modify the filename so that it's the same as the downloaded script file.
Done!
You must have the definition of class B
before you use the class. How else would the compiler otherwise know that there exists such a function as B::add
?
Either define class B
before class A
, or move the body of A::doSomething
to after class B
have been defined, like
class B;
class A
{
B* b;
void doSomething();
};
class B
{
A* a;
void add() {}
};
void A::doSomething()
{
b->add();
}
In the case it is not possibile to use the new Blob
solution, that is for sure the best solution in modern browser, it is still possible to use this simpler approach, that has a limit in the file size by the way:
function download() {
var fileContents=JSON.stringify(jsonObject, null, 2);
var fileName= "data.json";
var pp = document.createElement('a');
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
pp.setAttribute('download', fileName);
pp.click();
}
setTimeout(function() {download()}, 500);
$('#download').on("click", function() {_x000D_
function download() {_x000D_
var jsonObject = {_x000D_
"name": "John",_x000D_
"age": 31,_x000D_
"city": "New York"_x000D_
};_x000D_
var fileContents = JSON.stringify(jsonObject, null, 2);_x000D_
var fileName = "data.json";_x000D_
_x000D_
var pp = document.createElement('a');_x000D_
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));_x000D_
pp.setAttribute('download', fileName);_x000D_
pp.click();_x000D_
}_x000D_
setTimeout(function() {_x000D_
download()_x000D_
}, 500);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="download">Download me</button>
_x000D_
If you are looking for the solution in Android Studio :
If you add in app.gradle under android{
lintOptions {
quiet true
abortOnError false
}
}
It will get work
Just recently experienced this:
System.ServiceModel.CommunicationException:
An error occurred while making the HTTP request to http://example.com/WebServices/SomeService.svc. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server.
---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send.
---> System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.
Our license of the bluecoat proxy was expired! so it was not possible to to reach the external party (internet).
This worked like a charm for me, of-course it requires super-user privileges :-)
# hcitool cc <target-bdaddr>; hcitool auth <target-bdaddr>
To get <target-bdaddr>
you may issue below command:
$ hcitool scan
Note: Exclude #
& $
as they are command line prompts.
Just use .
for concatenating.
And you missed out the $personCount
increment!
while ($personCount < 10) {
$result .= $personCount . ' people';
$personCount++;
}
echo $result;
In Advance Tab -> scroll down and un-checked all options in advance security setting and try by checking one-by-one and finally app start running with one option TLS 1.1
that was the solution I got it.
In my experience the pythonw.exe is faster at least with using pygame.
Disclaimer: I don't do much C#
You are trying to modify the DictionaryEntry object which is stored in the HashTable. The Hashtable only stores one object -- your instance of DictionaryEntry. Changing the Key or the Value is enough to change the HashTable and cause the enumerator to become invalid.
You can do it outside of the loop:
if(hashtable.Contains(key))
{
hashtable[key] = value;
}
by first creating a list of all the keys of the values you wish to change and iterate through that list instead.
You'll have to write the SQL DML yourself explicitly. i.e.
UPDATE <table>
SET <column> = NULL;
Once it has completed you'll need to commit your updates
commit;
If you only want to set certain records to NULL use a WHERE clause in your UPDATE statement.
As your original question is pretty vague I hope this covers what you want.
for f, b in zip(foo, bar):
print(f, b)
zip
stops when the shorter of foo
or bar
stops.
In Python 3, zip
returns an iterator of tuples, like itertools.izip
in Python2. To get a list
of tuples, use list(zip(foo, bar))
. And to zip until both iterators are
exhausted, you would use
itertools.zip_longest.
In Python 2, zip
returns a list of tuples. This is fine when foo
and bar
are not massive. If they are both massive then forming zip(foo,bar)
is an unnecessarily massive
temporary variable, and should be replaced by itertools.izip
or
itertools.izip_longest
, which returns an iterator instead of a list.
import itertools
for f,b in itertools.izip(foo,bar):
print(f,b)
for f,b in itertools.izip_longest(foo,bar):
print(f,b)
izip
stops when either foo
or bar
is exhausted.
izip_longest
stops when both foo
and bar
are exhausted.
When the shorter iterator(s) are exhausted, izip_longest
yields a tuple with None
in the position corresponding to that iterator. You can also set a different fillvalue
besides None
if you wish. See here for the full story.
Note also that zip
and its zip
-like brethen can accept an arbitrary number of iterables as arguments. For example,
for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'],
['red', 'blue', 'green']):
print('{} {} {}'.format(num, color, cheese))
prints
1 red manchego
2 blue stilton
3 green brie
How about the good old Command-Q?
Have you tried getFilesDir().getAbsolutePath()
?
Seems you fixed your problem by initializing the File object with a full path. I believe this would also do the trick.
function reload() {_x000D_
document.location.reload();_x000D_
}_x000D_
_x000D_
setTimeout(reload, 5000);
_x000D_
just press the back button and then next button...jdk found :D
Apache Commons I/O provides FileUtils#readLines(), which should be fine for all but huge files: http://commons.apache.org/io/api-release/index.html. The 2.1 distribution includes FileUtils.lineIterator(), which would be suitable for large files. Google's Guava libraries include similar utilities.
If all you want to do is run your main class (without compiling the .java
files on which the main class doesn't depend), then you can do the following:
cd <root-package-directory>
javac <complete-path-to-main-class>
or
javac -cp <root-package-directory> <complete-path-to-main-class>
javac
would automatically resolve all the dependencies and compile all the dependencies as well.
For python >= 3.5 you can use **
, recursive=True
:
import glob
for x in glob.glob('/path/**/*.c', recursive=True):
print(x)
If recursive is
True
, the pattern**
will match any files and zero or moredirectories
andsubdirectories
. If the pattern is followed by anos.sep
, only directories andsubdirectories
match.
Note:
Python3.6
seems to default to recursive=True
when using **
so it can be omitted.
My solution to this was to write the script block dynamically with [scriptblock]:Create
:
# Or build a complex local script with MARKERS here, and do substitutions
# I was sending install scripts to the remote along with MSI packages
# ...for things like Backup and AV protection etc.
$p1 = "good stuff"; $p2 = "better stuff"; $p3 = "best stuff"; $etc = "!"
$script = [scriptblock]::Create("MyScriptOnRemoteServer.ps1 $p1 $p2 $etc")
#strings get interpolated/expanded while a direct scriptblock does not
# the $parms are now expanded in the script block itself
# ...so just call it:
$result = invoke-command $computer -script $script
Passing arguments was very frustrating, trying various methods, e.g.,
-arguments
, $using:p1
, etc. and this just worked as desired with no problems.
Since I control the contents and variable expansion of the string which creates the [scriptblock]
(or script file) this way, there is no real issue with the "invoke-command" incantation.
(It shouldn't be that hard. :) )
An enum
type is a special type of class
.
Your enum
will actually be compiled to something like
public final class MySingleton {
public final static MySingleton INSTANCE = new MySingleton();
private MySingleton(){}
}
When your code first accesses INSTANCE
, the class MySingleton
will be loaded and initialized by the JVM. This process initializes the static
field above once (lazily).
You can try this way
String input = "";
try {
int x = Integer.parseInt(input);
// You can use this method to convert String to int, But if input
//is not an int value then this will throws NumberFormatException.
System.out.println("Valid input");
}catch(NumberFormatException e) {
System.out.println("input is not an int value");
// Here catch NumberFormatException
// So input is not a int.
}
private constructor are useful when you don't want your class to be instantiated by user. To instantiate such classes, you need to declare a static method, which does the 'new' and returns the pointer.
A class with private ctors can not be put in the STL containers, as they require a copy ctor.
split
slice
concentrate
This is a good workout for beginners and it's easy to achieve.
Another advanced method is a function like this:
def trim(s):
return trim(s[slice])
And for this question, you just want to remove the last characters, so you can write like this:
def trim(s):
return s[ : -3]
I think you are over to care about what those three characters are, so you lost. You just want to remove last three, nevertheless who they are!
If you want to remove some specific characters, you can add some if judgements:
def trim(s):
if [conditions]: ### for some cases, I recommend using isinstance().
return trim(s[slice])
x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty).Where(l => l.Internal NAme != String.Empty)
or
x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty && l.Internal NAme != String.Empty)
Try this:
<td bgcolor="#FFFFFF" style="line-height:10px;" colspan=3> </td>
You can't cause a .Net application to elevate its own rights. It's simply not allowed. The best you can do is to specify elevated rights when you spawn another process. In this case you would have a two-stage application launch.
Stage 1 does nothing but prepare an elevated spawn using the System.Diagnostics.ProcessStartInfo object and the Start() call.
Stage 2 is the application running in an elevated state.
As mentioned above, though, you very rarely want to do this. And you certainly don't want to do it just so you can write temporary files into %programfiles%. Use this method only when you need to perform administrative actions like service start/stop, etc. Write your temporary files into a better place, as indicated in other answers here.
A stream is an object used to transfer data. There is a generic stream class System.IO.Stream
, from which all other stream classes in .NET are derived. The Stream
class deals with bytes.
The concrete stream classes are used to deal with other types of data than bytes. For example:
FileStream
class is used when the outside source is a fileMemoryStream
is used to store data in memorySystem.Net.Sockets.NetworkStream
handles network dataReader/writer streams such as StreamReader
and StreamWriter
are not streams - they are not derived from System.IO.Stream
, they are designed to help to write and read data from and to stream!
If the file includes a line break in the middle of the text neither strip()
nor rstrip()
will not solve the problem,
strip family are used to trim from the began and the end of the string
replace()
is the way to solve your problem
>>> my_name = "Landon\nWO"
>>> print my_name
Landon
WO
>>> my_name = my_name.replace('\n','')
>>> print my_name
LandonWO
Agree with previous answers.
A little correction: There's a better way to print the decimal digits from left to right, without allocating extra buffer. In addition you may want to display a zero characeter if the score
is 0 (the loop suggested in the previous answers won't print anythng).
This demands an additional pass:
int div;
for (div = 1; div <= score; div *= 10)
;
do
{
div /= 10;
printf("%d\n", score / div);
score %= div;
} while (score);
No there isn't and it's probably not there, because there are very few valid uses for it. I would think twice before using it. Also, it is indeed easy to create yourself.
Please refer to this discussion about why it's even in .NET.
I guess UnsupportedOperationException
comes close, although it doesn't say the operation is just not implemented, but unsupported even. That could imply no valid implementation is possible. Why would the operation be unsupported? Should it even be there?
Interface segregation or Liskov substitution issues maybe?
If it's work in progress I'd go for ToBeImplementedException
, but I've never caught myself defining a concrete method and then leave it for so long it makes it into production and there would be a need for such an exception.
You can also create custom states and update it's value duting task execution. This example is from docs:
@app.task(bind=True)
def upload_files(self, filenames):
for i, file in enumerate(filenames):
if not self.request.called_directly:
self.update_state(state='PROGRESS',
meta={'current': i, 'total': len(filenames)})
http://celery.readthedocs.org/en/latest/userguide/tasks.html#custom-states
select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
from (select id, name, author_id, count(1) as count_1
from names
group by id, name, author_id) n1
inner join (select distinct(author_id), count(1) as total_count
from names) n2
on (n2.author_id = n1.author_id)
Where true
used distinct
if more inner join, because more join group performance is slow
Global exclusions look like they're being worked on, but until then...
From the Sonatype maven reference (bottom of the page):
Dependency management in a top-level POM is different from just defining a dependency on a widely shared parent POM. For starters, all dependencies are inherited. If mysql-connector-java were listed as a dependency of the top-level parent project, every single project in the hierarchy would have a reference to this dependency. Instead of adding in unnecessary dependencies, using dependencyManagement allows you to consolidate and centralize the management of dependency versions without adding dependencies which are inherited by all children. In other words, the dependencyManagement element is equivalent to an environment variable which allows you to declare a dependency anywhere below a project without specifying a version number.
As an example:
<dependencies>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</dependencyManagement>
It doesn't make the code less verbose overall, but it does make it less verbose where it counts. If you still want it less verbose you can follow these tips also from the Sonatype reference.
I pretty much like the (relatively) new java.time library: it's close to awesome, imho.
You can calculate a duration between two instants this way:
import java.time.*
Instant before = Instant.now();
// do stuff
Instant after = Instant.now();
long delta = Duration.between(before, after).toMillis(); // .toWhatsoever()
API is awesome, highly readable and intuitive.
Classes are thread-safe too. !
References: Oracle Tutorial, Java Magazine
The method mentioned by steenslag is terse, and given the scope of the question it should be considered the correct answer. However it is also worth knowing that this can be achieved with a regular expression, which if you aren't already familiar with in Ruby, is an important skill to learn.
Have a play with Rubular: http://rubular.com/
But in this case, the following ruby statement will return true if the string on the left starts with 'abc'. The \A in the regex literal on the right means 'the beginning of the string'. Have a play with rubular - it will become clear how things work.
'abcdefg' =~ /\Aabc/
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
Looks like you have an extra parenthesis.
The following portion is parsed as an assignment so the interpreter/compiler will look for a semi-colon or attempt to insert one if certain conditions are met.
foob_name = $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
return '[' + (+$1 + 1) + ']';
})
I did found a way to convert (even bad) html into well formed XML. I started to base this on the DOM loadHTML function. However during time several issues occurred and I optimized and added patches to correct side effects.
function tryToXml($dom,$content) {
if(!$content) return false;
// xml well formed content can be loaded as xml node tree
$fragment = $dom->createDocumentFragment();
// wonderfull appendXML to add an XML string directly into the node tree!
// aappendxml will fail on a xml declaration so manually skip this when occurred
if( substr( $content,0, 5) == '<?xml' ) {
$content = substr($content,strpos($content,'>')+1);
if( strpos($content,'<') ) {
$content = substr($content,strpos($content,'<'));
}
}
// if appendXML is not working then use below htmlToXml() for nasty html correction
if(!@$fragment->appendXML( $content )) {
return $this->htmlToXml($dom,$content);
}
return $fragment;
}
// convert content into xml
// dom is only needed to prepare the xml which will be returned
function htmlToXml($dom, $content, $needEncoding=false, $bodyOnly=true) {
// no xml when html is empty
if(!$content) return false;
// real content and possibly it needs encoding
if( $needEncoding ) {
// no need to convert character encoding as loadHTML will respect the content-type (only)
$content = '<meta http-equiv="Content-Type" content="text/html;charset='.$this->encoding.'">' . $content;
}
// return a dom from the content
$domInject = new DOMDocument("1.0", "UTF-8");
$domInject->preserveWhiteSpace = false;
$domInject->formatOutput = true;
// html type
try {
@$domInject->loadHTML( $content );
} catch(Exception $e){
// do nothing and continue as it's normal that warnings will occur on nasty HTML content
}
// to check encoding: echo $dom->encoding
$this->reworkDom( $domInject );
if( $bodyOnly ) {
$fragment = $dom->createDocumentFragment();
// retrieve nodes within /html/body
foreach( $domInject->documentElement->childNodes as $elementLevel1 ) {
if( $elementLevel1->nodeName == 'body' and $elementLevel1->nodeType == XML_ELEMENT_NODE ) {
foreach( $elementLevel1->childNodes as $elementInject ) {
$fragment->insertBefore( $dom->importNode($elementInject, true) );
}
}
}
} else {
$fragment = $dom->importNode($domInject->documentElement, true);
}
return $fragment;
}
protected function reworkDom( $node, $level = 0 ) {
// start with the first child node to iterate
$nodeChild = $node->firstChild;
while ( $nodeChild ) {
$nodeNextChild = $nodeChild->nextSibling;
switch ( $nodeChild->nodeType ) {
case XML_ELEMENT_NODE:
// iterate through children element nodes
$this->reworkDom( $nodeChild, $level + 1);
break;
case XML_TEXT_NODE:
case XML_CDATA_SECTION_NODE:
// do nothing with text, cdata
break;
case XML_COMMENT_NODE:
// ensure comments to remove - sign also follows the w3c guideline
$nodeChild->nodeValue = str_replace("-","_",$nodeChild->nodeValue);
break;
case XML_DOCUMENT_TYPE_NODE: // 10: needs to be removed
case XML_PI_NODE: // 7: remove PI
$node->removeChild( $nodeChild );
$nodeChild = null; // make null to test later
break;
case XML_DOCUMENT_NODE:
// should not appear as it's always the root, just to be complete
// however generate exception!
case XML_HTML_DOCUMENT_NODE:
// should not appear as it's always the root, just to be complete
// however generate exception!
default:
throw new exception("Engine: reworkDom type not declared [".$nodeChild->nodeType. "]");
}
$nodeChild = $nodeNextChild;
} ;
}
Now this also allows to add more html pieces into one XML which I needed to use myself. In general it can be used like this:
$c='<p>test<font>two</p>';
$dom=new DOMDocument('1.0', 'UTF-8');
$n=$dom->appendChild($dom->createElement('info')); // make a root element
if( $valueXml=tryToXml($dom,$c) ) {
$n->appendChild($valueXml);
}
echo '<pre/>'. htmlentities($dom->saveXml($n)). '</pre>';
In this example '<p>test<font>two</p>'
will nicely be outputed in well formed XML as '<info><p>test<font>two</font></p></info>
'. The info root tag is added as it will also allow to convert '<p>one</p><p>two</p>
' which is not XML as it has not one root element. However if you html does for sure have one root element then the extra root <info>
tag can be skipped.
With this I'm getting real nice XML out of unstructured and even corrupted HTML!
I hope it's a bit clear and might contribute to other people to use it.
I know this is an old post, but figured I'd share my two cents. @Neji is correct in that you can use sessionStorage.getItem('label')
, and sessionStorage.setItem('label', 'value')
(although he had the setItem
parameters backwards, not a big deal). I much more prefer the following, I think it's more succinct:
var val = sessionStorage.myValue
in place of getItem
and
sessionStorage.myValue = 'value'
in place of setItem
.
Also, it should be noted that in order to store JavaScript objects, they must be stringified to set them, and parsed to get them, like so:
sessionStorage.myObject = JSON.stringify(myObject); //will set object to the stringified myObject
var myObject = JSON.parse(sessionStorage.myObject); //will parse JSON string back to object
The reason is that sessionStorage stores everything as a string, so if you just say sessionStorage.object = myObject
all you get is [object Object], which doesn't help you too much.
instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0;
once your window has scrolled pass a certain height:
jQuery
$(window).scroll(function(){
if ($(this).scrollTop() > 135) {
$('#task_flyout').addClass('fixed');
} else {
$('#task_flyout').removeClass('fixed');
}
});
css
.fixed {position:fixed; top:0; left:0;}
EclipseLink provided an annotation (e.g. @Index) to define an index on columns. There is an example of its use. Part of the example is included...
The firstName and lastName fields are indexed, together and individually.
@Entity
@Index(name="EMP_NAME_INDEX", columnNames={"F_NAME","L_NAME"}) // Columns indexed together
public class Employee{
@Id
private long id;
@Index // F_NAME column indexed
@Column(name="F_NAME")
private String firstName;
@Index // L_NAME column indexed
@Column(name="L_NAME")
private String lastName;
...
}
Bit late response to this question, however I do have something to add that might be useful for others.
If you make use of an iFrame and set the pdf file path to the src, it will load zoomed out to 100%, which the equivalence of FitH
select nvl(max(1), 0) from mytable;
This statement yields 0 if there are no rows, 1 if you have at least one row in that table. It's way faster than doing a select count(*). The optimizer "sees" that only a single row needs to be fetched to answer the question.
Here's a (verbose) little example:
declare
YES constant signtype := 1;
NO constant signtype := 0;
v_table_has_rows signtype;
begin
select nvl(max(YES), NO)
into v_table_has_rows
from mytable -- where ...
;
if v_table_has_rows = YES then
DBMS_OUTPUT.PUT_LINE ('mytable has at least one row');
end if;
end;
To install a specific package:
conda install <pkg>=<version>
eg:
conda install matplotlib=1.4.3
You can get with node.getScene
, if you don't call from Platform.runLater
, the result is a null value.
example null value:
node.getScene();
example no null value:
Platform.runLater(() -> {
node.getScene().addEventFilter(KeyEvent.KEY_PRESSED, event -> {
//your event
});
});
You could just go ahead and try :
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice=int.Parse(Console.ReadLine());
That should work for the case statement.
It works with the switch statement and doesn't throw an exception.
These posts helped me get past a couple of issues I had creating a CLR Stored Procedure with Restful API call against Infor M3 API.
The XML Result from these API's look like this for my code below:
miResult xmlns="http://lawson.com/m3/miaccess">
<Program>MMS200MI</Program>
<Transaction>Get</Transaction>
<Metadata>...</Metadata>
<MIRecord>
<RowIndex>0</RowIndex>
<NameValue>
<Name>STAT</Name>
<Value>20</Value>
</NameValue>
<NameValue>
<Name>ITNO</Name>
<Value>ITEM123</Value>
</NameValue>
<NameValue>
<Name>ITDS</Name>
<Value>ITEM DESCRIPTION 123 </Value>
</NameValue>
...
The CLR C# Code to accomplish listing out the Resultset from the API works as shown below:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using Microsoft.SqlServer.Server;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void CallM3API_Test1()
{
SqlPipe pipe_msg = SqlContext.Pipe;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://M3Server.domain.com:12345/m3api-rest/execute/MMS200MI/Get?ITNO=ITEM123");
request.Method = "Get";
request.ContentLength = 0;
request.Credentials = new NetworkCredential("[email protected]", "MyPassword");
request.ContentType = "application/xml";
request.Accept = "application/xml";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream receiveStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
{
string strContent = readStream.ReadToEnd();
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(strContent);
try
{
SqlPipe pipe = SqlContext.Pipe;
//Define Output Columns and Max Length of each Column in the Resultset
SqlMetaData[] cols = new SqlMetaData[2];
cols[0] = new SqlMetaData("Name", SqlDbType.NVarChar, 50);
cols[1] = new SqlMetaData("Value", SqlDbType.NVarChar, 120);
SqlDataRecord record = new SqlDataRecord(cols);
pipe.SendResultsStart(record);
XmlNodeList nodeList = xdoc.GetElementsByTagName("NameValue");
//List ALL Output Names + Values
foreach (XmlNode nodeRes in nodeList)
{
record.SetSqlString(0, nodeRes["Name"].InnerText);
record.SetSqlString(1, nodeRes["Value"].InnerText);
pipe.SendResultsRow(record);
}
pipe.SendResultsEnd();
}
catch (Exception ex)
{
SqlContext.Pipe.Send("Error (readStream): " + ex.Message);
}
}
}
}
}
catch (Exception ex)
{
SqlContext.Pipe.Send("Error (CallM3API_Test1): " + ex.Message);
}
}
}
Hopefully this provides helpful.
From Sql 2012 you can force ordering in views and subqueries with OFFSET
SELECT C.CustomerID,
C.CustomerName,
C.CustomerAge
FROM dbo.Customer C
ORDER BY CustomerAge OFFSET 0 ROWS;
Warning: this should only be used on small lists because OFFSET forces the full view to be evaluated even if further joins or filters on the view reduce its size!
There is no good way to force ordering in a view without a side effect really and for good reason.
Plenty of solutions are available above, but I think below solution is pretty simple and easy to understand.
Two segments Vector AB and Vector CD intersect if and only if
More specifically a and b are on opposite side of segment CD if and only if exactly one of the two triples a,c,d and b,c,d is in counterclockwise order.
Intersect(a, b, c, d)
if CCW(a, c, d) == CCW(b, c, d)
return false;
else if CCW(a, b, c) == CCW(a, b, d)
return false;
else
return true;
Here CCW represent counterclockwise which returns true/false based on the orientation of the points.
Source : http://compgeom.cs.uiuc.edu/~jeffe/teaching/373/notes/x06-sweepline.pdf Page 2
This is to make the variable of Optional type. Otherwise declared variables shows "undefined" if this variable is not used.
export interface ISearchResult {
title: string;
listTitle:string;
entityName?: string,
lookupName?:string,
lookupId?:string
}
You can use []
to extract values from a QueryDict
object like you would any ordinary dictionary.
# HTTP POST variables
request.POST['section'] # => [39]
request.POST['MAINS'] # => [137]
# HTTP GET variables
request.GET['section'] # => [39]
request.GET['MAINS'] # => [137]
# HTTP POST and HTTP GET variables (Deprecated since Django 1.7)
request.REQUEST['section'] # => [39]
request.REQUEST['MAINS'] # => [137]
I solved it by deleting WC_Lock record in the SQLite ".svn\wc.db" file lock record in the WC_LOCK table.
Just open "wc.db" file with SQLite editor and executed
delete from WC_LOCK
The solution was given in another link that I cannot find right now. But really quite a fix; without worrying about deleting all directories
Follow this :
1. File > Preferences > setting
2. In search type -> git path
3. Now scroll down a little > you will see "Git:path" section.
4. Click "Edit in settings.json".
5. Now just paste this path there "C:\\Program Files\\Git\\mingw64\\libexec\\git-core\\git.exe"
Restart VSCode and open new terminal in VSCode and try "git version"
In case still problem exists :
1. Inside terminal click on terminal options (1:Poweshell)
2. Select default shell
3. Select bash
open new terminal and change terminal option to 2:Bash Again try "git version" - this should work :)
You can get the week number directly from datetime as string.
>>> import datetime
>>> datetime.date(2010, 6, 16).strftime("%V")
'24'
Also you can get different "types" of the week number of the year changing the strftime
parameter for:
%U
- Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. Examples: 00, 01, …, 53
%W
- Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. Examples: 00, 01, …, 53[...]
(Added in Python 3.6, backported to some distribution's Python 2.7's) Several additional directives not required by the C89 standard are included for convenience. These parameters all correspond to ISO 8601 date values. These may not be available on all platforms when used with the
strftime()
method.[...]
%V
- ISO 8601 week as a decimal number with Monday as the first day of the week. Week 01 is the week containing Jan 4. Examples: 01, 02, …, 53from: datetime — Basic date and time types — Python 3.7.3 documentation
I've found out about it from here. It worked for me in Python 2.7.6
I just created this and it looks easier. You get these 2 functions:
=GetColorIndex(E5) <- returns color number for the cell
from (cell)
=CountColorIndexInRange(C7:C24,14) <- returns count of cells C7:C24 with color 14
from (range of cells, color number you want to count)
example shows percent of cells with color 14
=ROUND(CountColorIndexInRange(C7:C24,14)/18, 4 )
Create these 2 VBA functions in a Module (hit Alt-F11)
open + folders. double-click on Module1
Just paste this text below in, then close the module window (it must save it then):
Function GetColorIndex(Cell As Range)
GetColorIndex = Cell.Interior.ColorIndex
End Function
Function CountColorIndexInRange(Rng As Range, TestColor As Long)
Dim cnt
Dim cl As Range
cnt = 0
For Each cl In Rng
If GetColorIndex(cl) = TestColor Then
Rem Debug.Print ">" & TestColor & "<"
cnt = cnt + 1
End If
Next
CountColorIndexInRange = cnt
End Function
I have made somthink like this for one of my website accualy in developpement.
I have used StepCarousel for the caroussel because it's the only one I found that can accept different image size in the same carrousel.
In addition to this to add the touch swipe effect, I have used jquery.touchswipe plugin;
And stepcarousel move panel rigth or left with a fonction so I can make :
$("#slider-actu").touchwipe({
wipeLeft: function() {stepcarousel.stepBy('slider-actu', 3);},
wipeRight: function() {stepcarousel.stepBy('slider-actu', -3);},
min_move_x: 20
});
You can view the actual render at this page
Hope that help you.
I shall refer to the same sample of data as posted in the question:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
print('The original data frame is: \n{}'.format(df))
Running this code will give you
The original data frame is:
A B C D
0 0.494824 -0.328480 0.818117 0.100290
1 0.239037 0.954912 -0.186825 -0.651935
2 -1.818285 -0.158856 0.359811 -0.345560
3 -0.070814 -0.394711 0.081697 -1.178845
4 -1.638063 1.498027 -0.609325 0.882594
5 -0.510217 0.500475 1.039466 0.187076
6 1.116529 0.912380 0.869323 0.119459
7 -1.046507 0.507299 -0.373432 -1.024795
Now you wish to append a new row to this data frame, which doesn't need to be copy of any other row in the data frame. @Alon suggested an interesting approach to use df.loc
to append a new row with different index. The issue, however, with this approach is if there is already a row present at that index, it will be overwritten by new values. This is typically the case for datasets when row index is not unique, like store ID in transaction datasets. So a more general solution to your question is to create the row, transform the new row data into a pandas series, name it to the index you want to have and then append it to the data frame. Don't forget to overwrite the original data frame with the one with appended row. The reason is df.append
returns a view of the dataframe and does not modify its contents. Following is the code:
row = pd.Series({'A':10,'B':20,'C':30,'D':40},name=3)
df = df.append(row)
print('The new data frame is: \n{}'.format(df))
Following would be the new output:
The new data frame is:
A B C D
0 0.494824 -0.328480 0.818117 0.100290
1 0.239037 0.954912 -0.186825 -0.651935
2 -1.818285 -0.158856 0.359811 -0.345560
3 -0.070814 -0.394711 0.081697 -1.178845
4 -1.638063 1.498027 -0.609325 0.882594
5 -0.510217 0.500475 1.039466 0.187076
6 1.116529 0.912380 0.869323 0.119459
7 -1.046507 0.507299 -0.373432 -1.024795
3 10.000000 20.000000 30.000000 40.000000
SELECT
t.A,
t.B,
t.C,
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS number
FROM tableZ AS t
See working example at SQLFiddle
Of course, you may want to define the row-numbering order – if so, just swap OVER (ORDER BY (SELECT 1))
for, e.g., OVER (ORDER BY t.C)
, like in a normal ORDER BY
clause.
In Swift 3, 4, 5:
button.setTitle("Button Title", for: .normal)
Otherwise:
button.setTitle("Button Title", forState: UIControlState.Normal)
Also an @IBOutlet
has to declared for the button
.
Following this question, in Angular 7.2 you can pass data from parent to child using the history state. So you can do something like
Send:
this.router.navigate(['action-selection'], { state: { example: 'bar' } });
Retrieve:
constructor(private router: Router) { console.log(this.router.getCurrentNavigation().extras.state.example); }
But be careful to be consistent. For example, suppose you want to display a list on a left side bar and the details of the selected item on the right by using a router-outlet. Something like:
Item 1 (x) | ..............................................
Item 2 (x) | ......Selected Item Details.......
Item 3 (x) | ..............................................
Item 4 (x) | ..............................................
Now, suppose you have already clicked some items. Clicking the browsers back buttons will show the details from the previous item. But what if, meanwhile, you have clicked the (x) and delete from your list that item? Then performing the back click, will show you the details of a deleted item.
Here is an alternate approach using pure CSS. The idea is to include both the images in the HTML markup and have these displayed or hidden accordingly on :hover
HTML
<a>
<img src="https://cdn4.iconfinder.com/data/icons/imoticons/105/imoticon_15-128.png" />
<img src="https://cdn4.iconfinder.com/data/icons/imoticons/105/imoticon_12-128.png" />
</a>
CSS
a img:last-child {
display: none;
}
a:hover img:last-child {
display: block;
}
a:hover img:first-child {
display: none;
}
jsfiddle: https://jsfiddle.net/m4v1onyL/
Note that the images used are of the same dimensions for proper display. Also, these images file sizes are quite small so loading multiple is not an issue in this case but may be if you are looking to toggle display of large sized images.
The size of an array can't be modified. If you want a bigger array you have to instantiate a new one.
A better solution would be to use an ArrayList
which can grow as you need it. The method ArrayList.toArray( T[] a )
gives you back your array if you need it in this form.
List<String> where = new ArrayList<String>();
where.add( ContactsContract.Contacts.HAS_PHONE_NUMBER+"=1" );
where.add( ContactsContract.Contacts.IN_VISIBLE_GROUP+"=1" );
If you need to convert it to a simple array...
String[] simpleArray = new String[ where.size() ];
where.toArray( simpleArray );
But most things you do with an array you can do with this ArrayList, too:
// iterate over the array
for( String oneItem : where ) {
...
}
// get specific items
where.get( 1 );
Because async functions are promises, you can create a static function on your class which executes an async function which returns the instance of the class:
class Yql {
constructor () {
// Set up your class
}
static init () {
return (async function () {
let yql = new Yql()
// Do async stuff
await yql.build()
// Return instance
return yql
}())
}
async build () {
// Do stuff with await if needed
}
}
async function yql () {
// Do this instead of "new Yql()"
let yql = await Yql.init()
// Do stuff with yql instance
}
yql()
Call with let yql = await Yql.init()
from an async function.
It denotes an rvalue reference. Rvalue references will only bind to temporary objects, unless explicitly generated otherwise. They are used to make objects much more efficient under certain circumstances, and to provide a facility known as perfect forwarding, which greatly simplifies template code.
In C++03, you can't distinguish between a copy of a non-mutable lvalue and an rvalue.
std::string s;
std::string another(s); // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(const std::string&);
In C++0x, this is not the case.
std::string s;
std::string another(s); // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(std::string&&);
Consider the implementation behind these constructors. In the first case, the string has to perform a copy to retain value semantics, which involves a new heap allocation. However, in the second case, we know in advance that the object which was passed in to our constructor is immediately due for destruction, and it doesn't have to remain untouched. We can effectively just swap the internal pointers and not perform any copying at all in this scenario, which is substantially more efficient. Move semantics benefit any class which has expensive or prohibited copying of internally referenced resources. Consider the case of std::unique_ptr
- now that our class can distinguish between temporaries and non-temporaries, we can make the move semantics work correctly so that the unique_ptr
cannot be copied but can be moved, which means that std::unique_ptr
can be legally stored in Standard containers, sorted, etc, whereas C++03's std::auto_ptr
cannot.
Now we consider the other use of rvalue references- perfect forwarding. Consider the question of binding a reference to a reference.
std::string s;
std::string& ref = s;
(std::string&)& anotherref = ref; // usually expressed via template
Can't recall what C++03 says about this, but in C++0x, the resultant type when dealing with rvalue references is critical. An rvalue reference to a type T, where T is a reference type, becomes a reference of type T.
(std::string&)&& ref // ref is std::string&
(const std::string&)&& ref // ref is const std::string&
(std::string&&)&& ref // ref is std::string&&
(const std::string&&)&& ref // ref is const std::string&&
Consider the simplest template function- min and max. In C++03 you have to overload for all four combinations of const and non-const manually. In C++0x it's just one overload. Combined with variadic templates, this enables perfect forwarding.
template<typename A, typename B> auto min(A&& aref, B&& bref) {
// for example, if you pass a const std::string& as first argument,
// then A becomes const std::string& and by extension, aref becomes
// const std::string&, completely maintaining it's type information.
if (std::forward<A>(aref) < std::forward<B>(bref))
return std::forward<A>(aref);
else
return std::forward<B>(bref);
}
I left off the return type deduction, because I can't recall how it's done offhand, but that min can accept any combination of lvalues, rvalues, const lvalues.
I create color.xml file, for naming my color name (black, white...)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="white">#ffffff</color>
<color name="black">#000000</color>
</resources>
And in your EditText, set color
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="asdsadasdasd"
android:textColor="@color/black"
android:background="@color/white"
/>
or use style in you style.xml:
<style name="EditTextStyleWhite" parent="android:style/Widget.EditText">
<item name="android:textColor">@color/black</item>
<item name="android:background">@color/white</item>
</style>
and add ctreated style to EditText:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="asdsadasdasd"
style="@style/EditTextStyleWhite"
/>
Here's a suggestion: use two indices into the string, say start
and end
. start
points to the first character of the next string to extract, end
points to the character after the last one belonging to the next string to extract. start
starts at zero, end
gets the position of the first char after start
. Then you take the string between [start..end)
and add that to your array. You keep going until you hit the end of the string.
You're looking for TRIM.
UPDATE FOO set FIELD2 = TRIM(FIELD2);
Seems like it might be worth it to mention that TRIM can support multiple types of whitespace, but only one at a time and it will use a space by default. You can, however, nest TRIM
s.
TRIM(BOTH ' ' FROM TRIM(BOTH '\n' FROM column))
If you really want to get rid of all the whitespace in one call, you're better off using REGEXP_REPLACE
along with the [[:space:]]
notation. Here is an example:
SELECT
-- using concat to show that the whitespace is actually removed.
CONCAT(
'+',
REGEXP_REPLACE(
' ha ppy ',
-- This regexp matches 1 or more spaces at the beginning with ^[[:space:]]+
-- And 1 or more spaces at the end with [[:space:]]+$
-- By grouping them with `()` and splitting them with the `|`
-- we match all of the expected values.
'(^[[:space:]]+|[[:space:]]+$)',
-- Replace the above with nothing
''
),
'+')
as my_example;
-- outputs +ha ppy+
It's quite possible that someone will provide a truly detailed answer here, but I've always found this post from Robert Sosinski to be a great explanation of the subtleties between blocks, procs & lambdas.
I should add that I believe the post I'm linking to is specific to ruby 1.8. Some things have changed in ruby 1.9, such as block variables being local to the block. In 1.8, you'd get something like the following:
>> a = "Hello"
=> "Hello"
>> 1.times { |a| a = "Goodbye" }
=> 1
>> a
=> "Goodbye"
Whereas 1.9 would give you:
>> a = "Hello"
=> "Hello"
>> 1.times { |a| a = "Goodbye" }
=> 1
>> a
=> "Hello"
I don't have 1.9 on this machine so the above might have an error in it.
You can use numpy:
import numpy as np
Example from Empty Array:
np.empty([2, 2])
array([[ -9.74499359e+001, 6.69583040e-309],
[ 2.13182611e-314, 3.06959433e-309]])
string[,] myGridData = new string[dataGridView1.Rows.Count,3];
int i = 0;
foreach(DataRow row in dataGridView1.Rows)
{
myGridData[i][0] = row.Cells[0].Value.ToString();
myGridData[i][1] = row.Cells[1].Value.ToString();
myGridData[i][2] = row.Cells[2].Value.ToString();
i++;
}
Hope this helps....
Built-in Helpers
#if
You can use the if helper to conditionally render a block. If its argument returns false, undefined, null, "", 0, or [], Handlebars will not render the block.
template
<div class="entry">
{{#if author}}
<h1>{{firstName}} {{lastName}}</h1>
{{else}}
<h1>Unknown Author</h1>
{{/if}}
</div>
When you pass the following input to the above template
{
author: true,
firstName: "Yehuda",
lastName: "Katz"
}
this should be it try it.
document.getElementById("test").style.display="none";
data-target
is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.
The data-target
attribute should contain a CSS selector that points to the HTML Element that will be changed.
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
[...]
</div>
In this example, the button has data-target="#myModal"
, if you click on it, <div id="myModal">...</div>
will be modified (in this case faded in).
This happens because #myModal
in CSS selectors points to elements that have an id
attribute with the myModal
value.
Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
Let we have the following 2 tables(salary and employee)
Now i want those records from employee table which are not in salary. We can do this in 3 ways:
select * from employee
where id not in(select e.id from employee e inner join salary s on e.id=s.id)
select * from employee e
left outer join salary s on e.id=s.id where s.id is null
select * from employee e
full outer join salary s on e.id=s.id where e.id not in(select id from salary)
Here's a short one-liner using regular expressions:
print [re.compile(r"8").sub("", m) for m in mylist]
If we separate the regex operations and improve the namings:
pattern = re.compile(r"8") # Create the regular expression to match
res = [pattern.sub("", match) for match in mylist] # Remove match on each element
print res
-Filter only accepts a single string. -Include accepts multiple values, but qualifies the -Path argument. The trick is to append \*
to the end of the path, and then use -Include to select multiple extensions. BTW, quoting strings is unnecessary in cmdlet arguments unless they contain spaces or shell special characters.
Get-ChildItem $originalPath\* -Include *.gif, *.jpg, *.xls*, *.doc*, *.pdf*, *.wav*, .ppt*
Note that this will work regardless of whether $originalPath ends in a backslash, because multiple consecutive backslashes are interpreted as a single path separator. For example, try:
Get-ChildItem C:\\\\\Windows
You need to close the input element with />
at the end. In React, we have to close every element. Your code should be:
<input id="icon_prefix" type="text" class="validate/">
Just get a handle to the root logger and add the StreamHandler
. The StreamHandler
writes to stderr. Not sure if you really need stdout over stderr, but this is what I use when I setup the Python logger and I also add the FileHandler
as well. Then all my logs go to both places (which is what it sounds like you want).
import logging
logging.getLogger().addHandler(logging.StreamHandler())
If you want to output to stdout
instead of stderr
, you just need to specify it to the StreamHandler
constructor.
import sys
# ...
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
You could also add a Formatter
to it so all your log lines have a common header.
ie:
import logging
logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s")
rootLogger = logging.getLogger()
fileHandler = logging.FileHandler("{0}/{1}.log".format(logPath, fileName))
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
rootLogger.addHandler(consoleHandler)
Prints to the format of:
2012-12-05 16:58:26,618 [MainThread ] [INFO ] my message
You can use
app:cardBackgroundColor="@color/red"
or
android:backgroundTint="@color/red"
Rename the closing function as 'hide', for example and it will work.
function hide() {
if(document.getElementById('benefits').style.display=='block') {
document.getElementById('benefits').style.display='none';
}
}
The existing answers show a possible solution for single files or file types. However, you can define the charset standard in VS Code by following this path:
File > Preferences > Settings > Encoding > Choose your option
This will define a character set as default. Besides that, you can always change the encoding in the lower right corner of the editor (blue symbol line) for the current project.
As explained in the C++ Core Guidelines C.49: Prefer initialization to assignment in constructors it prevents unnecessary calls to default constructors.
Use the Git History Diff plugin for easy side-by-side branch diffing:
https://marketplace.visualstudio.com/items?itemName=huizhou.githd
Visit the link above and scroll down to the animated GIF image titled Diff Branch. You'll see you can easily pick any branch and do side-by-side comparison with the branch you are on! It is like getting a preview of what you will see in the GitHub Pull Request. For other Git stuff I prefer Visual Studio Code's built-in functionality or Git Lens as others have mentioned.
However, the above plugin is outstanding for doing branch diffing (i.e., for those doing a rebase Git flow and need to preview before a force push up to a GitHub PR).
Following are the steps to push Docker Image to Private Repository of DockerHub
1- First check Docker Images using command
docker images
2- Check Docker Tag command Help
docker tag help
3- Now Tag a name to your created Image
docker tag localImgName:tagName DockerHubUser\Private-repoName:tagName(tag name is optional. Default name is latest)
4- Before pushing Image to DockerHub Private Repo, first login to DockerHub using command
docker login [provide dockerHub username and Password to login]
5- Now push Docker Image to your private Repo using command
docker push [options] ImgName[:tag] e.g docker push DockerHubUser\Private-repoName:tagName
6- Now navigate to the DockerHub Private Repo and you will see Docker image is pushed on your private Repository with name written as TagName in previous steps
Just run into the same problem and was the database returning the values as strings.
I use this as a workaround:
$a = array(
'id' => $row['id'] * 1,
'another' => ...,
'ananother' => ...,
);
$json = json_encode($a);
That is multiplying the value by 1 to cast it into a number
Hope that helps someone
Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.
At this point, the simplest way is to just truncate the last two digits of the year. For credit cards, having a date in the past is unnecessary so Y2K has no meaning. The same applies for if somehow your code is still running in 90+ years.
I'd go further and say that instead of using a drop down list, let the user type in the year themselves. This is a common way of doing it and most users can handle it.
Even better!
long tStart = System.nanoTime();
long tEnd = System.nanoTime();
long tRes = tEnd - tStart; // time in nanoseconds
Read the documentation about nanoTime()!
I only have the need to push files during a build, so I just added a Post-build Event Command Line entry like this:
Copy /Y "$(SolutionDir)Third Party\SomeLibrary\*" "$(TargetDir)"
You can set this by right-clicking your Project in the Solution Explorer, then Properties > Build Events
I agree with sunetos that you'll have to use the $.ajax function in order to pass request headers. In order to do that, you'll have to write a function for the beforeSend event handler, which is one of the $.ajax() options. Here's a quick sample on how to do that:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'service.svc/Request',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
xhr.setRequestHeader('securityCode', 'Foo');
xhr.setRequestHeader('passkey', 'Bar');
}
</script>
</head>
<body>
<h1>Some Text</h1>
</body>
</html>
If you run the code above and watch the traffic in a tool like Fiddler, you'll see two requests headers passed in:
The setHeader function could also be inline in the $.ajax options, but I wanted to call it out.
Hope this helps!
To late for the original asker of the question, but with SQL Server 2008 R2 this is now possible:
Set the property "Pagebreak" on the tablix or table or other element to force a new tab, and then set the property "Pagename" on both the element before the pagebreak and the element after the pagebreak. These names will appear on the tabs when the report is exported to Excel.
Read about it here: http://technet.microsoft.com/en-us/library/dd255278.aspx
Use simply:
ListBox2.Items.Clear()
MSDN: ListBox.ObjectCollection.Clear
Removes all items from the collection.
Note that the problem with your approach is that RemoveAt
changes the index of all remaining items.
When you remove an item from the list, the indexes change for subsequent items in the list. All information about the removed item is deleted. You can use this method to remove a specific item from the list by specifying the index of the item to remove from the list. To specify the item to remove instead of the index to the item, use the Remove method. To remove all items from the list, use the Clear method.
If you want to use RemoveAt
anyway, you can go backwards, for example with:
a for
-loop:
For i As Int32 = ListBox2.Items.Count To 0 Step -1
ListBox2.Items.RemoveAt(i)
Next
or a while
While ListBox2.Items.Count > 0
ListBox2.Items.RemoveAt(ListBox2.Items.Count - 1)
End While
old C# code
for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
ListBox2.Items.RemoveAt(i);
while(ListBox2.Items.Count > 0)
ListBox2.Items.RemoveAt(ListBox2.Items.Count - 1);
Although there are already many good answers I'd like to add an option that hasn't been mentioned. Using the command:
php bin/console about
you can get many details about the current project. The first section is about Symfony itself and looks like this:
-------------------- -------------------------------------------
Symfony
-------------------- -------------------------------------------
Version 4.2.3
End of maintenance 07/2019
End of life 01/2020
-------------------- -------------------------------------------
I find the other information besides the version number very useful.
There are also other sections providing details about the (framework) Kernel, PHP, Environment.
A jar file is a zip archive. You can extract it using 7zip (a great simple tool to open archives). You can also change its extension to zip and use whatever to unzip the file.
Now you have your class file. There is no easy way to edit class file, because class files are binaries (you won't find source code in there. maybe some strings, but not java code). To edit your class file you can use a tool like classeditor.
You have all the strings your class is using hard-coded in the class file. So if the only thing you would like to change is some strings you can do it without using classeditor.
For VS 2013, .NET Framework 4.5.1 also has a AccessViolationException
bug (KB2915689) when dealing with SQL Server / TCP Sockets. Upgrading to .NET Framework 4.5.2 corrects this problem.
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
If you want a copy-paste bash script:
var=$(mysql -e 'SELECT CONCAT("ALTER TABLE ", TABLE_NAME," CONVERT TO CHARACTER SET utf8 COLLATE utf8_czech_ci;") AS execTabs FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="zabbix" AND TABLE_TYPE="BASE TABLE"' -uroot -p )
var+='ALTER DATABASE zabbix CHARACTER SET utf8 COLLATE utf8_general_ci;'
echo $var | cut -d " " -f2- | mysql -uroot -p zabbix
Change zabbix to your database name.
For this error was like others said a big image(1800px X 900px) which was in drawable directory, I edited the image and reduced the size proportionally using photoshop and it worked...!!
Consider the code below:
public class X
{
public void methodA() // Base class method
{
System.out.println ("hello, I'm methodA of class X");
}
}
public class Y extends X
{
public void methodA() // Derived Class method
{
System.out.println ("hello, I'm methodA of class Y");
}
}
public class Z
{
public static void main (String args []) {
//this takes input from the user during runtime
System.out.println("Enter x or y");
Scanner scanner = new Scanner(System.in);
String value= scanner.nextLine();
X obj1 = null;
if(value.equals("x"))
obj1 = new X(); // Reference and object X
else if(value.equals("y"))
obj2 = new Y(); // X reference but Y object
else
System.out.println("Invalid param value");
obj1.methodA();
}
}
Now, looking at the code you can never tell which implementation of methodA() will be executed, Because it depends on what value the user gives during runtime. So, it is only decided during the runtime as to which method will be called. Hence, Runtime polymorphism.
I realise this is a slightly old question, but it was driving me crazy too - and today I've found the solution that I believe the questioner was looking for (i.e. a direct mapping of Excel 2003's Web-->Address to the Excel 2010 Ribbon).
To customise the Ribbon, right-click on it and choose 'Customise the Ribbon'. You can make a new tab/group, or add this to an existing one. Choose to look in "All commands" and then the one you are after is simply called "Address". This puts a box with the full network path in it (that can be selected to copy) into the ribbon, just like Excel 2003.
Function FileExists(fullFileName As String) As Boolean
FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function
Works very well, almost, at my site. If I call it with "" the empty string, Dir returns "connection.odc"!! Would be great if you guys could share your result.
Anyway, I do like this:
Function FileExists(fullFileName As String) As Boolean
If fullFileName = "" Then
FileExists = False
Else
FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End If
End Function
It is written here that "By default, Android Studio 2.2 and the Android Plugin for Gradle 2.2 sign your app using both APK Signature Scheme v2 and the traditional signing scheme, which uses JAR signing."
As it seems that these new checkboxes appeared with Android 2.3, I understand that my previous versions of Android Studio (at least the 2.2) did sign with both signatures. So, to continue as I did before, I think that it is better to check both checkboxes.
EDIT March 31st, 2017 : submitted several apps with both signatures => no problem :)
In your entity class add @JsonInclude(JsonInclude.Include.NON_NULL)
annotation to resolve the problem
it will look like
@Entity
@JsonInclude(JsonInclude.Include.NON_NULL)
You can use the function system
.
system("color *background**foreground*");
For background and foreground, type in a number from 0 - 9 or a letter from A - F.
For example:
system("color A1");
std::cout<<"hi"<<std::endl;
That would display the letters "hi" with a green background and blue text.
To see all the color choices, just type in:
system("color %");
to see what number or letter represents what color.
I'm using Phonegap, but this thread keeps coming as the first one when Googling about the error message.
For me this issue went away by defining the imagetype to PNG.
encodingType : Camera.EncodingType.PNG
So the whole line being:
navigator.camera.getPicture(successFunction, failFunction, { encodingType : Camera.EncodingType.PNG, correctOrientation:true, sourceType : Camera.PictureSourceType .PHOTOLIBRARY, quality: 70, allowEdit : false , destinationType: Camera.DestinationType.DATA_URL});
Your mileage may vary, but that did the trick for me.
Another thing that can cause this error is creating a model with the centering/scaling standardize function from the arm package -- m <- standardize(lm(y ~ x, data = train))
If you then try predict(m)
, you get the same error as in this question.
/* for chrome */
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;}
/* for mozilla */
input[type=number] {-moz-appearance: textfield;}
Try using COUNT function like this
=IF(COUNT(SEARCH({"Romney","Obama","Gingrich"},C1)),1,"")
Note that you don't need the wildcards (as teylyn says) and unless there's a specific reason "1" doesn't need quotes (in fact that makes it a text value)
Set Python 3.5 with higher priority
sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.5 2
Check the result
sudo update-alternatives --config python
python -V
I had a similar error. The problem had to do with the child and parent table not having the same charset and collation. This can be fixed by appending ENGINE = InnoDB DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `country` (`id` INT(11) NOT NULL AUTO_INCREMENT,...) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8;
... on the SQL statement means that there is some missing code.
Unfortunately we need to run docker-compose logs
separately from docker-compose run
. In order to get this to work reliably we need to suppress the docker-compose run
exit status then redirect the log and exit with the right status.
#!/bin/bash
set -euo pipefail
docker-compose run app | tee app.log || failed=yes
docker-compose logs --no-color > docker-compose.log
[[ -z "${failed:-}" ]] || exit 1
Select
Count(Distinct user_id) As countUsers
, Count(site_id) As countVisits
, site_id As site
From cp_visits
Where ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
Group By site_id
I had the same scenario occuring..Very basic report, the SP (which only takes in 1 param) was taking 5 seconds to bring back 10K records, yet the report would take 6 minutes to run. According to profiler and the RS ExecutionLogStorage table, the report was spending all it's time on the query. Brian S.'s comment led me to the solution..I simply added WITH RECOMPILE before the AS statement in the SP, and now the report time pretty much matches the SP execution time.
I did everything from visiting http://www.google.com/accounts/DisplayUnlockCaptcha to setting up 2-fa and creating an application password. The only thing that worked was logging into http://mail.google.com and sending an email from the server itself.
Detecting mobile devices
Related answer: https://stackoverflow.com/a/13805337/1306809
There's no single approach that's truly foolproof. The best bet is to mix and match a variety of tricks as needed, to increase the chances of successfully detecting a wider range of handheld devices. See the link above for a few different options.
You need to create a object from your list like:
List<CartProduct> lst = new List<CartProduct>();
CartProduct obj = lst.Find(x => (x.Name == "product name"));
That object get the looked value searching by their properties: x.name
Then you can use List methods like Contains or Remove
if (lst.Contains(obj))
{
lst.Remove(obj);
}
I got this error with this ... unfortunate... package I have to use and I don't have source for. After much digging (thank you, Stack Overflow) and trying endless combinations, I finally got things running by:
Creating the JKS with the entire certificate chain.
Making sure the key in the JKS had the alias of the FQDN of the machine.
Renaming the alias of the certificate for my machine ${FQDN}.cert
This took endless experimentation with the java command line options:
-Djavax.net.debug=ssl:handshake:verbose:keymanager:trustmanager
-Djava.security.debug=access:stack
My key and CSR were produced in OpenSSL so I had to import the key with:
openssl pkcs12 -export -in cert.pem -inkey cert.key -CAfile fullChain.pem -name ${FQDN} -out cert.p12
keytool -importkeystore -destkeystore cert.jks -srckeystore cert.p12 -srcstoretype PKCS12
keytool complains about the format so I converted the format followed by adding my cert chain:
keytool -importkeystore -srckeystore cert.jks -destkeystore cert_p12.jks -deststoretype pkcs12
keytool -import -trustcacerts -alias 'DigiCert Global Root G2 IntermediateCA' -keystore cert_p12.jks -file cert2.pem -storepass "$STOREPASS" -keypass "$KEYPASS"
keytool -import -trustcacerts -alias 'DigiCert Global Root G2' -keystore cert_p12.jks -file cert3.pem -storepass "$STOREPASS" -keypass "$KEYPASS"
(where cert2.pem and cert3.pem were downloaded from the DigiCert web site and converted to PEM format.)
When I restarted the application with the resulting jks
file, things started to work.
Something else I figured out as part of this. You can check the certificate chain by using:
openssl x509 -in cert2.pem -noout -text
for all your certificates and studying the output, paying attention to the X509v3 Authority Key Identifier:
and X509v3 Authority Key Identifier:
lines. The X509v3 Authority Key Identifier:
of one level matches the X509v3 Subject Key Identifier:
of the next higher level. You found the top of chain when the Issuer:
string matches the Subject:
string.
I hope this can save somebody some of the time it took me.
Here is the configuration for those trying to accomplish the original goal (wildcards all pointing to same codebase -- install nothing, dev environment ie, XAMPP)
file: /etc/hosts (non-windows)
127.0.0.1 example.local
file: /XAMPP/etc/httpd.conf
# Virtual hosts
Include etc/extra/httpd-vhosts.conf
file: XAMPP/etc/extra/httpd-vhosts.conf
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "/path_to_XAMPP/htdocs"
ServerName example.local
ServerAlias *.example.local
# SetEnv APP_ENVIRONMENT development
# ErrorLog "logs/example.local-error_log"
# CustomLog "logs/example.local-access_log" common
</VirtualHost>
restart apache
save as whatever.pac wherever you want to and then load the file in the browser's network>proxy>auto_configuration settings (reload if you alter this)
function FindProxyForURL(url, host) {
if (shExpMatch(host, "*example.local")) {
return "PROXY example.local";
}
return "DIRECT";
}
Usually the process is the other way around. Do not go looking for situations where to use design patterns, look for code that can be optimized. When you have code that you think is not structured correctly. try to find a design pattern that will solve the problem.
Design patterns are meant to help you solve structural problems, do not go design your application just to be able to use design patterns.
The same problem happened with me also, nothing worked... I first deleted the service (in my case MySQL80 and MySQL) by command:
sc delete MySQL80
sc delete MySql
and then reinstalled MySQL. Mine was MySQL 8.0. And then everything was back to normal.
use this i hope this help ful to you... border:none !important; background-color:transparent;
try this
<div id="generic_search"><input type="search" onkeypress="return runScript(event)" /></div>
<button type="button" id="generic_search_button" /></button>
It's impossible, and for a good reason (for one, think about all those catch(Exception){} around).
If you want to continue execution after stack overflow, run dangerous code in a different AppDomain. CLR policies can be set to terminate current AppDomain on overflow without affecting original domain.
The answer would slightly tilt towards quicksort w.r.t to changes brought with DualPivotQuickSort for primitive values . It is used in JAVA 7 to sort in java.util.Arrays
It is proved that for the Dual-Pivot Quicksort the average number of
comparisons is 2*n*ln(n), the average number of swaps is 0.8*n*ln(n),
whereas classical Quicksort algorithm has 2*n*ln(n) and 1*n*ln(n)
respectively. Full mathematical proof see in attached proof.txt
and proof_add.txt files. Theoretical results are also confirmed
by experimental counting of the operations.
You can find the JAVA7 implmentation here - http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/Arrays.java
Further Awesome Reading on DualPivotQuickSort - http://permalink.gmane.org/gmane.comp.java.openjdk.core-libs.devel/2628
If you only want the keys which are specific to that particular object and not any derived prototype
properties:
function getKeys(obj) {
var r = []
for (var k in obj) {
if (!obj.hasOwnProperty(k))
continue
r.push(k)
}
return r
}
e.g:
var keys = getKeys({'eggs': null, 'spam': true})
var length = keys.length // access the `length` property as usual for arrays
Besides the previous post instructions, I had to install the package Microsoft.jQuery.Unobtrusive.Ajax and add to the view the following line
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
try using:
RAISERROR('your message here!!!',0,1) WITH NOWAIT
you could also try switching to "Results to Text" it is just a few icons to the right of "Execute" on the default tool bar.
With both of the above in place, and you still you do not see the messages, make sure you are running the same server/database/owner version of the procedure that you are editing. Make sure you are hitting the RAISERROR command, make it the first command inside the procedure.
If all else fails, you could create a table:
create table temp_log (RowID int identity(1,1) primary key not null
, MessageValue varchar(255))
then:
INSERT INTO temp_log VALUES ('Your message here')
then after running the procedure (provided no rollbacks) just select
the table.
For those who rooted the Android device with Magisk, you can install adb_root from https://github.com/evdenis/adb_root. Then adb root
can run smoothly.
I found the original answer incredibly helpful but I also wanted to grab a certain set of rows based on the row numbers I was inserting. As such, I wrapped the entire original answer in a subquery so that I could reference the row number I was inserting.
SELECT * FROM
(
SELECT *, @curRow := @curRow + 1 AS "row_number"
FROM db.tableName, (SELECT @curRow := 0) r
) as temp
WHERE temp.row_number BETWEEN 1 and 10;
Having a subquery in a subquery is not very efficient, so it would be worth testing whether you get a better result by having your SQL server handle this query, or fetching the entire table and having the application/web server manipulate the rows after the fact.
Personally my SQL server isn't overly busy, so having it handle the nested subqueries was preferable.
this
is a reference to the object typed as the current class, and super
is a reference to the object typed as its parent class.
In the constructor, this()
calls a constructor defined in the current class. super()
calls a constructor defined in the parent class. The constructor may be defined in any parent class, but it will refer to the one overridden closest to the current class. Calls to other constructors in this way may only be done as the first line in a constructor.
Calling methods works the same way. Calling this.method()
calls a method defined in the current class where super.method()
will call the same method as defined in the parent class.
Don't worry just change the
build.gradle
ext.kotlin_version = '1.2.41'
to previous version. It worked for me hope it works for you too. Happy coding.
554 is commonly used by dns blacklists when shooing away blacklisted servers. I'm assuming
Mon 2008-10-20 16:11:36: * relays.ordb.org - failed
in the log you included is to blame.
...
WHERE
x_field IN ('f', 'p', 'i', 'a') ...
ORDER BY
CASE x_field
WHEN 'f' THEN 1
WHEN 'p' THEN 2
WHEN 'i' THEN 3
WHEN 'a' THEN 4
ELSE 5 --needed only is no IN clause above. eg when = 'b'
END, id
As Peter Mortensen wrote:
In the Visual Studio 2005 menu:
Debug -> New Breakpoint -> New Data Breakpoint
Enter: &myVariable
Additional information:
Obviously, the system must know which address in memory to watch.
So
- set a normal breakpoint to the initialisation of myVariable
(or myClass.m_Variable
)
- run the system and wait till it stops at that breakpoint.
- Now the Menu entry is enabled, and you can watch the variable by entering &myVariable
,
or the instance by entering &myClass.m_Variable
. Now the addresses are well defined.
Sorry when I did things wrong by explaining an already given solution. But I could not add a comment, and there has been some comments regarding this.
If someone wants to handle dynamic data with multiple rows, this is for handing dynamic data.
You can check if the rowId is equal to 0.
If it is equal to 0, then you can set the state of the boolean value as true.
interface MyCellRendererState {
value: boolean;
}
constructor(props) {
super(props);
this.state = {
value: props.value ? props.value : false
};
this.handleCheckboxChange = this.handleCheckboxChange.bind(this);
}
handleCheckboxChange() {
this.setState({ value: !this.state.value });
};
render() {
const { value } = this.state;
const rowId = this.props.rowIndex
if (rowId === 0) {
this.state = {
value : true }
}
return (
<div onChange={this.handleCheckboxChange}>
<input
type="radio"
checked={this.state.value}
name="print"
/>
</div>
)
}
select x.dbname as db_name, x.table_name as table_name, x.bytesize as the_size from
(select
table_schema as dbname,
sum(index_length+data_length) as bytesize,
table_name
from
information_schema.tables
group by table_schema
) x
where
x.bytesize > 999999
order by x.bytesize desc;
Copy & paste this to use git find-file SEARCHPATTERN
Printing all searched branches:
git config --global alias.find-file '!for branch in `git for-each-ref --format="%(refname)" refs/heads`; do echo "${branch}:"; git ls-tree -r --name-only $branch | nl -bn -w3 | grep "$1"; done; :'
Print only branches with results:
git config --global alias.find-file '!for branch in $(git for-each-ref --format="%(refname)" refs/heads); do if git ls-tree -r --name-only $branch | grep "$1" > /dev/null; then echo "${branch}:"; git ls-tree -r --name-only $branch | nl -bn -w3 | grep "$1"; fi; done; :'
These commands will add some minimal shell scripts directly to your ~/.gitconfig
as global git alias.
Try Build > Clean Solution, then Build > Build Solution. This works for me.
You can use the [[:ascii:]]
class.
I'm not familiar with python 3 yet, but it seems like urllib.request.urlopen().read()
returns a byte
object rather than string.
You might try to feed it into a StringIO
object, or even do a str(response)
.
Another way to do it programmatically which looks a bit less like a hack than the Paint way:
Instead of doing:
tv.setText(s);
do:
private static final StrikethroughSpan STRIKE_THROUGH_SPAN = new StrikethroughSpan();
...
tv.setText(s, TextView.BufferType.SPANNABLE);
Spannable spannable = (Spannable) tv.getText();
spannable.setSpan(STRIKE_THROUGH_SPAN, 0, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
If you set the editable div style to "display:inline-block; white-space: pre-wrap" you don't get new child divs when you enter a new line, you just get LF character (i.e. 
);.
function showCursPos(){
selection = document.getSelection();
childOffset = selection.focusOffset;
const range = document.createRange();
eDiv = document.getElementById("eDiv");
range.setStart(eDiv, 0);
range.setEnd(selection.focusNode, childOffset);
var sHtml = range.toString();
p = sHtml.length;
sHtml=sHtml.replace(/(\r)/gm, "\\r");
sHtml=sHtml.replace(/(\n)/gm, "\\n");
document.getElementById("caretPosHtml").value=p;
document.getElementById("exHtml").value=sHtml;
}
_x000D_
click/type in div below:
<br>
<div contenteditable name="eDiv" id="eDiv"
onkeyup="showCursPos()" onclick="showCursPos()"
style="width: 10em; border: 1px solid; display:inline-block; white-space: pre-wrap; "
>123 456 789</div>
<p>
html caret position:<br> <input type="text" id="caretPosHtml">
<p>
html from start of div:<br> <input type="text" id="exHtml">
_x000D_
What I noticed was when you press "enter" in the editable div, it creates a new node, so the focusOffset resets to zero. This is why I've had to add a range variable, and extend it from the child nodes' focusOffset back to the start of eDiv (and thus capturing all text in-between).
Convert JSONObject into String and save as TEXT/ VARCHAR. While retrieving the same column convert the String into JSONObject.
For example
Write into DB
String stringToBeInserted = jsonObject.toString();
//and insert this string into DB
Read from DB
String json = Read_column_value_logic_here
JSONObject jsonObject = new JSONObject(json);
You can do the following. Add your ggplot code after the first line of code and end with dev.off()
.
tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()
res=300
specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.
Change width
and height
in the code above depending on the desired output.
Note that this also works for other R
plots including plot
, image
, and pheatmap
.
Other file formats
In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.
I think you set the marquee width related to 5 images total width. It works fine
ex: <marquee style="width:700px"></marquee>
With C++11 you can use the constexpr
keyword and write in your header:
private:
static constexpr const char* SOMETHING = "something";
Notes:
constexpr
makes SOMETHING
a constant pointer so you cannot write
SOMETHING = "something different";
later on.
Depending on your compiler, you might also need to write an explicit definition in the .cpp file:
constexpr const char* MyClass::SOMETHING;
Yes, that is possible. At its lowest level Bluetooth allows you to connect up to 7 devices to one master device. I have done this and it has worked well for me, but only on other platforms (linux) where I had lots of manual control - I've never tried that on Android and there are some possible complications so you will need to do some testing to be certain.
One of the issues is that you need the tablet to the master and Android doesn't give you any explicit control of this. It is likely that this won't be a problem because * the tablet will automatically become the master when you try to connect a second device to it, or * you will be able to control the master/slave roles by how you setup your socket connection
I will caution though that most apps using Bluetooth on mobile are not attempting many simultaneous connections and Bluetooth can be a bit fragile, e.g. what if two devices already have a Bluetooth connection for some other app - how might that affect the roles?
For those using npm to install packages, you can install jquery via npm install jquery
and then use elixir to compile jquery and your other npm packages into one file (e.g. vendor.js). Here's a sample gulpfile.js
var elixir = require('laravel-elixir');
elixir(function(mix) {
mix
.scripts([
'jquery/dist/jquery.min.js',
// list your other npm packages here
],
'public/js/vendor.js', // 2nd param is the output file
'node_modules') // 3rd param is saying "look in /node_modules/ for these scripts"
.scripts([
'scripts.js' // your custom js file located in default location: /resources/assets/js/
], 'public/js/app.js') // looks in default location since there's no 3rd param
.version([ // optionally append versioning string to filename
'js/vendor.js', // compiled files will be in /public/build/js/
'js/app.js'
]);
});
There are also several jquery plugins that deal with this issue, but many do not handle multiple lines of text. Following works:
There also some preformance tests.
Can't you originally get the data as a JSONObject?
Perhaps parse the string as both a JSONObject and a JSONArray in the first place? Where is the JSON string coming from?
I'm not sure that it is possible to convert a JsonArray into a JsonObject.
I presume you are using the following from json.org
JSONObject.java
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
JSONArray.java
A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
Swift 4 This works for me:
Step 1 into TARGETS Click on add capability and select Push Notifications
Step 2 in AppDelegate.swift add the following code:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound]) { (didAllow, error) in
}
UIApplication.shared.registerForRemoteNotifications()
return true
}
//Get device token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("The token: \(tokenString)")
}
<Snippet name="abc">
name is an attribute, not an element. That's why it's failing. Look into using SetAttribute on the <Snippet>
element.
root.SetAttribute("name", "name goes here");
is the code you need with what you have.
If you want get location of Database you can check Get All DBs Location.
you can use sys.master_files
for get location of db and sys.databse
to get db name
SELECT
db.name AS DBName,
type_desc AS FileType,
Physical_Name AS Location
FROM
sys.master_files mf
INNER JOIN
sys.databases db ON db.database_id = mf.database_id
Either attribute can be applied to View's (visual control) horizontal or vertical size. It's used to set a View or Layouts size based on either it's contents or the size of it's parent layout rather than explicitly specifying a dimension.
fill_parent
(deprecated and renamed MATCH_PARENT
in API Level 8 and higher)
Setting the layout of a widget to fill_parent will force it to expand to take up as much space as is available within the layout element it's been placed in. It's roughly equivalent of setting the dockstyle of a Windows Form Control to Fill
.
Setting a top level layout or control to fill_parent will force it to take up the whole screen.
wrap_content
Setting a View's size to wrap_content will force it to expand only far enough to contain the values (or child controls) it contains. For controls -- like text boxes (TextView) or images (ImageView) -- this will wrap the text or image being shown. For layout elements it will resize the layout to fit the controls / layouts added as its children.
It's roughly the equivalent of setting a Windows Form Control's Autosize
property to True.
Online Documentation
There's some details in the Android code documentation here.
There are plenty of examples of using JQuery to retrieve the mouse coordinates, but none fixed my issue.
The Body of my webpage is 1000 pixels wide, and I centre it in the middle of the user's browser window.
body {
position:absolute;
width:1000px;
left: 50%;
margin-left:-500px;
}
Now, in my JavaScript code, when the user right-clicked on my page, I wanted a div to appear at the mouse position.
Problem is, just using e.pageX value wasn't quite right. It'd work fine if I resized my browser window to be about 1000 pixels wide. Then, the pop div would appear at the correct position.
But if increased the size of my browser window to, say, 1200 pixels wide, then the div would appear about 100 pixels to the right of where the user had clicked.
The solution is to combine e.pageX with the bounding rectangle of the body element. When the user changes the size of their browser window, the "left" value of body element changes, and we need to take this into account:
// Temporary variables to hold the mouse x and y position
var tempX = 0;
var tempY = 0;
jQuery(document).ready(function () {
$(document).mousemove(function (e) {
var bodyOffsets = document.body.getBoundingClientRect();
tempX = e.pageX - bodyOffsets.left;
tempY = e.pageY;
});
})
Phew. That took me a while to fix ! I hope this is useful to other developers !
This error sometimes occurs in a situation like this:
#ifndef NAN
#include <stdlib.h>
#define NAN (strtod("NAN",NULL))
#endif
static void init_random(uint32_t initseed=0)
{
if (initseed==0)
{
struct timeval tv;
gettimeofday(&tv, NULL);
seed=(uint32_t) (4223517*getpid()*tv.tv_sec*tv.tv_usec);
}
else
seed=initseed;
#if !defined(CYGWIN) && !defined(__INTERIX)
//seed=42
//SG_SPRINT("initializing random number generator with %d (seed size %d)\n", seed, RNG_SEED_SIZE)
initstate(seed, CMath::rand_state, RNG_SEED_SIZE);
#endif
}
If the following code lines not run in the run-time:
#ifndef NAN
#include <stdlib.h>
#define NAN (strtod("NAN",NULL))
#endif
you will face with an error in your code like something as follows; because initstate is placed in the stdlib.h file and it's not included:
In file included from ../../shogun/features/SubsetStack.h:14:0,
from ../../shogun/features/Features.h:21,
from ../../shogun/ui/SGInterface.h:7,
from MatlabInterface.h:15,
from matlabInterface.cpp:7:
../../shogun/mathematics/Math.h: In static member function 'static void shogun::CMath::init_random(uint32_t)':
../../shogun/mathematics/Math.h:459:52: error: 'initstate' was not declared in this scope
I just want to add that if the constructor is called from a different file, then something as simple as forgetting to export the constructor with
module.exports = NAME_OF_CONSTRUCTOR
will also cause the "Not a constructor" exception.
if anyone else has problem with the above mentioned solutions, I ended up just going for the event:
$("#jquery_audioPlayer").jPlayer({
ready:function () {
$(this).jPlayer("setMedia", {
mp3:"media/song.mp3"
})
...
pause: function () {
$('#yoursoundcontrol').click(function () {
$("#jquery_audioPlayer").jPlayer('play');
})
},
play: function () {
$('#yoursoundcontrol').click(function () {
$("#jquery_audioPlayer").jPlayer('pause');
})}
});
works for me.
I implemented this in the following way after receiving a NullPointerException
from the accepted answer.
In my FXML:
<Button onMouseClicked="#onMouseClickedCancelBtn" text="Cancel">
In my Controller
class:
@FXML public void onMouseClickedCancelBtn(InputEvent e) {
final Node source = (Node) e.getSource();
final Stage stage = (Stage) source.getScene().getWindow();
stage.close();
}
In https://www.php.net/manual/es/function.usleep.php
<?php
// Wait 2 seconds
usleep(2000000);
// if you need 5 seconds
usleep(5000000);
?>
Old question but anyway !
Same thing happen to me this morning, everything was working fine for weeks before...... yes guess what ... I change my windows PC user account password yesterday night !!!!! (how stupid was I !!!)
So easy fix : IIS -> authentication -> Anonymous authentication -> edit and set the user and new PASSWORD !!!!!
You give a particular file at a certain path and you pull the directory from the file path. Then after making sure you have the directory, you attempt to open a file for reading. To comment on this code:
filename = "/my/directory/filename.txt" dir = os.path.dirname(filename)
We want to avoid overwriting the builtin function, dir
. Also, filepath
or perhaps fullfilepath
is probably a better semantic name than filename
so this would be better written:
import os
filepath = '/my/directory/filename.txt'
directory = os.path.dirname(filepath)
Your end goal is to open this file, you initially state, for writing, but you're essentially approaching this goal (based on your code) like this, which opens the file for reading:
if not os.path.exists(directory): os.makedirs(directory) f = file(filename)
Why would you make a directory for a file that you expect to be there and be able to read?
Just attempt to open the file.
with open(filepath) as my_file:
do_stuff(my_file)
If the directory or file isn't there, you'll get an IOError
with an associated error number: errno.ENOENT
will point to the correct error number regardless of your platform. You can catch it if you want, for example:
import errno
try:
with open(filepath) as my_file:
do_stuff(my_file)
except IOError as error:
if error.errno == errno.ENOENT:
print 'ignoring error because directory or file is not there'
else:
raise
This is probably what you're wanting.
In this case, we probably aren't facing any race conditions. So just do as you were, but note that for writing, you need to open with the w
mode (or a
to append). It's also a Python best practice to use the context manager for opening files.
import os
if not os.path.exists(directory):
os.makedirs(directory)
with open(filepath, 'w') as my_file:
do_stuff(my_file)
However, say we have several Python processes that attempt to put all their data into the same directory. Then we may have contention over creation of the directory. In that case it's best to wrap the makedirs
call in a try-except block.
import os
import errno
if not os.path.exists(directory):
try:
os.makedirs(directory)
except OSError as error:
if error.errno != errno.EEXIST:
raise
with open(filepath, 'w') as my_file:
do_stuff(my_file)
Kind of a mix:
Set it in your layout file :-
<CheckBox android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="new checkbox"
android:background="@drawable/checkbox_background"
android:button="@drawable/checkbox" />
where the @drawable/checkbox will look like:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:state_focused="true"
android:drawable="@drawable/checkbox_on_background_focus_yellow" />
<item android:state_checked="false" android:state_focused="true"
android:drawable="@drawable/checkbox_off_background_focus_yellow" />
<item android:state_checked="false"
android:drawable="@drawable/checkbox_off_background" />
<item android:state_checked="true"
android:drawable="@drawable/checkbox_on_background" />
</selector>
If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.
You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar
):
openssl genrsa -aes128 -passout pass:foobar 3072
However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.
A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:
openssl genrsa -aes128 -passout file:passphrase.txt 3072
Or supply the passphrase on standard input:
openssl genrsa -aes128 -passout stdin 3072
You can also used a named pipe with the file:
option, or a file descriptor.
To then obtain the matching public key, you need to use openssl rsa
, supplying the same passphrase with the -passin
parameter as was used to encrypt the private key:
openssl rsa -passin file:passphrase.txt -pubout
(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>
).
Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar
:
openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub