You need to overload operator <<
for mystruct
class
Something like :-
friend ostream& operator << (ostream& os, const mystruct& m)
{
os << m.m_a <<" " << m.m_b << endl;
return os ;
}
See here
In my case, I had trouble with GoDaddy and SSL encryption.
Setting the encryption to Null and Port to 80 (Or any supportive port) did the job.
In C++11, a range-based for loop might be a good solution:
vector<char> items = {'a','b','c'};
for (char n : items)
cout << n << ' ';
Output:
a b c
Qt has a method for copying files:
#include <QFile>
QFile::copy("originalFile.example","copiedFile.example");
Note that to use this you have to install Qt (instructions here) and include it in your project (if you're using Windows and you're not an administrator, you can download Qt here instead). Also see this answer.
What this means is that you are trying to print out/output a value which is at least partially uninitialized. Can you narrow it down so that you know exactly what value that is? After that, trace through your code to see where it is being initialized. Chances are, you will see that it is not being fully initialized.
If you need more help, posting the relevant sections of source code might allow someone to offer more guidance.
EDIT
I see you've found the problem. Note that valgrind watches for Conditional jump or move based on unitialized variables. What that means is that it will only give out a warning if the execution of the program is altered due to the uninitialized value (ie. the program takes a different branch in an if statement, for example). Since the actual arithmetic did not involve a conditional jump or move, valgrind did not warn you of that. Instead, it propagated the "uninitialized" status to the result of the statement that used it.
It may seem counterintuitive that it does not warn you immediately, but as mark4o pointed out, it does this because uninitialized values get used in C all the time (examples: padding in structures, the realloc()
call, etc.) so those warnings would not be very useful due to the false positive frequency.
If you are inserting into a single table, you can write your query like this (maybe only in MySQL):
INSERT INTO table1 (First, Last)
VALUES
('Fred', 'Smith'),
('John', 'Smith'),
('Michael', 'Smith'),
('Robert', 'Smith');
This is my Save Attachments script. You select all the messages that you want the attachments saved from, and it will save a copy there. It also adds text to the message body indicating where the attachment is saved. You could easily change the folder name to include the date, but you would need to make sure the folder existed before starting to save files.
Public Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem 'Object
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String
' Get the path to your My Documents folder
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next
' Instantiate an Outlook Application object.
Set objOL = CreateObject("Outlook.Application")
' Get the collection of selected objects.
Set objSelection = objOL.ActiveExplorer.Selection
' Set the Attachment folder.
strFolderpath = strFolderpath & "\Attachments\"
' Check each selected item for attachments. If attachments exist,
' save them to the strFolderPath folder and strip them from the item.
For Each objMsg In objSelection
' This code only strips attachments from mail items.
' If objMsg.class=olMail Then
' Get the Attachments collection of the item.
Set objAttachments = objMsg.Attachments
lngCount = objAttachments.Count
strDeletedFiles = ""
If lngCount > 0 Then
' We need to use a count down loop for removing items
' from a collection. Otherwise, the loop counter gets
' confused and only every other item is removed.
For i = lngCount To 1 Step -1
' Save attachment before deleting from item.
' Get the file name.
strFile = objAttachments.Item(i).FileName
' Combine with the path to the Temp folder.
strFile = strFolderpath & strFile
' Save the attachment as a file.
objAttachments.Item(i).SaveAsFile strFile
' Delete the attachment.
objAttachments.Item(i).Delete
'write the save as path to a string to add to the message
'check for html and use html tags in link
If objMsg.BodyFormat <> olFormatHTML Then
strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
Else
strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & _
strFile & "'>" & strFile & "</a>"
End If
'Use the MsgBox command to troubleshoot. Remove it from the final code.
'MsgBox strDeletedFiles
Next i
' Adds the filename string to the message body and save it
' Check for HTML body
If objMsg.BodyFormat <> olFormatHTML Then
objMsg.Body = vbCrLf & "The file(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
Else
objMsg.HTMLBody = "<p>" & "The file(s) were saved to " & strDeletedFiles & "</p>" & objMsg.HTMLBody
End If
objMsg.Save
End If
Next
ExitSub:
Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub
Just append a #
followed by the ID of the <a>
tag (or other HTML tag, like a <section>
) that you're trying to get to. For example, if you are trying to link to the header in this HTML:
<p>This is some content.</p>
<h2><a id="target">Some Header</a></h2>
<p>This is some more content.</p>
You could use the link <a href="http://url.to.site/index.html#target">Link</a>
.
My simple explanation is:
In some scenarios, based on the logic or code, the compiler will do optimisation of variables which it thinks do not change. The volatile
keyword prevents a variable being optimised.
For example:
bool usb_interface_flag = 0;
while(usb_interface_flag == 0)
{
// execute logic for the scenario where the USB isn't connected
}
From the above code, the compiler may think usb_interface_flag
is defined as 0, and that in the while loop it will be zero forever. After optimisation, the compiler will treat it as while(true)
all the time, resulting in an infinite loop.
To avoid these kinds of scenarios, we declare the flag as volatile, we are telling to compiler that this value may be changed by an external interface or other module of program, i.e., please don't optimise it. That's the use case for volatile.
Try this. For python 2.7.12 we need to define constructor or need to add self to each methods followed by defining an instance of an class called object.
import cv2
class calculator:
# def __init__(self):
def multiply(self, a, b):
x= a*b
print(x)
def subtract(self, a,b):
x = a-b
print(x)
def add(self, a,b):
x = a+b
print(x)
def div(self, a,b):
x = a/b
print(x)
calc = calculator()
calc.multiply(2,3)
calc.add(2,3)
calc.div(10,5)
calc.subtract(2,3)
Code written in Java is:
When does java interpret the bytecode and when does it compile it? The application code is initially interpreted, but the JVM monitors which sequences of bytecode are frequently executed and translates them to machine code for direct execution on the hardware. For bytecode which is executed only a few times, this saves the compilation time and reduces the initial latency; for frequently executed bytecode, JIT compilation is used to run at high speed, after an initial phase of slow interpretation. Additionally, since a program spends most time executing a minority of its code, the reduced compilation time is significant. Finally, during the initial code interpretation, execution statistics can be collected before compilation, which helps to perform better optimization.
Also be aware that when converting from numeric string ie '56.72'
to INT you may come up against a SQL error.
Conversion failed when converting the varchar value '56.72' to data type int.
To get around this just do two converts as follows:
STRING -> NUMERIC -> INT
or
SELECT CAST(CAST (MyVarcharCol AS NUMERIC(19,4)) AS INT)
When copying data from TableA to TableB, the conversion is implicit, so you dont need the second convert (if you are happy rounding down to nearest INT):
INSERT INTO TableB (MyIntCol)
SELECT CAST(MyVarcharCol AS NUMERIC(19,4)) as [MyIntCol]
FROM TableA
This worked for me (win10), place before you import keras:
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
It looks like github has a simple UI for creating branches. I opened the branch drop-down and it prompts me to "Find or create a branch ...". Type the name of your new branch, then click the "create" button that appears.
To retrieve your new branch from github, use the standard git fetch
command.
I'm not sure this will help your underlying problem, though, since the underlying data being pushed to the server (the commit objects) is the same no matter what branch it's being pushed to.
with 2008 Server 2008 and 2008 R2
Add-PSSnapin -Name SqlServerCmdletSnapin100, SqlServerProviderSnapin100
with 2012 and 2014
Push-Location
Import-Module -Name SQLPS -DisableNameChecking
Pop-Location
This is what I use to upload the image through upload window:
//open upload window
upload.click();
//put path to your image in a clipboard
StringSelection ss = new StringSelection("C:\\IMG_3827.JPG");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
//imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
done
If both arrays are in the correct order; where each item corresponds to its associated member identifier then you can simply use.
var merge = _.merge(arr1, arr2);
Which is the short version of:
var merge = _.chain(arr1).zip(arr2).map(function(item) {
return _.merge.apply(null, item);
}).value();
Or, if the data in the arrays is not in any particular order, you can look up the associated item by the member value.
var merge = _.map(arr1, function(item) {
return _.merge(item, _.find(arr2, { 'member' : item.member }));
});
You can easily convert this to a mixin. See the example below:
_.mixin({_x000D_
'mergeByKey' : function(arr1, arr2, key) {_x000D_
var criteria = {};_x000D_
criteria[key] = null;_x000D_
return _.map(arr1, function(item) {_x000D_
criteria[key] = item[key];_x000D_
return _.merge(item, _.find(arr2, criteria));_x000D_
});_x000D_
}_x000D_
});_x000D_
_x000D_
var arr1 = [{_x000D_
"member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
"bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
"country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
}, {_x000D_
"member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
"bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
"country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
}];_x000D_
_x000D_
var arr2 = [{_x000D_
"member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
"name": 'yyyyyyyyyy',_x000D_
"age": 26_x000D_
}, {_x000D_
"member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
"name": 'xxxxxx',_x000D_
"age": 25_x000D_
}];_x000D_
_x000D_
var arr3 = _.mergeByKey(arr1, arr2, 'member');_x000D_
_x000D_
document.body.innerHTML = JSON.stringify(arr3, null, 4);
_x000D_
body { font-family: monospace; white-space: pre; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
foo = foo.Substring(0,5);
I found myself requiring this functionality often enough that I packaged it into a library called std-pour. It should let you execute a command and view the output in real time. To install simply:
npm install std-pour
Then it's simple enough to execute a command and see the output in realtime:
const { pour } = require('std-pour');
pour('ping', ['8.8.8.8', '-c', '4']).then(code => console.log(`Error Code: ${code}`));
It's promised based so you can chain multiple commands. It's even function signature-compatible with child_process.spawn
so it should be a drop in replacement anywhere you're using it.
The answer above suggests changing the function to echo data rather than return it so that it can be captured.
For a function or program that you can't modify where the return value needs to be saved to a variable (like test
/[
, which returns a 0/1 success value), echo $?
within the command substitution:
# Test if we're remote.
isRemote="$(test -z "$REMOTE_ADDR"; echo $?)"
# Or:
isRemote="$([ -z "$REMOTE_ADDR" ]; echo $?)"
# Additionally you may want to reverse the 0 (success) / 1 (error) values
# for your own sanity, using arithmetic expansion:
remoteAddrIsEmpty="$([ -z "$REMOTE_ADDR" ]; echo $((1-$?)))"
E.g.
$ echo $REMOTE_ADDR
$ test -z "$REMOTE_ADDR"; echo $?
0
$ REMOTE_ADDR=127.0.0.1
$ test -z "$REMOTE_ADDR"; echo $?
1
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
1
$ unset REMOTE_ADDR
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
0
For a program which prints data but also has a return value to be saved, the return value would be captured separately from the output:
# Two different files, 1 and 2.
$ cat 1
1
$ cat 2
2
$ diffs="$(cmp 1 2)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [1] Diffs: [1 2 differ: char 1, line 1]
$ diffs="$(cmp 1 1)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [0] Diffs: []
# Or again, if you just want a success variable, reverse with arithmetic expansion:
$ cmp -s 1 2; filesAreIdentical=$((1-$?))
$ echo $filesAreIdentical
0
len
is a built-in function that calls the given container object's __len__
member function to get the number of elements in the object.
Functions encased with double underscores are usually "special methods" implementing one of the standard interfaces in Python (container, number, etc). Special methods are used via syntactic sugar (object creation, container indexing and slicing, attribute access, built-in functions, etc.).
Using obj.__len__()
wouldn't be the correct way of using the special method, but I don't see why the others were modded down so much.
I made a **
automatic-network-drive connector
** using a batch file.
Suddenly there was a networkdrive called "Data for Analysation", and yeah with the double quotes it works proper!
looks a little bit different but works:
net use y: "\\share.blabla.com\Folder\Subfolder\Data for Analysation" /USER:domain\username PW /PERSISTENT:YES
Thx for the Hint :)
Little addition. You can use boost::function
, to create functors from functions and methods, like this:
class Foo
{
public:
void operator () (int i) { printf("Foo %d", i); }
};
void Bar(int i) { printf("Bar %d", i); }
Foo foo;
boost::function<void (int)> f(foo);//wrap functor
f(1);//prints "Foo 1"
boost::function<void (int)> b(&Bar);//wrap normal function
b(1);//prints "Bar 1"
and you can use boost::bind to add state to this functor
boost::function<void ()> f1 = boost::bind(foo, 2);
f1();//no more argument, function argument stored in f1
//and this print "Foo 2" (:
//and normal function
boost::function<void ()> b1 = boost::bind(&Bar, 2);
b1();// print "Bar 2"
and most useful, with boost::bind and boost::function you can create functor from class method, actually this is a delegate:
class SomeClass
{
std::string state_;
public:
SomeClass(const char* s) : state_(s) {}
void method( std::string param )
{
std::cout << state_ << param << std::endl;
}
};
SomeClass *inst = new SomeClass("Hi, i am ");
boost::function< void (std::string) > callback;
callback = boost::bind(&SomeClass::method, inst, _1);//create delegate
//_1 is a placeholder it holds plase for parameter
callback("useless");//prints "Hi, i am useless"
You can create list or vector of functors
std::list< boost::function<void (EventArg e)> > events;
//add some events
....
//call them
std::for_each(
events.begin(), events.end(),
boost::bind( boost::apply<void>(), _1, e));
There is one problem with all this stuff, compiler error messages is not human readable :)
You can try c#
public string ProcessMyDataItem(object myValue)
{
if (myValue == null)
{
return "0 %"";
}
else
{
if(Convert.ToInt32(myValue) < 50)
return "0";
else
return myValue.ToString() + "%";
}
}
asp
<div class="tooltip" style="display: none">
<div style="text-align: center; font-weight: normal">
Value =<%# ProcessMyDataItem(Eval("Percentage")) %> </div>
</div>
This is using Gson in Kotlin
val listString = "[uno,dos,tres,cuatro,cinco]"
val gson = Gson()
val lista = gson.fromJson(listString , Array<String>::class.java).toList()
Log.e("GSON", lista[0])
Instead of set mouse=a
use set mouse=r
in .vimrc
execve()
replaces the current executable image with another one loaded from an executable file.fork()
creates a child process.vfork()
is a historical optimized version of fork()
, meant to be used when execve()
is called directly after fork()
. It turned out to work well in non-MMU systems (where fork()
cannot work in an efficient manner) and when fork()
ing processes with a huge memory footprint to run some small program (think Java's Runtime.exec()
). POSIX has standardized the posix_spawn()
to replace these latter two more modern uses of vfork()
.posix_spawn()
does the equivalent of a fork()/execve()
, and also allows some fd juggling in between. It's supposed to replace fork()/execve()
, mainly for non-MMU platforms.pthread_create()
creates a new thread.clone()
is a Linux-specific call, which can be used to implement anything from fork()
to pthread_create()
. It gives a lot of control. Inspired on rfork()
.rfork()
is a Plan-9 specific call. It's supposed to be a generic call, allowing several degrees of sharing, between full processes and threads.Normally, Spring should do the autowiring, as long as your abstract class is in the base-package provided for component scan.
See this and this for further reference.
@Service
and @Component
are both stereotypes that creates beans of the annotated type inside the Spring container. As Spring Docs state,
This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.
Just use substring: "apple".substring(3);
will return le
This is a revised solution that will also work for modal windows rendered using a Grails template, where you can have the same modal template called multiple times (with different values) in the same body. This thread helped me immensely, so I thought I'd share it in case other Grails users found their way here.
For those who are curious, the accepted solution didn't work for me because I am rendering a table; each row has a button that opens a modal window with more details about the record. This led to multiple printSection divs being created and printed on top of each other. Therefore I had to revise the js to clean up the div after it was done printing.
I added this CSS directly to my modal gsp, but adding it to the parent has the same effect.
<style type="text/css">
@media screen {
#printSection {
display: none;
}
}
@media print {
body > *:not(#printSection) {
display: none;
}
#printSection, #printSection * {
visibility: visible;
}
#printSection {
position:absolute;
left:0;
top:0;
}
}
</style>
Adding it to the site-wide CSS killed the print functionality in other parts of the site. I got this from ComFreak's accepted answer (based on Bennett McElwee answer), but it is revised using ':not' functionality from fanfavorite's answer on Print <div id=printarea></div> only? . I opted for 'display' rather than 'visibility' because my invisible body content was creating extra blank pages, which was unacceptable to my users.
And this to my javascript, revised from ComFreak's accepted answer to this question.
function printDiv(div) {
// Create and insert new print section
var elem = document.getElementById(div);
var domClone = elem.cloneNode(true);
var $printSection = document.createElement("div");
$printSection.id = "printSection";
$printSection.appendChild(domClone);
document.body.insertBefore($printSection, document.body.firstChild);
window.print();
// Clean up print section for future use
var oldElem = document.getElementById("printSection");
if (oldElem != null) { oldElem.parentNode.removeChild(oldElem); }
//oldElem.remove() not supported by IE
return true;
}
I had no need for appending elements, so I removed that aspect and changed the function to specifically print a div.
And the modal template. This prints the modal header & body and excludes the footer, where the buttons were located.
<div class="modal-content">
<div id="print-me"> <!-- This is the div that is cloned and printed -->
<div class="modal-header">
<!-- HEADER CONTENT -->
</div>
<div class="modal-body">
<!-- BODY CONTENT -->
</div>
</div>
<div class="modal-footer">
<!-- This is where I specify the div to print -->
<button type="button" class="btn btn-default" onclick="printDiv('print-me')">Print</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
I hope that helps someone!
Download the Visual C++ Redistributable 2015
Updated links to VC++ file:
>>> list(my_dataframe)
['y', 'gdp', 'cap']
To list the columns of a dataframe while in debugger mode, use a list comprehension:
>>> [c for c in my_dataframe]
['y', 'gdp', 'cap']
By the way, you can get a sorted list simply by using sorted
:
>>> sorted(my_dataframe)
['cap', 'gdp', 'y']
read.table
wants to return a data.frame
, which must have an element in each column. Therefore R expects each row to have the same number of elements and it doesn't fill in empty spaces by default. Try read.table("/PathTo/file.csv" , fill = TRUE )
to fill in the blanks.
e.g.
read.table( text= "Element1 Element2
Element5 Element6 Element7" , fill = TRUE , header = FALSE )
# V1 V2 V3
#1 Element1 Element2
#2 Element5 Element6 Element7
A note on whether or not to set header = FALSE
... read.table
tries to automatically determine if you have a header row thus:
header
is set toTRUE
if and only if the first row contains one fewer field than the number of columns
You need to alias the aggregate using the as
keyword in order to call it from mysqli_fetch_assoc
$result=mysqli_query($conn,"SELECT count(*) as total from Students");
$data=mysqli_fetch_assoc($result);
echo $data['total'];
The other features of CodeLens like: Show Bugs, Show Test Status, etc (other than Show Reference) might be useful.
However, if the only way to disable Show References is to disable CodeLens altogether.
Then, I guess I could do just that.
Furthermore, I would do like I always have, 'right-click on a member and choose Find all References or Ctrl+K, R'
If I wanted to know what references the member -- I too like not having any extra information crammed into my code, like extra white-space.
In short, uncheck Codelens...
You can use getComputedStyle()
.
var element = document.getElementById('image_1'),
style = window.getComputedStyle(element),
top = style.getPropertyValue('top');
Another important feature of the LEA
instruction is that it does not alter the condition codes such as CF
and ZF
, while computing the address by arithmetic instructions like ADD
or MUL
does. This feature decreases the level of dependency among instructions and thus makes room for further optimization by the compiler or hardware scheduler.
Rob Napier had already given a awesome answer using subscript. But i felt one drawback in that as there is no check for out of bound conditions. This can tend to crash. So i modified the extension and here it is
extension String {
subscript (r: Range<Int>) -> String? { //Optional String as return value
get {
let stringCount = self.characters.count as Int
//Check for out of boundary condition
if (stringCount < r.endIndex) || (stringCount < r.startIndex){
return nil
}
let startIndex = self.startIndex.advancedBy(r.startIndex)
let endIndex = self.startIndex.advancedBy(r.endIndex - r.startIndex)
return self[Range(start: startIndex, end: endIndex)]
}
}
}
Output below
var str2 = "Hello, World"
var str3 = str2[0...5]
//Hello,
var str4 = str2[0..<5]
//Hello
var str5 = str2[0..<15]
//nil
So i suggest always to check for the if let
if let string = str[0...5]
{
//Manipulate your string safely
}
In .NET Framework 4 there is enhancement System.Guid structure, These includes new TryParse and TryParseExact methods to Parse GUID. Here is example for this.
//Generate New GUID
Guid objGuid = Guid.NewGuid();
//Take invalid guid format
string strGUID = "aaa-a-a-a-a";
Guid newGuid;
if (Guid.TryParse(objGuid.ToString(), out newGuid) == true)
{
Response.Write(string.Format("<br/>{0} is Valid GUID.", objGuid.ToString()));
}
else
{
Response.Write(string.Format("<br/>{0} is InValid GUID.", objGuid.ToString()));
}
Guid newTmpGuid;
if (Guid.TryParse(strGUID, out newTmpGuid) == true)
{
Response.Write(string.Format("<br/>{0} is Valid GUID.", strGUID));
}
else
{
Response.Write(string.Format("<br/>{0} is InValid GUID.", strGUID));
}
In this example we create new guid object and also take one string variable which has invalid guid. After that we use TryParse method to validate that both variable has valid guid format or not. By running example you can see that string variable has not valid guid format and it gives message of "InValid guid". If string variable has valid guid than this will return true in TryParse method.
Try entering the url inside the function
$location.url('http://www.google.com')
I had the same problem but I solved in other way (becouse at right click on project folder no Maven tab apears only if I do that on pom.xml I can see a Maven tab):
So I tink that you get that error because the IDE (Eclipse) didn`t import the dependecies from Maven. Since you are using Spring framework and you probably have STS allready installed right-click on project folder Spring Tools -> Update Maven Dependecies.
I`m using Eclipse JUNO m2eclipse 1.3.0 Spring IDEE 3.1
If you have installed git on your machine, you can open a git terminal and just use the Linux diff
command as normal.
you can use the @ControllerAdvice to handle your Exceptions , The default behavior the @ControllerAdvice annotated class will assist all known Controllers.
so it will be called when any Controller you have throws 404 error .
like the following :
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.NOT_FOUND) // 404
@ExceptionHandler(Exception.class)
public void handleNoTFound() {
// Nothing to do
}
}
and map this 404 response error in your web.xml , like the following :
<error-page>
<error-code>404</error-code>
<location>/Error404.html</location>
</error-page>
Hope that Helps .
To refresh the component at regular intervals I found this the best method. In the ngOnInit method setTimeOut function
ngOnInit(): void {
setTimeout(() => { this.ngOnInit() }, 1000 * 10)
}
//10 is the number of seconds
<a class="btn btn-large btn-success" id="fire" href="http://twitter.github.io/bootstrap/examples/marketing-narrow.html#">Send Email</a>
$('#fire').on('click', function (e) {
//your awesome code here
})
Try browsing to http://localhost/ScraperService.svc in the web browser on the server hosting the service, using the same Windows credentials that the client normally runs under.
I imagine that IIS is displaying an html error message of some description instead of returning xml as expected.
This also can occur when you have an http proxy server that performs internet filtering. My experience with ContentKeeper is that it intercepts any http/https traffic and blocks it as "Unmanaged Content" - all we get back is an html error message. To avoid this, you can add proxy server exception rules to Internet Explorer so that the proxy doesn't intercept traffic to your site:
Control Panel > Internet Options > Connections > LAN Settings > Advanced > Proxy Settings
you can intersect types:
type TypeA = {
nameA: string;
};
type TypeB = {
nameB: string;
};
export type TypeC = TypeA & TypeB;
somewhere in you code you can now do:
const some: TypeC = {
nameB: 'B',
nameA: 'A',
};
Here is what worked for me.
I Have used rename command so that if any file contains spaces in name of it then , mv command dont get confused between spaces and actual file.
Here i replaced spaces , ' ' in a file name with '_' for all jpg files
#! /bin/bash rename 'y/ /_/' *jpg #replacing spaces with _ let x=0; for i in *.jpg;do let x=(x+1) mv $i $x.jpg done
the simplest way I found so far is from git official website. It just computed dependencies and downloaded all of the required libraries/tools
http://git-scm.com/book/en/Getting-Started-Installing-Git
The other major way is to install Git via MacPorts (http://www.macports.org). If you have MacPorts installed, install Git via
$ sudo port install git-core +svn +doc +bash_completion +gitweb
You can also use rcParams
to change the font family globally.
import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "cursive"
# This will change to your computer's default cursive font
The list of matplotlib's font family arguments is here.
This question is already resolved, but...
...also consider the solution suggested by Wouter in his original comment. The ability to handle missing data, including dropna()
, is built into pandas explicitly. Aside from potentially improved performance over doing it manually, these functions also come with a variety of options which may be useful.
In [24]: df = pd.DataFrame(np.random.randn(10,3))
In [25]: df.iloc[::2,0] = np.nan; df.iloc[::4,1] = np.nan; df.iloc[::3,2] = np.nan;
In [26]: df
Out[26]:
0 1 2
0 NaN NaN NaN
1 2.677677 -1.466923 -0.750366
2 NaN 0.798002 -0.906038
3 0.672201 0.964789 NaN
4 NaN NaN 0.050742
5 -1.250970 0.030561 -2.678622
6 NaN 1.036043 NaN
7 0.049896 -0.308003 0.823295
8 NaN NaN 0.637482
9 -0.310130 0.078891 NaN
In [27]: df.dropna() #drop all rows that have any NaN values
Out[27]:
0 1 2
1 2.677677 -1.466923 -0.750366
5 -1.250970 0.030561 -2.678622
7 0.049896 -0.308003 0.823295
In [28]: df.dropna(how='all') #drop only if ALL columns are NaN
Out[28]:
0 1 2
1 2.677677 -1.466923 -0.750366
2 NaN 0.798002 -0.906038
3 0.672201 0.964789 NaN
4 NaN NaN 0.050742
5 -1.250970 0.030561 -2.678622
6 NaN 1.036043 NaN
7 0.049896 -0.308003 0.823295
8 NaN NaN 0.637482
9 -0.310130 0.078891 NaN
In [29]: df.dropna(thresh=2) #Drop row if it does not have at least two values that are **not** NaN
Out[29]:
0 1 2
1 2.677677 -1.466923 -0.750366
2 NaN 0.798002 -0.906038
3 0.672201 0.964789 NaN
5 -1.250970 0.030561 -2.678622
7 0.049896 -0.308003 0.823295
9 -0.310130 0.078891 NaN
In [30]: df.dropna(subset=[1]) #Drop only if NaN in specific column (as asked in the question)
Out[30]:
0 1 2
1 2.677677 -1.466923 -0.750366
2 NaN 0.798002 -0.906038
3 0.672201 0.964789 NaN
5 -1.250970 0.030561 -2.678622
6 NaN 1.036043 NaN
7 0.049896 -0.308003 0.823295
9 -0.310130 0.078891 NaN
There are also other options (See docs at http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html), including dropping columns instead of rows.
Pretty handy!
You can also do this with ArgueJS:
function (){
arguments = __({nodebox: undefined, str: [String: "hai"]})
// and now on, you can access your arguments by
// arguments.nodebox and arguments.str
}
System.out.println(LocalDate.now().format(DateTimeFormatter.ofPattern("dd.MMMM yyyy")));
The above answer shows it for today
You can achieve this by using the following method (as mentioned in other answers):
strCmdText = "'/C some command";
Process.Start("CMD.exe", strCmdText);
When I tried the methods listed above I found that my custom command did not work using the syntax of some of the answers above.
I found out more complex commands need to be encapsulated in quotes to work:
string strCmdText;
strCmdText = "'/C cd " + path + " && composer update && composer install -o'";
Process.Start("CMD.exe", strCmdText);
To have multiple Xcode instances installed you can put them to different folders for example /Developer5.0.2/Xcode, but to use them in CI or build environment(command line) you need to setup some environment variables during the build. You can have more instructions here. So it is working not just with beta and fresh release, also it's working for the really old versions, you might need it to use with Marmalade or Unity plugins which is not support the latest Xcode versions yet(some times it's happens).
All of the above answers were perfectly clear and complete, but just for the record I'd like to confirm that the meaning of * and ** in python has absolutely no similarity with the meaning of similar-looking operators in C.
They are called the argument-unpacking and keyword-argument-unpacking operators.
Follow the instruction in here.
JAVA_HOME
should be like this
JAVA_HOME=C:\Program Files\Java\jdk1.7.0_07
Using btoa
with unescape
and encodeURIComponent
didn't work for me. Replacing all the special characters with XML/HTML entities and then converting to the base64 representation was the only way to solve this issue for me. Some code:
base64 = btoa(str.replace(/[\u00A0-\u2666]/g, function(c) {
return '&#' + c.charCodeAt(0) + ';';
}));
You can use jquery-disablescroll to solve the problem:
$window.disablescroll();
$window.disablescroll("undo");
Supports handleWheel
, handleScrollbar
, handleKeys
and scrollEventKeys
.
This works in Linux & Windows:
Python 3.x
>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe
Python 2.x
>>> import sys
>>> print sys.executable
/usr/bin/python
If you need to do this on the backend you can use the following URL structure:
https://maps.googleapis.com/maps/api/geocode/json?address=[STREET_ADDRESS]&key=[YOUR_API_KEY]
Sample PHP code using curl:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://maps.googleapis.com/maps/api/geocode/json?address=' . rawurlencode($address) . '&key=' . $api_key);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($curl);
curl_close ($curl);
$obj = json_decode($json);
See additional documentation for more details and expected json response.
The docs provide sample output and will assist you in getting your own API key in order to be able to make requests to the Google Maps Geocoding API.
After much struggle with this same issue I was able to solve the problem by installing the 32 bit version of the 2010 Access Database Engine. For some reason the 64bit version generates this error...
When we format any float value, that means we are changing its data type to string. So when we apply the formatting on any amount/float value then it will set with all possible notations like dot, comma, etc. For example
(float)0.00 => (string)'0.00',
(float)10000.56 => (string) '10,000.56'
(float)5000000.20=> (string) '5,000,000.20'
So, logically it's not possible to keep the float datatype after formatting.
I have just upgraded the Ubuntu Server version from 12.04 LTS to 14.04 LTS.
Indeed, as said above, the .conf extension to Apache 2.4.x is needed to the websites vhost files that resides on sites-available directory.
Before read this question I did not have a clue what was going on with the server.
Pretty nice solution.
Just summarizing I did the following steps on Terminal:
1) Access sites-enabled folder
$ cd /etc/apache2/sites-enabled
2) Because the command a2dissite will not work with deprecated files (without .conf) remove the old website files that was published
$ sudo rm <my-old-website-without-.conf>
3) Rename the website vhost files changing its extension adding .conf to the end
$ sudo mv /etc/apache2/sites-available/mywebsite /etc/apache2/sites-available/mywebsite.conf
4) Republish the new and correct vhost file
$ sudo a2ensite mywebsite.conf
5) Check the website on browser and have fun! :)
var jsonVariable = {};
for(var i=1; i < 3; i++) {
jsonVariable[i + 'name'] = 'name' + i;
}
Should be something to do with your Platform Settings. Try the below steps
If you have just started with angular and bootstrap then simple answer would be below steps: 1. Add node package of bootstrap as dev dependency
npm install --save bootstrap
import bootstrap stylessheet in angular.json file.
"styles": [
"projects/my-app/src/styles.scss",
"./node_modules/bootstrap/dist/css/bootstrap.min.css"
],
and you are ready to use bootstrap for styling, grid etc.
<div class="container">My first bootstrap div</div>
The best part of this which I found was that we are directing using bootstrap without any third-party module dependency. We can upgrade bootstrap anytime by just updating the command npm install --save [email protected]
etc.
This error happened to me while testing my soap service with SoapUI client, basically I was trying to get a very big message (>500kb) and SoapUI closed the connection by timeout.
On SoapUI go to:
File-->Preferences--Socket Timeout(ms)
...and put a large value, such as 180000 (3 minutes), this won't be the perfect fix for your issue because the file is in fact to large, but at least you will have a response.
This is the shortest way:
myString = Regex.Replace(myString, @"[;,\t\r ]|[\n]{2}", "\n");
<!DOCTYPE html>
<html lang="en">
<head>
<title>Change Image on Hover in CSS</title>
<style type="text/css">
.card {
width: 130px;
height: 195px;
background: url("../images/pic.jpg") no-repeat;
margin: 50px;
}
.card:hover {
background: url("../images/anotherpic.jpg") no-repeat;
}
</style>
</head>
<body>
<div class="card"></div>
</body>
</html>
Any given Spring context can only have one bean for any given id or name. In the case of the XML id
attribute, this is enforced by the schema validation. In the case of the name
attribute, this is enforced by Spring's logic.
However, if a context is constructed from two different XML descriptor files, and an id
is used by both files, then one will "override" the other. The exact behaviour depends on the ordering of the files when they get loaded by the context.
So while it's possible, it's not recommended. It's error-prone and fragile, and you'll get no help from Spring if you change the ID of one but not the other.
Eclipse will never see a file until you force a refresh of the IDE. Its a feature! So you can put the file all over the project and Eclipse will ignore it completely and throw these errors. Hit refresh in Eclipse project view and then it works.
Similar to older answers, but a bit simpler, without the lambda:
filter_kwargs = {
'field_a': 123,
'field_b__in': (3, 4, 5, ),
}
To filter these two conditions using OR
:
Item.objects.filter(Q(field_a=123) | Q(field_b__in=(3, 4, 5, ))
To get the same result programmatically:
list_of_Q = [Q(**{key: val}) for key, val in filter_kwargs.items()]
Item.objects.filter(reduce(operator.or_, list_of_Q))
(broken in two lines here, for clarity)
operator
is in standard library: import operator
From docstring:
or_(a, b) -- Same as a | b.
For Python3, reduce
is not a builtin any more but is still in the standard library: from functools import reduce
P.S.
Don't forget to make sure list_of_Q
is not empty - reduce()
will choke on empty list, it needs at least one element.
You can also use the drop_duplicates() instead of unique()
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].drop_duplicates()
a.sort()
print a
I can't really say for sure, but I'd guess it's mostly historical. Quite a few early C compilers didn't support floating point at all. It was added on later, and even then not as completely -- mostly the data type was added, and the most primitive operations supported in the language, but everything else left to the standard library.
Like Mertcan said, the best way to use scss is to create the project with that option:
ng new My_New_Project --style=scss
Angular-cli also adds an option to change the default css preprocessor after the project has been created by using the command:
ng set defaults.styleExt scss
For more info you can look here for their documentation:
From the jQuery.each() documentation:
.each( function(index, Element) )
function(index, Element)A function to execute for each matched element.
So you'll want to use:
$('#list option').each(function(i,e){
//do stuff
});
...where index will be the index and element will be the option element in list
We can use call method to use other class methods as static methods.
class _Callable:
def __init__(self, anycallable):
self.__call__ = anycallable
class Model:
def get_instance(conn, table_name):
""" do something"""
get_instance = _Callable(get_instance)
provs_fac = Model.get_instance(connection, "users")
I encountered this problem when I accidentally tried running my python module through the command prompt while my working directory was C:\Windows\System32
instead of the usual directory from which I run my python module
Try this one:
function show_sub(cat) {
var parent = cat,
sub = parent.getElementsByClassName('sub');
if (sub[0].style.display == 'inline'){
sub[0].style.display = 'none';
}
else {
sub[0].style.display = 'inline';
}
}
document.getElementById('cat').onclick = function(){
show_sub(this);
};?
and use this for IE6 & 7
if (typeof document.getElementsByClassName!='function') {
document.getElementsByClassName = function() {
var elms = document.getElementsByTagName('*');
var ei = new Array();
for (i=0;i<elms.length;i++) {
if (elms[i].getAttribute('class')) {
ecl = elms[i].getAttribute('class').split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
} else if (elms[i].className) {
ecl = elms[i].className.split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
}
}
return ei;
}
}
Yes, just open the "Source" Tab in the dev-tools and navigate to the script you want to change . Make your adjustments directly in the dev tools window and then hit ctrl+s to save the script - know the new js will be used until you refresh the whole page.
I like to use: ArgumentException
, ArgumentNullException
, and ArgumentOutOfRangeException
.
ArgumentException
– Something is wrong with the argument.ArgumentNullException
– Argument is null.ArgumentOutOfRangeException
– I don’t use this one much, but a common use is indexing into a collection, and giving an index which is to large.There are other options, too, that do not focus so much on the argument itself, but rather judge the call as a whole:
InvalidOperationException
– The argument might be OK, but not in the current state of the object. Credit goes to STW (previously Yoooder). Vote his answer up as well.NotSupportedException
– The arguments passed in are valid, but just not supported in this implementation. Imagine an FTP client, and you pass a command in that the client doesn’t support.The trick is to throw the exception that best expresses why the method cannot be called the way it is. Ideally, the exception should be detailed about what went wrong, why it is wrong, and how to fix it.
I love when error messages point to help, documentation, or other resources. For example, Microsoft did a good first step with their KB articles, e.g. “Why do I receive an "Operation aborted" error message when I visit a Web page in Internet Explorer?”. When you encounter the error, they point you to the KB article in the error message. What they don’t do well is that they don’t tell you, why specifically it failed.
Thanks to STW (ex Yoooder) again for the comments.
In response to your followup, I would throw an ArgumentOutOfRangeException
. Look at what MSDN says about this exception:
ArgumentOutOfRangeException
is thrown when a method is invoked and at least one of the arguments passed to the method is not null reference (Nothing
in Visual Basic) and does not contain a valid value.
So, in this case, you are passing a value, but that is not a valid value, since your range is 1–12. However, the way you document it makes it clear, what your API throws. Because although I might say ArgumentOutOfRangeException
, another developer might say ArgumentException
. Make it easy and document the behavior.
Note:
=""
is a blank cell) without a need to use data
twice. The solution for goolge-spreadhseet: =ARRAYFORMULA(SUM(IFERROR(IF(data="",0,1),1)))
. For excel ={SUM(IFERROR(IF(data="",0,1),1))}
should work (press Ctrl+Shift+Enter in the formula).If you DROP and CREATE the procedure, you will loose the security settings. This might annoy your DBA or break your application altogether.
What I do is create a trivial stored procedure if it doesn't exist yet. After that, you can ALTER the stored procedure to your liking.
IF object_id('YourSp') IS NULL
EXEC ('create procedure dbo.YourSp as select 1')
GO
ALTER PROCEDURE dbo.YourSp
AS
...
This way, security settings, comments and other meta deta will survive the deployment.
Here's how to change MySQL Workbench's colors (INCLUDING THE BACKGROUND COLOR).
Open the XML file called code_editor.xml
located in the data folder of the MySQL Workbench's installation directory (usually C:\Program Files\MySQL\MySQL Workbench 6.3 CE\data
). Here you'll find a lot of styling for different code elements, but there are some missing.
MySQL Workbench uses scintilla as the code editor, and scintilla defines a few more styles that you can use in the code_editor.xml
file. The one that is used for the background color is style id 32.
Here's the complete list for MySQL (scintilla has thousands of styles for many languages) with my configuration:
<style id= "0" fore-color="#DDDDDD" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_DEFAULT -->
<style id= "1" fore-color="#999999" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_COMMENT -->
<style id= "2" fore-color="#999999" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_COMMENTLINE -->
<style id= "3" fore-color="#DDDDDD" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_VARIABLE -->
<style id= "4" fore-color="#9B859D" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_SYSTEMVARIABLE -->
<style id= "5" fore-color="#9B859D" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE -->
<style id= "6" fore-color="#FF8080" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_NUMBER -->
<style id= "7" fore-color="#7AAAD7" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_MAJORKEYWORD -->
<style id= "8" fore-color="#7AAAD7" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_KEYWORD -->
<style id= "9" fore-color="#9B859D" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_DATABASEOBJECT -->
<style id="10" fore-color="#DDDDDD" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_PROCEDUREKEYWORD -->
<style id="11" fore-color="#B9CB89" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_STRING -->
<style id="12" fore-color="#B9CB89" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_SQSTRING -->
<style id="13" fore-color="#B9CB89" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_DQSTRING -->
<style id="14" fore-color="#FFBB80" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_OPERATOR -->
<style id="15" fore-color="#9B859D" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_FUNCTION -->
<style id="16" fore-color="#DDDDDD" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_IDENTIFIER -->
<style id="17" fore-color="#B9CB89" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_QUOTEDIDENTIFIER -->
<style id="18" fore-color="#B9CB89" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_USER1 -->
<style id="19" fore-color="#B9CB89" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_USER2 -->
<style id="20" fore-color="#B9CB89" back-color="#2A2A2A" bold="No" /> <!-- SCE_MYSQL_USER3 -->
<style id="21" fore-color="#FFBB80" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_HIDDENCOMMAND -->
<style id="22" fore-color="#909090" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_PLACEHOLDER -->
<!-- These two are for scintilla globally. -->
<style id="32" fore-color="#DDDDDD" back-color="#2A2A2A" bold="No" /> <!-- STYLE_DEFAULT THIS IS THE ONE FOR THE BACKGROUND!!!!! -->
<style id="33" fore-color="#2A2A2A" back-color="#DDDDDD" bold="No" /> <!-- STYLE_LINENUMBER -->
<!-- All styles again in their variant in a hidden command (with a 0x40 offset). -->
<style id="65" fore-color="#999999" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_COMMENT -->
<style id="66" fore-color="#999999" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_COMMENTLINE -->
<style id="67" fore-color="#DDDDDD" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_VARIABLE -->
<style id="68" fore-color="#9B859D" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_SYSTEMVARIABLE -->
<style id="69" fore-color="#9B859D" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE -->
<style id="70" fore-color="#FF8080" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_NUMBER -->
<style id="71" fore-color="#7AAAD7" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_MAJORKEYWORD -->
<style id="72" fore-color="#7AAAD7" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_KEYWORD -->
<style id="73" fore-color="#9B859D" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_DATABASEOBJECT -->
<style id="74" fore-color="#DDDDDD" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_PROCEDUREKEYWORD -->
<style id="75" fore-color="#B9CB89" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_STRING -->
<style id="76" fore-color="#B9CB89" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_SQSTRING -->
<style id="77" fore-color="#B9CB89" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_DQSTRING -->
<style id="78" fore-color="#FFBB80" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_OPERATOR -->
<style id="79" fore-color="#9B859D" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_FUNCTION -->
<style id="80" fore-color="#DDDDDD" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_IDENTIFIER -->
<style id="81" fore-color="#B9CB89" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_QUOTEDIDENTIFIER -->
<style id="82" fore-color="#B9CB89" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_USER1 -->
<style id="83" fore-color="#B9CB89" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_USER2 -->
<style id="84" fore-color="#B9CB89" back-color="#707070" bold="No" /> <!-- SCE_MYSQL_USER3 -->
<style id="85" fore-color="#FFBB80" back-color="#909090" bold="No" /> <!-- SCE_MYSQL_HIDDENCOMMAND -->
<style id="86" fore-color="#AAAAAA" back-color="#909090" bold="No" /> <!-- SCE_MYSQL_PLACEHOLDER -->
You could parse the JSON to an object, then create your malformed JSON from the ajavscript object. This may not be the best performance-wise, tho.
Otherwise, if you only need to make very small changes to the string, just treat it as a string, and mangle it using standard javascript.
There is a nice open source Git stack called Git Blit. It is available for different platform and in different packages. You can also easily deploy it to your existing Tomcat or any other servlet container. Take a look at Setup git server on windows in few clicks tutorial for more details, it will take you around 10 minutes to get basic setup.
Use
export LD_LIBRARY_PATH="/path/to/library/"
in your .bashrc otherwise, it'll only be available to bash and not any programs you start.
Try -R/path/to/library/
flag when you're linking, it'll make the program look in that directory and you won't need to set any environment variables.
EDIT: Looks like -R
is Solaris only, and you're on Linux.
An alternate way would be to add the path to /etc/ld.so.conf
and run ldconfig
. Note that this is a global change that will apply to all dynamically linked binaries.
you can try like this:
var request = require('request');
request.post({ headers: {'content-type' : 'application/json'}
, url: <your URL>, body: <req_body in json> }
, function(error, response, body){
console.log(body);
});
Simple variation on @erikkallen answer that shows which table the row is present in:
( SELECT 'table1' as source, * FROM table1
EXCEPT
SELECT * FROM table2)
UNION ALL
( SELECT 'table2' as source, * FROM table2
EXCEPT
SELECT * FROM table1)
If you get an error
All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.
then it may help to add
( SELECT 'table1' as source, * FROM table1
EXCEPT
SELECT 'table1' as source, * FROM table2)
UNION ALL
( SELECT 'table2' as source, * FROM table2
EXCEPT
SELECT 'table2' as source, * FROM table1)
In NetBeans 7.0 (may be lower too) you could declare the the return type "array with Text objects " just as @return Text
and the code hinting will work:
Edit: updated the example with @Bob Fanger suggestion
/**
* get all Tests
*
* @return Test|Array $tests
*/
public function getAllTexts(){
return array(new Test(), new Test());
}
and just use it:
$tests = $controller->getAllTests();
//$tests-> //codehinting works!
//$tests[0]-> //codehinting works!
foreach($tests as $text){
//$test-> //codehinting works!
}
It is not perfect but it is better then just to leave it just "mixed", which brings no value.
CONS is you are allowed to tread the array as Text Object which will throw errors.
Install Tkinter
. I've included the win32api for as a Windows-only solution.
#!/usr/bin/env python
"""Get the current mouse position."""
import logging
import sys
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
level=logging.DEBUG,
stream=sys.stdout)
def get_mouse_position():
"""
Get the current position of the mouse.
Returns
-------
dict :
With keys 'x' and 'y'
"""
mouse_position = None
import sys
if sys.platform in ['linux', 'linux2']:
pass
elif sys.platform == 'Windows':
try:
import win32api
except ImportError:
logging.info("win32api not installed")
win32api = None
if win32api is not None:
x, y = win32api.GetCursorPos()
mouse_position = {'x': x, 'y': y}
elif sys.platform == 'Mac':
pass
else:
try:
import Tkinter # Tkinter could be supported by all systems
except ImportError:
logging.info("Tkinter not installed")
Tkinter = None
if Tkinter is not None:
p = Tkinter.Tk()
x, y = p.winfo_pointerxy()
mouse_position = {'x': x, 'y': y}
print("sys.platform={platform} is unknown. Please report."
.format(platform=sys.platform))
print(sys.version)
return mouse_position
print(get_mouse_position())
I would think that your first question is simply a matter of scope. The ServletContext is a much more broad scoped object (the whole servlet context) than a ServletRequest, which is simply a single request. You might look to the Servlet specification itself for more detailed information.
As to how, I am sorry but I will have to leave that for others to answer at this time.
step1: show create table vendor_locations;
step2: ALTER TABLE vendor_locations drop foreign key vendor_locations_ibfk_1;
it worked for me.
Since you don't want stretching (all of the other answers ignore that) you can simply set max-width and max-height like in my jsFiddle edit.
#container img {
max-height: 250px;
max-width: 250px;
}
See my example with an image that isn't a square, it doesn't stretch
Use logging module (http://docs.python.org/library/logging.html):
import logging
logger = logging.getLogger('scope.name')
file_log_handler = logging.FileHandler('logfile.log')
logger.addHandler(file_log_handler)
stderr_log_handler = logging.StreamHandler()
logger.addHandler(stderr_log_handler)
# nice output format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_log_handler.setFormatter(formatter)
stderr_log_handler.setFormatter(formatter)
logger.info('Info message')
logger.error('Error message')
The trick is to make an invisible anchor tag in the render()
and add a React ref
allowing to trigger a click once we have the axios response:
class Example extends Component {
state = {
ref: React.createRef()
}
exportCSV = () => {
axios.get(
'/app/export'
).then(response => {
let blob = new Blob([response.data], {type: 'application/octet-stream'})
let ref = this.state.ref
ref.current.href = URL.createObjectURL(blob)
ref.current.download = 'data.csv'
ref.current.click()
})
}
render(){
return(
<div>
<a style={{display: 'none'}} href='empty' ref={this.state.ref}>ref</a>
<button onClick={this.exportCSV}>Export CSV</button>
</div>
)
}
}
Here is the documentation: https://reactjs.org/docs/refs-and-the-dom.html. You can find a similar idea here: https://thewebtier.com/snippets/download-files-with-axios/.
Method 1 :
var stringValue = "true";
var boolValue = (/true/i).test(stringValue) //returns true
Method 2 :
var stringValue = "true";
var boolValue = (stringValue =="true"); //returns true
Method 3 :
var stringValue = "true";
var boolValue = JSON.parse(stringValue); //returns true
Method 4 :
var stringValue = "true";
var boolValue = stringValue.toLowerCase() == 'true'; //returns true
Method 5 :
var stringValue = "true";
var boolValue = getBoolean(stringValue); //returns true
function getBoolean(value){
switch(value){
case true:
case "true":
case 1:
case "1":
case "on":
case "yes":
return true;
default:
return false;
}
}
source: http://codippa.com/how-to-convert-string-to-boolean-javascript/
I had to set
C:\ProgramData\MySQL\MySQL Server 8.0/my.ini secure-file-priv=""
When I commented line with secure-file-priv
, secure-file-priv was null and I couldn't download data.
date.setTime( date.getTime() + days * 86400000 );
Simpler solution without using regex:
import android.text.InputFilter;
import android.text.Spanned;
/**
* Input filter that limits the number of decimal digits that are allowed to be
* entered.
*/
public class DecimalDigitsInputFilter implements InputFilter {
private final int decimalDigits;
/**
* Constructor.
*
* @param decimalDigits maximum decimal digits
*/
public DecimalDigitsInputFilter(int decimalDigits) {
this.decimalDigits = decimalDigits;
}
@Override
public CharSequence filter(CharSequence source,
int start,
int end,
Spanned dest,
int dstart,
int dend) {
int dotPos = -1;
int len = dest.length();
for (int i = 0; i < len; i++) {
char c = dest.charAt(i);
if (c == '.' || c == ',') {
dotPos = i;
break;
}
}
if (dotPos >= 0) {
// protects against many dots
if (source.equals(".") || source.equals(","))
{
return "";
}
// if the text is entered before the dot
if (dend <= dotPos) {
return null;
}
if (len - dotPos > decimalDigits) {
return "";
}
}
return null;
}
}
To use:
editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(2)});
Yes, but what does grouping by more two columns mean? Well, it's the same as grouping by each unique pair per row. The order you list the columns changes the way the rows are sorted.
In your example, you would write
GROUP BY fV.tier_id, f.form_template_id
Meanwhile, the code
GROUP BY f.form_template_id, fV.tier_id
would give similar results, but sorted differently.
If you have a block of code+html that appears on several pages and is sort of independent of that page (say a block of latest news items), you could copy/paste the code to every page.
It is however better to put that code in its own block and just include that block on every page that needs it. That "block" is an ascx file.
If you are seeing this error in Android Studio 4.1 with Gradle 6.5 then you should move back to
classpath 'com.android.tools.build:gradle:4.0.2'
For some reason
classpath 'com.android.tools.build:gradle:4.2.0'
does not work correctly.
This is how did it works like a charm.
#loader {
position:fixed;
left:1px;
top:1px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('../images/ajax-loader100X100.gif') 50% 50% no-repeat rgb(249,249,249);
}
in _layout file inside body tag but outside the container div. Every time page loads it shows loading. Once page is loaded JS fadeout(second)
<div id="loader">
</div>
JS at the bottom of _layout file
<script type="text/javascript">
// With the element initially shown, we can hide it slowly:
$("#loader").fadeOut(1000);
</script>
Here is a little sub that may just interest some people who need to specify the browser. (but its not as good as a 12" pizza sub!) :P
Private Sub NavigateWebURL(ByVal URL As String, Optional browser As String = "default")
If Not (browser = "default") Then
Try
'// try set browser if there was an error (browser not installed)
Process.Start(browser, URL)
Catch ex As Exception
'// use default browser
Process.Start(URL)
End Try
Else
'// use default browser
Process.Start(URL)
End If
End Sub
Call: will open www.google.com in Firefox if it is installed on that PC.
NavigateWebURL("http://www.google.com", "Firefox") '// safari Firefox chrome etc
Call: will open www.google.com in default browser.
NavigateWebURL("http://www.google.com", "default")
OR
NavigateWebURL("http://www.google.com")
if anyone has a problem on Mac, can try this
sudo pip install --upgrade matplotlib --ignore-installed six
Cron jobs usually are stored in a per-user file under /var/spool/cron
The simplest thing for you to do is probably just create a text file with the job configured, then copy it to the cron spool folder and make sure it has the right permissions (600).
If your stack trace looks like following then you are sending a huge load of json objects to server
Operation is not valid due to the current state of the object.
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
at System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input)
at Failing.Page_Load(Object sender, EventArgs e)
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
For resolution, please update your web config with following key. If you are not able to get the stack trace then please use fiddler. If it still does not help then please try increasing the number to 10000 or something
<configuration>
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
</appSettings>
</configuration>
For more details, please read this Microsoft kb article
You need the extended permission "read_stream", then you need to call the Facebook API endpoint, and add likes,shares
to your fields
.
This call
https://developers.facebook.com/tools/explorer?method=GET&path=me/feed?fields=likes,shares
will return a data array like this
{
"data": [
{
"likes": {
"data": [
{
"name": "name of user who liked status ",
"id": "id of user who liked status "
}
],
"count": number of likes
},
"shares": {
"count": number of shares
},
"id": "post id",
"created_time": "post creation time"
}
]
}
Try:
sudo /etc/init.d/mysql reload
or
sudo /etc/init.d/mysql force-reload
That should initiate a reload of the configuration. Make sureyour init.d script supports it though, I don't know what version of MySQL/OS you are using?
My MySQL script contains the following:
'reload'|'force-reload')
log_daemon_msg "Reloading MySQL database server" "mysqld"
$MYADMIN reload
log_end_msg 0
;;
This could also be caused if you have no room on the partition you are saving to.
I checked my HD and foind it was maxed. Moving some un-needed files to a different partition resolved my problem.
IList<> is almost always preferable as per the other poster's advice, however note there is a bug in .NET 3.5 sp 1 when running an IList<> through more than one cycle of serialization / deserialization with the WCF DataContractSerializer.
There is now a SP to fix this bug : KB 971030
One line in the Makefile should be enough:
DIR := $(notdir $(CURDIR))
I found a mod_rewrite
solution that works well for both proxied and unproxied servers.
If you are using CloudFlare, AWS Elastic Load Balancing, Heroku, OpenShift or any other Cloud/PaaS solution and you are experiencing redirect loops with normal HTTPS redirects, try the following snippet instead.
RewriteEngine On
# If we receive a forwarded http request from a proxy...
RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]
# ...or just a plain old http request directly from the client
RewriteCond %{HTTP:X-Forwarded-Proto} =""
RewriteCond %{HTTPS} !=on
# Redirect to https version
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
According to the official documentation on sitemaps.org it needs to be a full URL:
You can specify the location of the Sitemap using a robots.txt file. To do this, simply add the following line including the full URL to the sitemap:
Sitemap: http://www.example.com/sitemap.xml
You can't remove keyword case
. But your example can be written shorter like this:
switch ((Answer - 1) / 4)
{
case 0:
cout << "You need more cars.";
break;
case 1:
cout << "Now you need a house.";
break;
default:
cout << "What are you? A peace-loving hippie freak?";
}
self
is the self-reference in a Class. Your code is not in a class, you only have functions defined. You have to wrap your methods in a class, like below. To use the method main()
, you first have to instantiate an object of your class and call the function on the object.
Further, your function setavalue
should be in __init___
, the method called when instantiating an object. The next step you probably should look at is supplying the name as an argument to init, so you can create arbitrarily named objects of the Name
class ;)
class Name:
def __init__(self):
self.myname = "harry"
def printaname(self):
print "Name", self.myname
def main(self):
self.printaname()
if __name__ == "__main__":
objName = Name()
objName.main()
Have a look at the Classes chapter of the Python tutorial an at Dive into Python for further references.
Heads up,
JAVASCRIPT
<script>
function readMtlAtClient(){
mtlFileContent = '';
var mtlFile = document.getElementById('mtlFileInput').files[0];
var readerMTL = new FileReader();
// Closure to capture the file information.
readerMTL.onload = (function(reader) {
return function() {
mtlFileContent = reader.result;
mtlFileContent = mtlFileContent.replace('data:;base64,', '');
mtlFileContent = window.atob(mtlFileContent);
};
})(readerMTL);
readerMTL.readAsDataURL(mtlFile);
}
</script>
HTML
<input class="FullWidth" type="file" name="mtlFileInput" value="" id="mtlFileInput"
onchange="readMtlAtClient()" accept=".mtl"/>
Then mtlFileContent has your text as a decoded string !
If you want to find webpack files and configurations go to your package.json file and look for scripts
You will find that scripts object is using a library react-scripts
Now go to node_modules and look for react-scripts folder react-script-in-node-modules
This react-scripts/scripts and react-scripts/config folder contains all the webpack configurations.
If you're not wanting to save changes set savechanges to false
Sub CloseBook2()
ActiveWorkbook.Close savechanges:=False
End Sub
for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used
ActiveWorkbook.Close False
since npm 5.2.0, there's a new command "npx" included with npm that makes this much simpler, if you run:
npx mocha <args>
Note: the optional args are forwarded to the command being executed (mocha in this case)
this will automatically pick the executable "mocha" command from your locally installed mocha (always add it as a dev dependency to ensure the correct one is always used by you and everyone else).
Be careful though that if you didn't install mocha, this command will automatically fetch and use latest version, which is great for some tools (like scaffolders for example), but might not be the most recommendable for certain dependencies where you might want to pin to a specific version.
You can read more on npx here
Now, if instead of invoking mocha directly, you want to define a custom npm script, an alias that might invoke other npm binaries...
you don't want your library tests to fail depending on the machine setup (mocha as global, global mocha version, etc), the way to use the local mocha that works cross-platform is:
node node_modules/.bin/mocha
npm puts aliases to all the binaries in your dependencies on that special folder. Finally, npm will add node_modules/.bin to the PATH automatically when running an npm script, so in your package.json you can do just:
"scripts": {
"test": "mocha"
}
and invoke it with
npm test
Answer is very simple use the .NET Framework tools sn.exe
. So open the Visual Studio 2008 Command Prompt and then point to the dll’s folder you want to get the public key,
Use the following command,
sn –T myDLL.dll
This will give you the public key token. Remember one thing this only works if the assembly has to be strongly signed.
Example
C:\WINNT\Microsoft.NET\Framework\v3.5>sn -T EdmGen.exe Microsoft (R) .NET Framework Strong Name Utility Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved. Public key token is b77a5c561934e089
You need to remove the npm package manually.
first unlink node: brew link -n node
remove npm folder: rm -R /usr/local/Cellar/node/0.8.10/lib/node_modules/npm
link again: brew link node
there will be a soft link to the new location of npm
Also u can consider this
$('#select_2').find('option:selected').text();
which might be a little faster solution though I am not sure.
Full Coding Structure
postgresql function
CREATE OR REPLACE FUNCTION admin.usp_itemdisplayid_byitemhead_select(
item_head_list int[])
RETURNS TABLE(item_display_id integer)
LANGUAGE 'sql'
COST 100
VOLATILE
ROWS 1000
AS $BODY$
SELECT vii.item_display_id from admin.view_item_information as vii
where vii.item_head_id = ANY(item_head_list);
$BODY$;
Model
public class CampaignCreator
{
public int item_display_id { get; set; }
public List<int> pitem_head_id { get; set; }
}
.NET CORE function
DynamicParameters _parameter = new DynamicParameters();
_parameter.Add("@item_head_list",obj.pitem_head_id);
string sql = "select * from admin.usp_itemdisplayid_byitemhead_select(@item_head_list)";
response.data = await _connection.QueryAsync<CampaignCreator>(sql, _parameter);
Environment variables are 'evaluated' (ie. they are attributed) in the following order:
Every process has an environment block that contains a set of environment variables and their values. There are two types of environment variables: user environment variables (set for each user) and system environment variables (set for everyone). A child process inherits the environment variables of its parent process by default.
Programs started by the command processor inherit the command processor's environment variables.
Environment variables specify search paths for files, directories for temporary files, application-specific options, and other similar information. The system maintains an environment block for each user and one for the computer. The system environment block represents environment variables for all users of the particular computer. A user's environment block represents the environment variables the system maintains for that particular user, including the set of system environment variables.
For me, the bug had two fixes.
I was using Spring boot as jar and deployed to aws ec2 Java variant of the solution is as below :
package com.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
public class XmlReader {
private static Logger LOGGER = LoggerFactory.getLogger(XmlReader.class);
public static void main(String[] args) {
String fileLocation = "classpath:cbs_response.xml";
String reponseXML = null;
try (ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext()){
Resource resource = appContext.getResource(fileLocation);
if (resource.isReadable()) {
BufferedReader reader =
new BufferedReader(new InputStreamReader(resource.getInputStream()));
Stream<String> lines = reader.lines();
reponseXML = lines.collect(Collectors.joining("\n"));
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
if you have textviews, buttons or stg clickable or selectable in your row view only
android:descendantFocusability="blocksDescendants"
is not enough. You have to set
android:textIsSelectable="false"
to your textviews and
android:focusable="false"
to your buttons and other focusable items.
Maybe this seems ugly, but why not just run cat
and let it wait for input forever?
Is this a local custom CSS file? Is this your website? Maybe you should clear your cache.
Also the last CSS declaration takes precedence.
Hi with carriage return:
sed -i '1s/^/your text\n/' file
I am giving a very simple example
1)
var data = {site:"mysite",name:"john",age:25};
var template = "Welcome you are at <%=site %>.This has been created by <%=name %> whose age is <%=age%>";
var parsedTemplate = _.template(template,data);
console.log(parsedTemplate);
The result would be
Welcome you are at mysite.This has been created by john whose age is 25.
2) This is a template
<script type="text/template" id="template_1">
<% _.each(items,function(item,key,arr) { %>
<li>
<span><%= key %></span>
<span><%= item.name %></span>
<span><%= item.type %></span>
</li>
<% }); %>
</script>
This is html
<div>
<ul id="list_2"></ul>
</div>
This is the javascript code which contains json object and putting template into html
var items = [
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
}
];
$(document).ready(function(){
var template = $("#template_1").html();
$("#list_2").html(_.template(template,{items:items}));
});
Quite simple:
var a = [1, 2, 3];
var b = [4, 5, 6];
var breakCheck1 = false;
for (var i in a) {
for (var j in b) {
breakCheck1 = true;
break;
}
if (breakCheck1) break;
}
(A) To split a sentence into its words (space separated) you can simply use the default IFS by using
array=( $string )
Example running the following snippet
#!/bin/bash
sentence="this is the \"sentence\" 'you' want to split"
words=( $sentence )
len="${#words[@]}"
echo "words counted: $len"
printf "%s\n" "${words[@]}" ## print array
will output
words counted: 8
this
is
the
"sentence"
'you'
want
to
split
As you can see you can use single or double quotes too without any problem
Notes:
-- this is basically the same of mob's answer, but in this way you store the array for any further needing. If you only need a single loop, you can use his answer, which is one line shorter :)
-- please refer to this question for alternate methods to split a string based on delimiter.
(B) To check for a character in a string you can also use a regular expression match.
Example to check for the presence of a space character you can use:
regex='\s{1,}'
if [[ "$sentence" =~ $regex ]]
then
echo "Space here!";
fi
Get rid of the this statements too
var img = document.createElement("img");
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src = document.getElementById("gamediv");
src.appendChild(this.img)
Just Add AjaxControlToolkit.dll to your Reference folder.
On your Project Solution
Right Click on Reference Folder > Add Reference > browse AjaxControlToolkit.dll .
Then build.
Regards
According to official docs to install node on Debian and Ubuntu based distributions:
node v12 (Old)
curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
sudo apt-get install -y nodejs
node v14 (For new users: install this one):
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
node v15 (Current version):
curl -sL https://deb.nodesource.com/setup_15.x | sudo -E bash -
sudo apt-get install -y nodejs
Other older versions: Just replace the desired version number in the link above.
Optional: install build tools
To compile and install native packages
sudo apt-get install -y build-essential
To update node to the latest version just:
sudo apt update
sudo apt upgrade
To keep npm updated
sudo npm i -g npm
To find out other versions try npm info npm
and in versions find your desired version and replace [version-tag] with that version tag in npm i -g npm@[version-tag]
And I also recommend trying yarn instead of npm
We need to put some kind of control that can wrap text like textblock/textbox
<Label Width="120" Height="100" >
<TextBlock TextWrapping="Wrap">
this is a very long text inside a textblock and this needs to be on multiline.
</TextBlock>
</Label>
If you use JAX-WS, the following works for me:
//Get Web service Port
WSTestService wsService = new WSTestService();
WSTest wsPort = wsService.getWSTestPort();
// Add username and password for Basic Authentication
Map<String, Object> reqContext = ((BindingProvider)
wsPort).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "username");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password");
you forgot for Java Desktop Aplication based on JSR296 as built-in Swing Framework in NetBeans
excluding AWT and JavaFX are all of your desribed frameworks are based on Swing, if you'll start with Swing then you'd be understand (clearly) for all these Swing's (Based Frameworks)
ATW, SWT (Eclipse), Java Desktop Aplication(Netbeans), SwingX, JGoodies
all there frameworks (I don't know something more about JGoodies) incl. JavaFX haven't long time any progress, lots of Swing's Based Frameworks are stoped, if not then without newest version
just my view - best of them is SwingX, but required deepest knowledge about Swing,
Look and Feel for Swing's Based Frameworks
Login using the system maintenance user and password created when you installed phpMyAdmin.
It can be found in the debian.cnf file at /etc/mysql then you will have total access.
cd /etc/mysql
sudo nano debian.cnf
Just look - don't change anything!
[mysql_upgrade]
host = localhost
user = debian-sys-maint <----use this user
password = s0meRaND0mChar$s <----use this password
socket = /var/run/mysqld/mysqld.sock
Worked for me.
Yes, this is possible and I would like to provide a slight alternative to Rajeev's answer that does not pass a php-generated datetime formatted string to the query.
The important distinction about how to declare the values to be SET in the UPDATE query is that they must not be quoted as literal strings.
To prevent CodeIgniter from doing this "favor" automatically, use the set()
method with a third parameter of false
.
$userId = 444;
$this->db->set('Last', 'Current', false);
$this->db->set('Current', 'NOW()', false);
$this->db->where('Id', $userId);
// return $this->db->get_compiled_update('Login'); // uncomment to see the rendered query
$this->db->update('Login');
return $this->db->affected_rows(); // this is expected to return the integer: 1
The generated query (depending on your database adapter) would be like this:
UPDATE `Login` SET Last = Current, Current = NOW() WHERE `Id` = 444
Demonstrated proof that the query works: https://www.db-fiddle.com/f/vcc6PfMcYhDD87wZE5gBtw/0
In this case, Last
and Current
ARE MySQL Keywords, but they are not Reserved Keywords, so they don't need to be backtick-wrapped.
If your precise query needs to have properly quoted identifiers (table/column names), then there is always protectIdentifiers().
AFAIK there is no way to visually see line endings in the editor space, but in the bottom-right corner of the window there is an indicator that says "CLRF" or "LF" which will let you set the line endings for a particular file. Clicking on the text will allow you to change the line endings as well.
char *replace(const char*instring, const char *old_part, const char *new_part)
{
#ifndef EXPECTED_REPLACEMENTS
#define EXPECTED_REPLACEMENTS 100
#endif
if(!instring || !old_part || !new_part)
{
return (char*)NULL;
}
size_t instring_len=strlen(instring);
size_t new_len=strlen(new_part);
size_t old_len=strlen(old_part);
if(instring_len<old_len || old_len==0)
{
return (char*)NULL;
}
const char *in=instring;
const char *found=NULL;
size_t count=0;
size_t out=0;
size_t ax=0;
char *outstring=NULL;
if(new_len> old_len )
{
size_t Diff=EXPECTED_REPLACEMENTS*(new_len-old_len);
size_t outstring_len=instring_len + Diff;
outstring =(char*) malloc(outstring_len);
if(!outstring){
return (char*)NULL;
}
while((found = strstr(in, old_part))!=NULL)
{
if(count==EXPECTED_REPLACEMENTS)
{
outstring_len+=Diff;
if((outstring=realloc(outstring,outstring_len))==NULL)
{
return (char*)NULL;
}
count=0;
}
ax=found-in;
strncpy(outstring+out,in,ax);
out+=ax;
strncpy(outstring+out,new_part,new_len);
out+=new_len;
in=found+old_len;
count++;
}
}
else
{
outstring =(char*) malloc(instring_len);
if(!outstring){
return (char*)NULL;
}
while((found = strstr(in, old_part))!=NULL)
{
ax=found-in;
strncpy(outstring+out,in,ax);
out+=ax;
strncpy(outstring+out,new_part,new_len);
out+=new_len;
in=found+old_len;
}
}
ax=(instring+instring_len)-in;
strncpy(outstring+out,in,ax);
out+=ax;
outstring[out]='\0';
return outstring;
}
To set methods PUT and DELETE I perform as following:
<form
method="PUT"
action="domain/route/param?query=value"
>
<input type="hidden" name="delete_id" value="1" />
<input type="hidden" name="put_id" value="1" />
<input type="text" name="put_name" value="content_or_not" />
<div>
<button name="update_data">Save changes</button>
<button name="remove_data">Remove</button>
</div>
</form>
<hr>
<form
method="DELETE"
action="domain/route/param?query=value"
>
<input type="hidden" name="delete_id" value="1" />
<input type="text" name="delete_name" value="content_or_not" />
<button name="delete_data">Remove item</button>
</form>
Then JS acts to perform the desired methods:
<script>
var putMethod = ( event ) => {
// Prevent redirection of Form Click
event.preventDefault();
var target = event.target;
while ( target.tagName != "FORM" ) {
target = target.parentElement;
} // While the target is not te FORM tag, it looks for the parent element
// The action attribute provides the request URL
var url = target.getAttribute( "action" );
// Collect Form Data by prefix "put_" on name attribute
var bodyForm = target.querySelectorAll( "[name^=put_]");
var body = {};
bodyForm.forEach( element => {
// I used split to separate prefix from worth name attribute
var nameArray = element.getAttribute( "name" ).split( "_" );
var name = nameArray[ nameArray.length - 1 ];
if ( element.tagName != "TEXTAREA" ) {
var value = element.getAttribute( "value" );
} else {
// if element is textarea, value attribute may return null or undefined
var value = element.innerHTML;
}
// all elements with name="put_*" has value registered in body object
body[ name ] = value;
} );
var xhr = new XMLHttpRequest();
xhr.open( "PUT", url );
xhr.setRequestHeader( "Content-Type", "application/json" );
xhr.onload = () => {
if ( xhr.status === 200 ) {
// reload() uses cache, reload( true ) force no-cache. I reload the page to make "redirects normal effect" of HTML form when submit. You can manipulate DOM instead.
location.reload( true );
} else {
console.log( xhr.status, xhr.responseText );
}
}
xhr.send( body );
}
var deleteMethod = ( event ) => {
event.preventDefault();
var confirm = window.confirm( "Certeza em deletar este conteúdo?" );
if ( confirm ) {
var target = event.target;
while ( target.tagName != "FORM" ) {
target = target.parentElement;
}
var url = target.getAttribute( "action" );
var xhr = new XMLHttpRequest();
xhr.open( "DELETE", url );
xhr.setRequestHeader( "Content-Type", "application/json" );
xhr.onload = () => {
if ( xhr.status === 200 ) {
location.reload( true );
console.log( xhr.responseText );
} else {
console.log( xhr.status, xhr.responseText );
}
}
xhr.send();
}
}
</script>
With these functions defined, I add a event listener to the buttons which make the form method request:
<script>
document.querySelectorAll( "[name=update_data], [name=delete_data]" ).forEach( element => {
var button = element;
var form = element;
while ( form.tagName != "FORM" ) {
form = form.parentElement;
}
var method = form.getAttribute( "method" );
if ( method == "PUT" ) {
button.addEventListener( "click", putMethod );
}
if ( method == "DELETE" ) {
button.addEventListener( "click", deleteMethod );
}
} );
</script>
And for the remove button on the PUT form:
<script>
document.querySelectorAll( "[name=remove_data]" ).forEach( element => {
var button = element;
button.addEventListener( "click", deleteMethod );
</script>
_ - - - - - - - - - - -
This article https://blog.garstasio.com/you-dont-need-jquery/ajax/ helps me a lot!
Beyond this, you can set postMethod function and getMethod to handle POST and GET submit methods as you like instead browser default behavior. You can do whatever you want instead use location.reload()
, like show message of successful changes or successful deletion.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
For reference, because this question is one of the first Google result.
The method presentViewController
is replaced by the method present
.
You can use it like the old one:
self.present(viewControllerToPresent, animated: true, completion: nil)
Example to open the camera:
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
Simple stuff here:
Incase you don't need a ScrollView for this approach you can go with the below code to achieve Something like this :
<View style={{flex: 1, backgroundColor:'grey'}}>
<View style={{flex: 1, backgroundColor: 'red'}} />
<View style={{height: 100, backgroundColor: 'green'}} />
</View>
Most of these answers are wrong due to the failure to use a locale based comparison for sorting. Look at localizedStandardCompare()
Starting with Node.js 11, the url.parse and other methods of the Legacy URL API were deprecated (only in the documentation, at first) in favour of the standardized WHATWG URL API. The new API does not offer parsing the query string into an object. That can be achieved using tthe querystring.parse method:
// Load modules to create an http server, parse a URL and parse a URL query.
const http = require('http');
const { URL } = require('url');
const { parse: parseQuery } = require('querystring');
// Provide the origin for relative URLs sent to Node.js requests.
const serverOrigin = 'http://localhost:8000';
// Configure our HTTP server to respond to all requests with a greeting.
const server = http.createServer((request, response) => {
// Parse the request URL. Relative URLs require an origin explicitly.
const url = new URL(request.url, serverOrigin);
// Parse the URL query. The leading '?' has to be removed before this.
const query = parseQuery(url.search.substr(1));
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end(`Hello, ${query.name}!\n`);
});
// Listen on port 8000, IP defaults to 127.0.0.1.
server.listen(8000);
// Print a friendly message on the terminal.
console.log(`Server running at ${serverOrigin}/`);
If you run the script above, you can test the server response like this, for example:
curl -q http://localhost:8000/status?name=ryan
Hello, ryan!
In Visual Studio go to
Tools/NuGet Package Manager / Package Manager Console
Type git config --global http.proxy http://xxx.xxxx.xxxx:Port
Adding the @ElementCollection
to the List field solved this issue:
@Column
@ElementCollection(targetClass=Integer.class)
private List<Integer> countries;
Sometimes, it might have a very simple solution
You have perhaps added a new version of the existing .jar file and forgot to remove the old version of the same .jar file.
Now try removing the old jar files (that are marked in red) in the Build Path > Configure Build Path
It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:
[bits 32]
.
.
and [ebp-4], 0
I had the same issue and this helped me.
<ImageView
android:id="@+id/image"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="fitXY"
/>
or if your using vi mode, hit Esc followed by cc
to get back what you just erased, Esc and then p :)
Since seaborn also uses matplotlib to do its plotting you can easily combine the two. If you only want to adopt the styling of seaborn the set_style
function should get you started:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set_style("darkgrid")
plt.plot(np.cumsum(np.random.randn(1000,1)))
plt.show()
Result:
If you want to select the last child and need to be specific on the element type you can use the selector last-of-type
Here is an example:
$("div p:last-of-type").css("border", "3px solid red");
$("div span:last-of-type").css("border", "3px solid red");
<div id="example">
<p>This is paragraph 1</p>
<p>This is paragraph 2</p>
<span>This is paragraph 3</span>
<span>This is paragraph 4</span>
<p>This is paragraph 5</p>
</div>
In the example above both Paragraph 4 and Paragraph 5 will have a red border since Paragraph 5 is the last element of "p" type in the div and Paragraph 4 is the last "span" in the div.
Short version: Yes it is faster, with less code!
String concatenation does a lot of work without knowing if it is needed or not (the traditional "is debugging enabled" test known from log4j), and should be avoided if possible, as the {} allows delaying the toString() call and string construction to after it has been decided if the event needs capturing or not. By having the logger format a single string the code becomes cleaner in my opinion.
You can provide any number of arguments. Note that if you use an old version of sljf4j and you have more than two arguments to {}
, you must use the new Object[]{a,b,c,d}
syntax to pass an array instead. See e.g. http://slf4j.org/apidocs/org/slf4j/Logger.html#debug(java.lang.String, java.lang.Object[]).
Regarding the speed: Ceki posted a benchmark a while back on one of the lists.
There looks to be an issue when the time of the phone/emulator is different to the one of the server (where react-native packager is running). In my case there was a 1 minute difference between the time of the phone and the computer. After synchronizing them (didn't do anything fancy, the phone was set on manual time, and I just set it to use the network(sim) provided time), everything worked fine. This github issue helped me find the problem.
If you are using PHP 7.4 or above, you can use the spread operator ...
as the following examples from the PHP Docs:
$arr1 = [1, 2, 3];
$arr2 = [...$arr1]; //[1, 2, 3]
$arr3 = [0, ...$arr1]; //[0, 1, 2, 3]
$arr4 = array(...$arr1, ...$arr2, 111); //[1, 2, 3, 1, 2, 3, 111]
$arr5 = [...$arr1, ...$arr1]; //[1, 2, 3, 1, 2, 3]
function getArr() {
return ['a', 'b'];
}
$arr6 = [...getArr(), 'c']; //['a', 'b', 'c']
$arr7 = [...new ArrayIterator(['a', 'b', 'c'])]; //['a', 'b', 'c']
function arrGen() {
for($i = 11; $i < 15; $i++) {
yield $i;
}
}
$arr8 = [...arrGen()]; //[11, 12, 13, 14]
It works like in JavaScript ES6.
See more on https://wiki.php.net/rfc/spread_operator_for_array.
Example of using a Timer
:
using System;
using System.Timers;
static void Main(string[] args)
{
Timer t = new Timer(TimeSpan.FromMinutes(5).TotalMilliseconds); // Set the time (5 mins in this case)
t.AutoReset = true;
t.Elapsed += new System.Timers.ElapsedEventHandler(your_method);
t.Start();
}
// This method is called every 5 mins
private static void your_method(object sender, ElapsedEventArgs e)
{
Console.WriteLine("...");
}
You can actually use angular-ui-utils' ui-route
directive:
<a ui-route ng-href="/">Home</a>
<a ui-route ng-href="/about">About</a>
<a ui-route ng-href="/contact">Contact</a>
or:
/**
* Header controller
*/
angular.module('myApp')
.controller('HeaderCtrl', function ($scope) {
$scope.menuItems = [
{
name: 'Home',
url: '/',
title: 'Go to homepage.'
},
{
name: 'About',
url: '/about',
title: 'Learn about the project.'
},
{
name: 'Contact',
url: '/contact',
title: 'Contact us.'
}
];
});
<!-- index.html: -->
<div class="header" ng-controller="HeaderCtrl">
<ul class="nav navbar-nav navbar-right">
<li ui-route="{{menuItem.url}}" ng-class="{active: $uiRoute}"
ng-repeat="menuItem in menuItems">
<a ng-href="#{{menuItem.url}}" title="{{menuItem.title}}">
{{menuItem.name}}
</a>
</li>
</ul>
</div>
If you're using ui-utils, you may also be interested in ui-router for managing partial/nested views.
I suspect you did not know that there are different &
escapes in HTML. The W3C you can see the codes. ×
means ×
in HTML code. Use &times
instead.
The Blue theme is now supported via Visual Studio update 2, and is accessed like the answer chosen for this question.
You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)
$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property
Or just this, xpath is case sensitive. Both have the same output:
$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml
Name Type #text
---- ---- -----
DisplayName System.String SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName System.String SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped
Spring Docs explain that
In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.
Consider the use of AspectJ mode (see mode attribute in table below) if you expect self-invocations to be wrapped with transactions as well. In this case, there will not be a proxy in the first place; instead, the target class will be weaved (that is, its byte code will be modified) in order to turn @Transactional into runtime behavior on any kind of method.
Another way is user BeanSelfAware
Try this code once-
public class FindPeopleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home,
container, false);
Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateDetail();
}
});
return rootView;
}
public void updateDetail() {
Intent intent = new Intent(getActivity(), MainActivityList.class);
startActivity(intent);
}
}
And as suggested by Raghunandan remove below code from your fragment_home.xml
-
android:onClick="goToAttract"
(Laravel 5.2) I find the simplest way is just to add one code line to monitor the sql queries:
\DB::listen(function($sql) {var_dump($sql); });
The easiest way would be to use Runtime.getRuntime.exec()
.
For example, to get a registry value for the default browser on Windows:
String command = "REG QUERY HKEY_CLASSES_ROOT\\http\\shell\\open\\command";
try
{
Process process = Runtime.getRuntime().exec(command);
} catch (IOException e)
{
e.printStackTrace();
}
Then use a Scanner
to get the output of the command, if necessary.
Scanner kb = new Scanner(process.getInputStream());
Note: the \
is an escape character in a String
, and must be escaped to work properly (hence the \\
).
However, there is no executable called cd
, because it can't be implemented in a separate process.
The one case where the current working directory matters is executing an external process (using ProcessBuilder
or Runtime.exec()
). In those cases you can specify the working directory to use for the newly started process explicitly.
Easiest way for your command:
System.setProperty("user.dir", "C:\\Program Files\\Flowella");
This issue might also be caused by a broken Maven repository.
I observe the SEVERE: A child container failed during start
message from time to time when working with Eclipse. My Eclipse workspace has several projects. Some of the projects have common external dependencies. If Maven repository is empty (or I add new dependencies into pom.xml
files), Eclipse starts downloading libraries specified in pom.xml
into Maven repository. And Eclipse does that in parallel for several projects in the workspace. It might happen that several Eclipse threads would be downloading the same file simultaneously into the same place in Maven repository. As a result, this file becomes corrupted.
So, this is how you could resolve the issue.
rm -rf $HOME/.m2
).mvn package
in the command line. It is important to run the command for each project one-by-one, not in parallel; thus, you ensure that only one instance of Maven runs each time.There are at least five different ways to break out of two or more loops:
1) Set parent(s) loop to the end
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
{
i = 5;
break;
}
}
}
2) Use label
fast:
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
break fast;
}
}
3) Use variable
var exit_loops = false;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
{
exit_loops = true;
break;
}
}
if (exit_loops)
break;
}
4) Use self executing function
(function()
{
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
return;
}
}
})();
5) Use regular function
function nested_loops()
{
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
return;
}
}
}
nested_loops();
This depends on the context.
In Pascal-like languages, functions and procedures are distinct entities, differing in whether they do or don't return a value. They behave differently wrt. the language syntax (eg. procedure calls form statements; you cannot use a procedure call inside an expression vs. function calls don't form statements, you must use them in other statements). Therefore, Pascal-bred programmers differentiate between those.
In C-like languages, and many other contemporary languages, this distinction is gone; in statically typed languages, procedures are just functions with a funny return type. This is probably why they are used interchangeably.
In functional languages, there is typically no such thing as a procedure - everything is a function.
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
business_key
values to a temporary tableThe group by
could be executed like:
business key
in a hashtableThe first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
This will print 1 character per line from the file.
try {
FileInputStream inputStream = new FileInputStream(theFile);
while (inputStream.available() > 0) {
inputData = inputStream.read();
System.out.println((char) inputData);
}
inputStream.close();
} catch (IOException ioe) {
System.out.println("Trouble reading from the file: " + ioe.getMessage());
}
A couple of examples:
infix fun Double.f(fmt: String) = "%$fmt".format(this)
infix fun Double.f(fmt: Float) = "%${if (fmt < 1) fmt + 1 else fmt}f".format(this)
val pi = 3.14159265358979323
println("""pi = ${pi f ".2f"}""")
println("pi = ${pi f .2f}")
Robi Code is work for me, just put if !null so that if phone number is null, user can fill the phone number by him/her self.
editTextPhoneNumber = (EditText) findViewById(R.id.editTextPhoneNumber);
TelephonyManager tMgr;
tMgr= (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
if (mPhoneNumber != null){
editTextPhoneNumber.setText(mPhoneNumber);
}
Your Manifest
Must Change like this Activity name must Specified like ".YourActivityname"
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.th.mybook"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8" android:targetSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainTabPanel"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MyBookActivity" >
</activity>
</application>
If you'd prefer to do it in SQL, enter this query into the query window:
CREATE SCHEMA Test
Press CTRL + Enter to submit it, and you should see confirmation in the output pane underneath the query window. You'll have to right-click on an existing schema in the Object panel and click "Refresh All" to see it show up, though.
Using nginx/1.14.0
i have a websocket-server running on port 8097 and users connect from to wss on port 8098, nginx just decrypts the content and forwards it to the websocket server
So i have this config file (in my case /etc/nginx/conf.d/default.conf
)
server {
listen 8098;
ssl on;
ssl_certificate /etc/ssl/certs/domain.crt;
ssl_certificate_key /root/domain.key;
location / {
proxy_pass http://hostname:8097;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400;
}
}
A fast way to convert strings to an integer is to use a bitwise or, like so:
x | 0
While it depends on how it is implemented, in theory it should be relatively fast (at least as fast as +x
) since it will first cast x
to a number and then perform a very efficient or.
Here is the complete syntax,
#!/usr/bin/python3
import time
def your_function():
print("Hello, World")
while True:
your_function()
time.sleep(10) #make function to sleep for 10 seconds
If you enabled it as a DHCP client then your router should get an IP address from a DHCP server. If you connect your router on a net with a DHCP server you should reach your router's administrator page on the IP address assigned by the DHCP.
You can write like that. This is for whenever you change context path you don't need to modify your jsp file.
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/styles.css" />
This trick supposed to prevent v = null
kind of typos.
But Java allows only boolean expressions as if()
conditions so that trick does not make much sense, compiler will find those typos anyway.
It is still valuable trick for C/C++ code though.
From Twitter Bootstrap documentation:
.col-sm-*
,.col-md-*
,.col-lg-*
.(shown in let's say cv2.imshow)
cv2.waitKey(0)
would continue after pressing "Scr" button (or its combination), but you can try this
cv2.waitKey(0)
input('')
cv2.waitkey(0) to give the program enough time to process everything you want to see in the imshow and input('')
to make it wait for you to press Enter in the console window
this works on python 3
As an update to The Minister's answer, you can now do this with es2015:
function Tuple(...args) {
args.forEach((val, idx) =>
Object.defineProperty(this, "item"+idx, { get: () => val })
)
}
var t = new Tuple("a", 123)
console.log(t.item0) // "a"
t.item0 = "b"
console.log(t.item0) // "a"
Hmmm, nobody said F1 for help.
Could it be that Google is faster and better for getting at the information that you need.
The "manual bootstrap" case can gain access to Angular services by manually creating an injector before bootstrap. This initial injector will stand alone (not be attached to any elements) and include only a subset of the modules that are loaded. If all you need is core Angular services, it's sufficient to just load ng
, like this:
angular.element(document).ready(
function() {
var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');
$http.get('/config.json').then(
function (response) {
var config = response.data;
// Add additional services/constants/variables to your app,
// and then finally bootstrap it:
angular.bootstrap(document, ['myApp']);
}
);
}
);
You can, for example, use the module.constant
mechanism to make data available to your app:
myApp.constant('myAppConfig', data);
This myAppConfig
can now be injected just like any other service, and in particular it's available during the configuration phase:
myApp.config(
function (myAppConfig, someService) {
someService.config(myAppConfig.someServiceConfig);
}
);
or, for a smaller app, you could just inject the global config directly into your service, at the expense of spreading knowledge about the configuration format throughout the application.
Of course, since the async operations here will block the bootstrap of the application, and thus block the compilation/linking of the template, it's wise to use the ng-cloak
directive to prevent the unparsed template from showing up during the work. You could also provide some sort of loading indication in the DOM , by providing some HTML that gets shown only until AngularJS initializes:
<div ng-if="initialLoad">
<!-- initialLoad never gets set, so this div vanishes as soon as Angular is done compiling -->
<p>Loading the app.....</p>
</div>
<div ng-cloak>
<!-- ng-cloak attribute is removed once the app is done bootstrapping -->
<p>Done loading the app!</p>
</div>
I created a complete, working example of this approach on Plunker, loading the configuration from a static JSON file as an example.
This, for example, will make files ending in .variables
and .overrides
being treated just like any other LESS file. In terms of code coloring, in terms of (auto) formatting. Define in user settings or project settings, as you like.
(Semantic UI uses these weird extensions, in case you wonder)
You can also pad the characters left by including a number following the X
, such as this: string.format("0x{0:X8}", string_to_modify)
, which yields "0x00000C20"
.
<%
String redirectURL = "http://whatever.com/myJSPFile.jsp";
response.sendRedirect(redirectURL);
%>
Thanks! to all above answers. I hope you have a .p12 file. Now, open terminal write following command. Set terminal to the path where you have put .12 file.
$ openssl pkcs12 -in yourCertifcate.p12 -out pemAPNSCert.pem -nodes
Enter Import Password: <Just enter your certificate password>
MAC verified OK
Now your .pem file is generated.
Verify .pem file First, open the .pem in a text editor to view its content. The certificate content should be in format as shown below. Make sure the pem file contains both Certificate content(from BEGIN CERTIFICATE to END CERTIFICATE) as well as Certificate Private Key (from BEGIN PRIVATE KEY to END PRIVATE KEY) :
> Bag Attributes
> friendlyName: Apple Push Services:<Bundle ID>
> localKeyID: <> subject=<>
> -----BEGIN CERTIFICATE-----
>
> <Certificate Content>
>
> -----END CERTIFICATE----- Bag Attributes
> friendlyName: <>
> localKeyID: <> Key Attributes: <No Attributes>
> -----BEGIN PRIVATE KEY-----
>
> <Certificate Private Key>
>
> -----END PRIVATE KEY-----
Also, you check the validity of the certificate by going to SSLShopper Certificate Decoder and paste the Certificate Content (from BEGIN CERTIFICATE to END CERTIFICATE) to get all the info about the certificate as shown below:
Its a very late answer, but you can also use the Collections.singleton
:
List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", null, "How"));
list.removeAll(Collections.singleton(null));
list.removeAll(Collections.singleton(""));
More likely it is 400 Bad Request
6.5.1. 400 Bad Request
The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
As the request contains duplicate value(value that already exists), it can be perceived as a client error. Need to change the request before the next try.
By considering these facts we can conclude as HTTP STATUS 400 Bad Request.
in Bootstrap, web inspector says the Headings are set to 'inherit'
all i needed to set my page to the new font was
div, p {font-family: Algerian}
that's in .scss
If you would like to modify file names in an editor (such as vim), the click library comes with the command click.edit()
, which can be used to receive user input from an editor. Here is an example of how it can be used to refactor files in a directory.
import click
from pathlib import Path
# current directory
direc_to_refactor = Path(".")
# list of old file paths
old_paths = list(direc_to_refactor.iterdir())
# list of old file names
old_names = [str(p.name) for p in old_paths]
# modify old file names in an editor,
# and store them in a list of new file names
new_names = click.edit("\n".join(old_names)).split("\n")
# refactor the old file names
for i in range(len(old_paths)):
old_paths[i].replace(direc_to_refactor / new_names[i])
I wrote a command line application that uses the same technique, but that reduces the volatility of this script, and comes with more options, such as recursive refactoring. Here is the link to the github page. This is useful if you like command line applications, and are interested in making some quick edits to file names. (My application is similar to the "bulkrename" command found in ranger).
try simple way to install intellij idea
Install IntelliJ on Ubuntu using Ubuntu Make
You need to install Ubuntu Make first. If you are using Ubuntu 16.04, 18.04 or a higher version, you can install Ubuntu Make using the command below:
Once you have Ubuntu Make installed, you can use the command below to install IntelliJ IDEA Community edition:
To install the IntelliJ IDEA Ultimate edition, use the command below:
To remove IntelliJ IDEA installed via Ubuntu Make, use the command below for your respective versions:
you may visit for more option.
As stated, all objects in sharepoint contain some sort of unique identifier (often an integer based counter for list items, and GUIDs for lists).
That said, there is also a feature available at http://www.codeplex.com/features called "Unique Column Policy", designed to add an other column with a unique value. A complete writeup is available at http://scothillier.spaces.live.com/blog/cns!8F5DEA8AEA9E6FBB!293.entry
-- Access:
SELECT CHR(13) & CHR(10)
-- SQL Server:
SELECT CHAR(13) + CHAR(10)
In 11g you can use the undocumented function wm_concat like this:
select wm_concat(distinct name) as names from demotable group by group_id