Try this: tar -cf file.tar file-to-compress ; xz -z file.tar
Note:
|
because this runs commands simultaneously. Using ;
or &
executes commands one after another.Another reason this can happen:
The component you are using formControl
in is not declared in a module that imports the ReactiveFormsModule
.
So check the module that declares the component that throws this error.
$('input').live("keypress", function(e) {
/* ENTER PRESSED*/
if (e.keyCode == 13) {
/* FOCUS ELEMENT */
var inputs = $(this).parents("form").eq(0).find(":input:visible");
var idx = inputs.index(this);
if (idx == inputs.length - 1) {
inputs[0].select()
} else {
inputs[idx + 1].focus(); // handles submit buttons
inputs[idx + 1].select();
}
return false;
}
});
visible input cann't be focused.
while true; do <your-bash-snippet> && break; done
while true; do openconnect x.x.x.x:xxxx && break; done
Basic Example Code, learning to code is easy. Check Style CSS comments.
table tr {_x000D_
display: flex;_x000D_
}_x000D_
table tr td {_x000D_
/* start */_x000D_
display: inline-block; /* <- Prevent <tr> in a display css */_x000D_
text-overflow: ellipsis;_x000D_
white-space: nowrap;_x000D_
/* end */_x000D_
padding: 10px;_x000D_
width: 150px; /* Space size limit */_x000D_
border: 1px solid black;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla egestas erat ut luctus posuere. Praesent et commodo eros. Vestibulum eu nisl vel dui ultrices ultricies vel in tellus._x000D_
</td>_x000D_
<td>_x000D_
Praesent vitae tempus nulla. Donec vel porta velit. Fusce mattis enim ex. Mauris eu malesuada ante. Aenean id aliquet leo, nec ultricies tortor. Curabitur non mollis elit. Morbi euismod ante sit amet iaculis pharetra. Mauris id ultricies urna. Cras ut_x000D_
nisi dolor. Curabitur tellus erat, condimentum ac enim non, varius tempor nisi. Donec dapibus justo odio, sed consequat eros feugiat feugiat._x000D_
</td>_x000D_
<td>_x000D_
Pellentesque mattis consequat ipsum sed sagittis. Pellentesque consectetur vestibulum odio, aliquet auctor ex elementum sed. Suspendisse porta massa nisl, quis molestie libero auctor varius. Ut erat nibh, fringilla sed ligula ut, iaculis interdum sapien._x000D_
Ut dictum massa mi, sit amet interdum mi bibendum nec._x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
Sed viverra massa laoreet urna dictum, et fringilla dui molestie. Duis porta, ligula ut venenatis pretium, sapien tellus blandit felis, non lobortis orci erat sed justo. Vivamus hendrerit, quam at iaculis vehicula, nibh nisi fermentum augue, at sagittis_x000D_
nibh dui et erat._x000D_
</td>_x000D_
<td>_x000D_
Nullam mollis nulla justo, nec tincidunt urna suscipit non. Donec malesuada dolor non dolor interdum, id ultrices neque egestas. Integer ac ante sed magna gravida dapibus sit amet eu diam. Etiam dignissim est sit amet libero dapibus, in consequat est_x000D_
aliquet._x000D_
</td>_x000D_
<td>_x000D_
Vestibulum mollis, dui eu eleifend tincidunt, erat eros tempor nibh, non finibus quam ante nec felis. Fusce egestas, orci in volutpat imperdiet, risus velit convallis sapien, sodales lobortis risus lectus id leo. Nunc vel diam vel nunc congue finibus._x000D_
Vestibulum turpis tortor, pharetra sed ipsum eu, tincidunt imperdiet lorem. Donec rutrum purus at tincidunt sagittis. Quisque nec hendrerit justo._x000D_
</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
This did the trick for me. It captures all the stdout output from the subprocess(For python 3.8):
from subprocess import check_output, STDOUT
cmd = "Your Command goes here"
try:
cmd_stdout = check_output(cmd, stderr=STDOUT, shell=True).decode()
except Exception as e:
print(e.output.decode()) # print out the stdout messages up to the exception
print(e) # To print out the exception message
Here is the example of the code:
public function getItemName()
{
$this->db->select('Id,Name');
$this->db->from('item');
$this->db->where(array('Active' => 1));
return $this->db->get()->result();
}
You have to get the csrf token..
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
After doing same issue is rise ,Just Add this meta tag< meta name="csrf-token" content="{{ csrf_token() }}" >
After this also the error arise ,you can check the Ajax error. Then Also check the Ajax error
$.ajax({
url: 'some_unknown_page.html',
success: function (response) {
$('#post').html(response.responseText);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$('#post').html(msg);
},
});
I have a solution for this issue, check the code:
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir","c:\\downloads");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");
WebDriver driver = new FirefoxDriver(firefoxProfile);//new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
driver.navigate().to("http://www.myfile.com/hey.csv");
You are trying to run bash
, an interactive shell that requires a tty in order to operate. It doesn't really make sense to run this in "detached" mode with -d
, but you can do this by adding -it
to the command line, which ensures that the container has a valid tty associated with it and that stdin
remains connected:
docker run -it -d -p 52022:22 basickarl/docker-git-test
You would more commonly run some sort of long-lived non-interactive process (like sshd
, or a web server, or a database server, or a process manager like systemd
or supervisor
) when starting detached containers.
If you are trying to run a service like sshd
, you cannot simply run service ssh start
. This will -- depending on the distribution you're running inside your container -- do one of two things:
It will try to contact a process manager like systemd
or upstart
to start the service. Because there is no service manager running, this will fail.
It will actually start sshd
, but it will be started in the background. This means that (a) the service sshd start
command exits, which means that (b) Docker considers your container to have failed, so it cleans everything up.
If you want to run just ssh in a container, consider an example like this.
If you want to run sshd
and other processes inside the container, you will need to investigate some sort of process supervisor.
For Swift 3 you can use the following:
func setupSpinner(){
spinner = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height:40))
spinner.color = UIColor(Colors.Accent)
self.spinner.center = CGPoint(x:UIScreen.main.bounds.size.width / 2, y:UIScreen.main.bounds.size.height / 2)
self.view.addSubview(spinner)
spinner.hidesWhenStopped = true
}
[Column(TypeName = "decimal(18,2)")]
this will work with EF Core code first migrations as described here.
iOS 9.2.1, Xcode 7.2.1, ARC enabled
You can always append the '%' by itself without any other format specifiers in the string you are appending, like so...
int test = 10;
NSString *stringTest = [NSString stringWithFormat:@"%d", test];
stringTest = [stringTest stringByAppendingString:@"%"];
NSLog(@"%@", stringTest);
For iOS7.0+
To expand the answer to other characters that might cause you conflict you may choose to use:
- (NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters
Written out step by step it looks like this:
int test = 10;
NSString *stringTest = [NSString stringWithFormat:@"%d", test];
stringTest = [[stringTest stringByAppendingString:@"%"]
stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet alphanumericCharacterSet]];
stringTest = [stringTest stringByRemovingPercentEncoding];
NSLog(@"percent value of test: %@", stringTest);
Or short hand:
NSLog(@"percent value of test: %@", [[[[NSString stringWithFormat:@"%d", test]
stringByAppendingString:@"%"] stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet alphanumericCharacterSet]] stringByRemovingPercentEncoding]);
Thanks to all the original contributors. Hope this helps. Cheers!
try
block will execute a sensitive code which can throw exceptionscatch
block will be used whenever an exception (of the type caught) is thrown in the try blockfinally
block is called in every case after the try/catch blocks. Even if the exception isn't caught or if your previous blocks break the execution flow.throw
keyword will allow you to throw an exception (which will break the execution flow and can be caught in a catch
block).throws
keyword in the method prototype is used to specify that your method might throw exceptions of the specified type. It's useful when you have checked exception (exception that you have to handle) that you don't want to catch in your current method.Resources :
On another note, you should really accept some answers. If anyone encounter the same problems as you and find your questions, he/she will be happy to directly see the right answer to the question.
i think, simply camera not initialize in first frame. Try to save image after 10 frames.
Use a recursive query. Given
create table t (a int, b int, c int);
Run:
with recursive
a (cid, name) as (select cid, name from pragma_table_info('t')),
b (cid, name) as (
select cid, '|' || name || '|' from a where cid = 0
union all
select a.cid, b.name || a.name || '|' from a join b on a.cid = b.cid + 1
)
select name
from b
order by cid desc
limit 1;
Alternatively, just use group_concat
:
select '|' || group_concat(name, '|') || '|' from pragma_table_info('t')
Both yield:
|a|b|c|
i just wanted to share this.
fileName.slice(fileName.lastIndexOf('.'))
although this has a downfall that files with no extension will return last string. but if you do so this will fix every thing :
function getExtention(fileName){
var i = fileName.lastIndexOf('.');
if(i === -1 ) return false;
return fileName.slice(i)
}
Also, for server admins, it may be important to note that browsers may present a prompt to the user if you use 307 redirect.
For example*, Firefox and Opera would ask the user for permission to redirect, whereas Chrome, IE and Safari would do the redirect transparently.
*per Bulletproof SSL and TLS (page 192).
This is stupid but for future reference. I did put all my code in:
$(document).ready(function () {
//your jQuery function
});
But still it wasn't working and it was returning undefined
value.
I check my HTML DOM
<input id="username" placeholder="Username"></input>
and I realised that I was referencing it wrong in jQuery:
var user_name = $('#user_name').val();
Making it:
var user_name = $('#username').val();
solved my problem.
So it's always better to check your previous code.
The usual error is one tries to put Content-Type: {multipart/form-data}
into the header of the post request. That will fail, it is best to let Postman do it for you. For example:
My good friend MSDN can explain it to you, with an example
Here is the code in case the link or content changes in the future:
using System;
class DynamicInstanceList
{
private static string instanceSpec = "System.EventArgs;System.Random;" +
"System.Exception;System.Object;System.Version";
public static void Main()
{
string[] instances = instanceSpec.Split(';');
Array instlist = Array.CreateInstance(typeof(object), instances.Length);
object item;
for (int i = 0; i < instances.Length; i++)
{
// create the object from the specification string
Console.WriteLine("Creating instance of: {0}", instances[i]);
item = Activator.CreateInstance(Type.GetType(instances[i]));
instlist.SetValue(item, i);
}
Console.WriteLine("\nObjects and their default values:\n");
foreach (object o in instlist)
{
Console.WriteLine("Type: {0}\nValue: {1}\nHashCode: {2}\n",
o.GetType().FullName, o.ToString(), o.GetHashCode());
}
}
}
// This program will display output similar to the following:
//
// Creating instance of: System.EventArgs
// Creating instance of: System.Random
// Creating instance of: System.Exception
// Creating instance of: System.Object
// Creating instance of: System.Version
//
// Objects and their default values:
//
// Type: System.EventArgs
// Value: System.EventArgs
// HashCode: 46104728
//
// Type: System.Random
// Value: System.Random
// HashCode: 12289376
//
// Type: System.Exception
// Value: System.Exception: Exception of type 'System.Exception' was thrown.
// HashCode: 55530882
//
// Type: System.Object
// Value: System.Object
// HashCode: 30015890
//
// Type: System.Version
// Value: 0.0
// HashCode: 1048575
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, date);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy MM dd");
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
}
If you want to parse using InputStreams
public Object xmlToObject(String xmlDataString) {
Object converted = null;
try {
JAXBContext jc = JAXBContext.newInstance(Response.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
InputStream stream = new ByteArrayInputStream(xmlDataString.getBytes(StandardCharsets.UTF_8));
converted = unmarshaller.unmarshal(stream);
} catch (JAXBException e) {
e.printStackTrace();
}
return converted;
}
This isn't exactly what the user asked, but another way to create a long string that spans multiple lines is by incrementally building it up, like so:
$ greeting="Hello"
$ greeting="$greeting, World"
$ echo $greeting
Hello, World
Obviously in this case it would have been simpler to build it one go, but this style can be very lightweight and understandable when dealing with longer strings.
Use the random library:
import java.util.Random;
Then create a random generator:
Random rand = new Random();
As colours are separated into red green and blue, you can create a new random colour by creating random primary colours:
// Java 'Color' class takes 3 floats, from 0 to 1.
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
Then to finally create the colour, pass the primary colours into the constructor:
Color randomColor = new Color(r, g, b);
You can also create different random effects using this method, such as creating random colours with more emphasis on certain colours ... pass in less green and blue to produce a "pinker" random colour.
// Will produce a random colour with more red in it (usually "pink-ish")
float r = rand.nextFloat();
float g = rand.nextFloat() / 2f;
float b = rand.nextFloat() / 2f;
Or to ensure that only "light" colours are generated, you can generate colours that are always > 0.5 of each colour element:
// Will produce only bright / light colours:
float r = rand.nextFloat() / 2f + 0.5;
float g = rand.nextFloat() / 2f + 0.5;
float b = rand.nextFloat() / 2f + 0.5;
There are various other colour functions that can be used with the Color
class, such as making the colour brighter:
randomColor.brighter();
An overview of the Color
class can be read here: http://download.oracle.com/javase/6/docs/api/java/awt/Color.html
You could use iterator to do that:
For keys:
for (Iterator <tab> itr= hash.keySet().iterator(); itr.hasNext();) {
// use itr.next() to get the key value
}
You can use iterator similarly with values.
drop returns a new array so that is why it choked in the og post; I had a similar requirement to rename some column headers and deleted some rows due to an ill formed csv file converted to Dataframe, so after reading this post I used:
newList = pd.DataFrame(newList)
newList.columns = ['Area', 'Price']
print(newList)
# newList = newList.drop(0)
# newList = newList.drop(len(newList))
newList = newList[1:-1]
print(newList)
and it worked great, as you can see with the two commented out lines above I tried the drop.() method and it work but not as kool and readable as using [n:-n], hope that helps someone, thanks.
This may be sufficient in many cases
stream.findAny().isPresent()
Why not using just css?
<div id="wrapper">
<input onkeyup="keyup(event)">
<div id="ghost"></div>
</div>
function keyup(e) {_x000D_
document.getElementById('ghost').innerText = e.target.value;_x000D_
}
_x000D_
#wrapper {_x000D_
position: relative;_x000D_
min-width: 30px;_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
input {_x000D_
position: absolute;_x000D_
left:0;_x000D_
right:0;_x000D_
border:1px solid blue;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
#ghost {_x000D_
color: transparent;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<input onkeyup="keyup(event)">_x000D_
<div id="ghost"></div>_x000D_
</div>
_x000D_
wrapper {
position: relative;
min-width: 30px;
border: 1px solid red;
display: inline-block;
}
input {
position: absolute;
left:0;
right:0;
width: 100%;
}
#ghost {
color: transparent;
}
this code was introduced by @Iain Todd to and I thought I should share it
As you said:
if you are adding conditions dynamically you don't have to worry about stripping the initial AND that's the only reason could be, you are right.
You cannot do file i/o on the client side using javascript as that would be a security risk. You'd either have to get them to download and run an exe, or if the file is on your server, use AJAX and a server-side language such as PHP to do the i/o on serverside
You can use varStatus in your c:forEach loop
In your first example you can get the counter to work properly as follows...
<c:forEach var="tableEntity" items='${requestScope.tables}'>
<c:forEach var="rowEntity" items='${tableEntity.rows}' varStatus="count">
my count is ${count.count}
</c:forEach>
</c:forEach>
Here are a few possibilities that don't parse the output of ls
and that are 100% safe regarding files with spaces and funny symbols in their name. All of them will populate an array randf
with a list of random files. This array is easily printed with printf '%s\n' "${randf[@]}"
if needed.
This one will possibly output the same file several times, and N
needs to be known in advance. Here I chose N=42.
a=( * )
randf=( "${a[RANDOM%${#a[@]}]"{1..42}"}" )
This feature is not very well documented.
If N is not known in advance, but you really liked the previous possibility, you can use eval
. But it's evil, and you must really make sure that N
doesn't come directly from user input without being thoroughly checked!
N=42
a=( * )
eval randf=( \"\${a[RANDOM%\${#a[@]}]\"\{1..$N\}\"}\" )
I personally dislike eval
and hence this answer!
The same using a more straightforward method (a loop):
N=42
a=( * )
randf=()
for((i=0;i<N;++i)); do
randf+=( "${a[RANDOM%${#a[@]}]}" )
done
If you don't want to possibly have several times the same file:
N=42
a=( * )
randf=()
for((i=0;i<N && ${#a[@]};++i)); do
((j=RANDOM%${#a[@]}))
randf+=( "${a[j]}" )
a=( "${a[@]:0:j}" "${a[@]:j+1}" )
done
Note. This is a late answer to an old post, but the accepted answer links to an external page that shows terrible bash practice, and the other answer is not much better as it also parses the output of ls
. A comment to the accepted answer points to an excellent answer by Lhunath which obviously shows good practice, but doesn't exactly answer the OP.
$(document).on("submit","form",function(e){
//e.preventDefault();
$form = $(this);
$i = 0;
$("form input[required],form select[required]").each(function(){
if ($(this).val().trim() == ''){
$(this).css('border-color', 'red');
$i++;
}else{
$(this).css('border-color', '');
}
})
if($i != 0) e.preventDefault();
});
$(document).on("change","input[required]",function(e){
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});
$(document).on("change","select[required]",function(e){
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});
_x000D_
Change the environment variable RAILS_ENV
to production
.
Car.js
class Car {
getName() {return 'car'};
}
export default Car;
TestFile.js
const object = require('./Car.js');
const instance = new object();
error: TypeError: instance is not a constructor
printing content of object
object = {default: Car}
append default to the require function and it will work as contructor
const object = require('object-fit-images').default;
const instance = new object();
instance.getName();
I was facing the same problem . Solution is given below
Right click on Source Program > Properties > Configuration Properties > C/C++ > Language > Now change Open MP support flag to Yes....
You will get the desired result.
There's another way if you don't want to have older Java versions installed you can do the following:
1) Download the iReport-5.6.0.zip from https://sourceforge.net/projects/ireport/files/iReport/iReport-5.6.0/
2) Download jre-7u67-windows-x64.tar.gz (the one packed in a tar) from https://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html
3) Extract the iReport and in the extracted folder that contains the bin and etc folders throw in the jre. For example if you unpack twice the jre-7u67-windows-x64.tar.gz you end up with a folder named jre1.7.0_67. Put that folder in the iReport-5.6.0 directory:
and then go into the etc folder and edit the file ireport.conf and add the following line into it:
For Windows jdkhome=".\jre1.7.0_67"
For Linux jdkhome="./jre1.7.0_67"
Note : jre version may change! according to your download of 1.7
now if you run the ireport_w.exe from the bin folder in the iReport directory it should load just fine.
The documentation here encourages listening to the onbeforeunload event and/or adding an event listener on window.
window.addEventListener('beforeunload', function(event) {
//do something here
}, false);
You can also just populate the .onunload or .onbeforeunload properties of window with a function or a function reference.
Though behaviour is not standardized across browsers, the function may return a value that the browser will display when confirming whether to leave the page.
Use a ByteArrayOutputStream
. Here is the process:
InputStream
to read dataByteArrayOutputStream
.InputStream
into the OutputStream
byte[]
from the ByteArrayOutputStream
using the toByteArray()
methodRails has a built in way to seed data as explained here.
Another way would be to use a gem for more advanced or easy seeding such as: seedbank.
The main advantage of this gem and the reason I use it is that it has advanced capabilities such as data loading dependencies and per environment seed data.
Adding an up to date answer as this answer was first on google.
We have been solving the same problem just today, and all you need to do is to increase the runtime version of .NET
4.5.2 didn't work for us with the above problem, while 4.6.1 was OK
If you need to keep the .NET version, then set
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
The precise meaning of these terms is going to depend a lot on what language/system/universe you are talking about.
In HTML/XML, an attribute is the part of a tag with an equals sign and a value, and property doesn't mean anything, for example.
So we need more information about what domain you're discussing.
if you're trying to use jQuery autocomplete plugin, then I think you don't need to bind to onChange event, it will
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
I wanted to be able to access my application with the HTML5 mode and a fixed token and then switch to the hashbang method (to keep the token so the user can refresh his page).
URL for accessing my app:
http://myapp.com/amazing_url?token=super_token
Then when the user loads the page:
http://myapp.com/amazing_url?token=super_token#/amazing_url
Then when the user navigates:
http://myapp.com/amazing_url?token=super_token#/another_url
With this I keep the token in the URL and keep the state when the user is browsing. I lost a bit of visibility of the URL, but there is no perfect way of doing it.
So don't enable the HTML5 mode and then add this controller:
.config ($stateProvider)->
$stateProvider.state('home-loading', {
url: '/',
controller: 'homeController'
})
.controller 'homeController', ($state, $location)->
if window.location.pathname != '/'
$location.url(window.location.pathname+window.location.search).replace()
else
$state.go('home', {}, { location: 'replace' })
text and varchar have different implicit type conversions. The biggest impact that I've noticed is handling of trailing spaces. For example ...
select ' '::char = ' '::varchar, ' '::char = ' '::text, ' '::varchar = ' '::text
returns true, false, true
and not true, true, true
as you might expect.
This works:
myWindow = window.open('http://www.yahoo.com','myWindow', "width=200, height=200");
I've had this exact same problem a few days ago. I eventually managed to solve it. I'm not quite sure how, but I'll tell you what I did anyway. Maybe it'll help you.
I started by downloading RVM. If you aren't using it yet, I highly recommend doing so. It basically creates a sandbox for a new separate installation of Ruby, RoR and RubyGems. In fact, you can have multiple installations simultaneously and instantly switch to one other. It works like a charm.
Why is this useful? Because you shouldn't mess with the default Ruby installation in OS X. The system depends on it. It's best to just leave the default Ruby and RoR installation alone and create a new one using RVM that you can use for your own development.
Once I created my separate Ruby installation, I just installed RoR, RubyGems and mysql, and it worked. For the exact steps I took, see my question: Installing Rails, MySQL, etc. everything goes wrong
Again: I don't know for certain this will solve your problem. But it certainly did the trick for me, and in any case using RVM is highly recommendable.
If you assign it to a class it should work:
<script>
function changeClass(){
document.getElementById('myButton').className = 'formatForButton';
}
</script>
<style>
.formatForButton {
background-color:pink;
}
</style>
<body>
<input id='myButton' type=button class=none value='Change Color to pink' onclick='changeClass()'>
</body>
Based on xcopy help, I tried and found that following works perfectly for me (tried on Win 7)
xcopy C:\folder1 C:\folder2\folder1 /E /C /I /Q /G /H /R /K /Y /Z /J
I use it and works fine:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView android:id="@+id/ScrollView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
<HorizontalScrollView android:id="@+id/HorizontalScrollView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView android:id="@+id/ImageView01"
android:src="@drawable/pic"
android:isScrollContainer="true"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:adjustViewBounds="true">
</ImageView>
</HorizontalScrollView>
</ScrollView>
The source link is here: Android-spa
Update: angular2-cookie is now deprecated. Please use my ngx-cookie instead.
Old answer:
Here is angular2-cookie which is the exact implementation of Angular 1 $cookies
service (plus a removeAll()
method) that I created. It is using the same methods, only implemented in typescript with Angular 2 logic.
You can inject it as a service in the components providers
array:
import {CookieService} from 'angular2-cookie/core';
@Component({
selector: 'my-very-cool-app',
template: '<h1>My Angular2 App with Cookies</h1>',
providers: [CookieService]
})
After that, define it in the consturctur as usual and start using:
export class AppComponent {
constructor(private _cookieService:CookieService){}
getCookie(key: string){
return this._cookieService.get(key);
}
}
You can get it via npm:
npm install angular2-cookie --save
Unfortunately, you can only turn on all invisible (whitespace) characters at the same time. I suggest you file an enhancement request but I doubt they will pick it up.
The text component in Eclipse is very complicated as it is and they are not keen on making them even worse.
[UPDATE] This has been fixed in Eclipse 3.7: Go to Window > Preferences > General > Editors > Text Editors
Click on the link "whitespace characters" to fine tune what should be shown.
Kudos go to John Isaacks
That was my case. It actually links to question #4485874, but I'm going to explain it here shortly.
When you try to require path/to/script.php?parameter=value
, PHP looks for file named script.php?parameter=value
, because UNIX allows you to have paths like this.
If you are really need to pass some data to included script, just declare it as $variable=...
or $GLOBALS[]=...
or other way you like.
I had my own instance of this error, and in my case none of the above solutions resolved the "cannot be resolved to a type" error by themselves, although they were necessary steps toward doing so. I found something silly that did though.
This seemed to be due a bug in Eclipse (Luna Service Release 1a (4.4.1) in my case). In the file where you're seeing the error, try saving after making and then undoing a trivial change (e.g. deleting one character and then typing it back in). For some reason this caused all my class references to resolve.
As ams said above, don't take a pointer to a member of a struct that's packed. This is simply playing with fire. When you say __attribute__((__packed__))
or #pragma pack(1)
, what you're really saying is "Hey gcc, I really know what I'm doing." When it turns out that you do not, you can't rightly blame the compiler.
Perhaps we can blame the compiler for it's complacency though. While gcc does have a -Wcast-align
option, it isn't enabled by default nor with -Wall
or -Wextra
. This is apparently due to gcc developers considering this type of code to be a brain-dead "abomination" unworthy of addressing -- understandable disdain, but it doesn't help when an inexperienced programmer bumbles into it.
Consider the following:
struct __attribute__((__packed__)) my_struct {
char c;
int i;
};
struct my_struct a = {'a', 123};
struct my_struct *b = &a;
int c = a.i;
int d = b->i;
int *e __attribute__((aligned(1))) = &a.i;
int *f = &a.i;
Here, the type of a
is a packed struct (as defined above). Similarly, b
is a pointer to a packed struct. The type of of the expression a.i
is (basically) an int l-value with 1 byte alignment. c
and d
are both normal int
s. When reading a.i
, the compiler generates code for unaligned access. When you read b->i
, b
's type still knows it's packed, so no problem their either. e
is a pointer to a one-byte-aligned int, so the compiler knows how to dereference that correctly as well. But when you make the assignment f = &a.i
, you are storing the value of an unaligned int pointer in an aligned int pointer variable -- that's where you went wrong. And I agree, gcc should have this warning enabled by default (not even in -Wall
or -Wextra
).
First create a string in your required format using the following functions in JavaScript
var date = new Date();
var day = date.getDate(); // yields date
var month = date.getMonth() + 1; // yields month (add one as '.getMonth()' is zero indexed)
var year = date.getFullYear(); // yields year
var hour = date.getHours(); // yields hours
var minute = date.getMinutes(); // yields minutes
var second = date.getSeconds(); // yields seconds
// After this construct a string with the above results as below
var time = day + "/" + month + "/" + year + " " + hour + ':' + minute + ':' + second;
Pass this string to codebehind function and accept it as a string parameter.Use the DateTime.ParseExact()
in codebehind to convert this string to DateTime
as follows,
DateTime.ParseExact(YourString, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Hope this helps...
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]
If post data is malformed, $_POST will not contain anything. Yet, php://input will have the malformed string.
For example there is some ajax applications, that do not form correct post key-value sequence for uploading a file, and just dump all the file as post data, without variable names or anything. $_POST will be empty, $_FILES empty also, and php://input will contain exact file, written as a string.
Please search "depends.exe" in google, it's a tiny utility to handle this.
If you use Eclipse you are able to filter by application just like it is possible with Android Studio as presented by shadmazumder.
Just go to logcat, click on Display Saved Filters view, then add new logcat filter. It will appear the following:
Then you add a name to the filter and, at by application name you specify the package of your application.
Iframe
<iframe id="fred" style="border:1px solid #666CCC" title="PDF in an i-Frame" src="PDFData.pdf" frameborder="1" scrolling="auto" height="1100" width="850" ></iframe>
Object
<object data="your_url_to_pdf" type="application/pdf">
<embed src="your_url_to_pdf" type="application/pdf" />
</object>
/**
* Count file rows.
*
* @param file file
* @return file row count
* @throws IOException
*/
public static long getLineCount(File file) throws IOException {
try (Stream<String> lines = Files.lines(file.toPath())) {
return lines.count();
}
}
Tested on JDK8_u31. But indeed performance is slow compared to this method:
/**
* Count file rows.
*
* @param file file
* @return file row count
* @throws IOException
*/
public static long getLineCount(File file) throws IOException {
try (BufferedInputStream is = new BufferedInputStream(new FileInputStream(file), 1024)) {
byte[] c = new byte[1024];
boolean empty = true,
lastEmpty = false;
long count = 0;
int read;
while ((read = is.read(c)) != -1) {
for (int i = 0; i < read; i++) {
if (c[i] == '\n') {
count++;
lastEmpty = true;
} else if (lastEmpty) {
lastEmpty = false;
}
}
empty = false;
}
if (!empty) {
if (count == 0) {
count = 1;
} else if (!lastEmpty) {
count++;
}
}
return count;
}
}
Tested and very fast.
$("video").prop('muted', true); //mute
AND
$("video").prop('muted', false); //unmute
See all events here
(side note: use attr
if in jQuery < 1.6)
A practical usage difference is how they handle booleans
:
True
and False
are just keywords that mean 1
and 0
in python. Thus,
isinstance(True, int)
and
isinstance(False, int)
both return True
. Both booleans are an instance of an integer. type()
, however, is more clever:
type(True) == int
returns False
.
There are several ways to create a thread
Why so complex?
$('#id:checked').val();
Will work just fine!
If you are using Kotlin in android then you can create Extension function.
Extension Functions are defined outside of any class - yet they reference the class name and can use this
. In our case we use applicationContext
.
So in Utility class you can define all extension functions.
Utility.kt
fun Context.loadJSONFromAssets(fileName: String): String {
return applicationContext.assets.open(fileName).bufferedReader().use { reader ->
reader.readText()
}
}
MainActivity.kt
You can define private function for load JSON data from assert like this:
lateinit var facilityModelList: ArrayList<FacilityModel>
private fun bindJSONDataInFacilityList() {
facilityModelList = ArrayList<FacilityModel>()
val facilityJsonArray = JSONArray(loadJSONFromAsserts("NDoH_facility_list.json")) // Extension Function call here
for (i in 0 until facilityJsonArray.length()){
val facilityModel = FacilityModel()
val facilityJSONObject = facilityJsonArray.getJSONObject(i)
facilityModel.Facility = facilityJSONObject.getString("Facility")
facilityModel.District = facilityJSONObject.getString("District")
facilityModel.Province = facilityJSONObject.getString("Province")
facilityModel.Subdistrict = facilityJSONObject.getString("Facility")
facilityModel.code = facilityJSONObject.getInt("code")
facilityModel.gps_latitude = facilityJSONObject.getDouble("gps_latitude")
facilityModel.gps_longitude = facilityJSONObject.getDouble("gps_longitude")
facilityModelList.add(facilityModel)
}
}
You have to pass facilityModelList
in your ListView
FacilityModel.kt
class FacilityModel: Serializable {
var District: String = ""
var Facility: String = ""
var Province: String = ""
var Subdistrict: String = ""
var code: Int = 0
var gps_latitude: Double= 0.0
var gps_longitude: Double= 0.0
}
In my case JSON response start with JSONArray
[
{
"code": 875933,
"Province": "Eastern Cape",
"District": "Amathole DM",
"Subdistrict": "Amahlathi LM",
"Facility": "Amabele Clinic",
"gps_latitude": -32.6634,
"gps_longitude": 27.5239
},
{
"code": 455242,
"Province": "Eastern Cape",
"District": "Amathole DM",
"Subdistrict": "Amahlathi LM",
"Facility": "Burnshill Clinic",
"gps_latitude": -32.7686,
"gps_longitude": 27.055
}
]
Your #container should be outside of the #header-wrap, then specify a fixed height for #header-wrap, after, specify margin-top for #container equal to the #header-wrap's height. Something like this:
#header-wrap {
position: fixed;
height: 200px;
top: 0;
width: 100%;
z-index: 100;
}
#container{
margin-top: 200px;
}
Hope this is what you need: http://jsfiddle.net/KTgrS/
I'm just returning to this question after taking sth's answer and making a small but very useful modification. This function prints all keys in the JSON tree as well as the size of leaf nodes in that tree.
def print_JSON_tree(d, indent=0):
for key, value in d.iteritems():
print ' ' * indent + unicode(key),
if isinstance(value, dict):
print; print_JSON_tree(value, indent+1)
else:
print ":", str(type(d[key])).split("'")[1], "-", str(len(unicode(d[key])))
It's really nice when you have large JSON objects and want to figure out where the meat is. Example:
>>> print_JSON_tree(JSON_object)
key1
value1 : int - 5
value2 : str - 16
key2
value1 : str - 34
value2 : list - 5623456
This would tell you that most of the data you care about is probably inside JSON_object['key1']['key2']['value2']
because the length of that value formatted as a string is very large.
You could try:
$(this).closest(".column").prev().find(".inputQty").val();
The following is a jQuery function call:
$(...);
Which is the "jQuery function." $
is a function, and $(...)
is you calling that function.
The first parameter you've supplied is the following:
function() {}
The parameter is a function that you specified, and the $
function will call the supplied method when the DOM finishes loading.
You can modify your REST project, so as to produce the needed static documents (html, pdf etc) upon building the project.
If you have a Java Maven project you can use the pom snippet below. It uses a series of plugins to generate a pdf and an html documentation (of the project's REST resources).
Please be aware that the order of execution matters, since the output of one plugin, becomes the input to the next:
<plugin>
<groupId>com.github.kongchen</groupId>
<artifactId>swagger-maven-plugin</artifactId>
<version>3.1.3</version>
<configuration>
<apiSources>
<apiSource>
<springmvc>false</springmvc>
<locations>some.package</locations>
<basePath>/api</basePath>
<info>
<title>Put your REST service's name here</title>
<description>Add some description</description>
<version>v1</version>
</info>
<swaggerDirectory>${project.build.directory}/api</swaggerDirectory>
<attachSwaggerArtifact>true</attachSwaggerArtifact>
</apiSource>
</apiSources>
</configuration>
<executions>
<execution>
<phase>${phase.generate-documentation}</phase>
<!-- fx process-classes phase -->
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>io.github.robwin</groupId>
<artifactId>swagger2markup-maven-plugin</artifactId>
<version>0.9.3</version>
<configuration>
<inputDirectory>${project.build.directory}/api</inputDirectory>
<outputDirectory>${generated.asciidoc.directory}</outputDirectory>
<!-- specify location to place asciidoc files -->
<markupLanguage>asciidoc</markupLanguage>
</configuration>
<executions>
<execution>
<phase>${phase.generate-documentation}</phase>
<goals>
<goal>process-swagger</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.3</version>
<dependencies>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj-pdf</artifactId>
<version>1.5.0-alpha.11</version>
</dependency>
<dependency>
<groupId>org.jruby</groupId>
<artifactId>jruby-complete</artifactId>
<version>1.7.21</version>
</dependency>
</dependencies>
<configuration>
<sourceDirectory>${asciidoctor.input.directory}</sourceDirectory>
<!-- You will need to create an .adoc file. This is the input to this plugin -->
<sourceDocumentName>swagger.adoc</sourceDocumentName>
<attributes>
<doctype>book</doctype>
<toc>left</toc>
<toclevels>2</toclevels>
<generated>${generated.asciidoc.directory}</generated>
<!-- this path is referenced in swagger.adoc file. The given file will simply
point to the previously create adoc files/assemble them. -->
</attributes>
</configuration>
<executions>
<execution>
<id>asciidoc-to-html</id>
<phase>${phase.generate-documentation}</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>html5</backend>
<outputDirectory>${generated.html.directory}</outputDirectory>
<!-- specify location to place html file -->
</configuration>
</execution>
<execution>
<id>asciidoc-to-pdf</id>
<phase>${phase.generate-documentation}</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>pdf</backend>
<outputDirectory>${generated.pdf.directory}</outputDirectory>
<!-- specify location to place pdf file -->
</configuration>
</execution>
</executions>
</plugin>
The asciidoctor plugin assumes the existence of an .adoc file to work on. You can create one that simply collects the ones that were created by the swagger2markup plugin:
include::{generated}/overview.adoc[]
include::{generated}/paths.adoc[]
include::{generated}/definitions.adoc[]
If you want your generated html document to become part of your war file you have to make sure that it is present on the top level - static files in the WEB-INF folder will not be served. You can do this in the maven-war-plugin:
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
<webResources>
<resource>
<directory>${generated.html.directory}</directory>
<!-- Add swagger.pdf to WAR file, so as to make it available as static content. -->
</resource>
<resource>
<directory>${generated.pdf.directory}</directory>
<!-- Add swagger.html to WAR file, so as to make it available as static content. -->
</resource>
</webResources>
</configuration>
</plugin>
The war plugin works on the generated documentation - as such, you must make sure that those plugins have been executed in an earlier phase.
Option 1: Likely fastest (but not supported by some browsers if used on Document or SVGElement) :
var elements = document.getElementById('parentContainer').children;
Option 2: Likely slowest :
var elements = document.getElementById('parentContainer').getElementsByTagName('*');
Option 3: Requires change to code (wrap a form instead of a div around it) :
// Since what you're doing looks like it should be in a form...
var elements = document.forms['parentContainer'].elements;
var matches = [];
for (var i = 0; i < elements.length; i++)
if (elements[i].value.indexOf('q17_') == 0)
matches.push(elements[i]);
If I understand you right, we talk about a text file attachment. Thats unfortunate because if it was the email's message body, you could always use "\r\n", referring to http://www.faqs.org/rfcs/rfc822.html
But as it's an attachment, you must live with system differences. If I were in your shoes, I would choose one of those options:
a) only support windows clients by using "\r\n" as line end.
b) provide two attachment files, one with linux format and one with windows format.
c) I don't know if the attachment is to be read by people or machines, but if it is people I would consider attaching an HTML file instead of plain text. more portable and much prettier, too :)
You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model
Post.objects.all().delete()
and to delete any Post with a future publication date
Post.objects.filter(pub_date__gt=datetime.now()).delete()
You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.
EDIT:
Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForm
s and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.
The EXCEL and OLED DB connection managers use the parameter names 0 and 1.
I was using a oledb connection and wasted couple of hours trying to figure out the reason why the query was not working or taking the parameters. the above explanation helped a lot Thanks a lot.
You are missing PIL (Python Image Library and Imaging package). To install PIL I used
pip install pillow
For my machine running Mac OSX 10.6.8, I downloaded Imaging package and installed it from source. http://effbot.org/downloads/Imaging-1.1.6.tar.gz and cd into Download directory. Then run these:
$ gunzip Imaging-1.1.6.tar.gz
$ tar xvf Imaging-1.1.6.tar
$ cd Imaging-1.1.6
$ python setup.py install
Or if you have PIP installed in your Mac
pip install http://effbot.org/downloads/Imaging-1.1.6.tar.gz
then you can use:
from PIL import Image
in your python code.
Answer by @Ben proved to be useful for me. But I needed to check the product version as it was the main increment happening in my software and followed semantic versioning.
myFileVersionInfo.ProductVersion
This method met my expectations
Update: Instead of explicitly mentioning dll path in program (as needed in production version), we can get product version using Assembly.
Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo fileVersionInfo =FileVersionInfo.GetVersionInfo(assembly.Location);
string ProdVersion= fileVersionInfo.ProductVersion;
The best way to work around this is to specify the Dockerfile independently of the build context, using -f.
For instance, this command will give the ADD command access to anything in your current directory.
docker build -f docker-files/Dockerfile .
Update: Docker now allows having the Dockerfile outside the build context (fixed in 18.03.0-ce, https://github.com/docker/cli/pull/886). So you can also do something like
docker build -f ../Dockerfile .
echo '\x12\x02'
will not be interpreted, and will literally write the string \x12\x02
(and append a newline) to the specified serial port. Instead use
echo -n ^R^B
which you can construct on the command line by typing CtrlVCtrlR and CtrlVCtrlB. Or it is easier to use an editor to type into a script file.
The stty
command should work, unless another program is interfering. A common culprit is gpsd
which looks for GPS devices being plugged in.
Why to invent the wheel?
There is a very popular NPM package, that let you do things like that easy.
var recursive = require("recursive-readdir");
recursive("some/path", function (err, files) {
// `files` is an array of file paths
console.log(files);
});
A flow chart details the processes to follow. A DFD details the flow of data through a system.
In a flow chart, the arrows represent transfer of control (not data) between elements and the elements are instructions or decision (or I/O, etc).
In a DFD, the arrows are actually data transfer between the elements, which are themselves parts of a system.
Wikipedia has a good article on DFDs here.
you can use Glide for load and transform into blur image, 1) for only one view,
val requestOptions = RequestOptions()
requestOptions.transform(BlurTransformation(50)) // 0-100
Glide.with(applicationContext).setDefaultRequestOptions(requestOptions)
.load(imageUrl).into(view)
2) if you are using the adapter to load an image in the item, you should write your code in the if-else block, otherwise, it will make all your images blurry.
if(isBlure){
val requestOptions = RequestOptions()
requestOptions.transform(BlurTransformation(50))
Glide.with(applicationContext).setDefaultRequestOptions(requestOptions)
.load(imageUrl).into(view )
}else{
val requestOptions = RequestOptions()
Glide.with(applicationContext).setDefaultRequestOptions(requestOptions).load(imageUrl).into(view)
}
The reason this occurs is because bash actually expands the asterisk to every matching file, producing a very long command line.
Try this:
find . -name "*.pdf" -print0 | xargs -0 rm
Warning: this is a recursive search and will find (and delete) files in subdirectories as well. Tack on -f
to the rm command only if you are sure you don't want confirmation.
You can do the following to make the command non-recursive:
find . -maxdepth 1 -name "*.pdf" -print0 | xargs -0 rm
Another option is to use find's -delete
flag:
find . -name "*.pdf" -delete
If you are using Java 1.6 or greater, you can use Arrays.copyOfRange
to copy a portion of the array. From the javadoc:
Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and
original.length
, inclusive. The value atoriginal[from]
is placed into the initial element of the copy (unlessfrom == original.length
orfrom == to
). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to
), which must be greater than or equal tofrom
, may be greater thanoriginal.length
, in which casefalse
is placed in all elements of the copy whose index is greater than or equal tooriginal.length - from
. The length of the returned array will beto - from
.
Here is a simple example:
/**
* @Program that Copies the specified range of the specified array into a new
* array.
* CopyofRange8Array.java
* Author:-RoseIndia Team
* Date:-15-May-2008
*/
import java.util.*;
public class CopyofRange8Array {
public static void main(String[] args) {
//creating a short array
Object T[]={"Rose","India","Net","Limited","Rohini"};
// //Copies the specified short array upto specified range,
Object T1[] = Arrays.copyOfRange(T, 1,5);
for (int i = 0; i < T1.length; i++)
//Displaying the Copied short array upto specified range
System.out.println(T1[i]);
}
}
Try this:
$.datepicker.parseDate("yy-mm-dd", minValue);
I created my own jQuery plugin for this task, you can try it out here:
http://jsfiddle.net/Sk8erPeter/8NF4r/
You can create character counters on-the-fly (and also remaining character counters), you can define whether you want to chop text, you can define the suffix texts and you can also define a short format and its separator.
Here's an example usage:
$(document).ready(function () {
$('#first_textfield').characterCounter();
$('#second_textfield').characterCounter({
maximumCharacters: 20,
chopText: true
});
$('#third_textfield').characterCounter({
maximumCharacters: 20,
shortFormat: true,
shortFormatSeparator: " / ",
positionBefore: true,
chopText: true
});
$('#fourth_textfield').characterCounter({
maximumCharacters: 20,
characterCounterNeeded: true,
charactersRemainingNeeded: true,
chopText: false
});
$('#first_textarea').characterCounter({
maximumCharacters: 50,
characterCounterNeeded: true,
charactersRemainingNeeded: false,
chopText: true
});
$('#second_textarea').characterCounter({
maximumCharacters: 25
});
});
Here's the code of the plugin:
/**
* Character counter and limiter plugin for textfield and textarea form elements
* @author Sk8erPeter
*/
(function ($) {
$.fn.characterCounter = function (params) {
// merge default and user parameters
params = $.extend({
// define maximum characters
maximumCharacters: 1000,
// create typed character counter DOM element on the fly
characterCounterNeeded: true,
// create remaining character counter DOM element on the fly
charactersRemainingNeeded: true,
// chop text to the maximum characters
chopText: false,
// place character counter before input or textarea element
positionBefore: false,
// class for limit excess
limitExceededClass: "character-counter-limit-exceeded",
// suffix text for typed characters
charactersTypedSuffix: " characters typed",
// suffix text for remaining characters
charactersRemainingSuffixText: " characters left",
// whether to use the short format (e.g. 123/1000)
shortFormat: false,
// separator for the short format
shortFormatSeparator: "/"
}, params);
// traverse all nodes
this.each(function () {
var $this = $(this),
$pluginElementsWrapper,
$characterCounterSpan,
$charactersRemainingSpan;
// return if the given element is not a textfield or textarea
if (!$this.is("input[type=text]") && !$this.is("textarea")) {
return this;
}
// create main parent div
if (params.characterCounterNeeded || params.charactersRemainingNeeded) {
// create the character counter element wrapper
$pluginElementsWrapper = $('<div>', {
'class': 'character-counter-main-wrapper'
});
if (params.positionBefore) {
$pluginElementsWrapper.insertBefore($this);
} else {
$pluginElementsWrapper.insertAfter($this);
}
}
if (params.characterCounterNeeded) {
$characterCounterSpan = $('<span>', {
'class': 'counter character-counter',
'text': 0
});
if (params.shortFormat) {
$characterCounterSpan.appendTo($pluginElementsWrapper);
var $shortFormatSeparatorSpan = $('<span>', {
'html': params.shortFormatSeparator
}).appendTo($pluginElementsWrapper);
} else {
// create the character counter element wrapper
var $characterCounterWrapper = $('<div>', {
'class': 'character-counter-wrapper',
'html': params.charactersTypedSuffix
});
$characterCounterWrapper.prepend($characterCounterSpan);
$characterCounterWrapper.appendTo($pluginElementsWrapper);
}
}
if (params.charactersRemainingNeeded) {
$charactersRemainingSpan = $('<span>', {
'class': 'counter characters-remaining',
'text': params.maximumCharacters
});
if (params.shortFormat) {
$charactersRemainingSpan.appendTo($pluginElementsWrapper);
} else {
// create the character counter element wrapper
var $charactersRemainingWrapper = $('<div>', {
'class': 'characters-remaining-wrapper',
'html': params.charactersRemainingSuffixText
});
$charactersRemainingWrapper.prepend($charactersRemainingSpan);
$charactersRemainingWrapper.appendTo($pluginElementsWrapper);
}
}
$this.keyup(function () {
var typedText = $this.val();
var textLength = typedText.length;
var charactersRemaining = params.maximumCharacters - textLength;
// chop the text to the desired length
if (charactersRemaining < 0 && params.chopText) {
$this.val(typedText.substr(0, params.maximumCharacters));
charactersRemaining = 0;
textLength = params.maximumCharacters;
}
if (params.characterCounterNeeded) {
$characterCounterSpan.text(textLength);
}
if (params.charactersRemainingNeeded) {
$charactersRemainingSpan.text(charactersRemaining);
if (charactersRemaining <= 0) {
if (!$charactersRemainingSpan.hasClass(params.limitExceededClass)) {
$charactersRemainingSpan.addClass(params.limitExceededClass);
}
} else {
$charactersRemainingSpan.removeClass(params.limitExceededClass);
}
}
});
});
// allow jQuery chaining
return this;
};
})(jQuery);
Major advantage :
ViewHolder
is not available by default in ListView
. We will be creating explicitly inside the getView()
.
RecyclerView
has inbuilt Viewholder
.
iirc :
cat filename.txt | awk '{ print $2 $4 }'
or, as mentioned in the comments :
awk '{ print $2 $4 }' filename.txt
If you can't use the delay
method as Robert Harvey suggested, you can use setTimeout
.
Eg.
setTimeout(function() {$("#test").animate({"top":"-=80px"})} , 1500); // delays 1.5 sec
setTimeout(function() {$("#test").animate({"opacity":"0"})} , 1500 + 1000); // delays 1 sec after the previous one
first add two frameworks in your project
1: MapKit
2: Corelocation (no longer necessary as of XCode 7.2.1)
Define in your class
var manager:CLLocationManager!
var myLocations: [CLLocation] = []
then in viewDidLoad method code this
manager = CLLocationManager()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()
//Setup our Map View
mapobj.showsUserLocation = true
do not forget to add these two value in plist file
1: NSLocationWhenInUseUsageDescription
2: NSLocationAlwaysUsageDescription
You see the two empty -D
entries in the g++
command line? They're causing the problem. You must have values in the -D
items e.g. -DWIN32
if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:
SYSTEM ?= generic
ENVIRONMENT ?= generic
in the makefile which gives them default values.
Your output looks to be missing the all important output:
<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers
just to clarify, what actually got sent to g++
was -D -DWindows_NT
, i.e. define a preprocessor macro called -DWindows_NT
; which is of course not a valid identifier (similarly for -D -I.
)
You should use formControlName="surveyType"
on an input
and not on a div
It means that somewhere in your code, you are calling a function which in turn calls another function and so forth, until you hit the call stack limit.
This is almost always because of a recursive function with a base case that isn't being met.
Consider this code...
(function a() {
a();
})();
Here is the stack after a handful of calls...
As you can see, the call stack grows until it hits a limit: the browser hardcoded stack size or memory exhaustion.
In order to fix it, ensure that your recursive function has a base case which is able to be met...
(function a(x) {
// The following condition
// is the base case.
if ( ! x) {
return;
}
a(--x);
})(10);
Easiest and Best Solution
Save your .py file in a folder. This case my folder name is test. In the command prompt run the following
c:\test> set FLASK_APP=application.py
c:\test> set FLASK_RUN_PORT=8000
c:\test> flask run
----------------- Following will be returned ----------------
* Serving Flask app "application.py"
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:8000/ (Press CTRL+C to quit)
127.0.0.1 - - [23/Aug/2019 09:40:04] "[37mGET / HTTP/1.1[0m" 200 -
127.0.0.1 - - [23/Aug/2019 09:40:04] "[33mGET /favicon.ico HTTP/1.1[0m" 404 -
Now on your browser type: http://127.0.0.1:8000. Thanks
change the background color of cell B5 based on the value of another cell - C5. If C5 is greater than 80% then the background color is green but if it's below, it will be amber/red.
There is no mention that B5 contains any value so assuming 80%
is .8
formatted as percentage without decimals and blank counts as "below":
Select B5, colour "amber/red" with standard fill then Format - Conditional formatting..., Custom formula is and:
=C5>0.8
with green fill and Done.
This is the demo how to trigger event
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("input").select(function(){
$("input").after(" Text marked!");
});
$("button").click(function(){
$("input").trigger("select");
});
});
</script>
</head>
<body>
<input type="text" value="Hello World"><br><br>
<button>Trigger the select event for the input field</button>
</body>
</html>
Try the following:
PreparedStatementCreator creator = new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? ");
updateSales.setInt(1, 75);
updateSales.setString(2, "Colombian");
return updateSales;
}
};
This worked for with maven 3.5.4 and now Intellij Idea see this code as source:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<generatedSourcesDirectory>src/main/generated</generatedSourcesDirectory>
</configuration>
</plugin>
Edit: This code will wait until all content (images and scripts) are fully loaded and rendered in the browser.
I've had this problem where $(window).on('load',function(){ ... })
would fire too quick for my code since the Javascript I used was for formatting purposes and hiding elements. The elements where hidden too soon and where left with a height of 0.
I now use $(window).on('pageshow',function(){ //code here });
and it fires at the time I need.
I have experienced very slow edits with Visual Studio 2015 Community Edition especially while working with HTML (and Razor as well) and JavaScript. I was able to resolve the issue by removing the references in the "Scripts/_references.js" file of my ASP.NET MVC project. Furthermore, I disabled autosyncing in that file by adding this to the top of the _references.js file.
This solution causes Visual Studio's IntelliSense to not load show all the JavaScript references available. However, ReSharper's IntelliSense will work perfectly fine and fast.
/// <autosync enabled="false" />
The git rev-parse
solution proposed by @Andy works fine if the date you're interested is the commit's date. If however you want to checkout based on the author's date, rev-parse
won't work, because it doesn't offer an option to use that date for selecting the commits. Instead, you can use the following.
git checkout $(
git log --reverse --author-date-order --pretty=format:'%ai %H' master |
awk '{hash = $4} $1 >= "2016-04-12" {print hash; exit 0 }
)
(If you also want to specify the time use $1 >= "2016-04-12" && $2 >= "11:37"
in the awk predicate.)
import React, {Component} from 'react';
import imagename from './imagename.png'; //image is in the current folder where the App.js exits
class App extends React. Component{
constructor(props){
super(props)
this.state={
imagesrc=imagename // as it is imported
}
}
render(){
return (
<ImageClass
src={this.state.imagesrc}
/>
);
}
}
class ImageClass extends React.Component{
render(){
return (
<img src={this.props.src} height='200px' width='100px' />
);
}
}
export default App;
As Brad Wilson states in his answer here:
ModelState.IsValid tells you if any model errors have been added to ModelState.
The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.
Try using :-
if (!ModelState.IsValid)
{
var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));
// Breakpoint, Log or examine the list with Exceptions.
}
If it helps catching you the error. Courtesy this and this
$.extend($.expr[':'], {
unchecked: function (obj) {
return ((obj.type == 'checkbox' || obj.type == 'radio') && !$(obj).is(':checked'));
}
});
$("input:checked")
$("input:unchecked")
Possibly:
select lpad(column, 8, 0) from table;
Edited in response to question from mylesg, in comments below:
ok, seems to make the change on the query- but how do I make it stick (change it) permanently in the table? I tried an UPDATE instead of SELECT
I'm assuming that you used a query similar to:
UPDATE table SET columnName=lpad(nums,8,0);
If that was successful, but the table's values are still without leading-zeroes, then I'd suggest you probably set the column as a numeric type? If that's the case then you'd need to alter the table so that the column is of a text/varchar() type in order to preserve the leading zeroes:
First:
ALTER TABLE `table` CHANGE `numberColumn` `numberColumn` CHAR(8);
Second, run the update:
UPDATE table SET `numberColumn`=LPAD(`numberColum`, 8, '0');
This should, then, preserve the leading-zeroes; the down-side is that the column is no longer strictly of a numeric type; so you may have to enforce more strict validation (depending on your use-case) to ensure that non-numerals aren't entered into that column.
References:
Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).
Example:
var divMapLoaded = false;
$("#container").scroll(function() {
if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
$("#map-iframe").html("<iframe id=\"map-iframe\" " +
"width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
"marginheight=\"0\" marginwidth=\"0\" " +
"src=\"http://www.google.it/maps?t=m&cid=0x3e589d98063177ab&ie=UTF8&iwloc=A&brcurrent=5,0,1&ll=41.123115,16.853177&spn=0.005617,0.009943&output=embed\"" +
"></iframe>");
divMapLoaded = true;
}
Maybe not very elegant, but it does the job:
exec(open("script.py").read())
I invite you to explore what Python 3.8 has to offer for the subject matter in form of Structural subtyping (static duck typing)
(PEP 544)
See the short description https://docs.python.org/3/library/typing.html#typing.Protocol
For the simple example here it goes like this:
from typing import Protocol
class MyShowProto(Protocol):
def show(self):
...
class MyClass:
def show(self):
print('Hello World!')
class MyOtherClass:
pass
def foo(o: MyShowProto):
return o.show()
foo(MyClass()) # ok
foo(MyOtherClass()) # fails
foo(MyOtherClass())
will fail static type checks:
$ mypy proto-experiment.py
proto-experiment.py:21: error: Argument 1 to "foo" has incompatible type "MyOtherClass"; expected "MyShowProto"
Found 1 error in 1 file (checked 1 source file)
In addition, you can specify the base class explicitly, for instance:
class MyOtherClass(MyShowProto):
but note that this makes methods of the base class actually available on the subclass, and thus the static checker will not report that a method definition is missing on the MyOtherClass
.
So in this case, in order to get a useful type-checking, all the methods that we want to be explicitly implemented should be decorated with @abstractmethod
:
from typing import Protocol
from abc import abstractmethod
class MyShowProto(Protocol):
@abstractmethod
def show(self): raise NotImplementedError
class MyOtherClass(MyShowProto):
pass
MyOtherClass() # error in type checker
Just a followup to smashery's answer. The ephemeral port range (on Linux at least, and I suspect other Unices as well) is not a fixed. This can be controlled by writing to
/proc/sys/net/ipv4/ip_local_port_range
The only restriction (as far as IANA is concerned) is that ports below 1024 are designated to be well-known ports. Ports above that are free for use. Often you'll find that ports below 1024 are restricted to superuser access, I believe for this very reason.
Clean up, check all check box => This work for me
mysql 5.7 exposes metadata lock information through the performance_schema.metadata_locks
table.
Documentation here
If that's your exact format, you can go through the list and modify the dictionaries.
for item in list_of_dicts:
for key, value in item.iteritems():
try:
item[key] = int(value)
except ValueError:
item[key] = float(value)
If you've got something more general, then you'll have to do some kind of recursive update on the dictionary. Check if the element is a dictionary, if it is, use the recursive update. If it's able to be converted into a float or int, convert it and modify the value in the dictionary. There's no built-in function for this and it can be quite ugly (and non-pythonic since it usually requires calling isinstance).
Enough to using eval javascript function to convert string to boolean
eval('true')
eval('false')
Change the = to : to
fix the error.
var makeRequest = function(message) {<br>
var options = {<br>
host: 'localhost',<br>
port : 8080,<br>
path : '/',<br>
method: 'POST'<br>
}
It can't parse that string because "UTC" is not a valid time zone designator.
UTC time is denoted by adding a 'Z' to the end of the time string, so your parsing code should look like this:
DateTime.Parse("Tue, 1 Jan 2008 00:00:00Z");
From the Wikipedia article on ISO 8601
If the time is in UTC, add a 'Z' directly after the time without a space. 'Z' is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "0930Z". "14:45:15 UTC" would be "14:45:15Z" or "144515Z".
UTC time is also known as 'Zulu' time, since 'Zulu' is the NATO phonetic alphabet word for 'Z'.
I know this was already answered, but I used this and extended it a little more in my code so that you didn't have search by only the uid. I just want to share it for anyone else who may need that functionality.
Here's my example and please bare in mind this is my first answer. I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid.
Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique.
/**
* @param array multidimensional
* @param string value to search for, ie a specific field name like name_first
* @param string associative key to find it in, ie field_name
*
* @return array keys.
*/
function search_revisions($dataArray, $search_value, $key_to_search) {
// This function will search the revisions for a certain value
// related to the associative key you are looking for.
$keys = array();
foreach ($dataArray as $key => $cur_value) {
if ($cur_value[$key_to_search] == $search_value) {
$keys[] = $key;
}
}
return $keys;
}
Later, I ended up writing this to allow me to search for another value and associative key. So my first example allows you to search for a value in any specific associative key, and return all the matches.
This second example shows you where a value ('Taylor') is found in a certain associative key (first_name) AND another value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name 'Taylor' AND are employed).
/**
* @param array multidimensional
* @param string $search_value The value to search for, ie a specific 'Taylor'
* @param string $key_to_search The associative key to find it in, ie first_name
* @param string $other_matching_key The associative key to find in the matches for employed
* @param string $other_matching_value The value to find in that matching associative key, ie true
*
* @return array keys, ie all the people with the first name 'Taylor' that are employed.
*/
function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null) {
// This function will search the revisions for a certain value
// related to the associative key you are looking for.
$keys = array();
foreach ($dataArray as $key => $cur_value) {
if ($cur_value[$key_to_search] == $search_value) {
if (isset($other_matching_key) && isset($other_matching_value)) {
if ($cur_value[$other_matching_key] == $other_matching_value) {
$keys[] = $key;
}
} else {
// I must keep in mind that some searches may have multiple
// matches and others would not, so leave it open with no continues.
$keys[] = $key;
}
}
}
return $keys;
}
Use of function
$data = array(
array(
'cust_group' => 6,
'price' => 13.21,
'price_qty' => 5
),
array(
'cust_group' => 8,
'price' => 15.25,
'price_qty' => 4
),
array(
'cust_group' => 8,
'price' => 12.75,
'price_qty' => 10
)
);
$findKey = search_revisions($data,'8', 'cust_group', '10', 'price_qty');
print_r($findKey);
Result
Array ( [0] => 2 )
As JERC said, make sure you have an updated version of git. If you are only using the default settings, when you try to install git you will get version 1.7.1. Other than manually downloading and installing the latest version of get, you can also accomplish this by adding a new repository to yum.
From tecadmin.net:
Download and install the rpmforge repository:
# use this for 64-bit
rpm -i 'http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm'
# use this for 32-bit
rpm -i 'http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.i686.rpm'
# then run this in either case
rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt
Then you need to enable the rpmforge-extras. Edit /etc/yum.repos.d/rpmforge.repo
and change enabled = 0
to enabled = 1
under [rpmforge-extras]
. The file looks like this:
### Name: RPMforge RPM Repository for RHEL 6 - dag
### URL: http://rpmforge.net/
[rpmforge]
name = RHEL $releasever - RPMforge.net - dag
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/rpmforge
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge
enabled = 1
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1
[rpmforge-extras]
name = RHEL $releasever - RPMforge.net - extras
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/extras
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge-extras
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge-extras
enabled = 0 ####### CHANGE THIS LINE TO "enabled = 1" #############
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1
[rpmforge-testing]
name = RHEL $releasever - RPMforge.net - testing
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/testing
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge-testing
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge-testing
enabled = 0
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1
Once you've done this, then you can update git with
yum update git
I'm not sure why, but they then suggest disabling rpmforge-extras (change back to enabled = 0
) and then running yum clean all
.
Most likely you'll need to use sudo
for these commands.
Instead of using Bitmap
, you can also do this through a trivial InputStream
. Well, I am not sure, but I think it's a bit efficient.
InputStream inputStream = new FileInputStream(fileName); // You can get an inputStream using any I/O API
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);
In my scenario, I was supposed to open a dialog box in the mouse position based on a GUI operation done with the mouse. The following code worked for me:
public Object open() {
//create the contents of the dialog
createContents();
//setting the shell location based on the curent position
//of the mouse
PointerInfo a = MouseInfo.getPointerInfo();
Point pt = a.getLocation();
shellEO.setLocation (pt.x, pt.y);
//once the contents are created and location is set-
//open the dialog
shellEO.open();
shellEO.layout();
Display display = getParent().getDisplay();
while (!shellEO.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
return result;
}
In neither case is the "syntax malformed". It's the semantics that are wrong. Hence, IMHO a 400 is inappropriate. Instead, it would be appropriate to return a 200 along with some kind of error object such as { "error": { "message": "Unknown request keyword" } }
or whatever.
Consider the client processing path(s). An error in syntax (e.g. invalid JSON) is an error in the logic of the program, in other words a bug of some sort, and should be handled accordingly, in a way similar to a 403, say; in other words, something bad has gone wrong.
An error in a parameter value, on the other hand, is an error of semantics, perhaps due to say poorly validated user input. It is not an HTTP error (although I suppose it could be a 422). The processing path would be different.
For instance, in jQuery, I would prefer not to have to write a single error handler that deals with both things like 500 and some app-specific semantic error. Other frameworks, Ember for one, also treat HTTP errors like 400s and 500s identically as big fat failures, requiring the programmer to detect what's going on and branch depending on whether it's a "real" error or not.
I just want to add that orderby is way more useful.
Why? Because I can do this:
Dim thisAccountBalances = account.DictOfBalances.Values.ToList
thisAccountBalances.ForEach(Sub(x) x.computeBalanceOtherFactors())
thisAccountBalances=thisAccountBalances.OrderBy(Function(x) x.TotalBalance).tolist
listOfBalances.AddRange(thisAccountBalances)
Why complicated comparer? Just sort based on a field. Here I am sorting based on TotalBalance.
Very easy.
I can't do that with sort. I wonder why. Do fine with orderBy.
As for speed it's always O(n).
Simple javascript document navigation to "#" will do it.
window.onload = function()
{
document.location.href = "#";
}
This will force the navigation bar to remove itself on load.
In my case the error was caused by cloud function invoker limit access. Please add allUsers to cloud function invoker. Please catch link. Please refer to article for more info
I had the very same issue. The answer is that you are doing it right already. It is the problem of MS Excel. Try opening the file with another editor and you will notice that your encoding was successful already. To make MS Excel happy, move from UTF-8 to UTF-16. This should work:
class UnicodeWriter:
def __init__(self, f, dialect=csv.excel_tab, encoding="utf-16", **kwds):
# Redirect output to a queue
self.queue = StringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
# Force BOM
if encoding=="utf-16":
import codecs
f.write(codecs.BOM_UTF16)
self.encoding = encoding
def writerow(self, row):
# Modified from original: now using unicode(s) to deal with e.g. ints
self.writer.writerow([unicode(s).encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = data.encode(self.encoding)
# strip BOM
if self.encoding == "utf-16":
data = data[2:]
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
None of these answers worked for me. Most of these answers give you a half-transparent border. To avoid this, you need to wrap your container once again with another container with your preferred color. Here is an example:
dashed_border_layout.xml
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="@color/black"
android:background="@drawable/dashed_border_out">
<LinearLayout
android:layout_width="150dp"
android:layout_height="50dp"
android:padding="5dp"
android:background="@drawable/dashed_border_in"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Dashed Container"
android:textSize="16sp" />
</LinearLayout>
dashed_border_in.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape>
<corners android:radius="10dp" />
<solid android:color="#ffffff" />
<stroke
android:dashGap="5dp"
android:dashWidth="5dp"
android:width="3dp"
android:color="#0000FF" />
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
</shape>
</item>
dashed_border_out.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape>
<corners android:radius="12dp" />
</shape>
</item>
You need to use isset() to check whether value is set.
You could do something like this if you want only whole numbers.
function make_whole($v){
$v = floor($v);
if(is_numeric($v)){
echo (int)$v;
// if you want only positive whole numbers
//echo (int)$v = abs($v);
}
}
In general, i agree with above answers that recommend to add maven dependency, but i prefer following solution.
Add a dependency with API classes for full JavaEE profile:
<properties>
<javaee-api.version>7.0</javaee-api.version>
<hibernate-entitymanager.version>5.1.3.Final</hibernate-entitymanager.version>
</properties>
<depencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javaee-api.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
Also add dependency with particular JPA provider like antonycc suggested:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-entitymanager.version}</version>
</dependency>
Note <scope>provided</scope>
in API dependency section: this means that corresponding jar will not be exported into artifact's lib/
, but will be provided by application server. Make sure your application server implements specified version of JavaEE API.
It appears that you are using the default route which is defined as this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The key part of that route is the {id}
piece. If you look at your action method, your parameter is k
instead of id
. You need to change your action method to this so that it matches the route parameter:
// change int k to int id
public ActionResult DetailsData(int id)
If you wanted to leave your parameter as k, then you would change the URL to be:
http://localhost:7317/Employee/DetailsData?k=4
You also appear to have a problem with your connection string. In your web.config, you need to change your connection string to this (provided by haim770 in another answer that he deleted):
<connectionStrings>
<add name="EmployeeContext"
connectionString="Server=.;Database=mytry;integrated security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Find the distance between the center of the circle and the points given. If the distance between them is less than the radius then the point is inside the circle. if the distance between them is equal to the radius of the circle then the point is on the circumference of the circle. if the distance is greater than the radius then the point is outside the circle.
int d = r^2 - ((center_x-x)^2 + (center_y-y)^2);
if(d>0)
print("inside");
else if(d==0)
print("on the circumference");
else
print("outside");
NSString *stringWithoutAsterisk(NSString *string) {
NSRange asterisk = [string rangeOfString:@"*"];
return asterisk.location == 0 ? [string substringFromIndex:1] : string;
}
the documentation has this blurb https://requests.readthedocs.io/en/master/user/quickstart/#redirection-and-history
import requests
r = requests.get('http://www.github.com')
r.url
#returns https://www.github.com instead of the http page you asked for
In my case new File()
doesn't work, it causes a FileNotFoundException
when run in a Jenkins pipeline job. The following code solved this, and is even easier in my opinion:
def fileContents = readFile "path/to/file"
I still don't understand this difference completely, but maybe it'll help anyone else with the same trouble. Possibly the exception was caused because new File()
creates a file on the system which executes the groovy code, which was a different system than the one that contains the file I wanted to read.
In case you are like me, and cannot work out how to use "regular expression with capturing groups" for extract
, the following code replicates the extract(...)
line in Hadleys' answer:
df %>%
gather(question_number, value, starts_with("Q3.")) %>%
mutate(loop_number = str_sub(question_number,-2,-2), question_number = str_sub(question_number,1,4)) %>%
select(id, time, loop_number, question_number, value) %>%
spread(key = question_number, value = value)
The problem here is that the initial gather forms a key column that is actually a combination of two keys. I chose to use mutate
in my original solution in the comments to split this column into two columns with equivalent info, a loop_number
column and a question_number
column. spread
can then be used to transform the long form data, which are key value pairs (question_number, value)
to wide form data.
composer dump-autoload
PATH vendor/composer/autoload_classmap.php
php artisan dump-autoload
Usually what you choose will depend on which methods you need access to. In general - IEnumerable<>
(MSDN: http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx) for a list of objects that only needs to be iterated through, ICollection<>
(MSDN: http://msdn.microsoft.com/en-us/library/92t2ye13.aspx) for a list of objects that needs to be iterated through and modified, List<>
for a list of objects that needs to be iterated through, modified, sorted, etc (See here for a full list: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx).
From a more specific standpoint, lazy loading comes in to play with choosing the type. By default, navigation properties in Entity Framework come with change tracking and are proxies. In order for the dynamic proxy to be created as a navigation property, the virtual type must implement ICollection
.
A navigation property that represents the "many" end of a relationship must return a type that implements ICollection, where T is the type of the object at the other end of the relationship. -Requirements for Creating POCO ProxiesMSDN
1 - Open the files '.vbox' and '.vbox-prev' (if exist) files in any text editor and replace the first character of HardDisk uuid (take note to revert this change on step 6)
Example: nano /home/virtualbox/WindowsServer/WindowsServer.vbox
Change:
<HardDisks>
<HardDisk uuid="{3ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>
To:
<HardDisks>
<HardDisk uuid="{2ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>
2 - Reboot machine
4 - Stop Virtual Machine (if started)
5 - On terminal:
su vbox
cd /home/virtualbox/WindowsServer/
VBoxManage modifyhd WindowsServer.vdi --resize SIZE
exit
exit
change SIZE for a number in Megabytes, example 80000 (80GB)
6 - Open again the files '.vbox' and '.vbox-prev' (if exist) files in any text editor and replace the first character of HardDisk uuid whith the original value
Example: nano /home/virtualbox/WindowsServer/WindowsServer.vbox
Change:
<HardDisks>
<HardDisk uuid="{2ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>
To:
<HardDisks>
<HardDisk uuid="{3ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>
7 - Reboot machine
If you wish, you can also use the column names instead of column numbers.
For example, if you want to read data from DataGridView on the 4. row and the "Name" column. It provides me a better understanding for which variable I am dealing with.
dataGridView.Rows[4].Cells["Name"].Value.ToString();
Hope it helps.
String[] values = new String[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
values[i] = arrayList.get(i).type;
}
You can find the list of formats here (in the Double.ToString()-MSDN-Article) as comments in the example section.
The way I usually do this is using the --suppress-common-lines
flag, though note that this only works if your do it in side-by-side format.
diff -y --suppress-common-lines file1.txt file2.txt
background-size: 200px 50px change it to 100% 100% and it will scale on the needs of the content tag like ul li or div... tried it
Below is an interesting use of the id attribute. It is used within the tag and used to identify the form for elements outside of the boundaries so that they will be included with the other fields within the form.
<form action="action_page.php" id="form1">
First name: <input type="text" name="fname"><br>
<input type="submit" value="Submit">
</form>
<p>The "Last name" field below is outside the form element, but still part of the form.</p>
Last name: <input type="text" name="lname" form="form1">
in my case using angular
in my HTTP interceptor , i set
with Credentials: true.
in the header of the request
For Mac .app
bundles, you should install them via cask, if available, as using symlinks can cause issues. You may even get the following warning if you brew linkapps
:
Unfortunately
brew linkapps
cannot behave nicely with e.g. Spotlight using either aliases or symlinks and Homebrew formulae do not build "proper".app
bundles that can be relocated. Instead, please consider usingbrew cask
and migrate formulae using.app
s to casks.
For MacVim, you can install with:
brew cask install macvim
You should then be able to launch MacVim like you do any other macOS app, including mvim
or open -a MacVim
from a terminal session.
UPDATE: A bit of clarification about brew
and brew cask
. In a nutshell, brew
handles software at the unix level, whereas brew cask
extends the functionality of brew
into the macOS domain for additional functionality such as handling the location of macOS app bundles. Remember that brew
is also implemented on Linux so it makes sense to have this division. There are other resources that explain the difference in more detail, such as What is the difference between brew
and brew cask
?
so I won't say much more here.
Just use Date.parse()
which returns a Number, then use new Date()
to parse it:
var thedate = new Date(Date.parse("2011-07-14 11:23:00"));
The .success
syntax was correct up to Angular v1.4.3.
For versions up to Angular v.1.6, you have to use then
method. The then()
method takes two arguments: a success
and an error
callback which will be called with a response object.
Using the then()
method, attach a callback
function to the returned promise
.
Something like this:
app.controller('MainCtrl', function ($scope, $http){
$http({
method: 'GET',
url: 'api/url-api'
}).then(function (response){
},function (error){
});
}
See reference here.
Shortcut
methods are also available.
$http.get('api/url-api').then(successCallback, errorCallback);
function successCallback(response){
//success code
}
function errorCallback(error){
//error code
}
The data you get from the response is expected to be in JSON
format.
JSON is a great way of transporting data, and it is easy to use within AngularJS
The major difference between the 2 is that .then()
call returns a promise
(resolved with a value returned from a callback
) while .success()
is more traditional way of registering callbacks
and doesn't return a promise
.
You are reinventing the wheel.
If you need persistence and other enterprise features use JMS (I'd suggest ActiveMq).
If you need fast in-memory queues use one of the impementations of java's Queue.
If you need to support java 1.4 or earlier, use Doug Lea's excellent concurrent package.
SCROLLBARS & $(window).scrollTop()
What I have discovered is that calling such functionality as in the solution thankfully provided above, (there are many more examples of this throughout this forum - which all work well) is only successful when scrollbars are actually visible and operating.
If (as I have maybe foolishly tried), you wish to implement such functionality, and you also wish to, shall we say, implement a minimalist "clean screen" free of scrollbars, such as at this discussion, then $(window).scrollTop()
will not work.
It may be a programming fundamental, but thought I'd offer the heads up to any fellow newbies, as I spent a long time figuring this out.
If anyone could offer some advice as to how to overcome this or a little more insight, feel free to reply, as I had to resort to show/hide onmouseover/mouseleave instead here
Live long and program, CollyG.
In case that it serves to someone, I leave here the Windows 10 base register for Python 3.4.4 - 64 bit:
Por si alguien lo necesita todavía, este es el registro base de Windows 10 para Python 3.4.4:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4]
"DisplayName"="Python 3.4 (64-bit)"
"SupportUrl"="http://www.python.org/"
"Version"="3.4.4"
"SysVersion"="3.4"
"SysArchitecture"="64bit"
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Help]
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Help\Main Python Documentation]
@="C:\\Python34\\Doc\\python364.chm"
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Idle]
@="C:\\Python34\\Lib\\idlelib\\idle.pyw"
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\IdleShortcuts]
@=dword:00000001
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstalledFeatures]
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath]
@="C:\\Python34\\"
"ExecutablePath"="C:\\Python34\\python.exe"
"WindowedExecutablePath"="C:\\Python34\\pythonw.exe"
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\PythonPath]
@="C:\\Python34\\Lib\\;C:\\Python34\\DLLs\\"
You can add this to the callback from $.post
$( '#newsletterform' ).each(function(){
this.reset();
});
You can't just call $( '#newsletterform' ).reset()
because .reset()
is a form object and not a jquery object, or something to that effect. You can read more about it here about half way down the page.
Something like this should work: From Frans Bouma's Blog
SELECT * FROM
(
SELECT a.*, rownum r__
FROM
(
SELECT * FROM ORDERS WHERE CustomerID LIKE 'A%'
ORDER BY OrderDate DESC, ShippingDate DESC
) a
WHERE rownum < ((pageNumber * pageSize) + 1 )
)
WHERE r__ >= (((pageNumber-1) * pageSize) + 1)
Simula, C++, and C#, which use static method binding by default, the programmer can specify that particular methods should use dynamic binding by labeling them as virtual. Dynamic method binding is central to object-oriented programming.
Object oriented programming requires three fundamental concepts: encapsulation, inheritance, and dynamic method binding.
Encapsulation allows the implementation details of an abstraction to be hidden behind a simple interface.
Inheritance allows a new abstraction to be defined as an extension or refinement of some existing abstraction, obtaining some or all of its characteristics automatically.
Dynamic method binding allows the new abstraction to display its new behavior even when used in a context that expects the old abstraction.
It is always better to have separate tables for multi valued attributes like phone number.
As you have no control on source data so, you can parse the data from XML file and convert it into the proper format so that there will not be any issue with formats of a particular country and store it in a separate table so that indexing and retrieval both will be efficient.
Thank you.
See this blog post. If you call preventDefault
on every touchstart
then you should also have a CSS rule to disable touch scrolling like
.sortable-handler {
touch-action: none;
}
try creating connection string this way:
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql7.000webhost.com";
conn_string.UserID = "a455555_test";
conn_string.Password = "a455555_me";
conn_string.Database = "xxxxxxxx";
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{ //watch out for this SQL injection vulnerability below
cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
OSGconv.deciLat, OSGconv.deciLon);
conn.Open();
cmd.ExecuteNonQuery();
}
The args parameter stores all command line arguments which are given by the user when you run the program.
If you run your program from the console like this:
program.exe there are 4 parameters
Your args parameter will contain the four strings: "there", "are", "4", and "parameters"
Here is an example of how to access the command line arguments from the args parameter: example
You can set custom font in two ways : design time
and run-time
.
First you need to download required font
(.ttf file format). Then, double click on the file to install it.
This will show a pop-up. Click on 'install font
' button.
'Fonts'
window.Add to targets
' is checked.Copy Bundle Resources'
present in Build Phases
of Targets
of your project.Info.plist
of your project.
Create a new key with 'Font Provided by application
' with type as Array.
Add a the font as an element with type String in Array.A. Design mode :
Font
attribute present in Attribute inspector
of Utilities
.B. Run-time mode :
self.lblWelcome.font = UIFont(name: "BananaYeti-Extrabold Trial", size: 16)
It seems that run-time mode doesn't work for dynamically formed string like
self.lblWelcome.text = "Welcome, " + fullname + "!"
Note that in above case only design-time approach worked correctly for me.
EDIT
Starting with Android Studio 3.1, you should go to:
File -> Sync Project with Gradle Files
OLD
Clicking the button 'Sync Project With Gradle Files' should do the trick:
Tools -> Android -> Sync Project with Gradle Files
If that fails, try running 'Rebuild project':
Build -> Rebuild Project
I did something like that :
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view.findViewById(android.R.id.text1);
textView.setHeight(30);
textView.setMinimumHeight(30);
/*YOUR CHOICE OF COLOR*/
textView.setTextColor(Color.BLACK);
return view;
}
You must put the both fields textView.setHeight(30); textView.setMinimumHeight(30); or it won't change anything. For me it worked & i had the same problem.
I think that if you stick strictly with TSQL
that this is the fastest way to truncate the time:
select convert(datetime,convert(int,convert(float,[Modified])))
I found this truncation method to be about 5% faster than the DateAdd
method. And this can be easily modified to round to the nearest day like this:
select convert(datetime,ROUND(convert(float,[Modified]),0))
Try this
#dimScreen {
width: 100%;
height: 100%;
background:rgba(255,255,255,0.5);
position: fixed;
top: 0;
left: 0;
}
Your error is caused by these:
Dim oTable As Table, oRow As Row,
These types, Table
and Row
are not variable types native to Excel. You can resolve this in one of two ways:
Dim oTable as Word.Table, oRow as Word.Row
. This is called early-binding. Object
type: Dim oTable as Object, oRow as Object
. With this method, you do not need to add the reference to Word, but you also lose the intellisense assistance in the VBE.I have not tested your code but I suspect ActiveDocument
won't work in Excel with method #2, unless you properly scope it to an instance of a Word.Application object. I don't see that anywhere in the code you have provided. An example would be like:
Sub DeleteEmptyRows()
Dim wdApp as Object
Dim oTable As Object, As Object, _
TextInRow As Boolean, i As Long
Set wdApp = GetObject(,"Word.Application")
Application.ScreenUpdating = False
For Each oTable In wdApp.ActiveDocument.Tables
I believe Mica's way deserves the rank of answer, since is not visible enough as a comment:
\begin{tikzpicture}[font=\small]
For the second part of your question, you can also use shift
, for example:
df['t-1'] = df['t'].shift(1)
t-1
would then contain the values from t one row above.
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html
This is a pure JavaScript solution without any libraries or plugins:
document.addEventListener('click', function (e) {
if (hasClass(e.target, 'bu')) {
// .bu clicked
// Do your thing
} else if (hasClass(e.target, 'test')) {
// .test clicked
// Do your other thing
}
}, false);
where hasClass
is
function hasClass(elem, className) {
return elem.className.split(' ').indexOf(className) > -1;
}
Credit goes to Dave and Sime Vidas
Using more modern JS, hasClass
can be implemented as:
function hasClass(elem, className) {
return elem.classList.contains(className);
}
It really works great, but you only have 30 minutes/month for free.
For 19$/month you have unlimited time.
Use datetime.datetime.fromtimestamp
:
>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'
%f
directive is only supported by datetime.datetime.strftime
, not by time.strftime
.
UPDATE Alternative using %
, str.format
:
>>> import time
>>> s, ms = divmod(1236472051807, 1000) # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
If you want to refresh the controller while refreshing any services you are using, you can use this solution:
i.e.
app.controller('myCtrl',['$scope','MyService','$state', function($scope,MyService,$state) {
//At the point where you want to refresh the controller including MyServices
$state.reload();
//OR:
$state.go($state.current, {}, {reload: true});
}
This will refresh the controller and the HTML as well you can call it Refresh or Re-Render.
... What about using Apache's FileFilters from:
org.apache.commons.io
?
just like:
import org.apache.commons.io.filefilter.FileFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
...
File dir = new File(".");
String[] filters = { "*.txt"};
IOFileFilter wildCardFilter = new WildcardFileFilter(filters, IOCase.INSENSITIVE);
String[] files = dir.list( wildCardFilter );
for ( int i = 0; i < files.length; i++ ) {
System.out.println(files[i]);
}
After trying a few others posted here without good results, this seemed to work for me:
convertUTCDateToLocalDate: function (date) {
return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
}
And this works to go the opposite way, from Local Date to UTC:
convertLocalDatetoUTCDate: function(date){
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following.
char *ptr = "Hello";
printf("%40s\n", ptr);
That will give you 35 spaces, then the word "Hello". This is how you format stuff when you know how wide you want the column, but the data changes (well, it's one way you can do it).
If you know you want exactly 40 spaces then some text, just save the 40 spaces in a constant and print them. If you need to print multiple lines, either use multiple printf
statements like the one above, or do it in a loop, changing the value of ptr
each time.
Wrote this implementation. It allows for missing values, negative values and keeps code consistent. The map is cached as well. Uses an interface and needs Java 8.
Enum
public enum Command implements OrdinalEnum{
PRINT_FOO(-7),
PRINT_BAR(6),
PRINT_BAZ(4);
private int val;
private Command(int val){
this.val = val;
}
public int getVal(){
return val;
}
private static Map<Integer, Command> map = OrdinalEnum.getValues(Command.class);
public static Command from(int i){
return map.get(i);
}
}
Interface
public interface OrdinalEnum{
public int getVal();
@SuppressWarnings("unchecked")
static <E extends Enum<E>> Map<Integer, E> getValues(Class<E> clzz){
Map<Integer, E> m = new HashMap<>();
for(Enum<E> e : EnumSet.allOf(clzz))
m.put(((OrdinalEnum)e).getVal(), (E)e);
return m;
}
}
You might want to add the following to your .bash_profile (or equivalent), which starts ssh-agent on login.
if [ -f ~/.agent.env ] ; then
. ~/.agent.env > /dev/null
if ! kill -0 $SSH_AGENT_PID > /dev/null 2>&1; then
echo "Stale agent file found. Spawning new agent… "
eval `ssh-agent | tee ~/.agent.env`
ssh-add
fi
else
echo "Starting ssh-agent"
eval `ssh-agent | tee ~/.agent.env`
ssh-add
fi
On some Linux distros (Ubuntu, Debian) you can use:
ssh-copy-id -i ~/.ssh/id_dsa.pub username@host
This will copy the generated id to a remote machine and add it to the remote keychain.
Remove those char * ret
declarations inside if
blocks which hide outer ret
. Therefor you have memory leak and on the other hand un-allocated memory for ret
.
To compare a c-style string you should use strcmp(array,"")
not array!=""
. Your final code should looks like below:
char* appendCharToCharArray(char* array, char a)
{
size_t len = strlen(array);
char* ret = new char[len+2];
strcpy(ret, array);
ret[len] = a;
ret[len+1] = '\0';
return ret;
}
Note that, you must handle the allocated memory of returned ret
somewhere by delete[]
it.
Why you don't use std::string
? it has .append
method to append a character at the end of a string:
std::string str;
str.append('x');
// or
str += x;
Simplest of all solutions:
In Python 3.x:
import urllib.request
url = "https://api.github.com/users?since=100"
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
data_content = response.read()
print(data_content)
Definitely late to the party; anyway, for those interested, picking up on Lan's mention of HTML5 canvas, you can use gRaphaël Charting which has a MIT License (instead of HighCharts dual license). It's not Bootstrap-specific either, so it's more of a general suggestion.
I have to admit that HighCharts demos seem very pretty, and I have to warn that gRaphaël is quite hard to understand before becoming proficient with it. Anyway you can easily add nice features to your gRaphaël charts (say, tooltips or zooming effects), so it may be worth the effort.
If multiple processes are writing to the file, you must use append mode or the data will be scrambled. Append mode will make the operating system put every write, at the end of the file irrespective of where the writer thinks his position in the file is. This is a common issue for multi-process services like nginx or apache where multiple instances of the same process, are writing to the same log file. Consider what happens if you try to seek, then write:
Example does not work well with multiple processes:
f = open("logfile", "w"); f.seek(0, os.SEEK_END); f.write("data to write");
writer1: seek to end of file. position 1000 (for example)
writer2: seek to end of file. position 1000
writer2: write data at position 1000 end of file is now 1000 + length of data.
writer1: write data at position 1000 writer1's data overwrites writer2's data.
By using append mode, the operating system will place any write at the end of the file.
f = open("logfile", "a"); f.seek(0, os.SEEK_END); f.write("data to write");
Append most does not mean, "open file, go to end of the file once after opening it". It means, "open file, every write I do will be at the end of the file".
WARNING: For this to work you must write all your record in one shot, in one write call. If you split the data between multiple writes, other writers can and will get their writes in between yours and mangle your data.
I would like to add a resolution that worked for me. Setup: Oracle 11g 64 bits running on Windows 2008 R2 (64 bits OS)
Client is a .net framework 3.5 application (ported from 2.0) compiled with x86 platform setting.
I had the exact same issue of BadImageFormatException. Compiling to 64 bits eliminates the exception but it was not an option for me as my app is using 32 bits activex components who do not work in 64 bits.
I solved the issue by downloading Oracle Instant Client 11 (this is just a bunch of DLL than can be xcopied) from Oracle website, and copying the files in my application files directory. See here : http://www.oracle.com/technetwork/database/features/oci/instant-client-wp-131479.pdf
This has solved the issue, from ProcMon tool I can see that the locally copied oci.dll gets loaded by System.Data.OracleClient and everything is fine.
It could probably be done by changing environment settings like proposed above, but this method has the advantage of not altering any settings on the server configuration.
If you are filtering by common date this will return it:
dfs = [df1, df2, df3]
checker = dfs[-1]
check = set(checker.loc[:, 0])
for df in dfs[:-1]:
check = check.intersection(set(df.loc[:, 0]))
print(checker[checker.loc[:, 0].isin(check)])
datetime library sometimes gives errors with strptime() so I switched to dateutil library. Here's an example of how you can use it :
from dateutil import parser
parser.parse('January 11, 2010').strftime("%a")
The output that you get from this is 'Mon'
. If you want the output as 'Monday', use the following :
parser.parse('January 11, 2010').strftime("%A")
This worked for me pretty quickly. I was having problems while using the datetime library because I wanted to store the weekday name instead of weekday number and the format from using the datetime library was causing problems. If you're not having problems with this, great! If you are, you cand efinitely go for this as it has a simpler syntax as well. Hope this helps.
Remove warnings.filterwarnings and add:
numpy.seterr(all='raise')
2014-12-01 Update: The answer below works only for one very specific format of CSV. As correctly pointed out by DG in the comments, this solution does not fit the RFC 4180 definition of CSV and it also does not fit Microsoft Excel format. This solution simply demonstrates how one can parse one (non-standard) CSV line of input which contains a mix of string types, where the strings may contain escaped quotes and commas.
As austincheney correctly points out, you really need to parse the string from start to finish if you wish to properly handle quoted strings that may contain escaped characters. Also, the OP does not clearly define what a "CSV string" really is. First we must define what constitutes a valid CSV string and its individual values.
For the purpose of this discussion, a "CSV string" consists of zero or more values, where multiple values are separated by a comma. Each value may consist of:
Rules/Notes:
'that\'s cool'
.\'
in single quoted values.\"
in double quoted values.A JavaScript function which converts a valid CSV string (as defined above) into an array of string values.
The regular expressions used by this solution are complex. And (IMHO) all non-trivial regular expressions should be presented in free-spacing mode with lots of comments and indentation. Unfortunately, JavaScript does not allow free-spacing mode. Thus, the regular expressions implemented by this solution are first presented in native regular expressions syntax (expressed using Python's handy r'''...'''
raw-multi-line-string syntax).
First here is a regular expression which validates that a CVS string meets the above requirements:
re_valid = r"""
# Validate a CSV string having single, double or un-quoted values.
^ # Anchor to start of string.
\s* # Allow whitespace before value.
(?: # Group for value alternatives.
'[^'\\]*(?:\\[\S\s][^'\\]*)*' # Either Single quoted string,
| "[^"\\]*(?:\\[\S\s][^"\\]*)*" # or Double quoted string,
| [^,'"\s\\]*(?:\s+[^,'"\s\\]+)* # or Non-comma, non-quote stuff.
) # End group of value alternatives.
\s* # Allow whitespace after value.
(?: # Zero or more additional values
, # Values separated by a comma.
\s* # Allow whitespace before value.
(?: # Group for value alternatives.
'[^'\\]*(?:\\[\S\s][^'\\]*)*' # Either Single quoted string,
| "[^"\\]*(?:\\[\S\s][^"\\]*)*" # or Double quoted string,
| [^,'"\s\\]*(?:\s+[^,'"\s\\]+)* # or Non-comma, non-quote stuff.
) # End group of value alternatives.
\s* # Allow whitespace after value.
)* # Zero or more additional values
$ # Anchor to end of string.
"""
If a string matches the above regular expression, then that string is a valid CSV string (according to the rules previously stated) and may be parsed using the following regular expression. The following regular expression is then used to match one value from the CSV string. It is applied repeatedly until no more matches are found (and all values have been parsed).
re_value = r"""
# Match one value in valid CSV string.
(?!\s*$) # Don't match empty last value.
\s* # Strip whitespace before value.
(?: # Group for value alternatives.
'([^'\\]*(?:\\[\S\s][^'\\]*)*)' # Either $1: Single quoted string,
| "([^"\\]*(?:\\[\S\s][^"\\]*)*)" # or $2: Double quoted string,
| ([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*) # or $3: Non-comma, non-quote stuff.
) # End group of value alternatives.
\s* # Strip whitespace after value.
(?:,|$) # Field ends on comma or EOS.
"""
Note that there is one special case value that this regular expression does not match - the very last value when that value is empty. This special "empty last value" case is tested for and handled by the JavaScript function which follows.
// Return array of string values, or NULL if CSV string not well formed.
function CSVtoArray(text) {
var re_valid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/;
var re_value = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g;
// Return NULL if input string is not well formed CSV string.
if (!re_valid.test(text)) return null;
var a = []; // Initialize array to receive values.
text.replace(re_value, // "Walk" the string using replace with callback.
function(m0, m1, m2, m3) {
// Remove backslash from \' in single quoted values.
if (m1 !== undefined) a.push(m1.replace(/\\'/g, "'"));
// Remove backslash from \" in double quoted values.
else if (m2 !== undefined) a.push(m2.replace(/\\"/g, '"'));
else if (m3 !== undefined) a.push(m3);
return ''; // Return empty string.
});
// Handle special case of empty last value.
if (/,\s*$/.test(text)) a.push('');
return a;
};
In the following examples, curly braces are used to delimit the {result strings}
. (This is to help visualize leading/trailing spaces and zero-length strings.)
// Test 1: Test string from original question.
var test = "'string, duppi, du', 23, lala";
var a = CSVtoArray(test);
/* Array has three elements:
a[0] = {string, duppi, du}
a[1] = {23}
a[2] = {lala} */
// Test 2: Empty CSV string.
var test = "";
var a = CSVtoArray(test);
/* Array has zero elements: */
// Test 3: CSV string with two empty values.
var test = ",";
var a = CSVtoArray(test);
/* Array has two elements:
a[0] = {}
a[1] = {} */
// Test 4: Double quoted CSV string having single quoted values.
var test = "'one','two with escaped \' single quote', 'three, with, commas'";
var a = CSVtoArray(test);
/* Array has three elements:
a[0] = {one}
a[1] = {two with escaped ' single quote}
a[2] = {three, with, commas} */
// Test 5: Single quoted CSV string having double quoted values.
var test = '"one","two with escaped \" double quote", "three, with, commas"';
var a = CSVtoArray(test);
/* Array has three elements:
a[0] = {one}
a[1] = {two with escaped " double quote}
a[2] = {three, with, commas} */
// Test 6: CSV string with whitespace in and around empty and non-empty values.
var test = " one , 'two' , , ' four' ,, 'six ', ' seven ' , ";
var a = CSVtoArray(test);
/* Array has eight elements:
a[0] = {one}
a[1] = {two}
a[2] = {}
a[3] = { four}
a[4] = {}
a[5] = {six }
a[6] = { seven }
a[7] = {} */
This solution requires that the CSV string be "valid". For example, unquoted values may not contain backslashes or quotes, e.g. the following CSV string is not valid:
var invalid1 = "one, that's me!, escaped \, comma"
This is not really a limitation because any sub-string may be represented as either a single or double quoted value. Note also that this solution represents only one possible definition for "comma-separated values".
This also works for https needed a solution to making project directories this was it. because chrome doesn't like non ssl anymore used free ssl. Notice: My Web Server is Wamp64 on Windows 10 so I wouldn't use this config because of variables unless your using wamp.
<VirtualHost *:443>
ServerAdmin [email protected]
ServerName test.com
ServerAlias *.test.com
SSLEngine On
SSLCertificateFile "conf/key/certificatecom.crt"
SSLCertificateKeyFile "conf/key/privatecom.key"
VirtualDocumentRoot "${INSTALL_DIR}/www/subdomains/%1/"
DocumentRoot "${INSTALL_DIR}/www/subdomains"
<Directory "${INSTALL_DIR}/www/subdomains/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>
The answer here worked better for me as it isolates the search on the hashtag, not just returning results that contain the search string. In the answer above you would still need to parse the JSON response to see if the entities.hashtags array is not empty.
For those that do know the width, you could do something like
div {
max-width: ???px; //px,%
margin-left:auto;
margin-right:auto;
}
I also agree about not setting text-align:center on the body because it can mess up the rest of your code and you might have to individually set text-align:left on a lot of things either then or in the future.
Go to python console by typing
$ python
in your terminal. Then, type the following 2 commands in your python shell to install the respective packages:
>> nltk.download('punkt') >> nltk.download('averaged_perceptron_tagger')
This solved the issue for me.
For personal usage, I add a vim plugin like Vrapper to Eclipse and just use yy
to copy entire line.
Eclipse with Pydev works best for me on any platform.
A good approach to solving this problem is to first write the code required to get one result, then incorporate threading code to parallelize the application.
In a perfect world this would simply mean simultaneously starting 100,000 threads which output their results into a dictionary or list for later processing, but in practice you are limited in how many parallel HTTP requests you can issue in this fashion. Locally, you have limits in how many sockets you can open concurrently, how many threads of execution your Python interpreter will allow. Remotely, you may be limited in the number of simultaneous connections if all the requests are against one server, or many. These limitations will probably necessitate that you write the script in such a way as to only poll a small fraction of the URLs at any one time (100, as another poster mentioned, is probably a decent thread pool size, although you may find that you can successfully deploy many more).
You can follow this design pattern to resolve the above issue:
list
or dict
in CPython, you can safely append or insert unique items from your threads without locks, but if you write to a file or require in more complex cross-thread data interaction you should use a mutual exclusion lock to protect this state from corruption.I would suggest you use the threading module. You can use it to launch and track running threads. Python's threading support is bare, but the description of your problem suggests that it is completely sufficient for your needs.
Finally, if you'd like to see a pretty straightforward application of a parallel network application written in Python, check out ssh.py. It's a small library which uses Python threading to parallelize many SSH connections. The design is close enough to your requirements that you may find it to be a good resource.
The pattern must have delimiters. Delimiters can be a forward slash (/) or any non alphanumeric characters(#,$,*,...). Examples
$pattern = "/My name is '(.*)' and im fine/";
$pattern = "#My name is '(.*)' and im fine#";
$pattern = "@My name is '(.*)' and im fine@";
Following ae the steps i followed to uninstall and reinstall. Which worked for me.
First remove the installed postgres :-
sudo apt-get purge postgr*
sudo apt-get autoremove
Then install 'synaptic':
sudo apt-get install synaptic
sudo apt-get update
Then install postgres
sudo apt-get install postgresql postgresql-contrib
Using DataBinding and setting background to the edittext with resources from the drawable folder causes the exception.
<EditText
android:background="@drawable/rectangle"
android:imeOptions="flagNoExtractUi"
android:layout_width="match_parent"
android:layout_height="45dp"
android:hint="Enter Your Name"
android:gravity="center"
android:textColorHint="@color/hintColor"
android:singleLine="true"
android:id="@+id/etName"
android:inputType="textCapWords"
android:text="@={viewModel.model.name}"
android:fontFamily="@font/avenir_roman"/>
Solution
I just change the background from android:background="@drawable/rectangle"
to android:background="@null"
Clean and Rebuild the Project.
To connect your tablet using TCP port. Make sure your system and device is connected to same network.
adb tcpip 5555
adb connect 192.168.1.2
this is your device IP addressConnected using port forward Try to do port forwarding,
adb forward tcp:<PC port>
tcp:<device port>
like:
adb forward tcp:5555 tcp:5555.
C:\Users\abc>adb forward tcp:7612 tcp:7612
C:\Users\abc>adb tcpip 7612 restarting in TCP mode port: 7612
C:\Users\abc>adb connect 10.0.0.1:7612
connected to 10.0.0.1:7612
If you get message error: device not found connect a usb device to system then follow same procedure.
for a rooted device
setprop service.adb.tcp.port 5555
stop adbd
start adbd
Try providing the proxy details as parameters
sbt compile -Dhttps.proxyHost=localhost -Dhttps.proxyPort=port -Dhttp.proxyHost=localhost -Dhttp.proxyPort=port
If that is not working then try with JAVA_OPTS (non windows)
export JAVA_OPTS = "-Dhttps.proxyHost=localhost -Dhttps.proxyPort=port -Dhttp.proxyHost=localhost -Dhttp.proxyPort=port"
sbt compile
or (windows)
set JAVA_OPTS = "-Dhttps.proxyHost=localhost -Dhttps.proxyPort=port -Dhttp.proxyHost=localhost -Dhttp.proxyPort=port"
sbt compile
if nothing works then set SBT_OPTS
(non windows)
export SBT_OPTS = "-Dhttps.proxyHost=localhost -Dhttps.proxyPort=port -Dhttp.proxyHost=localhost -Dhttp.proxyPort=port"'
sbt compile
or (windows)
set SBT_OPTS = "-Dhttps.proxyHost=localhost -Dhttps.proxyPort=port -Dhttp.proxyHost=localhost -Dhttp.proxyPort=port"
sbt compile