The answer is to place the root dir to the location directives:
root /srv/www/ducklington.org/public_html;
I found myself needing the same thing for a recent project. Building on Levi's solution, here's a cleaner and faster method:
Rack::Utils.parse_nested_query 'param1=value1¶m2=value2¶m3=value3'
# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}
It is possible. Make two functions: static and virtual
struct Object{
struct TypeInformation;
static const TypeInformation &GetTypeInformationStatic() const
{
return GetTypeInformationMain1();
}
virtual const TypeInformation &GetTypeInformation() const
{
return GetTypeInformationMain1();
}
protected:
static const TypeInformation &GetTypeInformationMain1(); // Main function
};
struct SomeObject : public Object {
static const TypeInformation &GetTypeInformationStatic() const
{
return GetTypeInformationMain2();
}
virtual const TypeInformation &GetTypeInformation() const
{
return GetTypeInformationMain2();
}
protected:
static const TypeInformation &GetTypeInformationMain2(); // Main function
};
Hello guys Most of the codes you will find will return you server ip address not client ip address .however this code returns correct client ip address.Give it a try. For More info just check this
https://www.youtube.com/watch?v=Nkf37DsxYjI
for getting your local ip address using javascript you can use put this code inside your script tag
<script>
var RTCPeerConnection = /*window.RTCPeerConnection ||*/
window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (RTCPeerConnection) (function () {
var rtc = new RTCPeerConnection({ iceServers: [] });
if (1 || window.mozRTCPeerConnection) {
rtc.createDataChannel('', { reliable: false });
};
rtc.onicecandidate = function (evt) {
if (evt.candidate)
grepSDP("a=" + evt.candidate.candidate);
};
rtc.createOffer(function (offerDesc) {
grepSDP(offerDesc.sdp);
rtc.setLocalDescription(offerDesc);
}, function (e) { console.warn("offer failed", e); });
var addrs = Object.create(null);
addrs["0.0.0.0"] = false;
function updateDisplay(newAddr) {
if (newAddr in addrs) return;
else addrs[newAddr] = true;
var displayAddrs = Object.keys(addrs).filter(function
(k) { return addrs[k]; });
document.getElementById('list').textContent =
displayAddrs.join(" or perhaps ") || "n/a";
}
function grepSDP(sdp) {
var hosts = [];
sdp.split('\r\n').forEach(function (line) {
if (~line.indexOf("a=candidate")) {
var parts = line.split(' '),
addr = parts[4],
type = parts[7];
if (type === 'host') updateDisplay(addr);
} else if (~line.indexOf("c=")) {
var parts = line.split(' '),
addr = parts[2];
updateDisplay(addr);
}
});
}
})(); else
{
document.getElementById('list').innerHTML = "<code>ifconfig| grep inet | grep -v inet6 | cut -d\" \" -f2 | tail -n1</code>";
document.getElementById('list').nextSibling.textContent = "In Chrome and Firefox your IP should display automatically, by the power of WebRTCskull.";
}
</script>
<body>
<div id="list"></div>
</body>
and For getting your public ip address you can use put this code inside your script tag
function getIP(json) {
document.write("My public IP address is: ", json.ip);
}
<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
you are in wrong cdb/pdb so connect to right pdb
Along the same lines as previous answers, but a very short addition that Allows to use all Control properties without having cross thread invokation exception.
Helper Method
/// <summary>
/// Helper method to determin if invoke required, if so will rerun method on correct thread.
/// if not do nothing.
/// </summary>
/// <param name="c">Control that might require invoking</param>
/// <param name="a">action to preform on control thread if so.</param>
/// <returns>true if invoke required</returns>
public bool ControlInvokeRequired(Control c,Action a)
{
if (c.InvokeRequired) c.Invoke(new MethodInvoker(delegate { a(); }));
else return false;
return true;
}
Sample Usage
// usage on textbox
public void UpdateTextBox1(String text)
{
//Check if invoke requied if so return - as i will be recalled in correct thread
if (ControlInvokeRequired(textBox1, () => UpdateTextBox1(text))) return;
textBox1.Text = ellapsed;
}
//Or any control
public void UpdateControl(Color c,String s)
{
//Check if invoke requied if so return - as i will be recalled in correct thread
if (ControlInvokeRequired(myControl, () => UpdateControl(c,s))) return;
myControl.Text = s;
myControl.BackColor = c;
}
Try ArrayDeque
or LinkedList
, which both implement the Queue
interface.
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayDeque.html
The issue is that you are trying to have multiple statements in an if
without using {}
.
What you currently have is interpreted like:
if( choice==5 )
{
System.out.println( ... );
}
break;
else
{
//...
}
You really want:
if( choice==5 )
{
System.out.println( ... );
break;
}
else
{
//...
}
Also, as Farce has stated, it would be better to use else if
for all the conditions instead of if
because if choice==1
, it will still go through and check if choice==5
, which would fail, and it will still go into your else block.
if( choice==1 )
//...
else if( choice==2 )
//...
else if( choice==3 )
//...
else if( choice==4 )
//...
else if( choice==5 )
{
//...
}
else
//...
A more elegant solution would be using a switch
statement. However, break
only breaks from the most inner "block" unless you use labels. So you want to label your loop and break from that if the case is 5:
LOOP:
for(;;)
{
System.out.println("---> Your choice: ");
choice = input.nextInt();
switch( choice )
{
case 1:
playGame();
break;
case 2:
loadGame();
break;
case 2:
options();
break;
case 4:
credits();
break;
case 5:
System.out.println("End of Game\n Thank you for playing with us!");
break LOOP;
default:
System.out.println( ... );
}
}
Instead of labeling the loop, you could also use a flag to tell the loop to stop.
bool finished = false;
while( !finished )
{
switch( choice )
{
// ...
case 5:
System.out.println( ... )
finished = true;
break;
// ...
}
}
In the <system.web>
element, add the following element:
<httpCookies requireSSL="true" />
However, if you have a <forms>
element in your system.web\authentication
block, then this will override the setting in httpCookies
, setting it back to the default false
.
In that case, you need to add the requireSSL="true"
attribute to the forms element as well.
So you will end up with:
<system.web>
<authentication mode="Forms">
<forms requireSSL="true">
<!-- forms content -->
</forms>
</authentication>
</system.web>
One way is that In case of Session Expire, in every action you have to check its session and if it is null then redirect to Login page.
But this is very hectic method
To over come this you need to create your own ActionFilterAttribute
which will do this, you just need to add this attribute in every action method.
Here is the Class which overrides ActionFilterAttribute.
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// check if session is supported
CurrentCustomer objCurrentCustomer = new CurrentCustomer();
objCurrentCustomer = ((CurrentCustomer)SessionStore.GetSessionValue(SessionStore.Customer));
if (objCurrentCustomer == null)
{
// check if a new session id was generated
filterContext.Result = new RedirectResult("~/Users/Login");
return;
}
base.OnActionExecuting(filterContext);
}
}
Then in action just add this attribute like so:
[SessionExpire]
public ActionResult Index()
{
return Index();
}
This will do you work.
Python has a built-in command specifically for spinning up a webserver:
Python3.x:
python -m http.server 8000
Other versions:
python -m SimpleHTTPServer 8000
Would start a webserver on port 8000
(Python is a prerequisite to this; if you don't have python installed, the other answers may be easier)
If using Newtonsoft.Json:
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
public static class Extensions
{
public static StringContent AsJson(this object o)
=> new StringContent(JsonConvert.SerializeObject(o), Encoding.UTF8, "application/json");
}
Example:
var httpClient = new HttpClient();
var url = "https://www.duolingo.com/2016-04-13/login?fields=";
var data = new { identifier = "username", password = "password" };
var result = await httpClient.PostAsync(url, data.AsJson())
answer 1
answer 2
simply press Alt+F5 after updating your pom.xml. This will build your project again and download all jar files
I had trouble with VS 2017 finding my UnitTest as well. It wasn't the exact problem John was asking - but this was the first result in google that I came looking for so I wanted to share my issue.
I had a legacy solution coming back from VS2010 going over VS2013, VS2015. Now in VS2017 it seems namespaces for the [TestMethod]
Attribute have changed.
Before it was using
Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0
I created a new Test.dll in the project and that one used by default
Microsoft.VisualStudio.TestPlatform.TestFramework, Version=14.0.0.0
So my solution was to create a new UnitTest project from within VS2017. Maybe changing assembly references for the old test project would have worked as well. With the new reference VS2017 did discover those unit tests.
The solution is fairly straight forward. To ensure that we don't impact the width of the cells in the table, we'll turn off white-space. To ensure we get a horizontal scroll bar, we'll turn on overflow-x. And that's pretty much it:
.container {
width: 30em;
overflow-x: auto;
white-space: nowrap;
}
You can see the end-result here, or in the animation below. If the table determines the height of your container, you should not need to explicitly set overflow-y
to hidden
. But understand that is also an option.
As Alex says, it works very well. The only tricky part is to remember to make any changes in the cmake files, rather than from within Visual Studio. So on all platforms, the workflow is similar to if you'd used plain old makefiles.
But it's fairly easy to work with, and I've had no issues with cmake generating invalid files or anything like that, so I wouldn't worry too much.
In python, everything is an object, also "simple" variables types (int, float, etc..).
When you changes a variable value, you actually changes it's pointer, and if you compares between two variables it's compares their pointers. (To be clear, pointer is the address in physical computer memory where a variable is stored).
As a result, when you changes an inner variable value, you changes it's value in the memory and it's affects all the variables that point to this address.
For your example, when you do:
a = b = 5
This means that a and b points to the same address in memory that contains the value 5, but when you do:
a = 6
It's not affect b because a is now points to another memory location that contains 6 and b still points to the memory address that contains 5.
But, when you do:
a = b = [1,2,3]
a and b, again, points to the same location but the difference is that if you change the one of the list values:
a[0] = 2
It's changes the value of the memory that a is points on, but a is still points to the same address as b, and as a result, b changes as well.
In newer versions change was made to the flags: from the documentation:
--extended-insert, -e
Write INSERT statements using multiple-row syntax that includes several VALUES lists. This results in a smaller dump file and speeds up inserts when the file is reloaded.
--opt
This option, enabled by default, is shorthand for the combination of --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset. It gives a fast dump operation and produces a dump file that can be reloaded into a MySQL server quickly.
Because the --opt option is enabled by default, you only specify its converse, the --skip-opt to turn off several default settings. See the discussion of mysqldump option groups for information about selectively enabling or disabling a subset of the options affected by --opt.
--skip-extended-insert
Turn off extended-insert
app.get
is called when the HTTP method is set to GET
, whereas app.use
is called regardless of the HTTP method, and therefore defines a layer which is on top of all the other RESTful types which the express packages gives you access to.
def hi():
bye = 5
return bye
print hi()
TempData will be always available until first read, once you read it its not available any more can be useful to pass quick message also to view that will be gone after first read. ViewBag Its more useful when passing quickly piece of data to the view, normally you should pass all data to the view through model , but there is cases when you model coming direct from class that is map into database like entity framework in that case you don't what to change you model to pass a new piece of data, you can stick that into the viewbag ViewData is just indexed version of ViewBag and was used before MVC3
One more thing to watch out for is if the second value was another Integer object instead of a literal '0', the '==' operator compares the object pointers and will not auto-unbox.
ie:
Integer a = new Integer(0);
Integer b = new Integer(0);
int c = 0;
boolean isSame_EqOperator = (a==b); //false!
boolean isSame_EqMethod = (a.equals(b)); //true
boolean isSame_EqAutoUnbox = ((a==c) && (a.equals(c)); //also true, because of auto-unbox
//Note: for initializing a and b, the Integer constructor
// is called explicitly to avoid integer object caching
// for the purpose of the example.
// Calling it explicitly ensures each integer is created
// as a separate object as intended.
// Edited in response to comment by @nolith
Overhead typically reffers to the amount of extra resources (memory, processor, time, etc.) that different programming algorithms take.
For example, the overhead of inserting into a balanced Binary Tree could be much larger than the same insert into a simple Linked List (the insert will take longer, use more processing power to balance the Tree, which results in a longer percieved operation time by the user).
It's been a little while since I coded with selenium, but your code looks ok to me. One thing to note is that if the element is not found, but the timeout is passed, I think the code will continue to execute. So you can do something like this:
boolean exists = driver.findElements(By.xpath("//*[@id='someID']")).size() != 0
What does the above boolean return? And are you sure selenium actually navigates to the expected page? (That may sound like a silly question but are you actually watching the pages change... selenium can be run remotely you know...)
With a different example:
Consider this is the string and pattern to be searched for is 'cat':
text = "catmania thiscat thiscatmaina";
Now definitions,
'\b' finds/matches the pattern at the beginning or end of each word.
'\B' does not find/match the pattern at the beginning or end of each word.
Different Cases:
Case 1: At the beginning of each word
result = text.replace(/\bcat/g, "ct");
Now, result is "ctmania thiscat thiscatmaina"
Case 2: At the end of each word
result = text.replace(/cat\b/g, "ct");
Now, result is "catmania thisct thiscatmaina"
Case 3: Not in the beginning
result = text.replace(/\Bcat/g, "ct");
Now, result is "catmania thisct thisctmaina"
Case 4: Not in the end
result = text.replace(/cat\B/g, "ct");
Now, result is "ctmania thiscat thisctmaina"
Case 5: Neither beginning nor end
result = text.replace(/\Bcat\B/g, "ct");
Now, result is "catmania thiscat thisctmaina"
Hope this helps :)
SELECT INTO is typically used to generate temp tables or to copy another table (data and/or structure).
In day to day code you use INSERT because your tables should already exist to be read, UPDATEd, DELETEd, JOINed etc. Note: the INTO keyword is optional with INSERT
That is, applications won't normally create and drop tables as part of normal operations unless it is a temporary table for some scope limited and specific usage.
A table created by SELECT INTO will have no keys or indexes or constraints unlike a real, persisted, already existing table
The 2 aren't directly comparable because they have almost no overlap in usage
The only objects in Python that have canonical names are modules, functions, and classes, and of course there is no guarantee that this canonical name has any meaning in any namespace after the function or class has been defined or the module imported. These names can also be modified after the objects are created so they may not always be particularly trustworthy.
What you want to do is not possible without recursively walking the tree of named objects; a name is a one-way reference to an object. A common or garden-variety Python object contains no references to its names. Imagine if every integer, every dict, every list, every Boolean needed to maintain a list of strings that represented names that referred to it! It would be an implementation nightmare, with little benefit to the programmer.
One more dict style clean syntax:
df["new_column"] = df.apply(lambda x: x["A"] * x["B"], axis = 1)
or,
df["new_column"] = df["A"] * df["B"]
iReports Custom Fields for columns (sum, average, etc)
Right-Click on Variables and click Create Variable
Click on the new variable
a. Notice the properties on the right
Rename the variable accordingly
Change the Value Class Name to the correct Data Type
a. You can search by clicking the 3 dots
Select the correct type of calculation
Change the Expression
a. Click the little icon
b. Select the column you are looking to do the calculation for
c. Click finish
Set Initial Value Expression to 0
Set the increment type to none
Set the Reset Type (usually report)
Drag a new Text Field to stage (Usually in Last Page Footer, or Column Footer)
Select the new variable
Click finish
if ( ( param & karen ) == karen )
{
// Do stuff
}
The bitwise 'and' will mask out everything except the bit that "represents" Karen. As long as each person is represented by a single bit position, you could check multiple people with a simple:
if ( ( param & karen ) == karen )
{
// Do Karen's stuff
}
if ( ( param & bob ) == bob )
// Do Bob's stuff
}
I see two parts to this:
Note that you can perfectly well use Spring in a web application without using Spring MVC. I would say most Java web applications do this, while using other web frameworks like Wicket, Struts, Seam, ...
Use the Apache BooleanUtils.
(If peak performance is the most important priority in your project then look at one of the other answers for a native solution that doesn't require including an external library.)
Don't reinvent the wheel. Leverage what's already been built and use isTrue()
:
BooleanUtils.isTrue( bool );
Checks if a Boolean
value is true, handling null
by returning false
.
If you're not limited to the libraries you're "allowed" to include, there are a bunch of great helper functions for all sorts of use-cases, including Booleans
and Strings
. I suggest you peruse the various Apache libraries and see what they already offer.
That entire block is misplaced.
class Example(object):
def main(self):
print "Hello World!"
if __name__ == '__main__':
Example().main()
But you really shouldn't be using a class just to run your main code.
Consider using background-size: cover
(IE9+) in conjunction with background-image
. For IE8-, there is a polyfill.
Suppose you want to create a vector x whose length is zero. Now let v be any vector.
> v<-c(4,7,8)
> v
[1] 4 7 8
> x<-v[0]
> length(x)
[1] 0
Using sed: It will insert at the end of line. You can also pass in variables as usual of course.
grep -qxF "port=9033" $light.conf
if [ $? -ne 0 ]; then
sed -i "$ a port=9033" $light.conf
else
echo "port=9033 already added"
fi
Using oneliner sed
grep -qxF "port=9033" $lightconf || sed -i "$ a port=9033" $lightconf
Using echo may not work under root, but will work like this. But it will not let you automate things if you are looking to do it since it might ask for password.
I had a problem when I was trying to edit from the root for a particular user. Just adding the $username
before was a fix for me.
grep -qxF "port=9033" light.conf
if [ $? -ne 0 ]; then
sudo -u $user_name echo "port=9033" >> light.conf
else
echo "already there"
fi
This is due to the fact that cv2 uses the type "uint8" from numpy. Therefore, you should define the type when creating the array.
Something like the following:
import numpy
import cv2
b = numpy.zeros([5,5,3], dtype=numpy.uint8)
b[:,:,0] = numpy.ones([5,5])*64
b[:,:,1] = numpy.ones([5,5])*128
b[:,:,2] = numpy.ones([5,5])*192
World of VS Default Browser Switcher for easily switching browser in web projects.
Give your button an id something like this:
<input id="mybutton" type="button" value="Dont show this again! " />
Then use jquery (to make this unobtrusive) and attach click action like so:
$(document).ready(function (){
$('#mybutton').click(function (){
fbLikeDump();
WriteCookie();
});
});
(this part should be in your .js file too)
I should have mentioned that you will need the jquery libraries on your page, so right before your closing body tag add these:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://PATHTOYOURJSFILE"></script>
The reason to add just before body closing tag is for performance of perceived page loading times
Some code to walk through a list of titles (circularily or one-shot):
var titles = [
" title",
"> title",
">> title",
">>> title"
];
// option 1:
function titleAniCircular(i) {
// from first to last title and back again, forever
i = (!i) ? 0 : (i*1+1) % titles.length;
$('title').html(titles[i]);
setTimeout(titleAniCircular, 1000, [i]);
};
// option 2:
function titleAniSequence(i) {
// from first to last title and stop
i = (!i) ? 0 : (i*1+1);
$('title').html(titles[i]);
if (i<titles.length-1) setTimeout(titleAniSequence, 1000, [i]);
};
// then call them when you like.
// e.g. to call one on document load, uncomment one of the rows below:
//$(document).load( titleAniCircular() );
//$(document).load( titleAniSequence() );
I just ran into this problem today. It turned out that a bug on the server (null pointer exception) was causing it to fail in creating a response, yet it still generated an HTTP status code of 200. Because of the 200 status code, Chrome expected a valid response. The first thing that Chrome did was to look for the 'Access-Control-Allow-Origin' header, which it did not find. Chrome then cancelled the request, and Angular gave me an error. The bug during processing the POST request is the reason why the OPTIONS would succeed, but the POST would fail.
In short, if you see this error, it may be that your server didn't return any headers at all in response to the POST request.
WHERE username LIKE '%[_]d'; -- @Lasse solution
WHERE username LIKE '%$_d' ESCAPE '$';
WHERE username LIKE '%^_d' ESCAPE '^';
If you are running on a 64 bit system and trying to load a 32 bit dll you need to compile your application as 32 bit instead of any cpu. If you are not doing this it behaves exactly as you describe.
If that isn't the case use Dependency Walker to verify that the dll has its required dependencies.
Linking to express issue #3330
You may set the timeout either globally for entire server:
var server = app.listen();
server.setTimeout(500000);
or just for specific route:
app.post('/xxx', function (req, res) {
req.setTimeout(500000);
});
For you Laravel Mix users out there running Bootstrap4, you will need to run
npm installer tether --save
Then update you resources/assets/js/bootstrap.js
to load Tether and bring it to the window object.
Here is what mine looks like: (Note I also had to run npm install popper.js --save
)
window.$ = window.jQuery = require('jquery');
window.Popper = require('popper.js').default;
window.Tether = require('tether');
require('bootstrap');
There is no way to convert a VBScript (.vbs file) into an executable (.exe file) because VBScript is not a compiled language. The process of converting source code into native executable code is called "compilation", and it's not supported by scripting languages like VBScript.
Certainly you can add your script to a self-extracting archive using something like WinZip, but all that will do is compress it. It's doubtful that the file size will shrink noticeably, and since it's a plain-text file to begin with, it's really not necessary to compress it at all. The only purpose of a self-extracting archive is that decompression software (like WinZip) is not required on the end user's computer to be able to extract or "decompress" the file. If it isn't compressed in the first place, this is a moot point.
Alternatively, as you mentioned, there are ways to wrap VBScript code files in a standalone executable file, but these are just wrappers that automatically execute the script (in its current, uncompiled state) when the user double-clicks on the .exe file. I suppose that can have its benefits, but it doesn't sound like what you're looking for.
In order to truly convert your VBScript into an executable file, you're going to have to rewrite it in another language that can be compiled. Visual Basic 6 (the latest version of VB, before the .NET Framework was introduced) is extremely similar in syntax to VBScript, but does support compiling to native code. If you move your VBScript code to VB 6, you can compile it into a native executable. Running the .exe file will require that the user has the VB 6 Run-time libraries installed, but they come built into most versions of Windows that are found now in the wild.
Alternatively, you could go ahead and make the jump to Visual Basic .NET, which remains somewhat similar in syntax to VB 6 and VBScript (although it won't be anywhere near a cut-and-paste migration). VB.NET programs will also compile to an .exe file, but they require the .NET Framework runtime to be installed on the user's computer. Fortunately, this has also become commonplace, and it can be easily redistributed if your users don't happen to have it. You mentioned going this route in your question (porting your current script in to VB Express 2008, which uses VB.NET), but that you were getting a lot of errors. That's what I mean about it being far from a cut-and-paste migration. There are some huge differences between VB 6/VBScript and VB.NET, despite some superficial syntactical similarities. If you want help migrating over your VBScript, you could post a question here on Stack Overflow. Ultimately, this is probably the best way to do what you want, but I can't promise you that it will be simple.
I suspect the or one or more characters had no match in the target code page part of the error.
If you remove the rows with values in that column, does it load? Can you identify, in other words, the rows which cause the package to fail? It could be the data is too long, or it could be that there's some funky character in there SQL Server doesn't like.
You can create functions in react components. It is actually regular ES6 class which inherits from React.Component
. Just be careful and bind it to the correct context in onClick
event:
export default class Archive extends React.Component {
saySomething(something) {
console.log(something);
}
handleClick(e) {
this.saySomething("element clicked");
}
componentDidMount() {
this.saySomething("component did mount");
}
render() {
return <button onClick={this.handleClick.bind(this)} value="Click me" />;
}
}
For your literal example you'd want to use the adjacent selector (+).
h4 + p {color:red}//any <p> that is immediately preceded by an <h4>
<h4>Some text</h4>
<p>I'm red</p>
<p>I'm not</p>
However, if you wanted to select all successive paragraphs, you'd need to use the general sibling selector (~).
h4 ~ p {color:red}//any <p> that has the same parent as, and comes after an <h4>
<h4>Some text</h4>
<p>I'm red</p>
<p>I am too</p>
You're missing a reference to System.Linq.
Add
using System.Linq
to get access to the ToList() function on the current code file.
To give a little bit of information over why this is necessary, Enumerable.ToList<TSource>
is an extension method. Extension methods are defined outside the original class that it targets. In this case, the extension method is defined on System.Linq
namespace.
Have a look at Hashtables
, Hashmaps
, HashSets
and so forth. They all store the hashed key as their keys. When invoking get(Object key)
the hash of the parameter is generated and lookup in the given hashes.
When not overwriting hashCode()
and the instance of the key has been changed (for example a simple string that doesn't matter at all), the hashCode()
could result in 2 different hashcodes for the same object, resulting in not finding your given key in map.get()
.
You don't need to go level up and use ..
since all buttons are on the same level:
//button[contains(.,'Arcade Reader')]/preceding-sibling::button[@name='settings']
As mentioned earlier, you can indicate that a variable or method is private by prefixing it with an underscore. If you don't feel like this is enough, you can always use the property
decorator. Here's an example:
class Foo:
def __init__(self, bar):
self._bar = bar
@property
def bar(self):
"""Getter for '_bar'."""
return self._bar
This way, someone or something that references bar
is actually referencing the return value of the bar
function rather than the variable itself, and therefore it can be accessed but not changed. However, if someone really wanted to, they could simply use _bar
and assign a new value to it. There is no surefire way to prevent someone from accessing variables and methods that you wish to hide, as has been said repeatedly. However, using property
is the clearest message you can send that a variable is not to be edited. property
can also be used for more complex getter/setter/deleter access paths, as explained here: https://docs.python.org/3/library/functions.html#property
tabindex
is a global attribute responsible for two things:
In my mind the second thing is even more important than the first one. There are very few elements that are focusable by default (e.g. <a> and form controls). Developers very often add some JavaScript event handlers (like 'onclick') on not focusable elements (<div>, <span> and so on), and the way to make your interface be responsive not only to mouse events but also to keyboard events (e.g. 'onkeypress') is to make such elements focusable. Lastly, if you don't want to set the order but just make your element focusable use tabindex="0"
on all such elements:
<div tabindex="0"></div>
Also, if you don't want it to be focusable via the tab key then use tabindex="-1"
. For example, the below link will not be focused while using tab keys to traverse.
<a href="#" tabindex="-1">Tab key cannot reach here!</a>
You can use
String hex = String.format("#%02x%02x%02x", r, g, b);
Use capital X's if you want your resulting hex-digits to be capitalized (#FFFFFF
vs. #ffffff
).
I have just been doing the exact same(ish) task of creating a batch script to run maven test scripts. The problem is that calling maven scrips with mvn clean install ... is itself a script and so needs to be done with call mvn clean install.
Code that will work
rem run a maven clean install
cd C:\rbe-ui-test-suite
call mvn clean install
rem now run through all the test scripts
call mvn clean install -Prun-integration-tests -Dpattern=tc-login
call mvn clean install -Prun-integration-tests -Dpattern=login-1
Note rather the use of call. This will allow the use of consecutive maven scripts in the batch file.
/var/www/html
is just the default root folder of the web server. You can change that to be whatever folder you want by editing your apache.conf
file (usually located in /etc/apache/conf
) and changing the DocumentRoot
attribute (see http://httpd.apache.org/docs/current/mod/core.html#documentroot for info on that)
Many hosts don't let you change these things yourself, so your mileage may vary. Some let you change them, but only with the built in admin tools (cPanel, for example) instead of via a command line or editing the raw config files.
You can also use IHtmlHelper.GetEnumSelectList.
// Summary:
// Returns a select list for the given TEnum.
//
// Type parameters:
// TEnum:
// Type to generate a select list for.
//
// Returns:
// An System.Collections.Generic.IEnumerable`1 containing the select list for the
// given TEnum.
//
// Exceptions:
// T:System.ArgumentException:
// Thrown if TEnum is not an System.Enum or if it has a System.FlagsAttribute.
IEnumerable<SelectListItem> GetEnumSelectList<TEnum>() where TEnum : struct;
This is how I did it with these easy steps:
Setup a new build system:
Tools > Build System > New Build System
Replace the default code with the following:
{
"cmd": ["javac","$file_name","&&","java","$file_base_name"],
"path": "C:\\Program Files\\Java\\jdk1.7.0_25\\bin\\",
"shell": true
}
// locate the path of your jdk installation and replace it with 'path'
Save the file by giving it a name (I named mine "Java")
Activate the build system:
In SQL Server, these statements yield the same plans.
Contrary to the popular opinion, in Oracle they do too.
SYS_GUID()
in Oracle is quite computation intensive function.
In my test database, t_even
is a table with 1,000,000
rows
This query:
SELECT COUNT(SYS_GUID())
FROM t_even
runs for 48
seconds, since the function needs to evaluate each SYS_GUID()
returned to make sure it's not a NULL
.
However, this query:
SELECT COUNT(*)
FROM (
SELECT SYS_GUID()
FROM t_even
)
runs for but 2
seconds, since it doen't even try to evaluate SYS_GUID()
(despite *
being argument to COUNT(*)
)
Executing PHP functions by the onclick event is a cumbersome task and near impossible.
Instead you can redirect to another PHP page.
Say you are currently on a page one.php and you want to fetch some data from this php script process the data and show it in another page i.e. two.php you can do it by writing the following code
<button onclick="window.location.href='two.php'">Click me</button>
Another good use for *args
and **kwargs
: you can define generic "catch all" functions, which is great for decorators where you return such a wrapper instead of the original function.
An example with a trivial caching decorator:
import pickle, functools
def cache(f):
_cache = {}
def wrapper(*args, **kwargs):
key = pickle.dumps((args, kwargs))
if key not in _cache:
_cache[key] = f(*args, **kwargs) # call the wrapped function, save in cache
return _cache[key] # read value from cache
functools.update_wrapper(wrapper, f) # update wrapper's metadata
return wrapper
import time
@cache
def foo(n):
time.sleep(2)
return n*2
foo(10) # first call with parameter 10, sleeps
foo(10) # returns immediately
I was looking for same answer & found this info from wiki useful: Loop Instructions
The loop instruction decrements ECX and jumps to the address specified by arg unless decrementing ECX caused its value to become zero. For example:
mov ecx, 5
start_loop:
; the code here would be executed 5 times
loop start_loop
loop does not set any flags.
loopx arg
These loop instructions decrement ECX and jump to the address specified by arg if their condition is satisfied (that is, a specific flag is set), unless decrementing ECX caused its value to become zero.
loope loop if equal
loopne loop if not equal
loopnz loop if not zero
loopz loop if zero
Source: X86 Assembly, Control Flow
Steps for configuring Sublime Text Editor3 for Python3 :-
Enjoy Coding.
You can multiply the variable by 1 to force JavaScript to convert the variable to a number for you and then add it to your other value. This works because multiplication isn't overloaded as addition is. Some may say that this is less clear than parseInt, but it is a way to do it and it hasn't been mentioned yet.
For Mac:
$ docker exec -it <container-name> sh
if you want to connect as root user:
$ docker exec -u 0 -it <container-name> sh
Here's an answer from 2018, on Debian 9 stretch.
Note the -e
for echo to allow newline characters, and -r
for mailx to show a name along with an outgoing email address:
$ echo -e "testing email via yourisp.com from command line\n\nsent on: $(date)" | mailx -r "Foghorn Leghorn <[email protected]>" -s "test cli email $(date)" -- [email protected]
Hope this helps!
If you create an object, you get a more readable output and also gain an object with properties you can access:
$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework'
$obj = New-Object -TypeName psobject
Get-Item -Path $path | Select-Object -ExpandProperty Property | Sort | % {
$command = [String]::Format('(Get-ItemProperty -Path "{0}" -Name "{1}")."{1}"', $path, $_)
$value = Invoke-Expression -Command $command
$obj | Add-Member -MemberType NoteProperty -Name $_ -Value $value}
Write-Output $obj | fl
Sample output: InstallRoot : C:\Windows\Microsoft.NET\Framework\
And the object: $obj.InstallRoot = C:\Windows\Microsoft.NET\Framework\
The truth of the matter is this is way more complicated than it needs to be. Here is a much better example, and much simpler:
$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework'
$objReg = Get-ItemProperty -Path $path | Select -Property *
$objReg is now a custom object where each registry entry is a property name. You can view the formatted list via:
write-output $objReg
InstallRoot : C:\Windows\Microsoft.NET\Framework\
DbgManagedDebugger : "C:\windows\system32\vsjitdebugger.exe"
And you have access to the object itself:
$objReg.InstallRoot
C:\Windows\Microsoft.NET\Framework\
From the ISO draft for C++ (ISO/IEC JTC 1/SC 22 N 4411)
So destructors should generally catch exceptions and not let them propagate out of the destructor.
3 The process of calling destructors for automatic objects constructed on the path from a try block to a throw- expression is called “stack unwinding.” [ Note: If a destructor called during stack unwinding exits with an exception, std::terminate is called (15.5.1). So destructors should generally catch exceptions and not let them propagate out of the destructor. — end note ]
if working in MS windows, you can use Anaconda navigator. click on the environment, in the drop-down box, it's "installed" by default. You can select "updatable" and start from there
I have not been able to find a Firefox option equivalent of --disable-web-security or an addon that does that for me. I really needed it for some testing scenarios where modifying the web server was not possible. What did help was to use Fiddler to auto-modify web responses so that they have the correct headers and CORS is no longer an issue.
The steps are:
Open fiddler.
If on https go to menu Tools -> Options -> Https and tick the Capture & Decrypt https options
Go to menu Rules -> Customize rules. Modify the OnBeforeResponseFunction so that it looks like the following, then save:
static function OnBeforeResponse(oSession: Session) {
//....
oSession.oResponse.headers.Remove("Access-Control-Allow-Origin");
oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
//...
}
This will make every web response to have the Access-Control-Allow-Origin: * header.
This still won't work as the OPTIONS preflight will pass through and cause the request to block before our above rule gets the chance to modify the headers. So to fix this, in the fiddler main window, on the right hand side there's an AutoResponder tab. Add a new rule and response: METHOD:OPTIONS https://yoursite.com/ with auto response: *CORSPreflightAllow and tick the boxes: "Enable Rules" and "Unmatched requests passthrough".
See picture below for reference:
The quickselect algorithm, O(n) cousin to quicksort, will do what you want. Quickselect has average performance O(n). Worst case performance is O(n^2) just like quicksort but that's rare, and modifications to quickselect reduce the worst case performance to O(n).
The idea of quickselect is to use the same pivot, lower, higher idea of quicksort, but to then ignore the lower part and to further order just the higher part.
var now = new Date();_x000D_
now.setMinutes(now.getMinutes() + 30); // timestamp_x000D_
now = new Date(now); // Date object_x000D_
console.log(now);
_x000D_
i found out the best way to refresh your Fragment when data change
if you have a button "search", you have to initialize your ARRAY list inside the button
mSearchBtn.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
mList = new ArrayList<Node>();
firebaseSearchQuery.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Node p = dataSnapshot1.getValue(Node .class);
mList.add(p);
}
YourAdapter = new NodeAdapter(getActivity(), mList);
mRecyclerView.setAdapter(YourAdapter );
}
One problem with the
SELECT SQL_NO_CACHE * FROM TABLE
method is that it seems to only prevent the result of your query from being cached. However, if you're querying a database that is actively being used with the query you want to test, then other clients may cache your query, affecting your results. I am continuing to research ways around this, will edit this post if I figure one out.
First let's create the dataframe you had, I'll ignore columns B and C as they are not relevant.
df = pd.DataFrame({'A': [0, 4, 5, 6, 7, 7, 6,5]})
And the mapping that you desire:
mapping = dict(enumerate([2,5,6,8,12,16,26,32]))
df['D'] = df['A'].map(mapping)
Done!
print df
Output:
A D
0 0 2
1 4 12
2 5 16
3 6 26
4 7 32
5 7 32
6 6 26
7 5 16
You have to replace the values one by one such as in a for-loop or copying another array over another such as using memcpy(..)
or std::copy
e.g.
for (int i = 0; i < arrayLength; i++) {
array[i] = newValue[i];
}
Take care to ensure proper bounds-checking and any other checking that needs to occur to prevent an out of bounds problem.
and here the fork of the toolkit wich contains the port to 4.O,
https://github.com/jogibear9988/wpftoolkit
it's worked very well to me .
You can create an interface
, pass it to AsyncTask
(in constructor), and then call method in onPostExecute()
For example:
Your interface:
public interface OnTaskCompleted{
void onTaskCompleted();
}
Your Activity:
public class YourActivity implements OnTaskCompleted{
// your Activity
}
And your AsyncTask:
public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
private OnTaskCompleted listener;
public YourTask(OnTaskCompleted listener){
this.listener=listener;
}
// required methods
protected void onPostExecute(Object o){
// your stuff
listener.onTaskCompleted();
}
}
EDIT
Since this answer got quite popular, I want to add some things.
If you're a new to Android development, AsyncTask
is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:
Activity
, it will stay in memory even after user left the screen (or rotated the device).AsyncTask
is not delivering result to Activity
if Activity
was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.Activity
When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.
There are numerous Flexbox bugs in IE11 and other browsers - see flexbox on Can I Use -> Known Issues, where the following are listed under IE11:
display: flex
and flex-direction: column
will not properly calculate their flexed childrens' sizes if the container has min-height
but no explicit height
propertymin-height
is usedAlso see Philip Walton's Flexbugs list of issues and workarounds.
It's built in from Sublime Editor 2 at least. Just press the following and it balances the HTML-tag
Shortcut (Mac): Shift + Command + A
Shortcut (Windows): Control + Alt + A
>>> average = [1,3,2,1,1,0,24,23,7,2,727,2,7,68,7,83,2]
>>> matches = [i for i in range(0,len(average)) if average[i]<2 or average[i]>4]
>>> matches
[0, 3, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15]
If you want to run test methods in a specific order in JUnit 5, you can use the below code.
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class MyClassTest {
@Test
@Order(1)
public void test1() {}
@Test
@Order(2)
public void test2() {}
}
Add an attribute colspan
(abbriviation for 'column span') in your top cell (<td>
) and set its value to 2.
Your table should resembles the following;
<table>
<tr>
<td colspan = "2">
<!-- Merged Columns -->
</td>
</tr>
<tr>
<td>
<!-- Column 1 -->
</td>
<td>
<!-- Column 2 -->
</td>
</tr>
</table>
See also
W3 official docs on HTML Tables
As stated from David Cournapeau, use figure().
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.figure()
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("first.ps")
plt.figure()
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")
Or subplot(121) / subplot(122) for the same plot, different position.
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.subplot(121)
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.subplot(122)
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")
Just ran into this issue - if you updated a bunch of files and don't want to do git mv
all of them this also works:
/dir/RenamedFile.js
to /whatever/RenamedFile.js
.git add -A
to stage that change/dir/RenamedFile.js
.git add -A
again, will re-stage vs that change, forcing git to pick up the filename change.I prefer to use mutex mechanism in such cases, but if you really want to use boolean, then you should declare it as volatile (to provide the change visibility across threads) and just run the body-less cycle with that boolean as a condition :
//.....some class
volatile boolean someBoolean;
Thread someThread = new Thread() {
@Override
public void run() {
//some actions
while (!someBoolean); //wait for condition
//some actions
}
};
This approach is ok but will not work for when you get params dynamically , sometimes 1, 2, 3 or more, just like a SOLR search query (for example)
Here is a more flexible solution. Crude but can be refined.
public static void main(String[] args) {
String host = "localhost";
String port = "9093";
String param = "/10-2014.01?description=cars&verbose=true&hl=true&hl.simple.pre=<b>&hl.simple.post=</b>";
String[] wholeString = param.split("\\?");
String theQueryString = wholeString.length > 1 ? wholeString[1] : "";
String SolrUrl = "http://" + host + ":" + port + "/mypublish-services/carclassifications/" + "loc";
GetMethod method = new GetMethod(SolrUrl );
if (theQueryString.equalsIgnoreCase("")) {
method.setQueryString(new NameValuePair[]{
});
} else {
String[] paramKeyValuesArray = theQueryString.split("&");
List<String> list = Arrays.asList(paramKeyValuesArray);
List<NameValuePair> nvPairList = new ArrayList<NameValuePair>();
for (String s : list) {
String[] nvPair = s.split("=");
String theKey = nvPair[0];
String theValue = nvPair[1];
NameValuePair nameValuePair = new NameValuePair(theKey, theValue);
nvPairList.add(nameValuePair);
}
NameValuePair[] nvPairArray = new NameValuePair[nvPairList.size()];
nvPairList.toArray(nvPairArray);
method.setQueryString(nvPairArray); // Encoding is taken care of here by setQueryString
}
}
I think the best way would be this:
From HTML5 boilerplate:
<!--[if lt IE 7]> <html lang="en-us" class="no-js ie6 oldie"> <![endif]-->
<!--[if IE 7]> <html lang="en-us" class="no-js ie7 oldie"> <![endif]-->
<!--[if IE 8]> <html lang="en-us" class="no-js ie8 oldie"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en-us" class="no-js"> <!--<![endif]-->
in JS:
if( $("html").hasClass("ie8") ) { /* do your things */ };
especially since $.browser
has been removed from jQuery 1.9+.
@CMW's answer is bang on the money. I've added this answer as an example of how to configure an initializer so that both Date and Time objects get the formatting
config/initializers/time_formats.rb
date_formats = {
concise: '%d-%b-%Y' # 13-Jan-2014
}
Time::DATE_FORMATS.merge! date_formats
Date::DATE_FORMATS.merge! date_formats
Also the following two commands will iterate through all the DATE_FORMATS
in your current environment, and display today's date and time in each format:
Date::DATE_FORMATS.keys.each{|k| puts [k,Date.today.to_s(k)].join(':- ')}
Time::DATE_FORMATS.keys.each{|k| puts [k,Time.now.to_s(k)].join(':- ')}
The use case that lead me to search for this is the following
def setfrom(self,f):
"""Set from iterable f"""
fi = iter(f)
for i in range(self.n):
try:
x = next(fi)
except StopIteration:
fi = iter(f)
x = next(fi)
self.a[i] = x
where hasnext() is available, one could do
def setfrom(self,f):
"""Set from iterable f"""
fi = iter(f)
for i in range(self.n):
if not hasnext(fi):
fi = iter(f) # restart
self.a[i] = next(fi)
which to me is cleaner. Obviously you can work around issues by defining utility classes, but what then happens is you have a proliferation of twenty-odd different almost-equivalent workarounds each with their quirks, and if you wish to reuse code that uses different workarounds, you have to either have multiple near-equivalent in your single application, or go around picking through and rewriting code to use the same approach. The 'do it once and do it well' maxim fails badly.
Furthermore, the iterator itself needs to have an internal 'hasnext' check to run to see if it needs to raise an exception. This internal check is then hidden so that it needs to be tested by trying to get an item, catching the exception and running the handler if thrown. This is unnecessary hiding IMO.
How about something much simpler: Given two numbers, A and B let str be the concatenation: 'A' + ';' + 'B'. Then let the output be hash(str). I know that this is not a mathematical answer, but a simple python (which has an in built hash function) script should do the job.
The parameters to main
represent the command line parameters provided to the program when it was started. The argc
parameter represents the number of command line arguments, and char *argv[]
is an array of strings (character pointers) representing the individual arguments provided on the command line.
Use cin.get()
to read the next character.
However, for this problem, it is very inefficient to read a character at a time. Use the istream::read()
instead.
int main()
{
char a[10];
cin.read(a, sizeof(a));
for(int i = 0; i < 10; i++)
{
if(a[i] == ' ')
cout<<"It is a space!!!"<<<endl;
}
return 0;
}
And use ==
to check equality, not =
.
Below are provided steps to fix your issue.
If you need two variables in the XML
, you can use:
%1$d text... %2$d
or %1$s text... %2$s
for string variables.
Example :
<string name="notyet">Website %1$s isn\'t yet available, I\'m working on it, please wait %2$s more days</string>
String site = "site.tld";
String days = "11";
//Toast example
String notyet = getString(R.string.notyet, site, days);
Toast.makeText(getApplicationContext(), notyet, Toast.LENGTH_LONG).show();
I got the top answer working (can't reply yet) after one small edit
This did not work for me:
FEATURE('authinfo','hash /etc/mail/auth/client-info')dnl
The first single quote for each string should be changed to a backtick (`) like this:
FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl
After the change I run:
sudo sendmailconfig
And I'm in business :)
In the Trace properties, click the Events Selection tab at the top next to General. Then click Column Filters... at the bottom right. You can then select what to filter, such as TextData
or DatabaseName
.
Expand the Like node and enter your filter with the percentage %
signs like %MyDatabaseName%
or %TextDataToFilter%
. Without the %%
signs the filter will not work.
Also, make sure to check the checkbox Exclude rows that do not contain values' If you cannot find the field you are looking to filter such as DatabaseName
go to the General tab and change your Template, blank one should contain all the fields.
This is the limitation in MYSQL 5.5 version. You need to update the version to 5.6.
Error
I was getting this error in adding a table in MYSQL
Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause My new MYSQL
table looks something like this.
create table table_name (col1 int(5) auto_increment primary key, col2 varchar(300), col3 varchar(500), col4 int(3), col5 tinyint(2), col6 timestamp default current_timestamp, col7 timestamp default current_timestamp on update current_timestamp, col8 tinyint(1) default 0, col9 tinyint(1) default 1);
After some time of reading about changes in different MYSQL versions and some of the googling. I found out that there was some changes that were made in MYSQL version 5.6 over version 5.5.
This article will help you to resolve the issue. http://www.oyewiki.com/MYSQL/Incorrect-table-definition-there-can-be-only-one-timestamp-column
You can't have bare words in the code, that's the reason why they created variables (your code will fail with NameError
).
The code you provided would create a database table named month
(plus whatever prefix django adds to that), because that's the name of the CharField
.
But there are better ways to create the particular choices you want. See a previous Stack Overflow question.
import calendar
tuple((m, m) for m in calendar.month_name[1:])
Prim's is better for more dense graphs, and in this we also do not have to pay much attention to cycles by adding an edge, as we are primarily dealing with nodes. Prim's is faster than Kruskal's in the case of complex graphs.
The Google Testing Blog discussed this problem recently:
So a naive answer is that writing test carries a 10% tax. But, we pay taxes in order to get something in return.
(snip)
These benefits translate to real value today as well as tomorrow. I write tests, because the additional benefits I get more than offset the additional cost of 10%. Even if I don't include the long term benefits, the value I get from test today are well worth it. I am faster in developing code with test. How much, well that depends on the complexity of the code. The more complex the thing you are trying to build is (more ifs/loops/dependencies) the greater the benefit of tests are.
You could just use REPLACE
:
UPDATE myTable SET emailCol = REPLACE(emailCol, '.com', '.org')`.
But take into account an email address such as [email protected]
will be updated to [email protected]
.
If you want to be on a safer side, you should check for the last 4 characters using RIGHT
, and append .org
to the SUBSTRING
manually instead. Notice the usage of UPPER
to make the search for the .com
ending case insensitive.
UPDATE myTable
SET emailCol = SUBSTRING(emailCol, 1, LEN(emailCol)-4) + '.org'
WHERE UPPER(RIGHT(emailCol,4)) = '.COM';
See it working in this SQLFiddle.
May be this is useful to you.
//Method writes a string to a text file
-(void) writeToTextFile{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = @"One\nTwo\nThree\nFour\nFive";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSUTF8StringEncoding
error:nil];
}
//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
//use simple alert from my library (see previous post for details)
[ASFunctions alert:content];
[content release];
}
I think this will bring it back using 3.0
.navbar .divider-vertical {
height: 50px;
margin: 0 9px;
border-right: 1px solid #ffffff;
border-left: 1px solid #f2f2f2;
}
.navbar-inverse .divider-vertical {
border-right-color: #222222;
border-left-color: #111111;
}
@media (max-width: 767px) {
.navbar-collapse .nav > .divider-vertical {
display: none;
}
}
I know this is quite old - but searching for an easy solution, I stumbled over this thread... If I got the question right, you were looking for a way to list more than one directory using Get-ChildItem. There seems to be a much easier way using powershell 5.0 - example
Get-ChildItem -Path D:\ -Directory -Name -Exclude tmp,music
chaos
docs
downloads
games
pics
videos
Without the -Exclude clause, tmp and music would still be in that list. If you don't use -Name the -Exclude clause won't work, because of the detailed output of Get-ChildItem. Hope this helps some people that are looking for an easy way to list all directory names without certain ones.
Use defaultdict
from collections import defaultdict
a = {}
a = defaultdict(lambda:0,a)
a["anything"] # => 0
This is very useful for case like this,where default values for every key is set as 0:
results ={ 'pre-access' : {'count': 4, 'pass_count': 2},'no-access' : {'count': 55, 'pass_count': 19}
for k,v in results.iteritems():
a['count'] += v['count']
a['pass_count'] += v['pass_count']
Very easy. First put
io.sockets.on('connection', function (socket) {
console.log(socket);
You will see all fields of socket. then use CTRL+F and search the word address. Finally, when you find the field remoteAddress use dots to filter data. in my case it is
console.log(socket.conn.remoteAddress);
Use
a = sorted(a, key=lambda x: x.modified, reverse=True)
# ^^^^
On Python 2.x, the sorted
function takes its arguments in this order:
sorted(iterable, cmp=None, key=None, reverse=False)
so without the key=
, the function you pass in will be considered a cmp
function which takes 2 arguments.
There is the beforeShowDay
option, which takes a function to be called for each date, returning true if the date is allowed or false if it is not. From the docs:
beforeShowDay
The function takes a date as a parameter and must return an array with [0] equal to true/false indicating whether or not this date is selectable and 1 equal to a CSS class name(s) or '' for the default presentation. It is called for each day in the datepicker before is it displayed.
Display some national holidays in the datepicker.
$(".selector").datepicker({ beforeShowDay: nationalDays})
natDays = [
[1, 26, 'au'], [2, 6, 'nz'], [3, 17, 'ie'],
[4, 27, 'za'], [5, 25, 'ar'], [6, 6, 'se'],
[7, 4, 'us'], [8, 17, 'id'], [9, 7, 'br'],
[10, 1, 'cn'], [11, 22, 'lb'], [12, 12, 'ke']
];
function nationalDays(date) {
for (i = 0; i < natDays.length; i++) {
if (date.getMonth() == natDays[i][0] - 1
&& date.getDate() == natDays[i][1]) {
return [false, natDays[i][2] + '_day'];
}
}
return [true, ''];
}
One built in function exists, called noWeekends, that prevents the selection of weekend days.
$(".selector").datepicker({ beforeShowDay: $.datepicker.noWeekends })
To combine the two, you could do something like (assuming the nationalDays
function from above):
$(".selector").datepicker({ beforeShowDay: noWeekendsOrHolidays})
function noWeekendsOrHolidays(date) {
var noWeekend = $.datepicker.noWeekends(date);
if (noWeekend[0]) {
return nationalDays(date);
} else {
return noWeekend;
}
}
Update: Note that as of jQuery UI 1.8.19, the beforeShowDay option also accepts an optional third paremeter, a popup tooltip
If you're using WPF and the previous answers don't help, you can retrieve the result using:
var result = MessageBox.Show("Message", "caption", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
// Do something
}
select * from mytable where mydate > now() - interval '1 year';
If you only care about the date and not the time, substitute current_date
for now()
You can do in this way:
Integer i = 1;
new BigInteger("" + i);
To be able to use the jobParameters I think you need to define your reader as scope 'step', but I am not sure if you can do it using annotations.
Using xml-config it would go like this:
<bean id="foo-readers" scope="step"
class="...MyReader">
<property name="fileName" value="#{jobExecutionContext['fileName']}" />
</bean>
See further at the Spring Batch documentation.
Perhaps it works by using @Scope
and defining the step scope in your xml-config:
<bean class="org.springframework.batch.core.scope.StepScope" />
There are three scenarios (that I can think of) where you would call a method in a subclass where the method exits in the parent class:
Method is not overwritten by subclass, only exists in parent.
This is the same as your example, and generally it's better to use $this -> get_species();
You are right that in this case the two are effectively the same, but the method has been inherited by the subclass, so there is no reason to differentiate. By using $this
you stay consistent between inherited methods and locally declared methods.
Method is overwritten by the subclass and has totally unique logic from the parent.
In this case, you would obviously want to use $this -> get_species();
because you don't want the parent's version of the method executed. Again, by consistently using $this
, you don't need to worry about the distinction between this case and the first.
Method extends parent class, adding on to what the parent method achieves.
In this case, you still want to use `$this -> get_species();
when calling the method from other methods of the subclass. The one place you will call the parent method would be from the method that is overwriting the parent method. Example:
abstract class Animal {
function get_species() {
echo "I am an animal.";
}
}
class Dog extends Animal {
function __construct(){
$this->get_species();
}
function get_species(){
parent::get_species();
echo "More specifically, I am a dog.";
}
}
The only scenario I can imagine where you would need to call the parent method directly outside of the overriding method would be if they did two different things and you knew you needed the parent's version of the method, not the local. This shouldn't be the case, but if it did present itself, the clean way to approach this would be to create a new method with a name like get_parentSpecies()
where all it does is call the parent method:
function get_parentSpecies(){
parent::get_species();
}
Again, this keeps everything nice and consistent, allowing for changes/modifications to the local method rather than relying on the parent method.
I think what you are looking for is this
activity.moveTaskToBack(Boolean nonRoot);
You may want to know why this is happening. Together with the great explanation by that other guy, find a reference of Why does my shell script choke on whitespace or other special characters? written by Gilles in Unix & Linux:
Why do I need to write
"$foo"
? What happens without the quotes?
$foo
does not mean “take the value of the variablefoo
”. It means something much more complex:
- First, take the value of the variable.
- Field splitting: treat that value as a whitespace-separated list of fields, and build the resulting list. For example, if the variable contains
foo * bar ?
then the result of this step is the 3-element listfoo
,*
,bar
.- Filename generation: treat each field as a glob, i.e. as a wildcard pattern, and replace it by the list of file names that match this pattern. If the pattern doesn't match any files, it is left unmodified. In our example, this results in the list containing
foo
, following by the list of files in the current directory, and finallybar
. If the current directory is empty, the result isfoo
,*
,bar
.Note that the result is a list of strings. There are two contexts in shell syntax: list context and string context. Field splitting and filename generation only happen in list context, but that's most of the time. Double quotes delimit a string context: the whole double-quoted string is a single string, not to be split. (Exception:
"$@"
to expand to the list of positional parameters, e.g."$@"
is equivalent to"$1" "$2" "$3"
if there are three positional parameters. See What is the difference between $* and $@?)The same happens to command substitution with
$(foo)
or with`foo`
. On a side note, don't use`foo`
: its quoting rules are weird and non-portable, and all modern shells support$(foo)
which is absolutely equivalent except for having intuitive quoting rules.The output of arithmetic substitution also undergoes the same expansions, but that isn't normally a concern as it only contains non-expandable characters (assuming
IFS
doesn't contain digits or-
).See When is double-quoting necessary? for more details about the cases when you can leave out the quotes.
Unless you mean for all this rigmarole to happen, just remember to always use double quotes around variable and command substitutions. Do take care: leaving out the quotes can lead not just to errors but to security holes.
You have to edit httpd.conf
and find this line: Listen 127.0.0.1:80
Then write down your desired IP you set for LAN. Don't use automatic IP.
e.g.: Listen 192.168.137.1:80
I used 192.167.137.1
as my LAN IP of Windows 7. Restart Apache and enjoy sharing.
Maybe this might work:
Sh.Range("A1", Sh.Range("A" & Rows.Count).End(xlUp))
You might try using @media query such as below.
Add a logo class first, then use @media to specify your logo height and width per device size. In the example below, I am targeting devices which have a max width of 320px (iPhone) You can play around with this until you find the best fit. Easy way to test: Use chrome or Firefox with inspect element. Shrink your browser as far as possible. Observe the logo size change based on the @media max width you specify. Test on iPhone, android devices, iPad etc to get the desired results.
.logo {
height: 42px;
width: 140px;
}
@media (max-width:320px) {
.logo {
height: 33px;
width: 110px;
}
}
Does the actual query return no results? First()
will fail if there are no results.
dic0.update(dic1)
Note this doesn't actually return the combined dictionary, it just mutates dic0
.
Background images sure can present data! In fact, this is often recommended where presenting visual icons is more compact and user-friendly than an equivalent list of text blurbs. Any use of image sprites can benefit from this approach.
It is quite common for hotel listings icons to display amenities. Imagine a page which listed 50 hotel and each hotel had 10 amenities. A CSS Sprite would be perfect for this sort of thing -- better user experience because it's faster. But how do you implement ALT tags for these images? Example site.
The answer is that they don't use alt
text at all, but instead use the title
attribute on the containing div.
HTML
<div class="hotwire-fitness" title="Fitness Centre"></div>
CSS
.hotwire-fitness {
float: left;
margin-right: 5px;
background: url(/prostyle/images/new_amenities.png) -71px 0;
width: 21px;
height: 21px;
}
According to the W3C (see links above), the title attribute serves much of the same purpose as the alt attribute
Title
Values of the title attribute may be rendered by user agents in a variety of ways. For instance, visual browsers frequently display the title as a "tool tip" (a short message that appears when the pointing device pauses over an object). Audio user agents may speak the title information in a similar context. For example, setting the attribute on a link allows user agents (visual and non-visual) to tell users about the nature of the linked resource:
alt
The alt attribute is defined in a set of tags (namely, img, area and optionally for input and applet) to allow you to provide a text equivalent for the object.
A text equivalent brings the following benefits to your website and its visitors in the following common situations:
- nowadays, Web browsers are available in a very wide variety of platforms with very different capacities; some cannot display images at all or only a restricted set of type of images; some can be configured to not load images. If your code has the alt attribute set in its images, most of these browsers will display the description you gave instead of the images
- some of your visitors cannot see images, be they blind, color-blind, low-sighted; the alt attribute is of great help for those people that can rely on it to have a good idea of what's on your page
- search engine bots belong to the two above categories: if you want your website to be indexed as well as it deserves, use the alt attribute to make sure that they won't miss important sections of your pages.
Just store the index generated in a variable, and then access the array using this varaible:
int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);
P.S. I usually don't like generating new Random
object per randoization - I prefer using a single Random
in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.
According to this approach, I will have some variable Random r
somewhere, and I will just use:
int idx = r.nextInt(fruits.length)
However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.
l.insert(index, obj)
doesn't actually return anything. It just updates the list.
As ATO said, you can do b = a[:index] + [obj] + a[index:]
.
However, another way is:
a = [1, 2, 4]
b = a[:]
b.insert(2, 3)
If you don't want to install the cors library and instead want to fix your original code, the other step you are missing is that Access-Control-Allow-Origin:* is wrong. When passing Authentication tokens (e.g. JWT) then you must explicitly state every url that is calling your server. You can't use "*" when doing authentication tokens.
If your concern was only that you making a extra column and deleting it later, just dun use a new column at the first place.
dataframe = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':list('abcab'), 'col3':list('ababb')})
dataframe.col3 = pd.Categorical.from_array(dataframe.col3).codes
You are done. Now as Categorical.from_array
is deprecated, use Categorical
directly
dataframe.col3 = pd.Categorical(dataframe.col3).codes
If you also need the mapping back from index to label, there is even better way for the same
dataframe.col3, mapping_index = pd.Series(dataframe.col3).factorize()
check below
print(dataframe)
print(mapping_index.get_loc("c"))
In order to append to a file you'll need to use a slightly different approach. You can still redirect an individual process' standard error and standard output to a file, but in order to append it to a file you'll need to do one of these things:
Start-Process
&
The first way would look like this:
$myLog = "C:\File.log"
$stdErrLog = "C:\stderr.log"
$stdOutLog = "C:\stdout.log"
Start-Process -File myjob.bat -RedirectStandardOutput $stdOutLog -RedirectStandardError $stdErrLog -wait
Get-Content $stdErrLog, $stdOutLog | Out-File $myLog -Append
The second way would look like this:
& myjob.bat 2>&1 >> C:\MyLog.txt
Or this:
& myjob.bat 2>&1 | Out-File C:\MyLog.txt -Append
The third way:
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "myjob.bat"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = ""
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$output = $p.StandardOutput.ReadToEnd()
$output += $p.StandardError.ReadToEnd()
$output | Out-File $myLog -Append
Add**/.DS_Store
into .gitignore
for the sub directory
If .DS_Store
already committed:
find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch
To ignore them in all repository: (sometimes it named ._.DS_Store
)
echo ".DS_Store" >> ~/.gitignore_global
echo "._.DS_Store" >> ~/.gitignore_global
echo "**/.DS_Store" >> ~/.gitignore_global
echo "**/._.DS_Store" >> ~/.gitignore_global
git config --global core.excludesfile ~/.gitignore_global
exit
in the C language takes an integer representing an exit status.
Typically, an exit status of 0 is considered a success, or an intentional exit caused by the program's successful execution.
An exit status of 1 is considered a failure, and most commonly means that the program had to exit for some reason, and was not able to successfully complete everything in the normal program flow.
Here's a GNU Resource talking about Exit Status.
As @Als has stated, two constants should be used in place of 0 and 1.
EXIT_SUCCESS
is defined by the standard to be zero.
EXIT_FAILURE
is not restricted by the standard to be one, but many systems do implement it as one.
Exception.Message
contains only the message (doh) associated with the exception. Example:
Object reference not set to an instance of an object
The Exception.ToString()
method will give a much more verbose output, containing the exception type, the message (from before), a stack trace, and all of these things again for nested/inner exceptions. More precisely, the method returns the following:
ToString returns a representation of the current exception that is intended to be understood by humans. Where the exception contains culture-sensitive data, the string representation returned by ToString is required to take into account the current system culture. Although there are no exact requirements for the format of the returned string, it should attempt to reflect the value of the object as perceived by the user.
The default implementation of ToString obtains the name of the class that threw the current exception, the message, the result of calling ToString on the inner exception, and the result of calling Environment.StackTrace. If any of these members is a null reference (Nothing in Visual Basic), its value is not included in the returned string.
If there is no error message or if it is an empty string (""), then no error message is returned. The name of the inner exception and the stack trace are returned only if they are not a null reference (Nothing in Visual Basic).
Turns out that Entity Framework will assume that any class that inherits from a POCO class that is mapped to a table on the database requires a Discriminator column, even if the derived class will not be saved to the DB.
The solution is quite simple and you just need to add [NotMapped]
as an attribute of the derived class.
Example:
class Person
{
public string Name { get; set; }
}
[NotMapped]
class PersonViewModel : Person
{
public bool UpdateProfile { get; set; }
}
Now, even if you map the Person class to the Person table on the database, a "Discriminator" column will not be created because the derived class has [NotMapped]
.
As an additional tip, you can use [NotMapped]
to properties you don't want to map to a field on the DB.
You can get all the information of active transaction by the help of below query
SELECT
trans.session_id AS [SESSION ID],
ESes.host_name AS [HOST NAME],login_name AS [Login NAME],
trans.transaction_id AS [TRANSACTION ID],
tas.name AS [TRANSACTION NAME],tas.transaction_begin_time AS [TRANSACTION
BEGIN TIME],
tds.database_id AS [DATABASE ID],DBs.name AS [DATABASE NAME]
FROM sys.dm_tran_active_transactions tas
JOIN sys.dm_tran_session_transactions trans
ON (trans.transaction_id=tas.transaction_id)
LEFT OUTER JOIN sys.dm_tran_database_transactions tds
ON (tas.transaction_id = tds.transaction_id )
LEFT OUTER JOIN sys.databases AS DBs
ON tds.database_id = DBs.database_id
LEFT OUTER JOIN sys.dm_exec_sessions AS ESes
ON trans.session_id = ESes.session_id
WHERE ESes.session_id IS NOT NULL
and it will give below similar result
and you close that transaction by the help below KILL query by refering session id
KILL 77
It is not faster. There is one difference when you can initialize a constant variable depending on some expression:
const int x = (a<b) ? b : a;
You can't do the same with if-else
.
iter->first
and iter->second
are variables, you are attempting to call them as methods.
Just completing the Vijay's post...
Manifest
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Function
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(Environment.getExternalStorageDirectory(), path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
Usage
createDirIfNotExists("mydir/"); //Create a directory sdcard/mydir
createDirIfNotExists("mydir/myfile") //Create a directory and a file in sdcard/mydir/myfile.txt
You could check for errors
if(createDirIfNotExists("mydir/")){
//Directory Created Success
}
else{
//Error
}
Extending @oopbase's answer with return;
statement.
Let's consider a use case of traditional authentication system where we store login information into the session. On each page we check for active session like,
/* Some Import Statements here. */
if(null == session || !session.getAttribute("is_login").equals("1")) {
response.sendRedirect("http://domain.com/login");
}
// ....
session.getAttribute("user_id");
// ....
/* Some More JSP+Java+HTML code here */
It looks fine at first glance however; It has one issue. If your server has expired session due to time limit and user is trying to access the page he might get error if you have not written your code in try..catch
block or handled if(null != session.getAttribute("attr_name"))
everytime.
So by putting a return;
statement I stopped further execution and forced to redirect page to certain location.
if(null == session || !session.getAttribute("is_login").equals("1")) {
response.sendRedirect("http://domain.com/login");
return;
}
Note that Use of redirection may vary based on the requirements. Nowadays people don't use such authentication system. (Modern approach - Token Based Authentication) It's just an simple example to understand where and how to place redirection(s).
I fixed it with adding the prefix (attr.) :
<create-report-card-form [attr.currentReportCardCount]="expression" ...
Unfortunately this haven't documented properly yet.
more detail here
Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML.
Adding a value of selected
to the item we want to appear as a header forces it to show in the first place as a placeholder.
Something like:
<option selected disabled>Choose here</option>
The complete markup should be along these lines:
<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
You can take a look at this fiddle, and here's the result:
If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden
attribute like so:
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check the fiddle here and the screenshot below.
Here is the solution:
<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
You cannot use primitive types in HashMap
. int
, or double
don't work. You have to use its enclosing type. for an example
Map<String,Integer> m = new HashMap<String,Integer>();
Now both are objects, so this will work.
Use the dist()
function, but you need to form a matrix from the two inputs for the first argument to dist()
:
dist(rbind(x1, x2))
For the input in the OP's question we get:
> dist(rbind(x1, x2))
x1
x2 7.94821
a single value that is the Euclidean distance between x1
and x2
.
There's another way with post
instead of ajax
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
.asterisc {_x000D_
display: block;_x000D_
color: red;_x000D_
margin: -19px 185px;_x000D_
}
_x000D_
<input style="width:200px">_x000D_
<span class="asterisc">*</span>
_x000D_
Sharing data between controllers is what Factories/Services are very good for. In short, it works something like this.
var app = angular.module('myApp', []);
app.factory('items', function() {
var items = [];
var itemsService = {};
itemsService.add = function(item) {
items.push(item);
};
itemsService.list = function() {
return items;
};
return itemsService;
});
function Ctrl1($scope,items) {
$scope.list = items.list;
}
function Ctrl2($scope, items) {
$scope.add = items.add;
}
You can see a working example in this fiddle: http://jsfiddle.net/mbielski/m8saa/
That worked for me in python3:
import urllib.request
htmlfile = urllib.request.urlopen("http://google.com")
htmltext = htmlfile.read()
print(htmltext)
You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ...
, it's not recommended. Take a closer look here
Well, if you had already created the log4j.properties you would add its path to the classpath so it would be found during execution.
Yes, the thingy will search for this file in the classpath.
Since you said you looked into axis and didnt find one, I am assuming you dont have a log4j.properties, so here's a crude but complete example.
Create it somewhere and add to your classpath. Put it for example, in c:/proj/resources/log4j.properties
In your classpath you simple add .......;c:/proj/resources
# Root logger option
log4j.rootLogger=DEBUG, stdout, file
# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=c:/project/resources/t-output/log4j-application.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
You can install these features on windows server 2012 with powershell using the following commands:
Install-WindowsFeature -Name NET-Framework-Features -IncludeAllSubFeature
Install-WindowsFeature -Name NET-WCF-HTTP-Activation45 -IncludeAllSubFeature
You can get a list of features with the following command:
Get-WindowsFeature | Format-Table
The solution I opted for was to format the date with the mysql query :
String l_mysqlQuery = "SELECT DATE_FORMAT(time, '%Y-%m-%d %H:%i:%s') FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));
I had the exact same issue.
Even though my mysql table contains dates formatted as such : 2017-01-01 21:02:50
String l_mysqlQuery = "SELECT time FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));
was returning a date formatted as such :
2017-01-01 21:02:50.0
If you can use javascipt, have the client handle laying out the content using javascript to place elements based on available space.
You could use the jquery columnizer plugin to dynamically lay out your content in fixed size blocks and position your headers and footers as part of the rendering routine. http://welcome.totheinter.net/columnizer-jquery-plugin/
See example 10 http://welcome.totheinter.net/autocolumn/sample10.html
The browser will still add its own headers or footers if enabled in the os. Consistent layout across platforms and browsers will likely require conditional css.
I also got the same issue and not able to create a jar, and I found that in Windows-->Prefernces-->Java-->installed JREs By default JRE was added to the build path of newly created java project so just changed it to your prefered JDK.
Breaking out of a for-loop is a little strange to me, since the semantics of a for-loop typically indicate that it will execute a specified number of times. However, it's not bad in all cases; if you're searching for something in a collection and want to break after you find it, it's useful. Breaking out of nested loops, however, isn't possible in C++; it is in other languages through the use of a labeled break. You can use a label and a goto, but that might give you heartburn at night..? Seems like the best option though.
you can use a formatstring
DateTime time = DateTime.Now;
String format = "MMM ddd d HH:mm yyyy";
Console.WriteLine(time.ToString(format));
public class SwingExample implements Runnable {
@Override
public void run() {
// Create the window
final JFrame f = new JFrame("Hello, World!");
SwingExample.centerWindow(f);
f.setPreferredSize(new Dimension(500, 250));
f.setMaximumSize(new Dimension(10000, 200));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void centerWindow(JFrame frame) {
Insets insets = frame.getInsets();
frame.setSize(new Dimension(insets.left + insets.right + 500, insets.top + insets.bottom + 250));
frame.setVisible(true);
frame.setResizable(false);
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, y);
}
}
I think you're talking about the logical meaning of both operators, here you have a table-resume:
boolean a, b;
Operation Meaning Note
--------- ------- ----
a && b logical AND short-circuiting
a || b logical OR short-circuiting
a & b boolean logical AND not short-circuiting
a | b boolean logical OR not short-circuiting
a ^ b boolean logical exclusive OR
!a logical NOT
short-circuiting (x != 0) && (1/x > 1) SAFE
not short-circuiting (x != 0) & (1/x > 1) NOT SAFE
Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true.
Not Safe means the operator always examines every condition in the clause, so in the examples above, 1/x may be evaluated when the x is, in fact, a 0 value, raising an exception.
To be more specific if you are missing the class com.vaadin.external.org.slf4j.LoggerFactory add the below dependency.
<dependency>
<groupId>com.vaadin.external.slf4j</groupId>
<artifactId>vaadin-slf4j-jdk14</artifactId>
<version>1.6.1</version>
</dependency>
If you are missing any other org.slf4j.LoggerFactory, just go to Maven central class name search and search for the exact class name to determine what exact dependency you are missing.
Can do this in jQuery. Try all options .height()
, .innerHeight()
or .outerHeight()
.
$('document').ready(function() {
$('#right_div').css({'height': $('#left_div').innerHeight()});
});
Example Screenshot
Hope this helps. Thanks!!
This issue I was solved by giving right permission of the folder as well as check from IIS.
I was given permission to everyone as I am testing in my local environment. But in publish mode I think we give only permission to ASP.Net user.
in the "Ouput Window". you can usually do CTRL-ALT-O to make it visible. Or through menus using View->Output.
$().live(function(){}); and jQuery.browser is undefined in jquery 1.9.0 - $.browser was deprecated in jquery update
sounds like you are using a different version of jquery 1.9 in godaddy so either change your code or include the migrate plugin http://code.jquery.com/jquery-migrate-1.0.0.js
Try the following command sequence:
$ git fetch origin <copy/past commit sha1 here>
$ git checkout FETCH_HEAD
$ git push origin master
Utilizing/Copying Darin Dimitrov's great response, this is how to access a custom attribute on a property and not a class:
The decorated property [of class Foo
]:
[MyCustomAttribute(SomeProperty = "This is a custom property")]
public string MyProperty { get; set; }
Fetching it:
PropertyInfo propertyInfo = typeof(Foo).GetProperty(propertyToCheck);
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
}
You can throw this in a loop and use reflection to access this custom attribute on each property of class Foo
, as well:
foreach (PropertyInfo propertyInfo in Foo.GetType().GetProperties())
{
string propertyName = propertyInfo.Name;
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
// Just in case you have a property without this annotation
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
// TODO: whatever you need with this propertyValue
}
}
Major thanks to you, Darin!!
The traditional for loop in Objective-C is inherited from standard C and takes the following form:
for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
// Do something.
}
For example, to print the numbers from 1 to 10, you could use the for loop:
for (int i = 1; i <= 10; i++)
{
NSLog(@"%d", i);
}
On the other hand, the for in loop was introduced in Objective-C 2.0, and is used to loop through objects in a collection, such as an NSArray instance. For example, to loop through a collection of NSString objects in an NSArray and print them all out, you could use the following format.
for (NSString* currentString in myArrayOfStrings)
{
NSLog(@"%@", currentString);
}
This is logically equivilant to the following traditional for loop:
for (int i = 0; i < [myArrayOfStrings count]; i++)
{
NSLog(@"%@", [myArrayOfStrings objectAtIndex:i]);
}
The advantage of using the for in loop is firstly that it's a lot cleaner code to look at. Secondly, the Objective-C compiler can optimize the for in loop so as the code runs faster than doing the same thing with a traditional for loop.
Hope this helps.
I am on shared hosting, so I can't do a lot of queries otherwise I get a blank page.
That sounds very peculiar. I've got the cheapest PHP hosting package I could find for my last project - and it does not behave like this. I would not pay for a service which did. Indeed, I'm stumped to even know how I could configure a server to replicate this behaviour.
Regardless of why it behaves this way, adding a sleep in the middle of the script cannot resolve the problem.
Since, presumably, you control your product catalog, new products should be relatively infrequent (or are you trying to get stock reports?). If you control when you change the data, why run the scripts automatically? Or do you mean that you already have these URLs and you get the expected files when you run them one at a time?
For a super succinct with jQuery approach try:
<div onclick="$(this).toggleClass('newclass')">click me</div>
Or pure JS:
<div onclick="this.classList.toggle('newclass');">click me</div>
Do you want to iterate over characters or words?
For words, you'll have to split the words first, such as
for index, word in enumerate(loopme.split(" ")):
print "CURRENT WORD IS", word, "AT INDEX", index
This prints the index of the word.
For the absolute character position you'd need something like
chars = 0
for index, word in enumerate(loopme.split(" ")):
print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
chars += len(word) + 1
Code from @mquander and @Yogurt The Wise used in extensions:
public static IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
yield return day;
}
public static IEnumerable<DateTime> EachMonth(DateTime from, DateTime thru)
{
for (var month = from.Date; month.Date <= thru.Date || month.Month == thru.Month; month = month.AddMonths(1))
yield return month;
}
public static IEnumerable<DateTime> EachDayTo(this DateTime dateFrom, DateTime dateTo)
{
return EachDay(dateFrom, dateTo);
}
public static IEnumerable<DateTime> EachMonthTo(this DateTime dateFrom, DateTime dateTo)
{
return EachMonth(dateFrom, dateTo);
}
I'd recommend looking for something such as Forever to restart Node in the event of a crash, and handle daemonizing this for you.
you can do it like this for multiple order by
IOrderedEnumerable<JToken> sort;
if (query.OrderBys[0].IsDESC)
{
sort = jarry.OrderByDescending(r => (string)r[query.OrderBys[0].Key]);
}
else
{
sort = jarry.OrderBy(r =>
(string) r[query.OrderBys[0].Key]);
}
foreach (var item in query.OrderBys.Skip(1))
{
if (item.IsDESC)
{
sort = sort.ThenByDescending(r => (string)r[item.Key]);
}
else
{
sort = sort.ThenBy(r => (string)r[item.Key]);
}
}
I found a solution that is more efficient than currently accepted answer, because current answer forces all list elements to be refreshed. My solution will refresh only one element (that was touched) by calling adapters getView and recycling current view which adds even more efficiency.
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Edit object data that is represented in Viewat at list's "position"
view = mAdapter.getView(position, view, parent);
}
});
You can use SharedPreferences for small amount of data. But if you have large and complex data then you should use Sqlite Database for local storage in flutter applications.
Use the setAttribute
method:
document.getElementById('item1').setAttribute('data', "icon: 'base2.gif', url: 'output.htm', target: 'AccessPage', output: '1'");
But you really should be using data followed with a dash and with its property, like:
<li ... data-icon="base.gif" ...>
And to do it in JS use the dataset
property:
document.getElementById('item1').dataset.icon = "base.gif";
I always store my date in UTC time.
This is my own function made from the different functions I found in this page.
It takes a STRING as a mysql DATETIME format (example : 2013-06-15 15:21:41). The checking with the regex is optional. You can delete this part to improve performance.
This function return a timestamp.
The DATETIME is considered as a UTC date. Be carefull : If you expect a local datetime, this function is not for you.
function datetimeToTimestamp(datetime)
{
var regDatetime = /^[0-9]{4}-(?:[0]?[0-9]{1}|10|11|12)-(?:[012]?[0-9]{1}|30|31)(?: (?:[01]?[0-9]{1}|20|21|22|23)(?::[0-5]?[0-9]{1})?(?::[0-5]?[0-9]{1})?)?$/;
if(regDatetime.test(datetime) === false)
throw("Wrong format for the param. `Y-m-d H:i:s` expected.");
var a=datetime.split(" ");
var d=a[0].split("-");
var t=a[1].split(":");
var date = new Date();
date.setUTCFullYear(d[0],(d[1]-1),d[2]);
date.setUTCHours(t[0],t[1],t[2], 0);
return date.getTime();
}
Here is a simple regex which will remove the url("
and ")
from the returned string.
var css = $("#myElem").css("background-image");
var img = css.replace(/(?:^url\(["']?|["']?\)$)/g, "");
if (AllocConsole() == 0)
{
// Handle error here. Use ::GetLastError() to get the error.
}
// Redirect CRT standard input, output and error handles to the console window.
FILE * pNewStdout = nullptr;
FILE * pNewStderr = nullptr;
FILE * pNewStdin = nullptr;
::freopen_s(&pNewStdout, "CONOUT$", "w", stdout);
::freopen_s(&pNewStderr, "CONOUT$", "w", stderr);
::freopen_s(&pNewStdin, "CONIN$", "r", stdin);
// Clear the error state for all of the C++ standard streams. Attempting to accessing the streams before they refer
// to a valid target causes the stream to enter an error state. Clearing the error state will fix this problem,
// which seems to occur in newer version of Visual Studio even when the console has not been read from or written
// to yet.
std::cout.clear();
std::cerr.clear();
std::cin.clear();
std::wcout.clear();
std::wcerr.clear();
std::wcin.clear();
There are two problems with this code:
Note in 2018: readAsBinaryString
is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer
(or in some cases, readAsDataURL
) instead.
readAsBinaryString
says that the data must be represented as a binary string, where:
...every byte is represented by an integer in the range [0..255].
JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)
If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).
If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText
and readAsBinaryString
, but with readAsBinaryString
you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText
, because readAsText
will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.
You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function loadFile() {
var input, file, fr;
if (typeof window.FileReader !== 'function') {
bodyAppend("p", "The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
bodyAppend("p", "Um, couldn't find the fileinput element.");
}
else if (!input.files) {
bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
bodyAppend("p", "Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
function receivedText() {
showResult(fr, "Text");
fr = new FileReader();
fr.onload = receivedBinary;
fr.readAsBinaryString(file);
}
function receivedBinary() {
showResult(fr, "Binary");
}
}
function showResult(fr, label) {
var markup, result, n, aByte, byteStr;
markup = [];
result = fr.result;
for (n = 0; n < result.length; ++n) {
aByte = result.charCodeAt(n);
byteStr = aByte.toString(16);
if (byteStr.length < 2) {
byteStr = "0" + byteStr;
}
markup.push(byteStr);
}
bodyAppend("p", label + " (" + result.length + "):");
bodyAppend("pre", markup.join(" "));
}
function bodyAppend(tagName, innerHTML) {
var elm;
elm = document.createElement(tagName);
elm.innerHTML = innerHTML;
document.body.appendChild(elm);
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>
If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:
Text (13): 54 65 73 74 69 6e 67 20 31 20 32 20 33 Binary (28): ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00
As you can see, readAsText
interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString
didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).
* XMLHttpRequest.response with responseType = "arraybuffer"
is supported in HTML 5.
** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.
If you want to remain both filename (only) and extension, you may use %~nxF
:
FOR /R C:\Directory %F in (*.*) do echo %~nxF
Try the following code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("URL");
JArray array = new JArray();
using (var twitpicResponse = (HttpWebResponse)request.GetResponse())
using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
JObject joResponse = JObject.Parse(objText);
JObject result = (JObject)joResponse["result"];
array = (JArray)result["Detail"];
string statu = array[0]["dlrStat"].ToString();
}
select * from tempdb.sys.columns where object_id =
object_id('tempdb..#mytemptable');
If you have your hex value, and your just wondering what the value for the alpha would be, this snippet may help:
const alphaToHex = (alpha => {_x000D_
if (alpha > 1 || alpha < 0 || isNaN(alpha)) {_x000D_
throw new Error('The argument must be a number between 0 and 1');_x000D_
}_x000D_
return Math.ceil(255 * alpha).toString(16).toUpperCase();_x000D_
})_x000D_
_x000D_
console.log(alphaToHex(0.45));
_x000D_
The shortcut is: CTRL+shift+- ("shift+-" results in "_") After typing the shortcut, nano will let you to enter the line you wanna jump to, type in the line number, then press ENTR.
Just to add to the other answers, there are still noteworthy differences here, specifically when dealing with <svg>
elements.
I have used both .childNodes
and .children
and have preferred working with the HTMLCollection
delivered by the .children
getter.
Today however, I ran into issues with IE/Edge failing when using .children
on an <svg>
.
While .children
is supported in IE on basic HTML elements, it isn't supported on document/document fragments, or SVG elements.
For me, I was able to simply grab the needed elements via .childNodes[n]
because I don't have extraneous text nodes to worry about. You may be able to do the same, but as mentioned elsewhere above, don't forget that you may run into unexpected elements.
Hope this is helpful to someone scratching their head trying to figure out why .children
works elsewhere in their js on modern IE and fails on document or SVG elements.
XAMPP Apache + MariaDB + PHP + Perl (X -any OS)
Open browser and in url type localhost
or 127.0.0.1
By default your port is listing with 80.If you want you can change it to your desired port number in httpd.conf file.(If port 80 is already using with other app then you have to change it).
For example you changed port number 80 to 8090 then you can run as 'localhost:8090' or '127.0.0.1:8090'
If you create a new database it's good to create user with permissions only for this database (if anything goes wrong you won't compromise root user login and password). So everything together will look like this:
mysql -u base_user -pbase_user_pass -e "create database new_db; GRANT ALL PRIVILEGES ON new_db.* TO new_db_user@localhost IDENTIFIED BY 'new_db_user_pass'"
Where:
base_user is the name for user with all privileges (probably the root)
base_user_pass it's the password for base_user (lack of space between -p and base_user_pass is important)
new_db is name for newly created database
new_db_user is name for the new user with access only for new_db
new_db_user_pass it's the password for new_db_user
The error means that the Postgres server is not running. Try starting it:
sudo systemctl start postgresql
Make sure that the server starts on boot:
sudo systemctl enable postgresql
My answer is similar to the others. If you do not want to create a new function you can use what pandas has defined for you already. Use the pipe method.
df.pipe(lambda d: d[d['column'] == value])
According to Alexis King answer, here is a plain JavaScript version.
function cleanUp(obj) {_x000D_
for (var attrKey in obj) {_x000D_
var attrValue = obj[attrKey];_x000D_
if (attrValue === null || attrValue === "") {_x000D_
delete obj[attrKey];_x000D_
} else if (Object.prototype.toString.call(attrValue) === "[object Object]") {_x000D_
cleanUp(attrValue);_x000D_
} else if (Array.isArray(attrValue)) {_x000D_
attrValue.forEach(function (arrayValue) {_x000D_
cleanUp(arrayValue);_x000D_
});_x000D_
}_x000D_
}_x000D_
}
_x000D_
If you need or want a simple HTTP server with the following:
I built one on top of the excellent SimpleHTTPAuthServer already on PyPI. This adds handling of POST requests: https://github.com/arielampol/SimpleHTTPAuthServerWithPOST
Otherwise, all the other options publicly available are already so good and robust.
Arrived here because my source repo had %20
in it which was creating local folders with %20
in them when using simplistic git clone <url>
.
Easy solution:
git clone https://teamname.visualstudio.com/Project%20Name/_git/Repo%20Name "Repo Name"
even shorter if you can lose the yearStart value:
var yearStart = 2000;
var yearEnd = 2040;
var arr = [];
while(yearStart < yearEnd+1){
arr.push(yearStart++);
}
UPDATE: If you can use the ES6 syntax you can do it the way proposed here:
let yearStart = 2000;
let yearEnd = 2040;
let years = Array(yearEnd-yearStart+1)
.fill()
.map(() => yearStart++);
If you are connecting to the MySQL using remote machine(Example workbench) etc., use following steps to eliminate this error on OS where MySQL is installed
mysql -u root -p
CREATE USER '<<username>>'@'%%' IDENTIFIED BY '<<password>>';
GRANT ALL PRIVILEGES ON * . * TO '<<username>>'@'%%';
FLUSH PRIVILEGES;
Try logging into the MYSQL instance.
This worked for me to eliminate this error.
There is no concept of folders or directories in S3. You can create file names like "abc/xys/uvw/123.jpg"
, which many S3 access tools like S3Fox
show like a directory structure, but it's actually just a single file in a bucket.
This was the order I got everything working. The second point is the most important one. Scipy needs Numpy+MKL
, not just vanilla Numpy
.
pip install "file path"
(download Numpy+MKL wheel from here http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy)pip install scipy
It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.
Other than that, I would suggest two things...
First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...
ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0
Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.
public interface IRepository
{
void Update<T>(T obj, params Expression<Func<T, object>>[] propertiesToUpdate) where T : class;
}
public class Repository : DbContext, IRepository
{
public void Update<T>(T obj, params Expression<Func<T, object>>[] propertiesToUpdate) where T : class
{
Set<T>().Attach(obj);
propertiesToUpdate.ToList().ForEach(p => Entry(obj).Property(p).IsModified = true);
SaveChanges();
}
}
Cloning the current database from the sqlite3 commandline worked for me.
.open /path/to/database/corrupted_database.sqlite3
.clone /path/to/database/new_database.sqlite3
In the Django setting file change the database name
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'new_database.sqlite3'),
}}
Simple answer
If you want to match single character, put it inside those brackets [ ]
Examples
...and so on. You can check your regular expresion online on this site: https://regex101.com/
(updated based on comment)
Just to add up, I did something like this.
<select class="form-control" data-ng-model="itemSelect" ng-change="selectedTemplate(itemSelect)" autofocus>
<option value="undefined" [selected]="itemSelect.Name == undefined" disabled="disabled">Select template...</option>
<option ng-repeat="itemSelect in templateLists" value="{{itemSelect.ID}}">{{itemSelect.Name}}</option></select>